question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
There are N cities numbered 1 to N, connected by M railroads.
You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.
The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes.
You cannot use gold coins to pay the fare.
There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin.
The transaction takes D_i minutes for each gold coin you give.
You can exchange any number of gold coins at each exchange counter.
For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.
-----Constraints-----
- 2 \leq N \leq 50
- N-1 \leq M \leq 100
- 0 \leq S \leq 10^9
- 1 \leq A_i \leq 50
- 1 \leq B_i,C_i,D_i \leq 10^9
- 1 \leq U_i < V_i \leq N
- There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
- Each city t=2,...,N can be reached from City 1 with some number of railroads.
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N
-----Output-----
For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.
-----Sample Input-----
3 2 1
1 2 1 2
1 3 2 4
1 11
1 2
2 5
-----Sample Output-----
2
14
The railway network in this input is shown in the figure below.
In this figure, each city is labeled as follows:
- The first line: the ID number i of the city (i for City i)
- The second line: C_i / D_i
Similarly, each railroad is labeled as follows:
- The first line: the ID number i of the railroad (i for the i-th railroad in input)
- The second line: A_i / B_i
You can travel from City 1 to City 2 in 2 minutes, as follows:
- Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.
You can travel from City 1 to City 3 in 14 minutes, as follows:
- Use the 1-st railroad to move from City 1 to City 2 in 2 minutes.
- At the exchange counter in City 2, exchange 3 gold coins for 3 silver coins in 6 minutes.
- Use the 1-st railroad to move from City 2 to City 1 in 2 minutes.
- Use the 2-nd railroad to move from City 1 to City 3 in 4 minutes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Caracal is fighting with a monster.
The health of the monster is H.
Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:
- If the monster's health is 1, it drops to 0.
- If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor.
(\lfloor r \rfloor denotes the greatest integer not exceeding r.)
Caracal wins when the healths of all existing monsters become 0 or below.
Find the minimum number of attacks Caracal needs to make before winning.
-----Constraints-----
- 1 \leq H \leq 10^{12}
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
H
-----Output-----
Find the minimum number of attacks Caracal needs to make before winning.
-----Sample Input-----
2
-----Sample Output-----
3
When Caracal attacks the initial monster, it disappears, and two monsters appear, each with the health of 1.
Then, Caracal can attack each of these new monsters once and win with a total of three attacks.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Eugene loves sequences, especially arithmetic progressions. One day he was asked to solve a difficult problem.
If a sequence of numbers A_{1}, A_{2}, ... , A_{N} form an arithmetic progression A, he was asked to calculate sum of F(A_{i}), for L ≤ i ≤ R.
F(X) is defined as:
If X < 10 then F(X) = X.
Else F(X) = F(sum_{of}_digits(X)).
Example:
F(1378) =
F(1+3+7+8) =
F(19) =
F(1 + 9) =
F(10) =
F(1+0) =
F(1) = 1
------ Input ------
The first line of the input contains an integer T denoting the number of test cases.
Each test case is described in one line containing four integers: A_{1} denoting the first element of the arithmetic progression A, D denoting the common difference between successive members of A, and L and R as described in the problem statement.
------ Output ------
For each test case, output a single line containing one integer denoting sum of F(A_{i}).
------ Constraints ------
$1 ≤ T ≤ 10^{5}$
$1 ≤ A_{1} ≤ 10^{9}$
$0 ≤ D ≤ 10^{9}$
$1 ≤ R ≤ 10^{18}$
$1 ≤ L ≤ R$
------ Subtasks ------
$Subtask 1: 0 ≤ D ≤ 100, 1 ≤ A_{1} ≤ 10^{9}, 1 ≤ R ≤ 100 - 15 points$
$Subtask 2: 0 ≤ D ≤ 10^{9}, 1 ≤ A_{1} ≤ 10^{9}, 1 ≤ R ≤ 10^{6} - 25 points$
$Subtask 3: Original constraints - 60 points$
----- Sample Input 1 ------
2
1 1 1 3
14 7 2 4
----- Sample Output 1 ------
6
12
----- explanation 1 ------
Example case 1.
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...}
A1 = 1
A2 = 2
A3 = 3
F(A1) = 1
F(A2) = 2
F(A3) = 3
1+2+3=6
Example case 2.
A = {14, 21, 28, 35, 42, 49, 56, 63, 70, 77, ...}
A2 = 21
A3 = 28
A4 = 35
F(A2) = 3
F(A3) = 1
F(A4) = 8
3+1+8=12
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:
* After the cutting each ribbon piece should have length a, b or c.
* After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon pieces after the required cutting.
Input
The first line contains four space-separated integers n, a, b and c (1 ≤ n, a, b, c ≤ 4000) — the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.
Output
Print a single number — the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.
Examples
Input
5 5 3 2
Output
2
Input
7 5 5 2
Output
2
Note
In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.
Constraints
* 1 \leq N \leq 17
* 0 \leq A \leq 2^N-1
* 0 \leq B \leq 2^N-1
* A \neq B
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
If there is no permutation that satisfies the conditions, print `NO`.
If there is such a permutation, print `YES` in the first line. Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between. If there are multiple solutions, any of them is accepted.
Examples
Input
2 1 3
Output
YES
1 0 2 3
Input
3 2 1
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a board with a 2 \times N grid.
Snuke covered the board with N dominoes without overlaps.
Here, a domino can cover a 1 \times 2 or 2 \times 1 square.
Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.
Find the number of such ways to paint the dominoes, modulo 1000000007.
The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:
- Each domino is represented by a different English letter (lowercase or uppercase).
- The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.
-----Constraints-----
- 1 \leq N \leq 52
- |S_1| = |S_2| = N
- S_1 and S_2 consist of lowercase and uppercase English letters.
- S_1 and S_2 represent a valid arrangement of dominoes.
-----Input-----
Input is given from Standard Input in the following format:
N
S_1
S_2
-----Output-----
Print the number of such ways to paint the dominoes, modulo 1000000007.
-----Sample Input-----
3
aab
ccb
-----Sample Output-----
6
There are six ways as shown below:
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor.
The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.
You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?"
Input
The first line contains five integers n, m, c_l, c_e, v (2 ≤ n, m ≤ 10^8, 0 ≤ c_l, c_e ≤ 10^5, 1 ≤ c_l + c_e ≤ m - 1, 1 ≤ v ≤ n - 1) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.
The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≤ l_i ≤ m), denoting the positions of the stairs. If c_l = 0, the second line is empty.
The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct.
The fourth line contains a single integer q (1 ≤ q ≤ 10^5) — the number of queries.
The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≤ x_1, x_2 ≤ n, 1 ≤ y_1, y_2 ≤ m) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i.
Output
Print q integers, one per line — the answers for the queries.
Example
Input
5 6 1 1 3
2
5
3
1 1 5 6
1 3 5 4
3 3 5 3
Output
7
5
4
Note
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.
In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
Chairman K is a regular customer of the JOI pizza shop in the center of JOI city. For some reason, he decided to start a life-saving life this month. So he wanted to order the pizza with the highest calories per dollar among the pizzas he could order at the JOI pizza store. Let's call such a pizza the "best pizza". The "best pizza" is not limited to one type.
At JOI Pizza, you can freely choose from N types of toppings and order the ones placed on the basic dough. You cannot put more than one topping of the same type. You can also order a pizza that doesn't have any toppings on the dough. The price of the dough is $ A and the price of the toppings is $ B. The price of pizza is the sum of the price of the dough and the price of the toppings. That is, the price of a pizza with k types of toppings (0 ≤ k ≤ N) is A + k x B dollars. The total calorie of the pizza is the sum of the calories of the dough and the calories of the toppings placed.
Create a program to find the number of calories per dollar for the "best pizza" given the price of the dough and the price of the toppings, and the calorie value of the dough and each topping.
input
The input consists of N + 3 lines.
On the first line, one integer N (1 ≤ N ≤ 100) representing the number of topping types is written. On the second line, two integers A and B (1 ≤ A ≤ 1000, 1 ≤ B ≤ 1000) are written with a blank as a delimiter. A is the price of the dough and B is the price of the toppings. On the third line, one integer C (1 ≤ C ≤ 10000) representing the number of calories in the dough is written.
On the 3 + i line (1 ≤ i ≤ N), one integer Di (1 ≤ Di ≤ 10000) representing the number of calories in the i-th topping is written.
output
Print the number of calories per dollar for the "best pizza" in one line. However, round down the numbers after the decimal point and output as an integer value.
Input / output example
Input example 1
3
12 2
200
50
300
100
Output example 1
37
In I / O Example 1, with the second and third toppings, 200 + 300 + 100 = 600 calories gives a pizza of $ 12 + 2 x 2 = $ 16.
This pizza has 600/16 = 37.5 calories per dollar. Since this is the "best pizza", we output 37, rounded down to the nearest whole number of 37.5.
Input example 2
Four
20 3
900
300
100
400
1300
Output example 2
100
The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics.
Example
Input
3
12 2
200
50
300
100
Output
37
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp had an array $a$ of $3$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $b$ of $7$ integers.
For example, if $a = \{1, 4, 3\}$, then Polycarp wrote out $1$, $4$, $3$, $1 + 4 = 5$, $1 + 3 = 4$, $4 + 3 = 7$, $1 + 4 + 3 = 8$. After sorting, he got an array $b = \{1, 3, 4, 4, 5, 7, 8\}.$
Unfortunately, Polycarp lost the array $a$. He only has the array $b$ left. Help him to restore the array $a$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 5000$) — the number of test cases.
Each test case consists of one line which contains $7$ integers $b_1, b_2, \dots, b_7$ ($1 \le b_i \le 10^9$; $b_i \le b_{i+1}$).
Additional constraint on the input: there exists at least one array $a$ which yields this array $b$ as described in the statement.
-----Output-----
For each test case, print $3$ integers — $a_1$, $a_2$ and $a_3$. If there can be several answers, print any of them.
-----Examples-----
Input
5
1 3 4 4 5 7 8
1 2 3 4 5 6 7
300000000 300000000 300000000 600000000 600000000 600000000 900000000
1 1 2 999999998 999999999 999999999 1000000000
1 2 2 3 3 4 5
Output
1 4 3
4 1 2
300000000 300000000 300000000
999999998 1 1
1 2 2
-----Note-----
The subsequence of the array $a$ is a sequence that can be obtained from $a$ by removing zero or more of its elements.
Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length $3$ has exactly $7$ different non-empty subsequences.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this Kata, two players, Alice and Bob, are playing a palindrome game. Alice starts with `string1`, Bob starts with `string2`, and the board starts out as an empty string. Alice and Bob take turns; during a turn, a player selects a letter from his or her string, removes it from the string, and appends it to the board; if the board becomes a palindrome (of length >= 2), the player wins. Alice makes the first move. Since Bob has the disadvantage of playing second, then he wins automatically if letters run out or the board is never a palindrome. Note also that each player can see the other player's letters.
The problem will be presented as `solve(string1,string2)`. Return 1 if Alice wins and 2 it Bob wins.
For example:
```Haskell
solve("abc","baxy") = 2 -- There is no way for Alice to win. If she starts with 'a', Bob wins by playing 'a'. The same case with 'b'. If Alice starts with 'c', Bob still wins because a palindrome is not possible. Return 2.
solve("eyfjy","ooigvo") = 1 -- Alice plays 'y' and whatever Bob plays, Alice wins by playing another 'y'. Return 1.
solve("abc","xyz") = 2 -- No palindrome is possible, so Bob wins; return 2
solve("gzyqsczkctutjves","hpaqrfwkdntfwnvgs") = 1 -- If Alice plays 'g', Bob wins by playing 'g'. Alice must be clever. She starts with 'z'. She knows that since she has two 'z', the win is guaranteed. Note that she also has two 's'. But she cannot play that. Can you see why?
solve("rmevmtw","uavtyft") = 1 -- Alice wins by playing 'm'. Can you see why?
```
Palindrome lengths should be at least `2` characters. More examples in the test cases.
Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have an array $a_1, a_2, \dots, a_n$ consisting of $n$ distinct integers. You are allowed to perform the following operation on it:
Choose two elements from the array $a_i$ and $a_j$ ($i \ne j$) such that $\gcd(a_i, a_j)$ is not present in the array, and add $\gcd(a_i, a_j)$ to the end of the array. Here $\gcd(x, y)$ denotes greatest common divisor (GCD) of integers $x$ and $y$.
Note that the array changes after each operation, and the subsequent operations are performed on the new array.
What is the maximum number of times you can perform the operation on the array?
-----Input-----
The first line consists of a single integer $n$ ($2 \le n \le 10^6$).
The second line consists of $n$ integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq 10^6$). All $a_i$ are distinct.
-----Output-----
Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.
-----Examples-----
Input
5
4 20 1 25 30
Output
3
Input
3
6 10 15
Output
4
-----Note-----
In the first example, one of the ways to perform maximum number of operations on the array is:
Pick $i = 1, j= 5$ and add $\gcd(a_1, a_5) = \gcd(4, 30) = 2$ to the array.
Pick $i = 2, j= 4$ and add $\gcd(a_2, a_4) = \gcd(20, 25) = 5$ to the array.
Pick $i = 2, j= 5$ and add $\gcd(a_2, a_5) = \gcd(20, 30) = 10$ to the array.
It can be proved that there is no way to perform more than $3$ operations on the original array.
In the second example one can add $3$, then $1$, then $5$, and $2$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A: Isono, let's do that! --Sendame -
story
Nakajima "Isono ~, let's do that!"
Isono "What is that, Nakajima"
Nakajima "Look, that's that. It's hard to explain because I have to express it in letters for some reason."
Isono "No, it seems that you can put in figures and photos, right?"
<image>
Nakajima "It's true!"
Isono "So what are you going to do?"
Nakajima "Look, the guy who rhythmically clapping his hands twice and then poses for defense, accumulation, and attack."
Isono "Hmm, I don't know ..."
Nakajima "After clapping hands twice, for example, if it was defense"
<image>
Nakajima "And if it was a reservoir"
<image>
Nakajima "If it was an attack"
<image>
Nakajima "Do you know who you are?"
Isono "Oh! It's dramatically easier to understand when a photo is included!"
Nakajima "This is the progress of civilization!"
(It's been a long time since then)
Hanazawa "Iso's" "I'm" "I'm"
Two people "(cracking ... crackling ... crackling ...)"
Hanazawa "You guys are doing that while sleeping ...!?"
Hanazawa: "You've won the game right now ... Isono-kun, have you won now?"
Isono "... Mr. Hanazawa was here ... Nakajima I'll do it again ... zzz"
Nakajima "(Kokuri)"
Two people "(cracking ... crackling ...)"
Hanazawa "Already ... I'll leave that winning / losing judgment robot here ..."
Then Mr. Hanazawa left.
Please write that winning / losing judgment program.
problem
"That" is a game played by two people. According to the rhythm, the two people repeat the pose of defense, accumulation, or attack at the same time. Here, the timing at which two people pose is referred to as "times". In this game, when there is a victory or defeat in a certain time and there is no victory or defeat in the previous times, the victory or defeat is the victory or defeat of the game.
Each of the two has a parameter called "attack power", and the attack power is 0 at the start of the game.
When the attack pose is taken, it becomes as follows according to the attack power at that time.
* If you pose for an attack when the attack power is 0, you will lose the foul. However, if the opponent also poses for an attack with an attack power of 0, he cannot win or lose at that time.
* If you pose for an attack when your attack power is 1 or more, you will attack your opponent. Also, if the opponent also poses for an attack at that time, the player with the higher attack power wins. However, if both players pose for an attack with the same attack power, they cannot win or lose at that time.
Also, at the end of the attack pose, your attack power becomes 0.
Taking a puddle pose increases the player's attack power by 1. However, if the attack power is 5, the attack power remains at 5 even if the player poses in the pool. If the opponent attacks in the time when you take the pose of the pool, the opponent wins. In addition, if the opponent takes a pose other than the attack in the time when the pose of the pool is taken, the victory or defeat cannot be determined.
If the opponent makes an attack with an attack power of 5 each time he takes a defensive pose, the opponent wins. On the other hand, if the opponent makes an attack with an attack power of 4 or less in the defense pose, or if the opponent poses for accumulation or defense, the victory or defeat cannot be achieved at that time. Even if you take a defensive pose, the attack power of that player does not change.
Since the poses of both players are given in order, output the victory or defeat. Both players may continue to pose after the victory or defeat is decided, but the pose after the victory or defeat is decided is ignored.
Input format
The input is given in the following format.
K
I_1_1
...
I_K
N_1_1
...
N_K
The first line of input is given an integer K (1 ≤ K ≤ 100). The pose I_i (1 ≤ i ≤ K) taken by Isono is given to the K lines from the second line in order. Immediately after that, the pose N_i (1 ≤ i ≤ K) taken by Nakajima is given to the K line in order. I_i and N_i are one of “mamoru”, “tameru”, and “kougekida”. These strings, in order, represent defense, pool, and attack poses.
Output format
Output “Isono-kun” if Isono wins, “Nakajima-kun” if Nakajima wins, and “Hikiwake-kun” if you cannot win or lose in K times.
Input example 1
3
tameru
tameru
tameru
tameru
kougekida
tameru
Output example 1
Nakajima-kun
In the second time, Isono is in the pose of the pool, while Nakajima is attacking with an attack power of 1, so Nakajima wins.
Input example 2
3
mamoru
mamoru
mamoru
tameru
tameru
tameru
Output example 2
Hikiwake-kun
Neither attacked, so I couldn't win or lose.
Input example 3
Five
tameru
tameru
mamoru
mamoru
kougekida
tameru
tameru
kougekida
tameru
kougekida
Output example 3
Isono-kun
There is no victory or defeat from the 1st to the 4th. In the 5th time, both players are posing for attack, but Isono's attack power is 2, while Nakajima's attack power is 1, so Isono wins.
Input example 4
3
kougekida
kougekida
tameru
kougekida
mamoru
kougekida
Output example 4
Nakajima-kun
In the first time, both players are posing for attack with 0 attack power, so there is no victory or defeat. In the second time, only Isono poses for an attack with an attack power of 0, so Nakajima wins.
Input example 5
8
tameru
mamoru
tameru
tameru
tameru
tameru
tameru
kougekida
tameru
kougekida
mamoru
mamoru
mamoru
mamoru
mamoru
mamoru
Output example 5
Isono-kun
In the second time, Nakajima poses for attack with an attack power of 1, but Isono poses for defense, so there is no victory or defeat. In the 7th time, Isono poses with an attack power of 5, so Isono's attack power remains at 5. In the 8th time, Isono poses for attack with an attack power of 5, and Nakajima poses for defense, so Isono wins.
Example
Input
3
tameru
tameru
tameru
tameru
kougekida
tameru
Output
Nakajima-kun
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp is going to participate in the contest. It starts at $h_1:m_1$ and ends at $h_2:m_2$. It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \% 2 = m_2 \% 2$, where $x \% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes.
Polycarp wants to know the time of the midpoint of the contest. For example, if the contest lasts from $10:00$ to $11:00$ then the answer is $10:30$, if the contest lasts from $11:10$ to $11:12$ then the answer is $11:11$.
-----Input-----
The first line of the input contains two integers $h_1$ and $m_1$ in the format hh:mm.
The second line of the input contains two integers $h_2$ and $m_2$ in the same format (hh:mm).
It is guaranteed that $0 \le h_1, h_2 \le 23$ and $0 \le m_1, m_2 \le 59$.
It is guaranteed that the contest lasts an even number of minutes (i.e. $m_1 \% 2 = m_2 \% 2$, where $x \% y$ is $x$ modulo $y$). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed that the contest lasts at least two minutes.
-----Output-----
Print two integers $h_3$ and $m_3$ ($0 \le h_3 \le 23, 0 \le m_3 \le 59$) corresponding to the midpoint of the contest in the format hh:mm. Print each number as exactly two digits (prepend a number with leading zero if needed), separate them with ':'.
-----Examples-----
Input
10:00
11:00
Output
10:30
Input
11:10
11:12
Output
11:11
Input
01:02
03:02
Output
02:02
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x_1, the second friend lives at the point x_2, and the third friend lives at the point x_3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer.
-----Input-----
The first line of the input contains three distinct integers x_1, x_2 and x_3 (1 ≤ x_1, x_2, x_3 ≤ 100) — the coordinates of the houses of the first, the second and the third friends respectively.
-----Output-----
Print one integer — the minimum total distance the friends need to travel in order to meet together.
-----Examples-----
Input
7 1 4
Output
6
Input
30 20 10
Output
20
-----Note-----
In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
Input
The first line contains two integers a, b (1 ≤ a, b ≤ 1000), separated by a single space.
Output
In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers — the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value.
Examples
Input
1 1
Output
NO
Input
5 5
Output
YES
2 1
5 5
-2 4
Input
5 10
Output
YES
-10 4
-2 -2
1 2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: Problemset of each division should be non-empty. Each problem should be used in exactly one division (yes, it is unusual requirement). Each problem used in division 1 should be harder than any problem used in division 2. If two problems are similar, they should be used in different divisions.
Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.
Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.
-----Input-----
The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000) — the number of problems prepared for the round and the number of pairs of similar problems, respectively.
Each of the following m lines contains a pair of similar problems u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}). It's guaranteed, that no pair of problems meets twice in the input.
-----Output-----
Print one integer — the number of ways to split problems in two divisions.
-----Examples-----
Input
5 2
1 4
5 2
Output
2
Input
3 3
1 2
2 3
1 3
Output
0
Input
3 2
3 1
3 2
Output
1
-----Note-----
In the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.
In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.
Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'
The head of the company decided to choose two suspects and invite them to his office. Naturally, he should consider the coders' opinions. That's why the head wants to make such a choice that at least p of n coders agreed with it. A coder agrees with the choice of two suspects if at least one of the two people that he named at the meeting was chosen as a suspect. In how many ways can the head of F choose two suspects?
Note that even if some coder was chosen as a suspect, he can agree with the head's choice if he named the other chosen coder at the meeting.
Input
The first line contains integers n and p (3 ≤ n ≤ 3·105; 0 ≤ p ≤ n) — the number of coders in the F company and the minimum number of agreed people.
Each of the next n lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of coders named by the i-th coder. It is guaranteed that xi ≠ i, yi ≠ i, xi ≠ yi.
Output
Print a single integer — the number of possible two-suspect sets. Note that the order of the suspects doesn't matter, that is, sets (1, 2) and (2, 1) are considered identical.
Examples
Input
4 2
2 3
1 4
1 4
2 1
Output
6
Input
8 6
5 6
5 7
5 8
6 2
2 1
7 3
1 3
1 4
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi has N days of summer vacation.
His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.
He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.
What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?
If Takahashi cannot finish all the assignments during the vacation, print -1 instead.
-----Constraints-----
- 1 \leq N \leq 10^6
- 1 \leq M \leq 10^4
- 1 \leq A_i \leq 10^4
-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 ... A_M
-----Output-----
Print the maximum number of days Takahashi can hang out during the vacation, or -1.
-----Sample Input-----
41 2
5 6
-----Sample Output-----
30
For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left.
In the grid, N Squares (r_1, c_1), (r_2, c_2), \ldots, (r_N, c_N) are wall squares, and the others are all empty squares. It is guaranteed that Squares (1, 1) and (H, W) are empty squares.
Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right or down to an adjacent empty square.
Find the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.
Constraints
* All values in input are integers.
* 2 \leq H, W \leq 10^5
* 1 \leq N \leq 3000
* 1 \leq r_i \leq H
* 1 \leq c_i \leq W
* Squares (r_i, c_i) are all distinct.
* Squares (1, 1) and (H, W) are empty squares.
Input
Input is given from Standard Input in the following format:
H W N
r_1 c_1
r_2 c_2
:
r_N c_N
Output
Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.
Examples
Input
3 4 2
2 2
1 4
Output
3
Input
5 2 2
2 1
4 2
Output
0
Input
5 5 4
3 1
3 5
1 3
5 3
Output
24
Input
100000 100000 1
50000 50000
Output
123445622
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
— This is not playing but duty as allies of justice, Nii-chan!
— Not allies but justice itself, Onii-chan!
With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!
There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of a, b and c distinct islands respectively.
Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length 1. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is at least 3, apparently in order to prevent oddities from spreading quickly inside a cluster.
The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo 998 244 353. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other.
-----Input-----
The first and only line of input contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 5 000) — the number of islands in the red, blue and purple clusters, respectively.
-----Output-----
Output one line containing an integer — the number of different ways to build bridges, modulo 998 244 353.
-----Examples-----
Input
1 1 1
Output
8
Input
1 2 2
Output
63
Input
1 3 5
Output
3264
Input
6 2 9
Output
813023575
-----Note-----
In the first example, there are 3 bridges that can possibly be built, and no setup of bridges violates the restrictions. Thus the answer is 2^3 = 8.
In the second example, the upper two structures in the figure below are instances of valid ones, while the lower two are invalid due to the blue and purple clusters, respectively. [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".
Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".
There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".
Sergey is very busy and asks you to help him and write the required program.
-----Input-----
The first line contains the integer n (1 ≤ n ≤ 100 000) — the number of letters in the word written by Stepan.
The second line contains the string s which has length that equals to n and contains only lowercase English letters — the word written by Stepan.
-----Output-----
Print the single string — the word written by Stepan converted according to the rules described in the statement.
-----Examples-----
Input
13
pobeeeedaaaaa
Output
pobeda
Input
22
iiiimpleeemeentatiioon
Output
implemeentatioon
Input
18
aeiouyaaeeiioouuyy
Output
aeiouyaeeioouy
Input
24
aaaoooiiiuuuyyyeeeggghhh
Output
aoiuyeggghhh
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
500-yen Saving
"500-yen Saving" is one of Japanese famous methods to save money. The method is quite simple; whenever you receive a 500-yen coin in your change of shopping, put the coin to your 500-yen saving box. Typically, you will find more than one million yen in your saving box in ten years.
Some Japanese people are addicted to the 500-yen saving. They try their best to collect 500-yen coins efficiently by using 1000-yen bills and some coins effectively in their purchasing. For example, you will give 1320 yen (one 1000-yen bill, three 100-yen coins and two 10-yen coins) to pay 817 yen, to receive one 500-yen coin (and three 1-yen coins) in the change.
A friend of yours is one of these 500-yen saving addicts. He is planning a sightseeing trip and wants to visit a number of souvenir shops along his way. He will visit souvenir shops one by one according to the trip plan. Every souvenir shop sells only one kind of souvenir goods, and he has the complete list of their prices. He wants to collect as many 500-yen coins as possible through buying at most one souvenir from a shop. On his departure, he will start with sufficiently many 1000-yen bills and no coins at all. The order of shops to visit cannot be changed. As far as he can collect the same number of 500-yen coins, he wants to cut his expenses as much as possible.
Let's say that he is visiting shops with their souvenir prices of 800 yen, 700 yen, 1600 yen, and 600 yen, in this order. He can collect at most two 500-yen coins spending 2900 yen, the least expenses to collect two 500-yen coins, in this case. After skipping the first shop, the way of spending 700-yen at the second shop is by handing over a 1000-yen bill and receiving three 100-yen coins. In the next shop, handing over one of these 100-yen coins and two 1000-yen bills for buying a 1600-yen souvenir will make him receive one 500-yen coin. In almost the same way, he can obtain another 500-yen coin at the last shop. He can also collect two 500-yen coins buying at the first shop, but his total expenditure will be at least 3000 yen because he needs to buy both the 1600-yen and 600-yen souvenirs in this case.
You are asked to make a program to help his collecting 500-yen coins during the trip. Receiving souvenirs' prices listed in the order of visiting the shops, your program is to find the maximum number of 500-yen coins that he can collect during his trip, and the minimum expenses needed for that number of 500-yen coins.
For shopping, he can use an arbitrary number of 1-yen, 5-yen, 10-yen, 50-yen, and 100-yen coins he has, and arbitrarily many 1000-yen bills. The shop always returns the exact change, i.e., the difference between the amount he hands over and the price of the souvenir. The shop has sufficient stock of coins and the change is always composed of the smallest possible number of 1-yen, 5-yen, 10-yen, 50-yen, 100-yen, and 500-yen coins and 1000-yen bills. He may use more money than the price of the souvenir, even if he can put the exact money, to obtain desired coins as change; buying a souvenir of 1000 yen, he can hand over one 1000-yen bill and five 100-yen coins and receive a 500-yen coin. Note that using too many coins does no good; handing over ten 100-yen coins and a 1000-yen bill for a souvenir of 1000 yen, he will receive a 1000-yen bill as the change, not two 500-yen coins.
Input
The input consists of at most 50 datasets, each in the following format.
> n
> p1
> ...
> pn
>
n is the number of souvenir shops, which is a positive integer not greater than 100. pi is the price of the souvenir of the i-th souvenir shop. pi is a positive integer not greater than 5000.
The end of the input is indicated by a line with a single zero.
Output
For each dataset, print a line containing two integers c and s separated by a space. Here, c is the maximum number of 500-yen coins that he can get during his trip, and s is the minimum expenses that he need to pay to get c 500-yen coins.
Sample Input
4
800
700
1600
600
4
300
700
1600
600
4
300
700
1600
650
3
1000
2000
500
3
250
250
1000
4
1251
667
876
299
0
Output for the Sample Input
2 2900
3 2500
3 3250
1 500
3 1500
3 2217
Example
Input
4
800
700
1600
600
4
300
700
1600
600
4
300
700
1600
650
3
1000
2000
500
3
250
250
1000
4
1251
667
876
299
0
Output
2 2900
3 2500
3 3250
1 500
3 1500
3 2217
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!
Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1·2·3·...·(x - 1)·x. For example 4! = 1·2·3·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.
Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?
-----Input-----
The first and single line contains two integers A and B (1 ≤ A, B ≤ 10^9, min(A, B) ≤ 12).
-----Output-----
Print a single integer denoting the greatest common divisor of integers A! and B!.
-----Example-----
Input
4 3
Output
6
-----Note-----
Consider the sample.
4! = 1·2·3·4 = 24. 3! = 1·2·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is an infinite board of square tiles. Initially all tiles are white.
Vova has a red marker and a blue marker. Red marker can color $a$ tiles. Blue marker can color $b$ tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly $a$ red tiles and exactly $b$ blue tiles across the board.
Vova wants to color such a set of tiles that:
they would form a rectangle, consisting of exactly $a+b$ colored tiles; all tiles of at least one color would also form a rectangle.
Here are some examples of correct colorings:
[Image]
Here are some examples of incorrect colorings:
[Image]
Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?
It is guaranteed that there exists at least one correct coloring.
-----Input-----
A single line contains two integers $a$ and $b$ ($1 \le a, b \le 10^{14}$) — the number of tiles red marker should color and the number of tiles blue marker should color, respectively.
-----Output-----
Print a single integer — the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly $a$ tiles red and exactly $b$ tiles blue.
It is guaranteed that there exists at least one correct coloring.
-----Examples-----
Input
4 4
Output
12
Input
3 9
Output
14
Input
9 3
Output
14
Input
3 6
Output
12
Input
506 2708
Output
3218
-----Note-----
The first four examples correspond to the first picture of the statement.
Note that for there exist multiple correct colorings for all of the examples.
In the first example you can also make a rectangle with sides $1$ and $8$, though its perimeter will be $18$ which is greater than $8$.
In the second example you can make the same resulting rectangle with sides $3$ and $4$, but red tiles will form the rectangle with sides $1$ and $3$ and blue tiles will form the rectangle with sides $3$ and $3$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
CQXYM is counting permutations length of $2n$.
A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array).
A permutation $p$(length of $2n$) will be counted only if the number of $i$ satisfying $p_i<p_{i+1}$ is no less than $n$. For example:
Permutation $[1, 2, 3, 4]$ will count, because the number of such $i$ that $p_i<p_{i+1}$ equals $3$ ($i = 1$, $i = 2$, $i = 3$).
Permutation $[3, 2, 1, 4]$ won't count, because the number of such $i$ that $p_i<p_{i+1}$ equals $1$ ($i = 3$).
CQXYM wants you to help him to count the number of such permutations modulo $1000000007$ ($10^9+7$).
In addition, modulo operation is to get the remainder. For example:
$7 \mod 3=1$, because $7 = 3 \cdot 2 + 1$,
$15 \mod 4=3$, because $15 = 4 \cdot 3 + 3$.
-----Input-----
The input consists of multiple test cases.
The first line contains an integer $t (t \geq 1)$ — the number of test cases. The description of the test cases follows.
Only one line of each test case contains an integer $n(1 \leq n \leq 10^5)$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$
-----Output-----
For each test case, print the answer in a single line.
-----Examples-----
Input
4
1
2
9
91234
Output
1
12
830455698
890287984
-----Note-----
$n=1$, there is only one permutation that satisfies the condition: $[1,2].$
In permutation $[1,2]$, $p_1<p_2$, and there is one $i=1$ satisfy the condition. Since $1 \geq n$, this permutation should be counted. In permutation $[2,1]$, $p_1>p_2$. Because $0<n$, this permutation should not be counted.
$n=2$, there are $12$ permutations: $[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,3,1,4],[2,3,4,1],[2,4,1,3],[3,1,2,4],[3,4,1,2],[4,1,2,3].$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function that takes a single array as an argument (containing multiple strings and/or positive numbers and/or arrays), and returns one of four possible string values, depending on the ordering of the lengths of the elements in the input array:
Your function should return...
- “Increasing” - if the lengths of the elements increase from left to right (although it is possible that some neighbouring elements may also be equal in length)
- “Decreasing” - if the lengths of the elements decrease from left to right (although it is possible that some neighbouring elements may also be equal in length)
- “Unsorted” - if the lengths of the elements fluctuate from left to right
- “Constant” - if all element's lengths are the same.
Numbers and Strings should be evaluated based on the number of characters or digits used to write them.
Arrays should be evaluated based on the number of elements counted directly in the parent array (but not the number of elements contained in any sub-arrays).
Happy coding! :)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are a mayor of Berlyatov. There are $n$ districts and $m$ two-way roads between them. The $i$-th road connects districts $x_i$ and $y_i$. The cost of travelling along this road is $w_i$. There is some path between each pair of districts, so the city is connected.
There are $k$ delivery routes in Berlyatov. The $i$-th route is going from the district $a_i$ to the district $b_i$. There is one courier on each route and the courier will always choose the cheapest (minimum by total cost) path from the district $a_i$ to the district $b_i$ to deliver products.
The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).
You can make at most one road to have cost zero (i.e. you choose at most one road and change its cost with $0$).
Let $d(x, y)$ be the cheapest cost of travel between districts $x$ and $y$.
Your task is to find the minimum total courier routes cost you can achieve, if you optimally select the some road and change its cost with $0$. In other words, you have to find the minimum possible value of $\sum\limits_{i = 1}^{k} d(a_i, b_i)$ after applying the operation described above optimally.
-----Input-----
The first line of the input contains three integers $n$, $m$ and $k$ ($2 \le n \le 1000$; $n - 1 \le m \le min(1000, \frac{n(n-1)}{2})$; $1 \le k \le 1000$) — the number of districts, the number of roads and the number of courier routes.
The next $m$ lines describe roads. The $i$-th road is given as three integers $x_i$, $y_i$ and $w_i$ ($1 \le x_i, y_i \le n$; $x_i \ne y_i$; $1 \le w_i \le 1000$), where $x_i$ and $y_i$ are districts the $i$-th road connects and $w_i$ is its cost. It is guaranteed that there is some path between each pair of districts, so the city is connected. It is also guaranteed that there is at most one road between each pair of districts.
The next $k$ lines describe courier routes. The $i$-th route is given as two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le n$) — the districts of the $i$-th route. The route can go from the district to itself, some couriers routes can coincide (and you have to count them independently).
-----Output-----
Print one integer — the minimum total courier routes cost you can achieve (i.e. the minimum value $\sum\limits_{i=1}^{k} d(a_i, b_i)$, where $d(x, y)$ is the cheapest cost of travel between districts $x$ and $y$) if you can make some (at most one) road cost zero.
-----Examples-----
Input
6 5 2
1 2 5
2 3 7
2 4 4
4 5 2
4 6 8
1 6
5 3
Output
22
Input
5 5 4
1 2 5
2 3 4
1 4 3
4 3 7
3 5 2
1 5
1 3
3 3
1 5
Output
13
-----Note-----
The picture corresponding to the first example:
[Image]
There, you can choose either the road $(2, 4)$ or the road $(4, 6)$. Both options lead to the total cost $22$.
The picture corresponding to the second example:
$A$
There, you can choose the road $(3, 4)$. This leads to the total cost $13$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Suppose $a_1, a_2, \dots, a_n$ is a sorted integer sequence of length $n$ such that $a_1 \leq a_2 \leq \dots \leq a_n$.
For every $1 \leq i \leq n$, the prefix sum $s_i$ of the first $i$ terms $a_1, a_2, \dots, a_i$ is defined by $$ s_i = \sum_{k=1}^i a_k = a_1 + a_2 + \dots + a_i. $$
Now you are given the last $k$ terms of the prefix sums, which are $s_{n-k+1}, \dots, s_{n-1}, s_{n}$. Your task is to determine whether this is possible.
Formally, given $k$ integers $s_{n-k+1}, \dots, s_{n-1}, s_{n}$, the task is to check whether there is a sequence $a_1, a_2, \dots, a_n$ such that
$a_1 \leq a_2 \leq \dots \leq a_n$, and
$s_i = a_1 + a_2 + \dots + a_i$ for all $n-k+1 \leq i \leq n$.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 10^5$) — the number of test cases. The following lines contain the description of each test case.
The first line of each test case contains two integers $n$ ($1 \leq n \leq 10^5$) and $k$ ($1 \leq k \leq n$), indicating the length of the sequence $a$ and the number of terms of prefix sums, respectively.
The second line of each test case contains $k$ integers $s_{n-k+1}, \dots, s_{n-1}, s_{n}$ ($-10^9 \leq s_i \leq 10^9$ for every $n-k+1 \leq i \leq n$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case, output "YES" (without quotes) if it is possible and "NO" (without quotes) otherwise.
You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
-----Examples-----
Input
4
5 5
1 2 3 4 5
7 4
-6 -5 -3 0
3 3
2 3 4
3 2
3 4
Output
Yes
Yes
No
No
-----Note-----
In the first test case, we have the only sequence $a = [1, 1, 1, 1, 1]$.
In the second test case, we can choose, for example, $a = [-3, -2, -1, 0, 1, 2, 3]$.
In the third test case, the prefix sums define the only sequence $a = [2, 1, 1]$, but it is not sorted.
In the fourth test case, it can be shown that there is no sequence with the given prefix sums.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive.
Input
Input contains one integer number n (1 ≤ n ≤ 3000).
Output
Output the amount of almost prime numbers between 1 and n, inclusive.
Examples
Input
10
Output
2
Input
21
Output
8
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).
He is dividing the problems into two categories by choosing an integer K, as follows:
- A problem with difficulty K or higher will be for ARCs.
- A problem with difficulty lower than K will be for ABCs.
How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?
-----Problem Statement-----
- 2 \leq N \leq 10^5
- N is an even number.
- 1 \leq d_i \leq 10^5
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
d_1 d_2 ... d_N
-----Output-----
Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.
-----Sample Input-----
6
9 1 4 4 6 7
-----Sample Output-----
2
If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya had a strictly increasing sequence of positive integers a_1, ..., a_{n}. Vasya used it to build a new sequence b_1, ..., b_{n}, where b_{i} is the sum of digits of a_{i}'s decimal representation. Then sequence a_{i} got lost and all that remained is sequence b_{i}.
Vasya wonders what the numbers a_{i} could be like. Of all the possible options he likes the one sequence with the minimum possible last number a_{n}. Help Vasya restore the initial sequence.
It is guaranteed that such a sequence always exists.
-----Input-----
The first line contains a single integer number n (1 ≤ n ≤ 300).
Next n lines contain integer numbers b_1, ..., b_{n} — the required sums of digits. All b_{i} belong to the range 1 ≤ b_{i} ≤ 300.
-----Output-----
Print n integer numbers, one per line — the correct option for numbers a_{i}, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to b_{i}.
If there are multiple sequences with least possible number a_{n}, print any of them. Print the numbers without leading zeroes.
-----Examples-----
Input
3
1
2
3
Output
1
2
3
Input
3
3
2
1
Output
3
11
100
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.
At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation:
* Choose a vertex v that contains one or more coins, and remove all the coins from v.
* Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.
The player who becomes unable to play, loses the game. That is, the player who takes his turn when there is no coin remaining on the tree, loses the game. Determine the winner of the game when both players play optimally.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq a_i, b_i \leq N
* a_i \neq b_i
* The graph given as input is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi will win, and print `Second` if Aoki will win.
Examples
Input
3
1 2
2 3
Output
First
Input
6
1 2
2 3
2 4
4 6
5 6
Output
Second
Input
7
1 7
7 4
3 4
7 5
6 3
2 1
Output
First
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian as well.
John's barn has a fence consisting of N consecutive parts numbered from left to right starting from 1 to N. Each part is initially painted in one of two colors: red or green, whose information is provided you by a string C. The color of i-th part C_{i} will be equal to 'R' if the color of the part is red and 'G' if it is green.
John decided to paint the whole fence in green color. To make the mundane process of painting more entertaining he decided to do it using the following process.
Every minute (until the whole fence is painted green) he will do the following steps:
Choose any part of the fence that is painted red. Let's denote the index of this part as X.
For each part with indices X, X+1, ..., min(N, X + K - 1), flip the color of the corresponding part from red to green and from green to red by repainting.
John is wondering how fast he can repaint the fence. Please help him in finding the minimum number of minutes required in repainting.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains the two integers N and K.
The next line contains the string C.
------ Output ------
For each test case, output a single line containing the answer to the corresponding test case.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N, K ≤ 10^{5}$
$C will consist only of uppercase English characters 'R' and 'G'.$
----- Sample Input 1 ------
1
7 3
RGGRGRG
----- Sample Output 1 ------
4
----- explanation 1 ------
Example case 1. One optimal solution (with 4 steps) looks like this:
Choose the 1-st character (1-based index) and get "GRRRGRG".
Choose the 2-st character (1-based index) and get "GGGGGRG".
Choose the 6-th character (1-based index) and get "GGGGGGR".
Choose the 7-th charatcer (1-based index) and get "GGGGGGG".
Now repainting is done :) It took total 4 steps. Hence answer is 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
DNA is a biomolecule that carries genetic information. It is composed of four different building blocks, called nucleotides: adenine (A), thymine (T), cytosine (C) and guanine (G). Two DNA strands join to form a double helix, whereby the nucleotides of one strand bond to the nucleotides of the other strand at the corresponding positions. The bonding is only possible if the nucleotides are complementary: A always pairs with T, and C always pairs with G.
Due to the asymmetry of the DNA, every DNA strand has a direction associated with it. The two strands of the double helix run in opposite directions to each other, which we refer to as the 'up-down' and the 'down-up' directions.
Write a function `checkDNA` that takes in two DNA sequences as strings, and checks if they are fit to form a fully complementary DNA double helix. The function should return a Boolean `true` if they are complementary, and `false` if there is a sequence mismatch (Example 1 below).
Note:
- All sequences will be of non-zero length, and consisting only of `A`, `T`, `C` and `G` characters.
- All sequences **will be given in the up-down direction**.
- The two sequences to be compared can be of different length. If this is the case and one strand is entirely bonded by the other, and there is no sequence mismatch between the two (Example 2 below), your function should still return `true`.
- If both strands are only partially bonded (Example 3 below), the function should return `false`.
Example 1:
Example 2:
Example 3:
---
#### If you enjoyed this kata, check out also my other DNA kata: [**Longest Repeated DNA Motif**](http://www.codewars.com/kata/longest-repeated-dna-motif)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
My little sister came back home from school with the following task:
given a squared sheet of paper she has to cut it in pieces
which, when assembled, give squares the sides of which form
an increasing sequence of numbers.
At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn paper.
So we decided to write a program that could help us and protects trees.
## Task
Given a positive integral number n, return a **strictly increasing** sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².
If there are multiple solutions (and there will be), return as far as possible the result with the largest possible values:
## Examples
`decompose(11)` must return `[1,2,4,10]`. Note that there are actually two ways to decompose 11²,
11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don't return `[2,6,9]`, since 9 is smaller than 10.
For `decompose(50)` don't return `[1, 1, 4, 9, 49]` but `[1, 3, 5, 8, 49]` since `[1, 1, 4, 9, 49]`
doesn't form a strictly increasing sequence.
## Note
Neither `[n]` nor `[1,1,1,…,1]` are valid solutions. If no valid solution exists, return `nil`, `null`, `Nothing`, `None` (depending on the language) or `"[]"` (C) ,`{}` (C++), `[]` (Swift, Go).
The function "decompose" will take a positive integer n
and return the decomposition of N = n² as:
- [x1 ... xk]
or
- "x1 ... xk"
or
- Just [x1 ... xk]
or
- Some [x1 ... xk]
or
- {x1 ... xk}
or
- "[x1,x2, ... ,xk]"
depending on the language (see "Sample tests")
# Note for Bash
```
decompose 50 returns "1,3,5,8,49"
decompose 4 returns "Nothing"
```
# Hint
Very often `xk` will be `n-1`.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = a·b.
<image> 10 pebbles are arranged in two rows, each row has 5 pebbles
Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble.
The game process can be represented as a finite sequence of integers c1, ..., ck, where:
* c1 = n
* ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≤ i < k). Note that ci > ci + 1.
* ck = 1
The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.
Input
The single line of the input contains a single integer n — the initial number of pebbles the Smart Beaver has.
The input limitations for getting 30 points are:
* 2 ≤ n ≤ 50
The input limitations for getting 100 points are:
* 2 ≤ n ≤ 109
Output
Print a single number — the maximum possible result of the game.
Examples
Input
10
Output
16
Input
8
Output
15
Note
Consider the first example (c1 = 10). The possible options for the game development are:
* Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11.
* Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) — 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13.
* Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 — the maximum possible result.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:
the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1).
Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?
-----Input-----
The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers a_{i}1, a_{i}2, ..., a_{im} (0 ≤ a_{ij} ≤ 1) — the i-th row of the matrix a.
-----Output-----
In the single line, print the answer to the problem — the minimum number of rows of matrix b.
-----Examples-----
Input
4 3
0 0 1
1 1 0
1 1 0
0 0 1
Output
2
Input
3 3
0 0 0
0 0 0
0 0 0
Output
3
Input
8 1
0
1
1
0
0
1
1
0
Output
2
-----Note-----
In the first test sample the answer is a 2 × 3 matrix b:
001
110
If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:
001
110
110
001
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself).
Input
The first line of the input contains two integers n and m (1 ≤ n ≤ 15, 0 ≤ m ≤ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10000), x, y are edge endpoints, and w is the edge length.
Output
Output minimal cycle length or -1 if it doesn't exists.
Examples
Input
3 3
1 2 1
2 3 1
3 1 1
Output
3
Input
3 2
1 2 3
2 3 4
Output
14
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write function describeList which returns "empty" if the list is empty or "singleton" if it contains only one element or "longer"" if more.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.
After practice competition, participant number i got a score of a_{i}. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.
-----Input-----
The single line contains six integers a_1, ..., a_6 (0 ≤ a_{i} ≤ 1000) — scores of the participants
-----Output-----
Print "YES" (quotes for clarity), if it is possible to build teams with equal score, and "NO" otherwise.
You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").
-----Examples-----
Input
1 3 2 1 2 1
Output
YES
Input
1 1 1 1 1 99
Output
NO
-----Note-----
In the first sample, first team can be composed of 1st, 2nd and 6th participant, second — of 3rd, 4th and 5th: team scores are 1 + 3 + 1 = 2 + 1 + 2 = 5.
In the second sample, score of participant number 6 is too high: his team score will be definitely greater.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.
The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point $x = 0$ is where these parts meet.
The right part of the corridor is filled with $n$ monsters — for each monster, its initial coordinate $x_i$ is given (and since all monsters are in the right part, every $x_i$ is positive).
The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to $0$), it gets instantly killed by a trap.
The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point $c$. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be $y$, then:
if $c = y$, then the monster is killed; if $y < c$, then the monster is pushed $r$ units to the left, so its current coordinate becomes $y - r$; if $y > c$, then the monster is pushed $r$ units to the right, so its current coordinate becomes $y + r$.
Ivan is going to kill the monsters as follows: choose some integer point $d$ and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on.
What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally.
You have to answer $q$ independent queries.
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries.
The first line of each query contains two integers $n$ and $r$ ($1 \le n, r \le 10^5$) — the number of enemies and the distance that the enemies are thrown away from the epicenter of the explosion.
The second line of each query contains $n$ integers $x_i$ ($1 \le x_i \le 10^5$) — the initial positions of the monsters.
It is guaranteed that sum of all $n$ over all queries does not exceed $10^5$.
-----Output-----
For each query print one integer — the minimum number of shots from the Phoenix Rod required to kill all monsters.
-----Example-----
Input
2
3 2
1 3 5
4 1
5 2 3 5
Output
2
2
-----Note-----
In the first test case, Ivan acts as follows: choose the point $3$, the first monster dies from a crusher trap at the point $-1$, the second monster dies from the explosion, the third monster is pushed to the point $7$; choose the point $7$, the third monster dies from the explosion.
In the second test case, Ivan acts as follows: choose the point $5$, the first and fourth monsters die from the explosion, the second monster is pushed to the point $1$, the third monster is pushed to the point $2$; choose the point $2$, the first monster dies from a crusher trap at the point $0$, the second monster dies from the explosion.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
The function `fold_cube(number_list)` should return a boolean based on a net (given as a number list), if the net can fold into a cube.
Your code must be effecient and complete the tests within 500ms.
## Input
Imagine a net such as the one below.
```
@
@ @ @ @
@
```
Then, put it on the table with each `@` being one cell.
```
--------------------------
| 1 | 2 | 3 | 4 | 5 |
--------------------------
| 6 | 7 | 8 | 9 | 10 |
--------------------------
| 11 | 12 | 13 | 14 | 15 |
--------------------------
| 16 | 17 | 18 | 19 | 20 |
--------------------------
| 21 | 22 | 23 | 24 | 25 |
--------------------------
```
The number list for a net will be the numbers the net falls on when placed on the table. Note that the numbers in the list won't always be in order. The position of the net can be anywhere on the table, it can also be rotated.
For the example above, a possible number list will be `[1, 7, 8, 6, 9, 13]`.
## Output
`fold_cube` should return `True` if the net can be folded into a cube. `False` if not.
---
# Examples
### Example 1:
`number_list` = `[24, 20, 14, 19, 18, 9]`
Shape and rotation of net:
```
@
@
@ @ @
@
```
Displayed on the table:
```
--------------------------
| 1 | 2 | 3 | 4 | 5 |
--------------------------
| 6 | 7 | 8 | @ | 10 |
--------------------------
| 11 | 12 | 13 | @ | 15 |
--------------------------
| 16 | 17 | @ | @ | @ |
--------------------------
| 21 | 22 | 23 | @ | 25 |
--------------------------
```
So, `fold_cube([24, 20, 14, 19, 18, 9])` should return `True`.
### Example 2:
`number_list` = `[1, 7, 6, 17, 12, 16]`
Shape and rotation of net:
```
@
@ @
@
@ @
```
Displayed on the table:
```
--------------------------
| @ | 2 | 3 | 4 | 5 |
--------------------------
| @ | @ | 8 | 9 | 10 |
--------------------------
| 11 | @ | 13 | 14 | 15 |
--------------------------
| @ | @ | 18 | 19 | 20 |
--------------------------
| 21 | 22 | 23 | 24 | 25 |
--------------------------
```
`fold_cube([1, 7, 6, 17, 12, 16])` should return `False`.
#### *Translations appreciated!!*
---
### If you liked this kata.... check out these!
- [Folding a 4D Cube (Tesseract)](https://www.codewars.com/kata/5f3b561bc4a71f000f191ef7)
- [Wraping a net around a cube](https://www.codewars.com/kata/5f4af9c169f1cd0001ae764d)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is an integer sequence A of length N whose values are unknown.
Given is an integer sequence B of length N-1 which is known to satisfy the following:
B_i \geq \max(A_i, A_{i+1})
Find the maximum possible sum of the elements of A.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 100
- 0 \leq B_i \leq 10^5
-----Input-----
Input is given from Standard Input in the following format:
N
B_1 B_2 ... B_{N-1}
-----Output-----
Print the maximum possible sum of the elements of A.
-----Sample Input-----
3
2 5
-----Sample Output-----
9
A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation.
Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s.
Input
The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators.
The given number a doesn't contain leading zeroes.
Output
Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes.
Examples
Input
1024
010
Output
1124
Input
987
1234567
Output
987
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
At the big break Nastya came to the school dining room. There are $n$ pupils in the school, numbered from $1$ to $n$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.
Formally, there are some pairs $u$, $v$ such that if the pupil with number $u$ stands directly in front of the pupil with number $v$, Nastya can ask them and they will change places.
Nastya asks you to find the maximal number of places in queue she can move forward.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \leq n \leq 3 \cdot 10^{5}$, $0 \leq m \leq 5 \cdot 10^{5}$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second.
The second line contains $n$ integers $p_1$, $p_2$, ..., $p_n$ — the initial arrangement of pupils in the queue, from the queue start to its end ($1 \leq p_i \leq n$, $p$ is a permutation of integers from $1$ to $n$). In other words, $p_i$ is the number of the pupil who stands on the $i$-th position in the queue.
The $i$-th of the following $m$ lines contains two integers $u_i$, $v_i$ ($1 \leq u_i, v_i \leq n, u_i \neq v_i$), denoting that the pupil with number $u_i$ agrees to change places with the pupil with number $v_i$ if $u_i$ is directly in front of $v_i$. It is guaranteed that if $i \neq j$, than $v_i \neq v_j$ or $u_i \neq u_j$. Note that it is possible that in some pairs both pupils agree to change places with each other.
Nastya is the last person in the queue, i.e. the pupil with number $p_n$.
-----Output-----
Print a single integer — the number of places in queue she can move forward.
-----Examples-----
Input
2 1
1 2
1 2
Output
1
Input
3 3
3 1 2
1 2
3 1
3 2
Output
2
Input
5 2
3 1 5 4 2
5 2
5 4
Output
1
-----Note-----
In the first example Nastya can just change places with the first pupil in the queue.
Optimal sequence of changes in the second example is change places for pupils with numbers $1$ and $3$. change places for pupils with numbers $3$ and $2$. change places for pupils with numbers $1$ and $2$.
The queue looks like $[3, 1, 2]$, then $[1, 3, 2]$, then $[1, 2, 3]$, and finally $[2, 1, 3]$ after these operations.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi participated in a contest on AtCoder.
The contest had N problems.
Takahashi made M submissions during the contest.
The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA).
The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.
The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.
Find the numbers of Takahashi's correct answers and penalties.
-----Constraints-----
- N, M, and p_i are integers.
- 1 \leq N \leq 10^5
- 0 \leq M \leq 10^5
- 1 \leq p_i \leq N
- S_i is AC or WA.
-----Input-----
Input is given from Standard Input in the following format:
N M
p_1 S_1
:
p_M S_M
-----Output-----
Print the number of Takahashi's correct answers and the number of Takahashi's penalties.
-----Sample Input-----
2 5
1 WA
1 AC
2 WA
2 AC
2 WA
-----Sample Output-----
2 2
In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.
In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.
Thus, he has two correct answers and two penalties.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Some integral numbers are odd. All are more odd, or less odd, than others.
Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`.
Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :]
Even numbers are always less odd than odd numbers, but they also can be more, or less, odd than other even numbers, by the same mechanism.
# Task
Given a _non-empty_ finite list of _unique_ integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_.
Given the constraints, there will always be exactly one such number.
# Examples
```python
oddest([1,2]) => 1
oddest([1,3]) => 3
oddest([1,5]) => 5
```
# Hint
Do you _really_ want one? Point or tap here.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A series or sequence of numbers is usually the product of a function and can either be infinite or finite.
In this kata we will only consider finite series and you are required to return a code according to the type of sequence:
|Code|Type|Example|
|-|-|-|
|`0`|`unordered`|`[3,5,8,1,14,3]`|
|`1`|`strictly increasing`|`[3,5,8,9,14,23]`|
|`2`|`not decreasing`|`[3,5,8,8,14,14]`|
|`3`|`strictly decreasing`|`[14,9,8,5,3,1]`|
|`4`|`not increasing`|`[14,14,8,8,5,3]`|
|`5`|`constant`|`[8,8,8,8,8,8]`|
You can expect all the inputs to be non-empty and completely numerical arrays/lists - no need to validate the data; do not go for sloppy code, as rather large inputs might be tested.
Try to achieve a good solution that runs in linear time; also, do it functionally, meaning you need to build a *pure* function or, in even poorer words, do NOT modify the initial input!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(101) = 1 + 0 + 1 = 2.
Given an integer N, determine if S(N) divides N.
-----Constraints-----
- 1 \leq N \leq 10^9
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
If S(N) divides N, print Yes; if it does not, print No.
-----Sample Input-----
12
-----Sample Output-----
Yes
In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.
Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.
The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.
-----Input-----
The first line contains a single integer — n (1 ≤ n ≤ 5·10^5). Each of the next n lines contains an integer s_{i} — the size of the i-th kangaroo (1 ≤ s_{i} ≤ 10^5).
-----Output-----
Output a single integer — the optimal number of visible kangaroos.
-----Examples-----
Input
8
2
5
7
6
9
8
4
2
Output
5
Input
8
9
1
6
2
6
5
8
3
Output
5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.
She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and also she gave a half of an apple to some of them as a gift (if the number of apples at the moment of purchase was odd), until she sold all the apples she had.
So each buyer took some integral positive number of apples, but maybe he didn't pay for a half of an apple (if the number of apples at the moment of the purchase was odd).
For each buyer grandma remembers if she gave a half of an apple as a gift or not. The cost of an apple is p (the number p is even).
Print the total money grandma should have at the end of the day to check if some buyers cheated her.
-----Input-----
The first line contains two integers n and p (1 ≤ n ≤ 40, 2 ≤ p ≤ 1000) — the number of the buyers and the cost of one apple. It is guaranteed that the number p is even.
The next n lines contains the description of buyers. Each buyer is described with the string half if he simply bought half of the apples and with the string halfplus if grandma also gave him a half of an apple as a gift.
It is guaranteed that grandma has at least one apple at the start of the day and she has no apples at the end of the day.
-----Output-----
Print the only integer a — the total money grandma should have at the end of the day.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
-----Examples-----
Input
2 10
half
halfplus
Output
15
Input
3 10
halfplus
halfplus
halfplus
Output
55
-----Note-----
In the first sample at the start of the day the grandma had two apples. First she sold one apple and then she sold a half of the second apple and gave a half of the second apple as a present to the second buyer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's say you are standing on the $XY$-plane at point $(0, 0)$ and you want to reach point $(n, n)$.
You can move only in two directions:
to the right, i. e. horizontally and in the direction that increase your $x$ coordinate,
or up, i. e. vertically and in the direction that increase your $y$ coordinate.
In other words, your path will have the following structure:
initially, you choose to go to the right or up;
then you go some positive integer distance in the chosen direction (distances can be chosen independently);
after that you change your direction (from right to up, or from up to right) and repeat the process.
You don't like to change your direction too much, so you will make no more than $n - 1$ direction changes.
As a result, your path will be a polygonal chain from $(0, 0)$ to $(n, n)$, consisting of at most $n$ line segments where each segment has positive integer length and vertical and horizontal segments alternate.
Not all paths are equal. You have $n$ integers $c_1, c_2, \dots, c_n$ where $c_i$ is the cost of the $i$-th segment.
Using these costs we can define the cost of the path as the sum of lengths of the segments of this path multiplied by their cost, i. e. if the path consists of $k$ segments ($k \le n$), then the cost of the path is equal to $\sum\limits_{i=1}^{k}{c_i \cdot length_i}$ (segments are numbered from $1$ to $k$ in the order they are in the path).
Find the path of the minimum cost and print its cost.
-----Input-----
The first line contains the single integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains the single integer $n$ ($2 \le n \le 10^5$).
The second line of each test case contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le 10^9$) — the costs of each segment.
It's guaranteed that the total sum of $n$ doesn't exceed $10^5$.
-----Output-----
For each test case, print the minimum possible cost of the path from $(0, 0)$ to $(n, n)$ consisting of at most $n$ alternating segments.
-----Examples-----
Input
3
2
13 88
3
2 3 1
5
4 3 2 1 4
Output
202
13
19
-----Note-----
In the first test case, to reach $(2, 2)$ you need to make at least one turn, so your path will consist of exactly $2$ segments: one horizontal of length $2$ and one vertical of length $2$. The cost of the path will be equal to $2 \cdot c_1 + 2 \cdot c_2 = 26 + 176 = 202$.
In the second test case, one of the optimal paths consists of $3$ segments: the first segment of length $1$, the second segment of length $3$ and the third segment of length $2$.
The cost of the path is $1 \cdot 2 + 3 \cdot 3 + 2 \cdot 1 = 13$.
In the third test case, one of the optimal paths consists of $4$ segments: the first segment of length $1$, the second one — $1$, the third one — $4$, the fourth one — $4$. The cost of the path is $1 \cdot 4 + 1 \cdot 3 + 4 \cdot 2 + 4 \cdot 1 = 19$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N balls in a row. Initially, the i-th ball from the left has the integer A_i written on it.
When Snuke cast a spell, the following happens:
* Let the current number of balls be k. All the balls with k written on them disappear at the same time.
Snuke's objective is to vanish all the balls by casting the spell some number of times. This may not be possible as it is. If that is the case, he would like to modify the integers on the minimum number of balls to make his objective achievable.
By the way, the integers on these balls sometimes change by themselves. There will be M such changes. In the j-th change, the integer on the X_j-th ball from the left will change into Y_j.
After each change, find the minimum number of modifications of integers on the balls Snuke needs to make if he wishes to achieve his objective before the next change occurs. We will assume that he is quick enough in modifying integers. Here, note that he does not actually perform those necessary modifications and leaves them as they are.
Constraints
* 1 \leq N \leq 200000
* 1 \leq M \leq 200000
* 1 \leq A_i \leq N
* 1 \leq X_j \leq N
* 1 \leq Y_j \leq N
Input
Input is given from Standard Input in the following format:
N M
A_1 A_2 ... A_N
X_1 Y_1
X_2 Y_2
:
X_M Y_M
Output
Print M lines. The j-th line should contain the minimum necessary number of modifications of integers on the balls to make Snuke's objective achievable.
Examples
Input
5 3
1 1 3 4 5
1 2
2 5
5 4
Output
0
1
1
Input
4 4
4 4 4 4
4 1
3 1
1 1
2 1
Output
0
1
2
3
Input
10 10
8 7 2 9 10 6 6 5 5 4
8 1
6 3
6 2
7 10
9 7
9 9
2 4
8 1
1 8
7 7
Output
1
0
1
2
2
3
3
3
3
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1.
Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.
Input
The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).
Output
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
Examples
Input
abc
Output
YES
abc
Input
abcd
Output
NO
Input
xxxyxxx
Output
YES
xxxxxxy
Note
In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".
In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).
In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
Input
The first and the single line contains three space-separated integers — the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement.
Output
Print a single number — the sum of all edges of the parallelepiped.
Examples
Input
1 1 1
Output
12
Input
4 6 6
Output
28
Note
In the first sample the parallelepiped has sizes 1 × 1 × 1, in the second one — 2 × 2 × 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, …, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i ≠ a_j or b_i ≠ b_j.
Input
The first line contains two integers n and k (1 ≤ n,k ≤ 10^5) — the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, …, x_k (1 ≤ x_i ≤ n) — Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| ≤ 1 except for (42, 42) are valid scenarios.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met: There are y elements in F, and all of them are integer numbers; $\prod_{i = 1}^{y} F_{i} = x$.
You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1 ≤ i ≤ y) such that A_{i} ≠ B_{i}. Since the answer can be very large, print it modulo 10^9 + 7.
-----Input-----
The first line contains one integer q (1 ≤ q ≤ 10^5) — the number of testcases to solve.
Then q lines follow, each containing two integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ 10^6). Each of these lines represents a testcase.
-----Output-----
Print q integers. i-th integer has to be equal to the number of y_{i}-factorizations of x_{i} modulo 10^9 + 7.
-----Example-----
Input
2
6 3
4 2
Output
36
6
-----Note-----
In the second testcase of the example there are six y-factorizations: { - 4, - 1}; { - 2, - 2}; { - 1, - 4}; {1, 4}; {2, 2}; {4, 1}.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
She loves e-mail so much! She sends e-mails by her cellular phone to her friends when she has breakfast, she talks with other friends, and even when she works in the library! Her cellular phone has somewhat simple layout (Figure 1). Pushing button 1 once displays a character (’), pushing
<image>
it twice in series displays a character (,), and so on, and pushing it 6 times displays (’) again. Button 2 corresponds to charaters (abcABC), and, for example, pushing it four times displays (A). Button 3-9 have is similar to button 1. Button 0 is a special button: pushing it once make her possible to input characters in the same button in series. For example, she has to push “20202” to display “aaa” and “660666” to display “no”. In addition, pushing button 0 n times in series (n > 1) displays n − 1 spaces. She never pushes button 0 at the very beginning of her input. Here are some examples of her input and output:
666660666 --> No
44444416003334446633111 --> I’m fine.
20202202000333003330333 --> aaba f ff
One day, the chief librarian of the library got very angry with her and hacked her cellular phone when she went to the second floor of the library to return books in shelves. Now her cellular phone can only display button numbers she pushes. Your task is to write a program to convert the sequence of button numbers into correct characters and help her continue her e-mails!
Input
Input consists of several lines. Each line contains the sequence of button numbers without any spaces. You may assume one line contains no more than 10000 numbers. Input terminates with EOF.
Output
For each line of input, output the corresponding sequence of characters in one line.
Example
Input
666660666
44444416003334446633111
20202202000333003330333
Output
No
I'm fine.
aaba f ff
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer.
When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes.
Your task is correct the errors in the digitised text. You only have to handle the following mistakes:
* `S` is misinterpreted as `5`
* `O` is misinterpreted as `0`
* `I` is misinterpreted as `1`
The test cases contain numbers only by mistake.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move.
There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0).
You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
Input
The first line contains four integers: xp, yp, xv, yv (0 ≤ xp, yp, xv, yv ≤ 105) — Polycarp's and Vasiliy's starting coordinates.
It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0).
Output
Output the name of the winner: "Polycarp" or "Vasiliy".
Examples
Input
2 1 2 2
Output
Polycarp
Input
4 7 7 4
Output
Vasiliy
Note
In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Your job is to write a function which increments a string, to create a new string.
- If the string already ends with a number, the number should be incremented by 1.
- If the string does not end with a number. the number 1 should be appended to the new string.
Examples:
`foo -> foo1`
`foobar23 -> foobar24`
`foo0042 -> foo0043`
`foo9 -> foo10`
`foo099 -> foo100`
*Attention: If the number has leading zeros the amount of digits should be considered.*
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob begin their day with a quick game. They first choose a starting number X_0 ≥ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime p < X_{i} - 1 and then finds the minimum X_{i} ≥ X_{i} - 1 such that p divides X_{i}. Note that if the selected prime p already divides X_{i} - 1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given X_2, help her determine what is the smallest possible starting number X_0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
-----Input-----
The input contains a single integer X_2 (4 ≤ X_2 ≤ 10^6). It is guaranteed that the integer X_2 is composite, that is, is not prime.
-----Output-----
Output a single integer — the minimum possible X_0.
-----Examples-----
Input
14
Output
6
Input
20
Output
15
Input
8192
Output
8191
-----Note-----
In the first test, the smallest possible starting number is X_0 = 6. One possible course of the game is as follows: Alice picks prime 5 and announces X_1 = 10 Bob picks prime 7 and announces X_2 = 14.
In the second case, let X_0 = 15. Alice picks prime 2 and announces X_1 = 16 Bob picks prime 5 and announces X_2 = 20.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.
Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≤ i ≤ k) is evenly divisible by d. At that, we assume that all ai's are greater than zero.
Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives a1 sweets, the 2-nd one gives a2 sweets, ..., the n-th one gives an sweets. At the same time, for any i and j (1 ≤ i, j ≤ n) they want the GCD(ai, aj) not to be equal to 1. However, they also want the following condition to be satisfied: GCD(a1, a2, ..., an) = 1. One more: all the ai should be distinct.
Help the friends to choose the suitable numbers a1, ..., an.
Input
The first line contains an integer n (2 ≤ n ≤ 50).
Output
If there is no answer, print "-1" without quotes. Otherwise print a set of n distinct positive numbers a1, a2, ..., an. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them.
Do not forget, please, that all of the following conditions must be true:
* For every i and j (1 ≤ i, j ≤ n): GCD(ai, aj) ≠ 1
* GCD(a1, a2, ..., an) = 1
* For every i and j (1 ≤ i, j ≤ n, i ≠ j): ai ≠ aj
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
Output
99
55
11115
Input
4
Output
385
360
792
8360
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 ≤ a1, a2, a3, a4 ≤ 106).
Output
On the single line print without leading zeroes the answer to the problem — the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until...
Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1 ≤ i ≤ 12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters.
Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters.
Input
The first line contains exactly one integer k (0 ≤ k ≤ 100). The next line contains twelve space-separated integers: the i-th (1 ≤ i ≤ 12) number in the line represents ai (0 ≤ ai ≤ 100).
Output
Print the only integer — the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1.
Examples
Input
5
1 1 1 1 2 2 3 2 2 1 1 1
Output
2
Input
0
0 0 0 0 0 0 0 1 1 2 3 0
Output
0
Input
11
1 1 4 1 1 5 1 1 4 1 1 1
Output
3
Note
Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters.
In the second sample Petya's parents will believe him even if the flower doesn't grow at all (k = 0). So, it is possible for Petya not to water the flower at all.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 ≤ n ≤ 105) — the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 ≤ xi, yi ≤ n, 0 ≤ wi ≤ 2 × 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A cricket team consists of 11 players and some are good at batting, others are good at bowling and some of them are good at both batting and bowling. The batting coach wants to select exactly K players having maximum possible sum of scores. Given the batting score of each of the 11 players, find the number of ways in which we can select exactly K players such that the sum of their scores is the maximum possible. Two ways are different if there is a player who is selected in one of them is not in the other. See explanation of sample cases for more clarity.
------ Input ------
First line contains T, number of test cases ( 1 ≤ T ≤ 100 ). T cases follow, each having 2 lines. First line of each case contains scores of 11 players ( 1 ≤ score ≤ 100 ) and the second line contains K (1 ≤ K ≤ 11)
------ Output ------
For each test case, output the answer in a new line.
----- Sample Input 1 ------
2
1 2 3 4 5 6 7 8 9 10 11
3
2 5 1 2 4 1 6 5 2 2 1
6
----- Sample Output 1 ------
1
6
----- explanation 1 ------
Case 1 : Maximum possible sum of scores = 11 + 10 + 9 = 30 and can be achieved only by selecting the last 3 players. Only one possible way.
Case 2 : Maximum possible sum of scores = 6 + 5 + 5 + 4 + 2 + 2 = 24 and considering the players as p1 p2 p3 ... p11 in that order, the ones with maximum possible sum of scores is as follows
{p1, p2, p4, p5, p7, p8 }
{p10, p2, p4, p5, p7, p8 }
{p1, p2, p10, p5, p7, p8 }
{p9, p2, p4, p5, p7, p8 }
{p1, p2, p9, p5, p7, p8 }
{p10, p2, p9, p5, p7, p8 }
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob are playing a game on a line with $n$ cells. There are $n$ cells labeled from $1$ through $n$. For each $i$ from $1$ to $n-1$, cells $i$ and $i+1$ are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers $x_1, x_2, \ldots, x_k$ in order. In the $i$-th question, Bob asks Alice if her token is currently on cell $x_i$. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given $n$ and Bob's questions $x_1, \ldots, x_k$. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let $(a,b)$ denote a scenario where Alice starts at cell $a$ and ends at cell $b$. Two scenarios $(a_i, b_i)$ and $(a_j, b_j)$ are different if $a_i \neq a_j$ or $b_i \neq b_j$.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \leq n,k \leq 10^5$) — the number of cells and the number of questions Bob asked.
The second line contains $k$ integers $x_1, x_2, \ldots, x_k$ ($1 \leq x_i \leq n$) — Bob's questions.
-----Output-----
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
-----Examples-----
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
-----Note-----
The notation $(i,j)$ denotes a scenario where Alice starts at cell $i$ and ends at cell $j$.
In the first example, the valid scenarios are $(1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5)$. For example, $(3,4)$ is valid since Alice can start at cell $3$, stay there for the first three questions, then move to cell $4$ after the last question.
$(4,5)$ is valid since Alice can start at cell $4$, stay there for the first question, the move to cell $5$ for the next two questions. Note that $(4,5)$ is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all $(i,j)$ where $|i-j| \leq 1$ except for $(42, 42)$ are valid scenarios.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are a prime number p and a sequence of p integers a_0, \ldots, a_{p-1} consisting of zeros and ones.
Find a polynomial of degree at most p-1, f(x) = b_{p-1} x^{p-1} + b_{p-2} x^{p-2} + \ldots + b_0, satisfying the following conditions:
- For each i (0 \leq i \leq p-1), b_i is an integer such that 0 \leq b_i \leq p-1.
- For each i (0 \leq i \leq p-1), f(i) \equiv a_i \pmod p.
-----Constraints-----
- 2 \leq p \leq 2999
- p is a prime number.
- 0 \leq a_i \leq 1
-----Input-----
Input is given from Standard Input in the following format:
p
a_0 a_1 \ldots a_{p-1}
-----Output-----
Print b_0, b_1, \ldots, b_{p-1} of a polynomial f(x) satisfying the conditions, in this order, with spaces in between.
It can be proved that a solution always exists. If multiple solutions exist, any of them will be accepted.
-----Sample Input-----
2
1 0
-----Sample Output-----
1 1
f(x) = x + 1 satisfies the conditions, as follows:
- f(0) = 0 + 1 = 1 \equiv 1 \pmod 2
- f(1) = 1 + 1 = 2 \equiv 0 \pmod 2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Вася купил стол, у которого n ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2n частей возможно составить n ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2n частей в произвольном порядке.
Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2n части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть.
-----Входные данные-----
В первой строке задано число n (1 ≤ n ≤ 1000) — количество ножек у стола, купленного Васей.
Во второй строке следует последовательность из 2n целых положительных чисел a_1, a_2, ..., a_2n (1 ≤ a_{i} ≤ 100 000) — длины частей ножек стола в произвольном порядке.
-----Выходные данные-----
Выведите n строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать n ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них.
-----Примеры-----
Входные данные
3
1 3 2 4 5 3
Выходные данные
1 5
2 4
3 3
Входные данные
3
1 1 1 2 2 2
Выходные данные
1 2
2 1
1 2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Soroush and Keshi each have a labeled and rooted tree on n vertices. Both of their trees are rooted from vertex 1.
Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph on n vertices.
They add an edge between vertices u and v in the memorial graph if both of the following conditions hold:
* One of u or v is the ancestor of the other in Soroush's tree.
* Neither of u or v is the ancestor of the other in Keshi's tree.
Here vertex u is considered ancestor of vertex v, if u lies on the path from 1 (the root) to the v.
Popping out of nowhere, Mashtali tried to find the maximum clique in the memorial graph for no reason. He failed because the graph was too big.
Help Mashtali by finding the size of the maximum clique in the memorial graph.
As a reminder, clique is a subset of vertices of the graph, each two of which are connected by an edge.
Input
The first line contains an integer t (1≤ t≤ 3 ⋅ 10^5) — the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer n (2≤ n≤ 3 ⋅ 10^5).
The second line of each test case contains n-1 integers a_2, …, a_n (1 ≤ a_i < i), a_i being the parent of the vertex i in Soroush's tree.
The third line of each test case contains n-1 integers b_2, …, b_n (1 ≤ b_i < i), b_i being the parent of the vertex i in Keshi's tree.
It is guaranteed that the given graphs are trees.
It is guaranteed that the sum of n over all test cases doesn't exceed 3 ⋅ 10^5.
Output
For each test case print a single integer — the size of the maximum clique in the memorial graph.
Example
Input
4
4
1 2 3
1 2 3
5
1 2 3 4
1 1 1 1
6
1 1 1 1 2
1 2 1 2 2
7
1 1 3 4 4 5
1 2 1 4 2 5
Output
1
4
1
3
Note
In the first and third test cases, you can pick any vertex.
In the second test case, one of the maximum cliques is \{2, 3, 4, 5\}.
In the fourth test case, one of the maximum cliques is \{3, 4, 6\}.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $1$ to $n$. For every edge $e$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $e$ (and only this edge) is erased from the tree.
Monocarp has given you a list of $n - 1$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 1\,000$) — the number of vertices in the tree.
Each of the next $n-1$ lines contains two integers $a_i$ and $b_i$ each ($1 \le a_i < b_i \le n$) — the maximal indices of vertices in the components formed if the $i$-th edge is removed.
-----Output-----
If there is no such tree that can produce the given list of pairs, print "NO" (without quotes).
Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next $n - 1$ lines. Each of the last $n - 1$ lines should contain two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$) — vertices connected by an edge.
Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.
-----Examples-----
Input
4
3 4
1 4
3 4
Output
YES
1 3
3 2
2 4
Input
3
1 3
1 3
Output
NO
Input
3
1 2
2 3
Output
NO
-----Note-----
Possible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs. [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi's house has only one socket.
Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.
One power strip with A sockets can extend one empty socket into A empty sockets.
Find the minimum number of power strips required.
-----Constraints-----
- All values in input are integers.
- 2 \leq A \leq 20
- 1 \leq B \leq 20
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
Print the minimum number of power strips required.
-----Sample Input-----
4 10
-----Sample Output-----
3
3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takayuki and Kazuyuki are good twins, but their behavior is exactly the opposite. For example, if Takayuki goes west, Kazuyuki goes east, and if Kazuyuki goes north, Takayuki goes south. Currently the two are in a department store and are in different locations. How can two people who move in the opposite direction meet as soon as possible?
A department store is represented by a grid consisting of W horizontal x H vertical squares, and two people can move one square from north, south, east, and west per unit time. However, you cannot move outside the grid or to a square with obstacles.
As shown, the position of the grid cells is represented by the coordinates (x, y).
<image>
Create a program that inputs the grid information and the initial positions of the two people and outputs the shortest time until the two people meet. If you can't meet, or if it takes more than 100 hours to meet, print NA. The grid information is given by the numbers in rows H and columns W, and the location information of the two people is given by the coordinates.
If either Takayuki-kun or Kazuyuki-kun is out of the range of the obstacle or grid after moving, you cannot move, so the one who is out of the range of the obstacle or grid is the original place. But if you don't, you can move without returning to the original place.
When two people meet, it means that they stay in the same square after moving. Even if two people pass each other, they do not meet.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
W H
tx ty
kx ky
d11 d21 ... dW1
d12 d22 ... dW2
::
d1H d2H ... dWH
The first line gives the department store sizes W, H (1 ≤ W, H ≤ 50). The second line gives Takayuki's initial position tx, ty, and the third line gives Kazuyuki's initial position kx, ky.
The H line that follows gives the department store information. di, j represents the type of square (i, j), 0 for movable squares and 1 for obstacles.
The number of datasets does not exceed 100.
Output
Outputs the shortest time on one line for each input dataset.
Example
Input
6 6
2 4
6 2
0 0 0 0 1 0
0 1 0 0 0 0
0 1 0 0 0 0
0 0 0 1 0 0
0 0 0 0 0 1
0 0 0 0 0 0
3 3
1 1
3 3
0 0 0
0 1 0
0 0 0
0 0
Output
3
NA
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.
A sequence of l integers b1, b2, ..., bl (1 ≤ b1 ≤ b2 ≤ ... ≤ bl ≤ n) is called good if each number divides (without a remainder) by the next number in the sequence. More formally <image> for all i (1 ≤ i ≤ l - 1).
Given n and k find the number of good sequences of length k. As the answer can be rather large print it modulo 1000000007 (109 + 7).
Input
The first line of input contains two space-separated integers n, k (1 ≤ n, k ≤ 2000).
Output
Output a single integer — the number of good sequences of length k modulo 1000000007 (109 + 7).
Examples
Input
3 2
Output
5
Input
6 4
Output
39
Input
2 1
Output
2
Note
In the first sample the good sequences are: [1, 1], [2, 2], [3, 3], [1, 2], [1, 3].
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
And again a misfortune fell on Poor Student. He is being late for an exam.
Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.
Poor Student knows the following:
* during one run the minibus makes n stops, the i-th stop is in point (xi, 0)
* coordinates of all the stops are different
* the minibus drives at a constant speed, equal to vb
* it can be assumed the passengers get on and off the minibus at a bus stop momentarily
* Student can get off the minibus only at a bus stop
* Student will have to get off the minibus at a terminal stop, if he does not get off earlier
* the University, where the exam will be held, is in point (xu, yu)
* Student can run from a bus stop to the University at a constant speed vs as long as needed
* a distance between two points can be calculated according to the following formula: <image>
* Student is already on the minibus, so, he cannot get off at the first bus stop
Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.
Input
The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.
Output
In the only line output the answer to the problem — index of the optimum bus stop.
Examples
Input
4 5 2
0 2 4 6
4 1
Output
3
Input
2 1 1
0 100000
100000 100000
Output
2
Note
As you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≤ n ≤ 2 ⋅ 10^5, -10^9 ≤ b_i ≤ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray?
The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order.
Input
Each test contains multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows.
The first line of each test case contains an integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array b.
The second line contains n integers b_1, b_2, …, b_n (-10^9 ≤ b_i ≤ 10^9) — the elements of b.
It is guaranteed the sum of n across all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).
Examples
Input
5
4
6 2 1 3
1
4
5
4 -8 5 6 -7
2
3 3
4
2 1 2 3
Output
NO
YES
NO
YES
YES
Input
5
8
-8 2 -6 -5 -4 3 3 2
7
1 1 3 1 0 -2 -1
7
6 12 8 6 2 6 10
6
5 1 2 3 6 7
5
1 3 4 3 0
Output
NO
YES
NO
NO
NO
Note
In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4.
In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3.
In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as
* the median of 2 is 2
* the median of 0, 1, 2 is 1
* the median of 0, 1, 2, 3, 4 is 2
* and the median of 0, 1, 2, 3, 3, 4, 4 is 3.
In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as
* the median of 1 is 1
* the median of 0, 1, 4 is 1
* the median of 0, 1, 3, 4, 5 is 3
* the median of -2, -2, 0, 1, 3, 4, 5 is 1
* the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0
* the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2
* and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1
For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a sequence a_1, a_2, ..., a_{n} of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment a_{i} lies within segment a_{j}.
Segment [l_1, r_1] lies within segment [l_2, r_2] iff l_1 ≥ l_2 and r_1 ≤ r_2.
Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 3·10^5) — the number of segments.
Each of the next n lines contains two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^9) — the i-th segment.
-----Output-----
Print two distinct indices i and j such that segment a_{i} lies within segment a_{j}. If there are multiple answers, print any of them. If no answer exists, print -1 -1.
-----Examples-----
Input
5
1 10
2 9
3 9
2 3
2 9
Output
2 1
Input
3
1 5
2 6
6 20
Output
-1 -1
-----Note-----
In the first example the following pairs are considered correct: (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders; (3, 2), (4, 2), (3, 5), (4, 5) — touch one border; (5, 2), (2, 5) — match exactly.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Zeke loves to spend time with Penny and likes her. Penny is having an issue to solve a mathematics problem and is confused. She seeks Zeke's help as she feels he could help her with the problem. He finds this problem very simple. The problem is to count the number of unique triplets of different numbers (N1, N2, N3), where Ni could be any positive integer from 1 to Ni, inclusive (i = 1, 2, 3). Here the numbers can not be repeated in a triplet set.
This looks simple right?
But oops !!!! There is a catch here which was missed by Zeke that the numbers N1, N2, N3 could be well up to 10^18.
Zeke finds it difficult due to large numbers in stake and needs your help for them so that he can give a solution to Penny. You need to find an optimal solution of the number of unique triplets possible which the above conditions satisfied.
Since, the answer could be quite large. Hence you should output it modulo 10^9 + 7.
Input:
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each line of a test case contains three space-separated integers N1, N2, N3.
Output:
For each test case, output a single line containing the number of required triples modulo 10^9 + 7.
Constraints
1 ≤ T ≤ 10^3
1 ≤ Ni ≤ 10^18
Sample Input:
5
3 3 3
2 3 2
29 11 1994
1 2 3
1 1 50
Sample Output:
6
2
613536
1
0
Explanation
Case 1. We have the following triples composed of different numbers up to 3:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Case 2. Here the triplets are:
(1, 3, 2)
(2, 3, 1)
Case 3. 613536 triplets exist
Case 4. Here the only triplet is (1, 2, 3).
Case 5. The only choice for N1 and for is N2 is 1, so any such triple will have the same numbers which does not satisfy the conditions. Hence, no triplets are possible.
SAMPLE INPUT
5
3 3 3
2 3 2
29 11 1994
1 2 3
1 1 50
SAMPLE OUTPUT
6
2
613536
1
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.
Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.
Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.
Next line describe the second permutation in the same format.
Output
Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.
Examples
Input
3
3 2 1
1 2 3
Output
2
Input
5
1 2 3 4 5
1 5 2 3 4
Output
1
Input
5
1 5 2 3 4
1 2 3 4 5
Output
3
Note
In the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.
In the second sample, he removes number 5 and inserts it after 1.
In the third sample, the sequence of changes are like this:
* 1 5 2 3 4
* 1 4 5 2 3
* 1 3 4 5 2
* 1 2 3 4 5
So he needs three moves.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Taro and Hanako decided to play hit-and-blow. The hit-and-blow rules are as follows.
* Separated into questioners and respondents.
* The questioner decides a 4-digit number (correct answer) that does not include duplicate numbers.
* Respondents guess the 4-digit number (answer).
* For the answer, the questioner gives a hint by the number of hits and blows.
* Comparing the answer and the correct answer, the fact that both the number and the digit position are the same is called a hit, and the fact that only the number is the same but the digit position is different is called a blow. For example, if the correct answer is 1234 and the answer is 1354, the questioner gives the hint "2 hits, 1 blow" and repeats until the correct answer.
* The questioner and the respondent take turns playing the game, and the one who guesses the correct answer with fewer answers wins.
Taro and Hanako seem to find it a little annoying to judge the number of hits and the number of blows each time. For those two, let's create a program that instantly shows the number of hits and the number of blows.
Create a program that inputs the correct answer r and the answer a and outputs the number of hits and the number of blows. r and a are a sequence of four numbers, 0 to 9, respectively.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. For each dataset, r and a are given on one line, separated by blanks.
The number of datasets does not exceed 12000.
Output
Outputs the number of hits and the number of blows on one line for each input dataset.
Example
Input
1234 5678
1234 1354
1234 1234
1230 1023
0123 1234
0 0
Output
0 0
2 1
4 0
1 3
0 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played.
The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.
-----Output-----
If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output.
If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output.
If Anton and Danik won the same number of games, print "Friendship" (without quotes).
-----Examples-----
Input
6
ADAAAA
Output
Anton
Input
7
DDDAADA
Output
Danik
Input
6
DADADA
Output
Friendship
-----Note-----
In the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".
In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".
In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not.
Ahcl wants to construct a beautiful string. He has a string $s$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him!
More formally, after replacing all characters '?', the condition $s_i \neq s_{i+1}$ should be satisfied for all $1 \leq i \leq |s| - 1$, where $|s|$ is the length of the string $s$.
-----Input-----
The first line contains positive integer $t$ ($1 \leq t \leq 1000$) — the number of test cases. Next $t$ lines contain the descriptions of test cases.
Each line contains a non-empty string $s$ consisting of only characters 'a', 'b', 'c' and '?'.
It is guaranteed that in each test case a string $s$ has at least one character '?'. The sum of lengths of strings $s$ in all test cases does not exceed $10^5$.
-----Output-----
For each test case given in the input print the answer in the following format:
If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them.
-----Example-----
Input
3
a???cb
a??bbc
a?b?c
Output
ababcb
-1
acbac
-----Note-----
In the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful.
In the second test case, it is impossible to create a beautiful string, because the $4$-th and $5$-th characters will be always equal.
In the third test case, the only answer is "acbac".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let us consider a grid of squares with 10^9 rows and N columns. Let (i, j) be the square at the i-th column (1 \leq i \leq N) from the left and j-th row (1 \leq j \leq 10^9) from the bottom.
Snuke has cut out some part of the grid so that, for each i = 1, 2, ..., N, the bottom-most h_i squares are remaining in the i-th column from the left. Now, he will paint the remaining squares in red and blue. Find the number of the ways to paint the squares so that the following condition is satisfied:
* Every remaining square is painted either red or blue.
* For all 1 \leq i \leq N-1 and 1 \leq j \leq min(h_i, h_{i+1})-1, there are exactly two squares painted red and two squares painted blue among the following four squares: (i, j), (i, j+1), (i+1, j) and (i+1, j+1).
Since the number of ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1 \leq N \leq 100
* 1 \leq h_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
h_1 h_2 ... h_N
Output
Print the number of the ways to paint the squares, modulo 10^9+7.
Examples
Input
9
2 3 5 4 1 2 4 2 1
Output
12800
Input
2
2 2
Output
6
Input
5
2 1 2 1 2
Output
256
Input
9
27 18 28 18 28 45 90 45 23
Output
844733013
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a digital clock with $n$ digits. Each digit shows an integer from $0$ to $9$, so the whole clock shows an integer from $0$ to $10^n-1$. The clock will show leading zeroes if the number is smaller than $10^{n-1}$.
You want the clock to show $0$ with as few operations as possible. In an operation, you can do one of the following:
decrease the number on the clock by $1$, or
swap two digits (you can choose which digits to swap, and they don't have to be adjacent).
Your task is to determine the minimum number of operations needed to make the clock show $0$.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$).
The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) — number of digits on the clock.
The second line of each test case contains a string of $n$ digits $s_1, s_2, \ldots, s_n$ ($0 \le s_1, s_2, \ldots, s_n \le 9$) — the number on the clock.
Note: If the number is smaller than $10^{n-1}$ the clock will show leading zeroes.
-----Output-----
For each test case, print one integer: the minimum number of operations needed to make the clock show $0$.
-----Examples-----
Input
7
3
007
4
1000
5
00000
3
103
4
2020
9
123456789
30
001678294039710047203946100020
Output
7
2
0
5
6
53
115
-----Note-----
In the first example, it's optimal to just decrease the number $7$ times.
In the second example, we can first swap the first and last position and then decrease the number by $1$.
In the third example, the clock already shows $0$, so we don't have to perform any operations.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Valera had two bags of potatoes, the first of these bags contains x (x ≥ 1) potatoes, and the second — y (y ≥ 1) potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.
Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.
-----Input-----
The first line of input contains three integers y, k, n (1 ≤ y, k, n ≤ 10^9; $\frac{n}{k}$ ≤ 10^5).
-----Output-----
Print the list of whitespace-separated integers — all possible values of x in ascending order. You should print each possible value of x exactly once.
If there are no such values of x print a single integer -1.
-----Examples-----
Input
10 1 10
Output
-1
Input
10 6 40
Output
2 8 14 20 26
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a string X, which has an even number of characters. Half the characters are `S`, and the other half are `T`.
Takahashi, who hates the string `ST`, will perform the following operation 10^{10000} times:
* Among the occurrences of `ST` in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.
Find the eventual length of X.
Constraints
* 2 ≦ |X| ≦ 200,000
* The length of X is even.
* Half the characters in X are `S`, and the other half are `T`.
Input
The input is given from Standard Input in the following format:
X
Output
Print the eventual length of X.
Examples
Input
TSTTSS
Output
4
Input
SSTTST
Output
0
Input
TSSTTTSS
Output
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation a_{i}x + b_{i}y + c_{i} = 0, where a_{i} and b_{i} are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.
Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).
Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.
-----Input-----
The first line contains two space-separated integers x_1, y_1 ( - 10^6 ≤ x_1, y_1 ≤ 10^6) — the coordinates of your home.
The second line contains two integers separated by a space x_2, y_2 ( - 10^6 ≤ x_2, y_2 ≤ 10^6) — the coordinates of the university you are studying at.
The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 10^6 ≤ a_{i}, b_{i}, c_{i} ≤ 10^6; |a_{i}| + |b_{i}| > 0) — the coefficients of the line a_{i}x + b_{i}y + c_{i} = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).
-----Output-----
Output the answer to the problem.
-----Examples-----
Input
1 1
-1 -1
2
0 1 0
1 0 0
Output
2
Input
1 1
-1 -1
3
1 0 0
0 1 0
1 1 -3
Output
2
-----Note-----
Pictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): [Image] [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be present in exactly one subsegment.
Input
The first line contains two integers n and k (2 ≤ n ≤ 105, 2 ≤ k ≤ min (n, 20)) — the length of the array and the number of segments you need to split the array into.
The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the array.
Output
Print single integer: the minimum possible total cost of resulting subsegments.
Examples
Input
7 3
1 1 3 3 3 2 1
Output
1
Input
10 2
1 2 1 2 1 2 1 2 1 2
Output
8
Input
13 3
1 2 2 2 1 2 1 1 1 2 2 1 1
Output
9
Note
In the first example it's optimal to split the sequence into the following three subsegments: [1], [1, 3], [3, 3, 2, 1]. The costs are 0, 0 and 1, thus the answer is 1.
In the second example it's optimal to split the sequence in two equal halves. The cost for each half is 4.
In the third example it's optimal to split the sequence in the following way: [1, 2, 2, 2, 1], [2, 1, 1, 1, 2], [2, 1, 1]. The costs are 4, 4, 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a building with n rooms, numbered 1 to n.
We can move from any room to any other room in the building.
Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j).
Initially, there was one person in each room in the building.
After that, we know that there were exactly k moves happened up to now.
We are interested in the number of people in each of the n rooms now. How many combinations of numbers of people in the n rooms are possible?
Find the count modulo (10^9 + 7).
-----Constraints-----
- All values in input are integers.
- 3 \leq n \leq 2 \times 10^5
- 2 \leq k \leq 10^9
-----Input-----
Input is given from Standard Input in the following format:
n k
-----Output-----
Print the number of possible combinations of numbers of people in the n rooms now, modulo (10^9 + 7).
-----Sample Input-----
3 2
-----Sample Output-----
10
Let c_1, c_2, and c_3 be the number of people in Room 1, 2, and 3 now, respectively. There are 10 possible combination of (c_1, c_2, c_3):
- (0, 0, 3)
- (0, 1, 2)
- (0, 2, 1)
- (0, 3, 0)
- (1, 0, 2)
- (1, 1, 1)
- (1, 2, 0)
- (2, 0, 1)
- (2, 1, 0)
- (3, 0, 0)
For example, (c_1, c_2, c_3) will be (0, 1, 2) if the person in Room 1 goes to Room 2 and then one of the persons in Room 2 goes to Room 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
Yesterday you found some shoes in your room. Each shoe is described by two values:
```
type indicates if it's a left or a right shoe;
size is the size of the shoe.
```
Your task is to check whether it is possible to pair the shoes you found in such a way that each pair consists of a right and a left shoe of an equal size.
# Example
For:
```
shoes = [[0, 21],
[1, 23],
[1, 21],
[0, 23]]
```
the output should be `true;`
For:
```
shoes = [[0, 21],
[1, 23],
[1, 21],
[1, 23]]
```
the output should be `false.`
# Input/Output
- `[input]` 2D integer array `shoes`
Array of shoes. Each shoe is given in the format [type, size], where type is either 0 or 1 for left and right respectively, and size is a positive integer.
Constraints: `2 ≤ shoes.length ≤ 50, 1 ≤ shoes[i][1] ≤ 100.`
- `[output]` a boolean value
`true` if it is possible to pair the shoes, `false` otherwise.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Hofstadter sequences are a family of related integer sequences, among which the first ones were described by an American professor Douglas Hofstadter in his book Gödel, Escher, Bach.
### Task
Today we will be implementing the rather chaotic recursive sequence of integers called Hofstadter Q.
The Hofstadter Q is defined as:
As the author states in the aforementioned book:It is reminiscent of the Fibonacci definition in that each new value is a sum of two
previous values-but not of the immediately previous two values. Instead, the two
immediately previous values tell how far to count back to obtain the numbers to be added
to make the new value.
The function produces the starting sequence:
`1, 1, 2, 3, 3, 4, 5, 5, 6 . . .`
Test info: 100 random tests, n is always positive
Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have N cards. A number a_i is written on the i-th card.
Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.
The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards he/she has taken. When both players take the optimal strategy to maximize their scores, find Alice's score minus Bob's score.
-----Constraints-----
- N is an integer between 1 and 100 (inclusive).
- a_i \ (1 \leq i \leq N) is an integer between 1 and 100 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 a_3 ... a_N
-----Output-----
Print Alice's score minus Bob's score when both players take the optimal strategy to maximize their scores.
-----Sample Input-----
2
3 1
-----Sample Output-----
2
First, Alice will take the card with 3. Then, Bob will take the card with 1.
The difference of their scores will be 3 - 1 = 2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second — from a2 to b2
What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.
Input
The first line of the input file contains integers n and x0 (1 ≤ n ≤ 100; 0 ≤ x0 ≤ 1000). The following n lines contain pairs of integers ai, bi (0 ≤ ai, bi ≤ 1000; ai ≠ bi).
Output
Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.
Examples
Input
3 3
0 7
14 2
4 6
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.
This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1 + a2 ... + ak, a2 + a3 + ... + ak + 1, ..., an - k + 1 + an - k + 2 + ... + an), then those numbers will form strictly increasing sequence.
For example, for the following sample: n = 5, k = 3, a = (1, 2, 4, 5, 6) the sequence of numbers will look as follows: (1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6) = (7, 11, 15), that means that sequence a meets the described property.
Obviously the sequence of sums will have n - k + 1 elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.
The next line contains n space-separated elements ai (1 ≤ i ≤ n).
If ai = ?, then the i-th element of Arthur's sequence was replaced by a question mark.
Otherwise, ai ( - 109 ≤ ai ≤ 109) is the i-th element of Arthur's sequence.
Output
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).
Otherwise, print n integers — Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
Examples
Input
3 2
? 1 2
Output
0 1 2
Input
5 1
-10 -9 ? -7 -6
Output
-10 -9 -8 -7 -6
Input
5 3
4 6 7 2 9
Output
Incorrect sequence
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this Kata, you will be given two integers `n` and `k` and your task is to remove `k-digits` from `n` and return the lowest number possible, without changing the order of the digits in `n`. Return the result as a string.
Let's take an example of `solve(123056,4)`. We need to remove `4` digits from `123056` and return the lowest possible number. The best digits to remove are `(1,2,3,6)` so that the remaining digits are `'05'`. Therefore, `solve(123056,4) = '05'`.
Note also that the order of the numbers in `n` does not change: `solve(1284569,2) = '12456',` because we have removed `8` and `9`.
More examples in the test cases.
Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.
There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly qi items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the qi items in the cart.
Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.
Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
Input
The first line contains integer m (1 ≤ m ≤ 105) — the number of discount types. The second line contains m integers: q1, q2, ..., qm (1 ≤ qi ≤ 105).
The third line contains integer n (1 ≤ n ≤ 105) — the number of items Maxim needs. The fourth line contains n integers: a1, a2, ..., an (1 ≤ ai ≤ 104) — the items' prices.
The numbers in the lines are separated by single spaces.
Output
In a single line print a single integer — the answer to the problem.
Examples
Input
1
2
4
50 50 100 100
Output
200
Input
2
2 3
5
50 50 50 50 50
Output
150
Input
1
1
7
1 1 1 1 1 1 1
Output
3
Note
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.
In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a string A = A_1 A_2 ... A_n consisting of lowercase English letters.
You can choose any two indices i and j such that 1 \leq i \leq j \leq n and reverse substring A_i A_{i+1} ... A_j.
You can perform this operation at most once.
How many different strings can you obtain?
Constraints
* 1 \leq |A| \leq 200,000
* A consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
A
Output
Print the number of different strings you can obtain by reversing any substring in A at most once.
Examples
Input
aatt
Output
5
Input
xxxxxxxxxx
Output
1
Input
abracadabra
Output
44
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature will appear in the nearest update, when developers faced some troubles that only you may help them to solve.
All the messages are represented as a strings consisting of only lowercase English letters. In order to reduce the network load strings are represented in the special compressed form. Compression algorithm works as follows: string is represented as a concatenation of n blocks, each block containing only equal characters. One block may be described as a pair (l_{i}, c_{i}), where l_{i} is the length of the i-th block and c_{i} is the corresponding letter. Thus, the string s may be written as the sequence of pairs $\langle(l_{1}, c_{1}),(l_{2}, c_{2}), \ldots,(l_{n}, c_{n}) \rangle$.
Your task is to write the program, that given two compressed string t and s finds all occurrences of s in t. Developers know that there may be many such occurrences, so they only ask you to find the number of them. Note that p is the starting position of some occurrence of s in t if and only if t_{p}t_{p} + 1...t_{p} + |s| - 1 = s, where t_{i} is the i-th character of string t.
Note that the way to represent the string in compressed form may not be unique. For example string "aaaa" may be given as $\langle(4, a) \rangle$, $\langle(3, a),(1, a) \rangle$, $\langle(2, a),(2, a) \rangle$...
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of blocks in the strings t and s, respectively.
The second line contains the descriptions of n parts of string t in the format "l_{i}-c_{i}" (1 ≤ l_{i} ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter.
The second line contains the descriptions of m parts of string s in the format "l_{i}-c_{i}" (1 ≤ l_{i} ≤ 1 000 000) — the length of the i-th part and the corresponding lowercase English letter.
-----Output-----
Print a single integer — the number of occurrences of s in t.
-----Examples-----
Input
5 3
3-a 2-b 4-c 3-a 2-c
2-a 2-b 1-c
Output
1
Input
6 1
3-a 6-b 7-a 4-c 8-e 2-a
3-a
Output
6
Input
5 5
1-h 1-e 1-l 1-l 1-o
1-w 1-o 1-r 1-l 1-d
Output
0
-----Note-----
In the first sample, t = "aaabbccccaaacc", and string s = "aabbc". The only occurrence of string s in string t starts at position p = 2.
In the second sample, t = "aaabbbbbbaaaaaaacccceeeeeeeeaa", and s = "aaa". The occurrences of s in t start at positions p = 1, p = 10, p = 11, p = 12, p = 13 and p = 14.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You will be given a fruit which a farmer has harvested, your job is to see if you should buy or sell.
You will be given 3 pairs of fruit. Your task is to trade your harvested fruit back into your harvested fruit via the intermediate pair, you should return a string of 3 actions.
if you have harvested apples, you would buy this fruit pair: apple_orange, if you have harvested oranges, you would sell that fruit pair.
(In other words, to go from left to right (apples to oranges) you buy, and to go from right to left you sell (oranges to apple))
e.g.
apple_orange, orange_pear, apple_pear
1. if you have harvested apples, you would buy this fruit pair: apple_orange
2. Then you have oranges, so again you would buy this fruit pair: orange_pear
3. After you have pear, but now this time you would sell this fruit pair: apple_pear
4. Finally you are back with the apples
So your function would return a list: [“buy”,”buy”,”sell”]
If any invalid input is given, "ERROR" should be returned
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.