question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of $n$ heroes, the strength of the $i$-th hero is equal to $a_i$.
According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to $x$, then you have to send a hero with a strength of at least $x$ to kill it. If the dragon's attack power is $y$, then the total strength of the heroes defending the castle should be at least $y$.
The player can increase the strength of any hero by $1$ for one gold coin. This operation can be done any number of times.
There are $m$ dragons in the game, the $i$-th of them has defense equal to $x_i$ and attack power equal to $y_i$. Petya was wondering what is the minimum number of coins he needs to spend to defeat the $i$-th dragon.
Note that the task is solved independently for each dragon (improvements are not saved).
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$) β number of heroes.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{12}$), where $a_i$ is the strength of the $i$-th hero.
The third line contains a single integer $m$ ($1 \le m \le 2 \cdot 10^5$) β the number of dragons.
The next $m$ lines contain two integers each, $x_i$ and $y_i$ ($1 \le x_i \le 10^{12}; 1 \le y_i \le 10^{18}$) β defense and attack power of the $i$-th dragon.
-----Output-----
Print $m$ lines, $i$-th of which contains a single integer β the minimum number of coins that should be spent to defeat the $i$-th dragon.
-----Examples-----
Input
4
3 6 2 3
5
3 12
7 9
4 14
1 10
8 7
Output
1
2
4
0
2
-----Note-----
To defeat the first dragon, you can increase the strength of the third hero by $1$, then the strength of the heroes will be equal to $[3, 6, 3, 3]$. To kill the dragon, you can choose the first hero.
To defeat the second dragon, you can increase the forces of the second and third heroes by $1$, then the strength of the heroes will be equal to $[3, 7, 3, 3]$. To kill the dragon, you can choose a second hero.
To defeat the third dragon, you can increase the strength of all the heroes by $1$, then the strength of the heroes will be equal to $[4, 7, 3, 4]$. To kill the dragon, you can choose a fourth hero.
To defeat the fourth dragon, you don't need to improve the heroes and choose a third hero to kill the dragon.
To defeat the fifth dragon, you can increase the strength of the second hero by $2$, then the strength of the heroes will be equal to $[3, 8, 2, 3]$. To kill the dragon, you can choose a second hero.
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 special jigsaw puzzle consisting of $n\cdot m$ identical pieces. Every piece has three tabs and one blank, as pictured below. $\{3$
The jigsaw puzzle is considered solved if the following conditions hold: The pieces are arranged into a grid with $n$ rows and $m$ columns. For any two pieces that share an edge in the grid, a tab of one piece fits perfectly into a blank of the other piece.
Through rotation and translation of the pieces, determine if it is possible to solve the jigsaw puzzle.
-----Input-----
The test consists of multiple test cases. The first line contains a single integer $t$ ($1\le t\le 1000$)Β β the number of test cases. Next $t$ lines contain descriptions of test cases.
Each test case contains two integers $n$ and $m$ ($1 \le n,m \le 10^5$).
-----Output-----
For each test case output a single line containing "YES" if it is possible to solve the jigsaw puzzle, or "NO" otherwise. You can print each letter in any case (upper or lower).
-----Example-----
Input
3
1 3
100000 100000
2 2
Output
YES
NO
YES
-----Note-----
For the first test case, this is an example solution: [Image]
For the second test case, we can show that no solution exists.
For the third test case, this is an example solution: $\left\{\begin{array}{l}{3} \\{3} \end{array} \right\}$
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 given picture with size $w \times h$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:
A "+" shape has one center nonempty cell. There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction. All other cells are empty.
Find out if the given picture has single "+" shape.
-----Input-----
The first line contains two integers $h$ and $w$ ($1 \le h$, $w \le 500$)Β β the height and width of the picture.
The $i$-th of the next $h$ lines contains string $s_{i}$ of length $w$ consisting "." and "*" where "." denotes the empty space and "*" denotes the non-empty space.
-----Output-----
If the given picture satisfies all conditions, print "YES". Otherwise, print "NO".
You can output each letter in any case (upper or lower).
-----Examples-----
Input
5 6
......
..*...
.****.
..*...
..*...
Output
YES
Input
3 5
..*..
****.
.*...
Output
NO
Input
7 7
.......
...*...
..****.
...*...
...*...
.......
.*.....
Output
NO
Input
5 6
..**..
..**..
******
..**..
..**..
Output
NO
Input
3 7
.*...*.
***.***
.*...*.
Output
NO
Input
5 10
..........
..*.......
.*.******.
..*.......
..........
Output
NO
-----Note-----
In the first example, the given picture contains one "+".
In the second example, two vertical branches are located in a different column.
In the third example, there is a dot outside of the shape.
In the fourth example, the width of the two vertical branches is $2$.
In the fifth example, there are two shapes.
In the sixth example, there is an empty space inside of the shape.
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 three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.
Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:
* Operation: Choose one of the strings A, B and C, and specify an integer i between 1 and N (inclusive). Change the i-th character from the beginning of the chosen string to some other lowercase English letter.
What is the minimum number of operations required to achieve the objective?
Constraints
* 1 \leq N \leq 100
* Each of the strings A, B and C is a string of length N.
* Each character in each of the strings A, B and C is a lowercase English letter.
Input
Input is given from Standard Input in the following format:
N
A
B
C
Output
Print the minimum number of operations required.
Examples
Input
4
west
east
wait
Output
3
Input
9
different
different
different
Output
0
Input
7
zenkoku
touitsu
program
Output
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.
Given a string, determine if it's a valid identifier.
## Here is the syntax for valid identifiers:
* Each identifier must have at least one character.
* The first character must be picked from: alpha, underscore, or dollar sign. The first character cannot be a digit.
* The rest of the characters (besides the first) can be from: alpha, digit, underscore, or dollar sign. In other words, it can be any valid identifier character.
### Examples of valid identifiers:
* i
* wo_rd
* b2h
### Examples of invalid identifiers:
* 1i
* wo rd
* !b2h
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
```python
function repeating_fractions(numerator, denominator)
```
that given two numbers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part has repeated digits, replace those digits with a single digit in parentheses.
For example:
```python
repeating_fractions(1,1) === '1'
repeating_fractions(1,3) === '0.(3)'
repeating_fractions(2,888) === '0.(0)(2)5(2)5(2)5(2)5(2)5(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 traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the i-th rest point the distance from the start equals xi, and its picturesqueness equals bi. The traveler will move down the river in one direction, we can assume that he will start from point 0 on the coordinate axis and rest points are points with coordinates xi.
Every day the traveler wants to cover the distance l. In practice, it turns out that this is not always possible, because he needs to end each day at one of the resting points. In addition, the traveler is choosing between two desires: cover distance l every day and visit the most picturesque places.
Let's assume that if the traveler covers distance rj in a day, then he feels frustration <image>, and his total frustration over the hike is calculated as the total frustration on all days.
Help him plan the route so as to minimize the relative total frustration: the total frustration divided by the total picturesqueness of all the rest points he used.
The traveler's path must end in the farthest rest point.
Input
The first line of the input contains integers n, l (1 β€ n β€ 1000, 1 β€ l β€ 105) β the number of rest points and the optimal length of one day path.
Then n lines follow, each line describes one rest point as a pair of integers xi, bi (1 β€ xi, bi β€ 106). No two rest points have the same xi, the lines are given in the order of strictly increasing xi.
Output
Print the traveler's path as a sequence of the numbers of the resting points he used in the order he used them. Number the points from 1 to n in the order of increasing xi. The last printed number must be equal to n.
Examples
Input
5 9
10 10
20 10
30 1
31 5
40 10
Output
1 2 4 5
Note
In the sample test the minimum value of relative total frustration approximately equals 0.097549. This value can be calculated as <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.
It is a simplified version of problem F2. The difference between them is the constraints (F1: $k \le 2$, F2: $k \le 10$).
You are given an integer $n$. Find the minimum integer $x$ such that $x \ge n$ and the number $x$ is $k$-beautiful.
A number is called $k$-beautiful if its decimal representation having no leading zeroes contains no more than $k$ different digits. E.g. if $k = 2$, the numbers $3434443$, $55550$, $777$ and $21$ are $k$-beautiful whereas the numbers $120$, $445435$ and $998244353$ are not.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$) β the number of test cases. Then $t$ test cases follow.
Each test case consists of one line containing two integers $n$ and $k$ ($1 \le n \le 10^9$, $1 \le k \le 2$).
-----Output-----
For each test case output on a separate line $x$ β the minimum $k$-beautiful integer such that $x \ge n$.
-----Examples-----
Input
4
1 1
221 2
177890 2
998244353 1
Output
1
221
181111
999999999
-----Note-----
None
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 undirected graph with N vertices and 0 edges. Process Q queries of the following types.
* `0 u v`: Add an edge (u, v).
* `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise.
Constraints
* 1 \leq N \leq 200,000
* 1 \leq Q \leq 200,000
* 0 \leq u_i, v_i \lt N
Input
Input is given from Standard Input in the following format:
N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q
εΊε
For each query of the latter type, print the answer.
Example
Input
4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3
Output
0
1
0
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 are n heaps of stone. The i-th heap has h_i stones. You want to change the number of stones in the heap by performing the following process once:
* You go through the heaps from the 3-rd heap to the n-th heap, in this order.
* Let i be the number of the current heap.
* You can choose a number d (0 β€ 3 β
d β€ h_i), move d stones from the i-th heap to the (i - 1)-th heap, and 2 β
d stones from the i-th heap to the (i - 2)-th heap.
* So after that h_i is decreased by 3 β
d, h_{i - 1} is increased by d, and h_{i - 2} is increased by 2 β
d.
* You can choose different or same d for different operations. Some heaps may become empty, but they still count as heaps.
What is the maximum number of stones in the smallest heap after the process?
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 2β
10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (3 β€ n β€ 2 β
10^5).
The second lines of each test case contains n integers h_1, h_2, h_3, β¦, h_n (1 β€ h_i β€ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, print the maximum number of stones that the smallest heap can contain.
Example
Input
4
4
1 2 10 100
4
100 100 100 1
5
5 1 1 1 8
6
1 2 3 4 5 6
Output
7
1
1
3
Note
In the first test case, the initial heap sizes are [1, 2, 10, 100]. We can move the stones as follows.
* move 3 stones and 6 from the 3-rd heap to the 2-nd and 1 heap respectively. The heap sizes will be [7, 5, 1, 100];
* move 6 stones and 12 stones from the last heap to the 3-rd and 2-nd heap respectively. The heap sizes will be [7, 17, 7, 82].
In the second test case, the last heap is 1, and we can not increase its size.
In the third test case, it is better not to move any stones.
In the last test case, the final achievable configuration of the heaps can be [3, 5, 3, 4, 3, 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.
Your task is to write function which takes string and list of delimiters as an input and returns list of strings/characters after splitting given string.
Example:
```python
multiple_split('Hi, how are you?', [' ']) => ['Hi,', 'how', 'are', 'you?']
multiple_split('1+2-3', ['+', '-']) => ['1', '2', '3']
```
List of delimiters is optional and can be empty, so take that into account.
Important note: Result cannot contain empty string.
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.
Example
Input
3 2
R1
Output
3 1 2
4 5 6
7 8 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.
There are N islands and M bridges.
The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.
Initially, we can travel between any two islands using some of these bridges.
However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.
Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.
For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10^5
- 1 \leq M \leq 10^5
- 1 \leq A_i < B_i \leq N
- All pairs (A_i, B_i) are distinct.
- The inconvenience is initially 0.
-----Input-----
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M
-----Output-----
In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.
-----Sample Input-----
4 5
1 2
3 4
1 3
2 3
1 4
-----Sample Output-----
0
0
4
5
6
For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 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.
Niwango-kun is an employee of Dwango Co., Ltd.
One day, he is asked to generate a thumbnail from a video a user submitted.
To generate a thumbnail, he needs to select a frame of the video according to the following procedure:
* Get an integer N and N integers a_0, a_1, ..., a_{N-1} as inputs. N denotes the number of the frames of the video, and each a_i denotes the representation of the i-th frame of the video.
* Select t-th frame whose representation a_t is nearest to the average of all frame representations.
* If there are multiple such frames, select the frame with the smallest index.
Find the index t of the frame he should select to generate a thumbnail.
Constraints
* 1 \leq N \leq 100
* 1 \leq a_i \leq 100
* All numbers given in input are integers
Input
Input is given from Standard Input in the following format:
N
a_{0} a_{1} ... a_{N-1}
Output
Print the answer.
Examples
Input
3
1 2 3
Output
1
Input
4
2 5 2 5
Output
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.
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.
Mike has $n$ sweets with sizes $a_1, a_2, \ldots, a_n$. All his sweets have different sizes. That is, there is no such pair $(i, j)$ ($1 \leq i, j \leq n$) such that $i \ne j$ and $a_i = a_j$.
Since Mike has taught for many years, he knows that if he gives two sweets with sizes $a_i$ and $a_j$ to one child and $a_k$ and $a_p$ to another, where $(a_i + a_j) \neq (a_k + a_p)$, then a child who has a smaller sum of sizes will be upset. That is, if there are two children who have different sums of sweets, then one of them will be upset. Apparently, Mike does not want somebody to be upset.
Mike wants to invite children giving each of them two sweets. Obviously, he can't give one sweet to two or more children. His goal is to invite as many children as he can.
Since Mike is busy preparing to his first lecture in the elementary school, he is asking you to find the maximum number of children he can invite giving each of them two sweets in such way that nobody will be upset.
-----Input-----
The first line contains one integer $n$ ($2 \leq n \leq 1\,000$)Β β the number of sweets Mike has.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^5$)Β β the sizes of the sweets. It is guaranteed that all integers are distinct.
-----Output-----
Print one integerΒ β the maximum number of children Mike can invite giving each of them two sweets in such way that nobody will be upset.
-----Examples-----
Input
8
1 8 3 11 4 9 2 7
Output
3
Input
7
3 1 7 11 9 2 12
Output
2
-----Note-----
In the first example, Mike can give $9+2=11$ to one child, $8+3=11$ to another one, and $7+4=11$ to the third child. Therefore, Mike can invite three children. Note that it is not the only solution.
In the second example, Mike can give $3+9=12$ to one child and $1+11$ to another one. Therefore, Mike can invite two children. Note that it is not the only solution.
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 hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. [Image]
One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of h_{i} centimeters above the floor of the house, its mass is m_{i}. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.
What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?
-----Input-----
The first line contains two integers, n and x (1 β€ n, x β€ 2000) β the number of sweets Evan has and the initial height of Om Nom's jump.
Each of the following n lines contains three integers t_{i}, h_{i}, m_{i} (0 β€ t_{i} β€ 1;Β 1 β€ h_{i}, m_{i} β€ 2000) β the type, height and the mass of the i-th candy. If number t_{i} equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.
-----Output-----
Print a single integer β the maximum number of candies Om Nom can eat.
-----Examples-----
Input
5 3
0 2 4
1 3 1
0 8 3
0 20 10
1 5 5
Output
4
-----Note-----
One of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario: Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7. Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12. At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15. Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 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.
Example
Input
2
1 2
Output
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 chessboard n Γ m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues ad infinitum. You have to figure out how many squares we repainted exactly x times.
The upper left square of the board has to be assumed to be always black. Two squares are called corner-adjacent, if they have exactly one common point.
Input
The first line contains integers n and m (1 β€ n, m β€ 5000). The second line contains integer x (1 β€ x β€ 109).
Output
Print how many squares will be painted exactly x times.
Examples
Input
3 3
1
Output
4
Input
3 3
2
Output
1
Input
1 1
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.
Takahashi has a tower which is divided into N layers. Initially, all the layers are uncolored. Takahashi is going to paint some of the layers in red, green or blue to make a beautiful tower. He defines the beauty of the tower as follows:
* The beauty of the tower is the sum of the scores of the N layers, where the score of a layer is A if the layer is painted red, A+B if the layer is painted green, B if the layer is painted blue, and 0 if the layer is uncolored.
Here, A and B are positive integer constants given beforehand. Also note that a layer may not be painted in two or more colors.
Takahashi is planning to paint the tower so that the beauty of the tower becomes exactly K. How many such ways are there to paint the tower? Find the count modulo 998244353. Two ways to paint the tower are considered different when there exists a layer that is painted in different colors, or a layer that is painted in some color in one of the ways and not in the other.
Constraints
* 1 β€ N β€ 3Γ10^5
* 1 β€ A,B β€ 3Γ10^5
* 0 β€ K β€ 18Γ10^{10}
* All values in the input are integers.
Input
Input is given from Standard Input in the following format:
N A B K
Output
Print the number of the ways to paint tiles, modulo 998244353.
Examples
Input
4 1 2 5
Output
40
Input
2 5 6 0
Output
1
Input
90081 33447 90629 6391049189
Output
577742975
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 likes numbers that are divisible by 3.
He has a huge number $s$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $3$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $m$ such cuts, there will be $m+1$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $3$.
For example, if the original number is $s=3121$, then Polycarp can cut it into three parts with two cuts: $3|1|21$. As a result, he will get two numbers that are divisible by $3$.
Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.
What is the maximum number of numbers divisible by $3$ that Polycarp can obtain?
-----Input-----
The first line of the input contains a positive integer $s$. The number of digits of the number $s$ is between $1$ and $2\cdot10^5$, inclusive. The first (leftmost) digit is not equal to 0.
-----Output-----
Print the maximum number of numbers divisible by $3$ that Polycarp can get by making vertical cuts in the given number $s$.
-----Examples-----
Input
3121
Output
2
Input
6
Output
1
Input
1000000000000000000000000000000000
Output
33
Input
201920181
Output
4
-----Note-----
In the first example, an example set of optimal cuts on the number is 3|1|21.
In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $3$.
In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $33$ digits 0. Each of the $33$ digits 0 forms a number that is divisible by $3$.
In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $0$, $9$, $201$ and $81$ are divisible by $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.
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.
This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.
Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.
Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.
It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.
Help Vasya to recover the initial set of cards with numbers.
Input
The single line contains three space-separated integers: n (2 β€ n β€ 100) β the initial number of cards on the table, d (|d| β€ 104) β the number on the card that was left on the table after all the magical actions, and l (1 β€ l β€ 100) β the limits for the initial integers.
Output
If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.
Examples
Input
3 3 2
Output
2 1 2
Input
5 -4 3
Output
-1
Input
5 -4 4
Output
2 4 1 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.
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Write a program which reads a list of N integers and prints the number of prime numbers in the list.
Constraints
1 β€ N β€ 10000
2 β€ an element of the list β€ 108
Input
The first line contains an integer N, the number of elements in the list.
N numbers are given in the following lines.
Output
Print the number of prime numbers in the given list.
Examples
Input
5
2
3
4
5
6
Output
3
Input
11
7
8
9
10
11
12
13
14
15
16
17
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.
Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 11, 20, 29]$ and $[3, 2, 1, 0]$ are arithmetic progressions, but $[1, 0, 1]$, $[1, 3, 9]$ and $[2, 3, 1]$ are not.
It follows from the definition that any sequence of length one or two is an arithmetic progression.
Polycarp found some sequence of positive integers $[b_1, b_2, \dots, b_n]$. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by $1$, an element can be increased by $1$, an element can be left unchanged.
Determine a minimum possible number of elements in $b$ which can be changed (by exactly one), so that the sequence $b$ becomes an arithmetic progression, or report that it is impossible.
It is possible that the resulting sequence contains element equals $0$.
-----Input-----
The first line contains a single integer $n$ $(1 \le n \le 100\,000)$ β the number of elements in $b$.
The second line contains a sequence $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 10^{9})$.
-----Output-----
If it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer β the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).
-----Examples-----
Input
4
24 21 14 10
Output
3
Input
2
500 500
Output
0
Input
3
14 5 1
Output
-1
Input
5
1 3 6 9 12
Output
1
-----Note-----
In the first example Polycarp should increase the first number on $1$, decrease the second number on $1$, increase the third number on $1$, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to $[25, 20, 15, 10]$, which is an arithmetic progression.
In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.
In the third example it is impossible to make an arithmetic progression.
In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like $[0, 3, 6, 9, 12]$, which is an arithmetic progression.
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.
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or Hearts β H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).
At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.
In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.
-----Input-----
The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.
Each string is two characters long. The first character denotes the rank and belongs to the set $\{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}$. The second character denotes the suit and belongs to the set $\{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}$.
All the cards in the input are different.
-----Output-----
If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
AS
2H 4C TH JH AD
Output
YES
Input
2H
3D 4C AC KD AS
Output
NO
Input
4D
AS AC AD AH 5H
Output
YES
-----Note-----
In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.
In the second example, you cannot play any card.
In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
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 integer variable x.
Initially, x=0.
Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.
Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).
-----Constraints-----
- 1β€Nβ€100
- |S|=N
- No characters except I and D occur in S.
-----Input-----
The input is given from Standard Input in the following format:
N
S
-----Output-----
Print the maximum value taken by x during the operations.
-----Sample Input-----
5
IIDID
-----Sample Output-----
2
After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.
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 play 5-in-a-row game. They have a playing field of size 10 Γ 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.
In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.
Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.
-----Input-----
You are given matrix 10 Γ 10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell.
It is guaranteed that in the current arrangement nobody has still won.
-----Output-----
Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.
-----Examples-----
Input
XX.XX.....
.....OOOO.
..........
..........
..........
..........
..........
..........
..........
..........
Output
YES
Input
XXOXX.....
OO.O......
..........
..........
..........
..........
..........
..........
..........
..........
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.
Your friend won't stop texting his girlfriend. It's all he does. All day. Seriously. The texts are so mushy too! The whole situation just makes you feel ill.
Being the wonderful friend that you are, you hatch an evil plot. While he's sleeping, you take his phone and change the autocorrect options so that every time he types "you" or "u" it gets changed to "your sister."
Write a function called autocorrect that takes a string and replaces all instances of "you" or "u" (not case sensitive) with "your sister" (always lower case).
Return the resulting string.
Here's the slightly tricky part: These are text messages, so there are different forms of "you" and "u".
For the purposes of this kata, here's what you need to support:
"youuuuu" with any number of u characters tacked onto the end
"u" at the beginning, middle, or end of a string, but NOT part of a word
"you" but NOT as part of another word like youtube or bayou
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.
prison
There are an infinite number of prisoners. Initially, the prisoners are numbered 0, 1, 2, ....
Do the following N times:
* Release the 0th prisoner and execute the k, 2k, 3k, ... th prisoners.
* Then renumber the remaining prisoners. At this time, the prisoners with the smallest original numbers are numbered 0, 1, 2, ... in order.
Find the number that was originally assigned to the prisoner released in the Nth operation.
Constraints
* 1 β€ N β€ 10 ^ 5
* 2 β€ k β€ 10 ^ 5
* The answer is less than 10 ^ {18}.
Input Format
Input is given from standard input in the following format.
N k
Output Format
Print the answer in one line.
Sample Input 1
4 2
Sample Output 1
7
Sample Input 2
13
Sample Output 2
0
Sample Input 3
100000 100000
Sample Output 3
99999
Example
Input
4 2
Output
7
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
**_Given_** an *array/list [] of n integers* , *find maximum triplet sum in the array* **_Without duplications_** .
___
# Notes :
* **_Array/list_** size is *at least 3* .
* **_Array/list_** numbers could be a *mixture of positives , negatives and zeros* .
* **_Repetition_** of numbers in *the array/list could occur* , So **_(duplications are not included when summing)_**.
___
# Input >> Output Examples
## **_Explanation_**:
* As the **_triplet_** that *maximize the sum* **_{6,8,3}_** in order , **_their sum is (17)_**
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
## **_Explanation_**:
* As the **_triplet_** that *maximize the sum* **_{8, 6, 4}_** in order , **_their sum is (18)_** ,
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
## **_Explanation_**:
* As the **_triplet_** that *maximize the sum* **_{12 , 29 , 0}_** in order , **_their sum is (41)_** ,
* *Note* : **_duplications_** *are not included when summing* , **(i.e) the numbers added only once** .
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
___
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
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 might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.
The square still has a rectangular shape of $n \times m$ meters. However, the picture is about to get more complicated now. Let $a_{i,j}$ be the $j$-th square in the $i$-th row of the pavement.
You are given the picture of the squares: if $a_{i,j} = $ "*", then the $j$-th square in the $i$-th row should be black; if $a_{i,j} = $ ".", then the $j$-th square in the $i$-th row should be white.
The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: $1 \times 1$ tilesΒ β each tile costs $x$ burles and covers exactly $1$ square; $1 \times 2$ tilesΒ β each tile costs $y$ burles and covers exactly $2$ adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into $1 \times 1$ tiles.
You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.
What is the smallest total price of the tiles needed to cover all the white squares?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 500$)Β β the number of testcases. Then the description of $t$ testcases follow.
The first line of each testcase contains four integers $n$, $m$, $x$ and $y$ ($1 \le n \le 100$; $1 \le m \le 1000$; $1 \le x, y \le 1000$)Β β the size of the Theatre square, the price of the $1 \times 1$ tile and the price of the $1 \times 2$ tile.
Each of the next $n$ lines contains $m$ characters. The $j$-th character in the $i$-th line is $a_{i,j}$. If $a_{i,j} = $ "*", then the $j$-th square in the $i$-th row should be black, and if $a_{i,j} = $ ".", then the $j$-th square in the $i$-th row should be white.
It's guaranteed that the sum of $n \times m$ over all testcases doesn't exceed $10^5$.
-----Output-----
For each testcase print a single integerΒ β the smallest total price of the tiles needed to cover all the white squares in burles.
-----Example-----
Input
4
1 1 10 1
.
1 2 10 1
..
2 1 10 1
.
.
3 3 3 7
..*
*..
.*.
Output
10
1
20
18
-----Note-----
In the first testcase you are required to use a single $1 \times 1$ tile, even though $1 \times 2$ tile is cheaper. So the total price is $10$ burles.
In the second testcase you can either use two $1 \times 1$ tiles and spend $20$ burles or use a single $1 \times 2$ tile and spend $1$ burle. The second option is cheaper, thus the answer is $1$.
The third testcase shows that you can't rotate $1 \times 2$ tiles. You still have to use two $1 \times 1$ tiles for the total price of $20$.
In the fourth testcase the cheapest way is to use $1 \times 1$ tiles everywhere. The total cost is $6 \cdot 3 = 18$.
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 $n$. In one move, you can either multiply $n$ by two or divide $n$ by $6$ (if it is divisible by $6$ without the remainder).
Your task is to find the minimum number of moves needed to obtain $1$ from $n$ or determine if it's impossible to do that.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) β the number of test cases. Then $t$ test cases follow.
The only line of the test case contains one integer $n$ ($1 \le n \le 10^9$).
-----Output-----
For each test case, print the answer β the minimum number of moves needed to obtain $1$ from $n$ if it's possible to do that or -1 if it's impossible to obtain $1$ from $n$.
-----Example-----
Input
7
1
2
3
12
12345
15116544
387420489
Output
0
-1
2
-1
-1
12
36
-----Note-----
Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $15116544$:
Divide by $6$ and get $2519424$; divide by $6$ and get $419904$; divide by $6$ and get $69984$; divide by $6$ and get $11664$; multiply by $2$ and get $23328$; divide by $6$ and get $3888$; divide by $6$ and get $648$; divide by $6$ and get $108$; multiply by $2$ and get $216$; divide by $6$ and get $36$; divide by $6$ and get $6$; divide by $6$ and get $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 are two buttons, one of size A and one of size B.
When you press a button of size X, you get X coins and the size of that button decreases by 1.
You will press a button twice. Here, you can press the same button twice, or press both buttons once.
At most how many coins can you get?
-----Constraints-----
- All values in input are integers.
- 3 \leq A, B \leq 20
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
Print the maximum number of coins you can get.
-----Sample Input-----
5 3
-----Sample Output-----
9
You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum 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.
Create a function `isAlt()` that accepts a string as an argument and validates whether the vowels (a, e, i, o, u) and consonants are in alternate order.
```python
is_alt("amazon")
// true
is_alt("apple")
// false
is_alt("banana")
// true
```
Arguments consist of only lowercase letters.
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 cube which consists of n Γ n Γ n small cubes. Small cubes have marks on their surfaces. An example where n = 4 is shown in the following figure.
<image>
Then, as shown in the figure above (right), make a hole that penetrates horizontally or vertically from the marked surface to the opposite surface.
Your job is to create a program that reads the positions marked n and counts the number of small cubes with no holes.
Input
The input consists of several datasets. Each dataset is given in the following format:
n h
c1 a1 b1
c2 a2 b2
..
..
..
ch ah bh
h is an integer indicating the number of marks. The h lines that follow enter the positions of the h marks. The coordinate axes shown in the figure below will be used to specify the position of the mark. (x, y, z) = (1, 1, 1) is the lower left cube, and (x, y, z) = (n, n, n) is the upper right cube.
<image>
ci is a string indicating the plane marked with the i-th. ci is one of "xy", "xz", and "yz", indicating that the i-th mark is on the xy, xz, and yz planes, respectively.
ai and bi indicate the coordinates on the plane indicated by ci. For the xy, xz, and yz planes, ai and bi indicate the plane coordinates (x, y), (x, z), and (y, z), respectively. For example, in the above figure, the values ββof ci, ai, and bi of marks A, B, and C are "xy 4 4", "xz 1 2", and "yz 2 3", respectively.
When both n and h are 0, it indicates the end of input.
You can assume that n β€ 500 and h β€ 200.
Output
For each dataset, print the number of non-perforated cubes on one line.
Example
Input
4 3
xy 4 4
xz 1 2
yz 2 3
4 5
xy 1 1
xy 3 3
xz 3 3
yz 2 1
yz 3 3
0 0
Output
52
46
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.
Constraints
* 1 β€ |V| β€ 1000
* 0 β€ |E| β€ 2000
* -10000 β€ di β€ 10000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value) which is reachable from the source r, print
NEGATIVE CYCLE
in a line.
Otherwise, print
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print "INF".
Examples
Input
4 5 0
0 1 2
0 2 3
1 2 -5
1 3 1
2 3 2
Output
0
2
-3
-1
Input
4 6 0
0 1 2
0 2 3
1 2 -5
1 3 1
2 3 2
3 1 0
Output
NEGATIVE CYCLE
Input
4 5 1
0 1 2
0 2 3
1 2 -5
1 3 1
2 3 2
Output
INF
0
-5
-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.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 β€ n β€ 105) β the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 β€ ki, bi β€ 109) that determine the i-th function.
Output
Print a single number β the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
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.
You are given a sequence $a$, initially consisting of $n$ integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer $x$ that occurs at least once in $a$, and then perform the following operation any number of times (possibly zero): choose some segment $[l, r]$ of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains $x$. More formally, you choose some contiguous subsequence $[a_l, a_{l + 1}, \dots, a_r]$ such that $a_i \ne x$ if $l \le i \le r$, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the $(r+1)$-th is now $l$-th, the element that was $(r+2)$-th is now $(l+1)$-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change $x$ after you chose it.
For example, suppose $n = 6$, $a = [1, 3, 2, 4, 1, 2]$. Then one of the ways to transform it in two operations is to choose $x = 1$, then:
choose $l = 2$, $r = 4$, so the resulting sequence is $a = [1, 1, 2]$;
choose $l = 3$, $r = 3$, so the resulting sequence is $a = [1, 1]$.
Note that choosing $x$ is not an operation. Also, note that you can not remove any occurrence of $x$.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) β the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of elements in $a$. The second line of the test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$.
It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
-----Examples-----
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
-----Note-----
None
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.
B: Hokkaido University Hard
Note
Please note that the question settings are the same as question A, except for the constraints.
story
Homura-chan, who passed Hokkaido University and is excited about the beginning of a new life. But in front of her, a huge campus awaits ...
"Eh ... I'm not in time for the next class ..."
problem
Hokkaido University Sapporo Campus is famous for being unusually large. The Sapporo campus is represented by rectangular squares with H squares vertically and W squares horizontally. We will use (i, j) to represent the cells that are i-mass from the north and j-mass from the west. There are several buildings on campus, with a'B'if there is a building in the location represented by the square (i, j) and a'.' If not, in c_ {i, j}.
Homura, a freshman at Hokkaido University, was surprised at the size of the campus and was worried about moving between buildings. So I was wondering how far the farthest of the two squares with the building were. Here we define the distance between two pairs of squares (i, j), (i', j') as | i-i'| + | j-j'|.
Homura found this problem difficult for him and asked his classmates for help. Please ask for an answer instead of Homura-chan.
Input format
H W
c_ {11} c_ {12} ... c_ {1W}
::
c_ {H1} c_ {H2} ... c_ {HW}
Constraint
* 2 \ leq H, W \ leq 10 ^ 3
* H and W are integers
* c_ {i, j} is either'B'or'.'.
* At least two of c_ {i, j} are'B'.
Output format
Print the integer that represents the answer on one line.
Input example 1
3 3
B.B
..B
.BB
Output example 1
Four
* The longest is between the two points (1,1) and (3,3).
Input example 2
4 3
B ..
B ..
...
...
Output example 2
1
* Adjacent positions may be the longest.
Input example 3
6 6
... B ..
B.B.B.
.B.B.B
... B.B
.B..B.
..B ...
Output example 3
7
Example
Input
3 3
B.B
..B
.BB
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.
Implement `String#whitespace?(str)` (Ruby), `String.prototype.whitespace(str)` (JavaScript), `String::whitespace(str)` (CoffeeScript), or `whitespace(str)` (Python), which should return `true/True` if given object consists exclusively of zero or more whitespace characters, `false/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.
Takahashi is solving quizzes. He has easily solved all but the last one.
The last quiz has three choices: 1, 2, and 3.
With his supernatural power, Takahashi has found out that the choices A and B are both wrong.
Print the correct choice for this problem.
-----Constraints-----
- Each of the numbers A and B is 1, 2, or 3.
- A and B are different.
-----Input-----
Input is given from Standard Input in the following format:
A
B
-----Output-----
Print the correct choice.
-----Sample Input-----
3
1
-----Sample Output-----
2
When we know 3 and 1 are both wrong, the correct choice 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.
You are given an array $a[0 \ldots n-1]$ of length $n$ which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $i$ ($0 \le i \le n - 1$) the equality $i \bmod 2 = a[i] \bmod 2$ holds, where $x \bmod 2$ is the remainder of dividing $x$ by 2.
For example, the arrays [$0, 5, 2, 1$] and [$0, 17, 0, 3$] are good, and the array [$2, 4, 6, 7$] is bad, because for $i=1$, the parities of $i$ and $a[i]$ are different: $i \bmod 2 = 1 \bmod 2 = 1$, but $a[i] \bmod 2 = 4 \bmod 2 = 0$.
In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).
Find the minimum number of moves in which you can make the array $a$ good, or say that this is not possible.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$)Β β the number of test cases in the test. Then $t$ test cases follow.
Each test case starts with a line containing an integer $n$ ($1 \le n \le 40$)Β β the length of the array $a$.
The next line contains $n$ integers $a_0, a_1, \ldots, a_{n-1}$ ($0 \le a_i \le 1000$)Β β the initial array.
-----Output-----
For each test case, output a single integerΒ β the minimum number of moves to make the given array $a$ good, or -1 if this is not possible.
-----Example-----
Input
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
Output
2
1
-1
0
-----Note-----
In the first test case, in the first move, you can swap the elements with indices $0$ and $1$, and in the second move, you can swap the elements with indices $2$ and $3$.
In the second test case, in the first move, you need to swap the elements with indices $0$ and $1$.
In the third test case, you cannot make the array good.
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 postal code in Atcoder Kingdom is A+B+1 characters long, its (A+1)-th character is a hyphen -, and the other characters are digits from 0 through 9.
You are given a string S. Determine whether it follows the postal code format in Atcoder Kingdom.
-----Constraints-----
- 1β€A,Bβ€5
- |S|=A+B+1
- S consists of - and digits from 0 through 9.
-----Input-----
Input is given from Standard Input in the following format:
A B
S
-----Output-----
Print Yes if S follows the postal code format in AtCoder Kingdom; print No otherwise.
-----Sample Input-----
3 4
269-6650
-----Sample Output-----
Yes
The (A+1)-th character of S is -, and the other characters are digits from 0 through 9, so it follows the format.
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 found a rectangle A of size n Γ m. There are n rows and m columns of blocks. Each block of the rectangle is an obsidian block or empty. CQXYM can change an obsidian block to an empty block or an empty block to an obsidian block in one operation.
A rectangle M size of a Γ b is called a portal if and only if it satisfies the following conditions:
* a β₯ 5,b β₯ 4.
* For all 1 < x < a, blocks M_{x,1} and M_{x,b} are obsidian blocks.
* For all 1 < x < b, blocks M_{1,x} and M_{a,x} are obsidian blocks.
* For all 1<x<a,1<y<b, block M_{x,y} is an empty block.
* M_{1, 1}, M_{1, b}, M_{a, 1}, M_{a, b} can be any type.
Note that the there must be a rows and b columns, not b rows and a columns.
Note that corners can be any type
CQXYM wants to know the minimum number of operations he needs to make at least one sub-rectangle a portal.
Input
The first line contains an integer t (t β₯ 1), which is the number of test cases.
For each test case, the first line contains two integers n and m (5 β€ n β€ 400, 4 β€ m β€ 400).
Then n lines follow, each line contains m characters 0 or 1. If the j-th character of i-th line is 0, block A_{i,j} is an empty block. Otherwise, block A_{i,j} is an obsidian block.
It is guaranteed that the sum of n over all test cases does not exceed 400.
It is guaranteed that the sum of m over all test cases does not exceed 400.
Output
Output t answers, and each answer in a line.
Examples
Input
1
5 4
1000
0000
0110
0000
0001
Output
12
Input
1
9 9
001010001
101110100
000010011
100000001
101010101
110001111
000001111
111100000
000110000
Output
5
Note
In the first test case, the final portal is like this:
1110
1001
1001
1001
0111
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.
Note that girls in Arpaβs land are really attractive.
Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the a_{i}-th chair, and his girlfriend, sitting on the b_{i}-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair.
[Image]
There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that: Each person had exactly one type of food, No boy had the same type of food as his girlfriend, Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive.
Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
-----Input-----
The first line contains an integer n (1 β€ n β€ 10^5)Β β the number of pairs of guests.
The i-th of the next n lines contains a pair of integers a_{i} and b_{i} (1 β€ a_{i}, b_{i} β€ 2n)Β β the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.
-----Output-----
If there is no solution, print -1.
Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2.
If there are multiple solutions, print any of them.
-----Example-----
Input
3
1 4
2 5
3 6
Output
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.
Mash 2 arrays together so that the returning array has alternating elements of the 2 arrays . Both arrays will always be the same length.
eg. [1,2,3] + ['a','b','c'] = [1, 'a', 2, 'b', 3, 'c']
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 wrote on the board a string $s$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.
After that, he erased some letters from the string $s$, and he rewrote the remaining letters in any order. As a result, he got some new string $t$. You have to find it with some additional information.
Suppose that the string $t$ has length $m$ and the characters are numbered from left to right from $1$ to $m$. You are given a sequence of $m$ integers: $b_1, b_2, \ldots, b_m$, where $b_i$ is the sum of the distances $|i-j|$ from the index $i$ to all such indices $j$ that $t_j > t_i$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $b_i$, Polycarp finds all such indices $j$ that the index $j$ contains a letter that is later in the alphabet than $t_i$ and sums all the values $|i-j|$.
For example, if $t$ = "abzb", then: since $t_1$='a', all other indices contain letters which are later in the alphabet, that is: $b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$; since $t_2$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_2=|2-3|=1$; since $t_3$='z', then there are no indexes $j$ such that $t_j>t_i$, thus $b_3=0$; since $t_4$='b', only the index $j=3$ contains the letter, which is later in the alphabet, that is: $b_4=|4-3|=1$.
Thus, if $t$ = "abzb", then $b=[6,1,0,1]$.
Given the string $s$ and the array $b$, find any possible string $t$ for which the following two requirements are fulfilled simultaneously: $t$ is obtained from $s$ by erasing some letters (possibly zero) and then writing the rest in any order; the array, constructed from the string $t$ according to the rules above, equals to the array $b$ specified in the input data.
-----Input-----
The first line contains an integer $q$ ($1 \le q \le 100$)Β β the number of test cases in the test. Then $q$ test cases follow.
Each test case consists of three lines: the first line contains string $s$, which has a length from $1$ to $50$ and consists of lowercase English letters; the second line contains positive integer $m$ ($1 \le m \le |s|$), where $|s|$ is the length of the string $s$, and $m$ is the length of the array $b$; the third line contains the integers $b_1, b_2, \dots, b_m$ ($0 \le b_i \le 1225$).
It is guaranteed that in each test case an answer exists.
-----Output-----
Output $q$ lines: the $k$-th of them should contain the answer (string $t$) to the $k$-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.
-----Example-----
Input
4
abac
3
2 1 0
abc
1
0
abba
3
1 0 1
ecoosdcefr
10
38 13 24 14 11 5 3 24 17 0
Output
aac
b
aba
codeforces
-----Note-----
In the first test case, such strings $t$ are suitable: "aac', "aab".
In the second test case, such trings $t$ are suitable: "a", "b", "c".
In the third test case, only the string $t$ equals to "aba" is suitable, but the character 'b' can be from the second or third position.
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.
Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 β€ i < k, and a1 = x and ak = y.
<image>
Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it.
Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.
Input
The first line contains integers n, m and w (1 β€ n β€ 1000, <image>, 1 β€ w β€ 1000) β the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.
The second line contains n integers w1, w2, ..., wn (1 β€ wi β€ 1000) β the weights of the Hoses.
The third line contains n integers b1, b2, ..., bn (1 β€ bi β€ 106) β the beauties of the Hoses.
The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 β€ xi, yi β€ n, xi β yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.
Output
Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.
Examples
Input
3 1 5
3 2 5
2 4 2
1 2
Output
6
Input
4 2 11
2 4 6 6
6 4 2 1
1 2
2 3
Output
7
Note
In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.
In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.
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 rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.
You must paint a fence which consists of $10^{100}$ planks in two colors in the following way (suppose planks are numbered from left to right from $0$): if the index of the plank is divisible by $r$ (such planks have indices $0$, $r$, $2r$ and so on) then you must paint it red; if the index of the plank is divisible by $b$ (such planks have indices $0$, $b$, $2b$ and so on) then you must paint it blue; if the index is divisible both by $r$ and $b$ you can choose the color to paint the plank; otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it).
Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $k$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.
The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.
-----Input-----
The first line contains single integer $T$ ($1 \le T \le 1000$) β the number of test cases.
The next $T$ lines contain descriptions of test cases β one per line. Each test case contains three integers $r$, $b$, $k$ ($1 \le r, b \le 10^9$, $2 \le k \le 10^9$) β the corresponding coefficients.
-----Output-----
Print $T$ words β one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.
-----Example-----
Input
4
1 1 2
2 10 4
5 2 3
3 2 2
Output
OBEY
REBEL
OBEY
OBEY
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 program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 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.
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems.
Kirk has a binary string $s$ (a string which consists of zeroes and ones) of length $n$ and he is asking you to find a binary string $t$ of the same length which satisfies the following conditions:
For any $l$ and $r$ ($1 \leq l \leq r \leq n$) the length of the longest non-decreasing subsequence of the substring $s_{l}s_{l+1} \ldots s_{r}$ is equal to the length of the longest non-decreasing subsequence of the substring $t_{l}t_{l+1} \ldots t_{r}$;
The number of zeroes in $t$ is the maximum possible.
A non-decreasing subsequence of a string $p$ is a sequence of indices $i_1, i_2, \ldots, i_k$ such that $i_1 < i_2 < \ldots < i_k$ and $p_{i_1} \leq p_{i_2} \leq \ldots \leq p_{i_k}$. The length of the subsequence is $k$.
If there are multiple substrings which satisfy the conditions, output any.
-----Input-----
The first line contains a binary string of length not more than $2\: 000$.
-----Output-----
Output a binary string which satisfied the above conditions. If there are many such strings, output any of them.
-----Examples-----
Input
110
Output
010
Input
010
Output
010
Input
0001111
Output
0000000
Input
0111001100111011101000
Output
0011001100001011101000
-----Note-----
In the first example:
For the substrings of the length $1$ the length of the longest non-decreasing subsequnce is $1$; For $l = 1, r = 2$ the longest non-decreasing subsequnce of the substring $s_{1}s_{2}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{2}$ is $01$; For $l = 1, r = 3$ the longest non-decreasing subsequnce of the substring $s_{1}s_{3}$ is $11$ and the longest non-decreasing subsequnce of the substring $t_{1}t_{3}$ is $00$; For $l = 2, r = 3$ the longest non-decreasing subsequnce of the substring $s_{2}s_{3}$ is $1$ and the longest non-decreasing subsequnce of the substring $t_{2}t_{3}$ is $1$;
The second example is similar to the first one.
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 university student, Takahashi, has to take N examinations and pass all of them. Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination.
Takahashi thinks that he may not be able to pass all the examinations, and he has decided to ask a magician, Aoki, to change the readiness for as few examinations as possible so that he can pass all of them, while not changing the total readiness.
For Takahashi, find the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the following conditions:
* The sum of the sequence A_1, A_2, ..., A_{N} and the sum of the sequence C_1, C_2, ..., C_{N} are equal.
* For every i, B_i \leq C_i holds.
If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* 1 \leq B_i \leq 10^9
* A_i and B_i are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{N}
Output
Print the minimum possible number of indices i such that A_i and C_i are different, for a sequence C_1, C_2, ..., C_{N} that satisfies the conditions. If such a sequence C_1, C_2, ..., C_{N} cannot be constructed, print -1.
Examples
Input
3
2 3 5
3 4 1
Output
3
Input
3
2 3 3
2 2 1
Output
0
Input
3
17 7 1
25 6 14
Output
-1
Input
12
757232153 372327760 440075441 195848680 354974235 458054863 463477172 740174259 615762794 632963102 529866931 64991604
74164189 98239366 465611891 362739947 147060907 118867039 63189252 78303147 501410831 110823640 122948912 572905212
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.
Snuke has an integer sequence A of length N.
He will freely choose an integer b. Here, he will get sad if A_i and b+i are far from each other. More specifically, the sadness of Snuke is calculated as follows:
* abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))
Here, abs(x) is a function that returns the absolute value of x.
Find the minimum possible sadness of Snuke.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible sadness of Snuke.
Examples
Input
5
2 2 3 5 5
Output
2
Input
9
1 2 3 4 5 6 7 8 9
Output
0
Input
6
6 5 4 3 2 1
Output
18
Input
7
1 1 1 1 2 3 4
Output
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.
Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!
To compose a story, Stephen wrote out $n$ words consisting of the first $5$ lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story.
Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.
For example, the story consisting of three words "bac", "aaada", "e" is interesting (the letter 'a' occurs $5$ times, all other letters occur $4$ times in total). But the story consisting of two words "aba", "abcde" is not (no such letter that it occurs more than all other letters in total).
You are given a sequence of $n$ words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output $0$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 5000$) β the number of test cases. Then $t$ test cases follow.
The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of the words in the sequence. Then $n$ lines follow, each of them contains a word β a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i. e. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$; the sum of the lengths of all words over all test cases doesn't exceed $4 \cdot 10^5$.
-----Output-----
For each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story.
-----Examples-----
Input
6
3
bac
aaada
e
3
aba
abcde
aba
2
baba
baba
4
ab
ab
c
bc
5
cbdca
d
a
d
e
3
b
c
ca
Output
3
2
0
2
3
2
-----Note-----
In the first test case of the example, all $3$ words can be used to make an interesting story. The interesting story is "bac aaada e".
In the second test case of the example, the $1$-st and the $3$-rd words can be used to make an interesting story. The interesting story is "aba aba". Stephen can't use all three words at the same time.
In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is $0$.
In the fourth test case of the example, Stephen can use the $3$-rd and the $4$-th words to make an interesting story. The interesting story is "c bc".
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:
Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner.
1. Start with `n = 213` (as an example).
2. To approximate the square root of n, we will first find the greatest perfect square that is below or equal to `n`. (In this example, that would be 196, or 14 squared.) We will call the square root of this number (which means sqrt 196, or 14) `base`.
3. Then, we will take the lowest perfect square that is greater than or equal to `n`. (In this example, that would be 225, or 15 squared.)
4. Next, subtract 196 (greatest perfect square less than or equal to `n`) from `n`. (213 - 196 = **17**) We will call this value `diff_gn`.
5. Find the difference between the lowest perfect square greater than or equal to `n` and the greatest perfect square less than or equal to `n`. (225 β 196 = **29**) We will call this value `diff_lg`.
6. Your final answer is `base` + (`diff_gn` / `diff_lg`). In this example: 14 + (17 / 29) which is 14.59, rounded to the nearest hundredth.
Just to clarify, if the input is a perfect square itself, you should return the exact square of the input.
In case you are curious, the approximation (computed like above) for 213 rounded to four decimal places is 14.5862. The actual square root of 213 is 14.5945.
Inputs will always be positive whole numbers. If you are having trouble understanding it, let me know with a comment, or take a look at the second group of the example cases.
#### Some examples:
```python
approx_root(400) #=> 20
approx_root(401) #=>
# smallest perfect square above 401 is 441 or 21 squared
# greatest perfect square below 401 is 400 or 20 squared
# difference between 441 and 400 is 41
# difference between 401 and 400 is 1
# answer is 20 + (1 / 41) which becomes 20.02, rounded to the nearest hundredth
# final answer = 20.02.
approx_root(2) #=>
# smallest perfect square above 2 is 4 or 2 squared
# greatest perfect square below 2 is 1 or 1 squared
# difference between 4 and 1 is 3
# difference between 2 and 1 is 1
# answer is 1 + (1 / 3), which becomes 1.33, rounded to the nearest hundredth
# final answer = 1.33.
# math.sqrt() isn't disabled.
```
Also check out my other creations β [Square Roots: Simplifying/Desimplifying](https://www.codewars.com/kata/square-roots-simplify-slash-desimplify/), [Square and Cubic Factors](https://www.codewars.com/kata/square-and-cubic-factors), [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
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.
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiadβ'1' for a correctly identified cow and '0' otherwise.
However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.
Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substringβthat is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.
Input
The first line contains the number of questions on the olympiad n (1 β€ n β€ 100 000).
The following line contains a binary string of length n representing Kevin's results on the USAICO.
Output
Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.
Examples
Input
8
10000011
Output
5
Input
2
01
Output
2
Note
In the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.
In the second sample, Kevin can flip the entire string and still have the same score.
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 connected undirected weighted graph consisting of $n$ vertices and $m$ edges.
You need to print the $k$-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from $i$ to $j$ and from $j$ to $i$ are counted as one).
More formally, if $d$ is the matrix of shortest paths, where $d_{i, j}$ is the length of the shortest path between vertices $i$ and $j$ ($1 \le i < j \le n$), then you need to print the $k$-th element in the sorted array consisting of all $d_{i, j}$, where $1 \le i < j \le n$.
-----Input-----
The first line of the input contains three integers $n, m$ and $k$ ($2 \le n \le 2 \cdot 10^5$, $n - 1 \le m \le \min\Big(\frac{n(n-1)}{2}, 2 \cdot 10^5\Big)$, $1 \le k \le \min\Big(\frac{n(n-1)}{2}, 400\Big)$Β β the number of vertices in the graph, the number of edges in the graph and the value of $k$, correspondingly.
Then $m$ lines follow, each containing three integers $x$, $y$ and $w$ ($1 \le x, y \le n$, $1 \le w \le 10^9$, $x \ne y$) denoting an edge between vertices $x$ and $y$ of weight $w$.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices $x$ and $y$, there is at most one edge between this pair of vertices in the graph).
-----Output-----
Print one integerΒ β the length of the $k$-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from $i$ to $j$ and from $j$ to $i$ are counted as one).
-----Examples-----
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
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.
Karen has just arrived at school, and she has a math test today!
<image>
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.
Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.
The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.
Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?
Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7.
Input
The first line of input contains a single integer n (1 β€ n β€ 200000), the number of numbers written on the first row.
The next line contains n integers. Specifically, the i-th one among these is ai (1 β€ ai β€ 109), the i-th number on the first row.
Output
Output a single integer on a line by itself, the number on the final row after performing the process above.
Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7.
Examples
Input
5
3 6 9 12 15
Output
36
Input
4
3 7 5 2
Output
1000000006
Note
In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.
Karen performs the operations as follows:
<image>
The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output.
In the second test case, the numbers written on the first row are 3, 7, 5 and 2.
Karen performs the operations as follows:
<image>
The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct output.
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 Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.
Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types:
Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset. Count the number of instances of the given integer that are stored in the multiset.
But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example.
First Artem adds integer 5 to the multiset at the 1-st moment of time. Then Artem adds integer 3 to the multiset at the moment 5. Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1. Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0. Then Artem goes back in time again and removes 5 from the multiset at moment 3. Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3.
Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.
Help Artem implement time travellers multiset.
-----Input-----
The first line of the input contains a single integer n (1 β€ n β€ 100 000)Β β the number of Artem's queries.
Then follow n lines with queries descriptions. Each of them contains three integers a_{i}, t_{i} and x_{i} (1 β€ a_{i} β€ 3, 1 β€ t_{i}, x_{i} β€ 10^9)Β β type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.
-----Output-----
For each ask operation output the number of instances of integer being queried at the given moment of time.
-----Examples-----
Input
6
1 1 5
3 5 5
1 2 5
3 6 5
2 3 5
3 7 5
Output
1
2
1
Input
3
1 1 1
2 2 1
3 3 1
Output
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.
Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 10^9.
In the evening after the conference, all n scientists decided to go to the cinema. There are m movies in the cinema they came to. Each of the movies is characterized by two distinct numbersΒ β the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different).
Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.
-----Input-----
The first line of the input contains a positive integer n (1 β€ n β€ 200 000)Β β the number of scientists.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 10^9), where a_{i} is the index of a language, which the i-th scientist knows.
The third line contains a positive integer m (1 β€ m β€ 200 000)Β β the number of movies in the cinema.
The fourth line contains m positive integers b_1, b_2, ..., b_{m} (1 β€ b_{j} β€ 10^9), where b_{j} is the index of the audio language of the j-th movie.
The fifth line contains m positive integers c_1, c_2, ..., c_{m} (1 β€ c_{j} β€ 10^9), where c_{j} is the index of subtitles language of the j-th movie.
It is guaranteed that audio languages and subtitles language are different for each movie, that is b_{j} β c_{j}.
-----Output-----
Print the single integerΒ β the index of a movie to which scientists should go. After viewing this movie the number of very pleased scientists should be maximum possible. If in the cinema there are several such movies, you need to choose among them one, after viewing which there will be the maximum possible number of almost satisfied scientists.
If there are several possible answers print any of them.
-----Examples-----
Input
3
2 3 2
2
3 2
2 3
Output
2
Input
6
6 3 1 1 3 7
5
1 2 3 4 5
2 3 4 5 1
Output
1
-----Note-----
In the first sample, scientists must go to the movie with the index 2, as in such case the 1-th and the 3-rd scientists will be very pleased and the 2-nd scientist will be almost satisfied.
In the second test case scientists can go either to the movie with the index 1 or the index 3. After viewing any of these movies exactly two scientists will be very pleased and all the others will be not satisfied.
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
Alice and Bob are competing in the 50m dash.
However, in this world, the higher the AOJ rate is, the better, so the higher the AOJ rate wins.
If there is no AOJ rate on either side, there is no comparison, so there is no choice but to compete in the 50m sprint time. In this case, the one with the shorter time wins.
If the AOJ rates are the same, it is a draw, and if you have to compete in the 50m time, it is a draw if the times are the same.
Constraints
The input satisfies the following conditions.
* $ 1 \ leq T_1, T_2 \ lt 100 $
* $ -1 \ leq R_1, R_2 \ lt 2850 $
* All inputs are integers
Input
The input is given in the following format.
$ T_1 $ $ T_2 $ $ R_1 $ $ R_2 $
Each element is given separated by blanks.
$ T_1 and T_2 $ represent the time of Alice and Bob's 50m run, respectively, and $ R_1 and R_2 $ represent the rates of Alice and Bob's AOJ, respectively.
However, $ R_1 = -1 $ indicates that there is no Alice rate, and $ R_2 = -1 $ indicates that there is no Bob rate.
Output
Print "Alice" if Alice wins, "Bob" if Bob wins, and "Draw" if it's a draw on the $ 1 $ line.
Examples
Input
9 8 1000 999
Output
Alice
Input
9 8 1000 1000
Output
Draw
Input
9 8 2849 -1
Output
Bob
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 two positive integers A and B.
It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).
Constraints
* 2 β€ N β€ 10^5
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".
Examples
Input
15
Output
6
Input
100000
Output
10
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.
A version control system(VCS) is a repository of files, often the files for the source code of computer programs, with monitored access. Every change made to the source is tracked, along with who made the change, why they made it, and references to problems fixed, or enhancements introduced, by the change.
Version control systems are essential for any form of distributed, collaborative development. Whether it is the history of a wiki page or large software development project, the ability to track each change as it was made, and to reverse changes when necessary can make all the difference between a well managed and controlled process and an uncontrolled βfirst come, first servedβ system. It can also serve as a mechanism for due diligence for software projects.
In this problem we'll consider a simplified model of a development project. Let's suppose, that there are N source files in the project. All the source files are distinct and numbered from 1 to N.
A VCS, that is used for maintaining the project, contains two sequences of source files. The first sequence contains the source files, that are ignored by the VCS. If a source file is not in the first sequence, then it's considered to be unignored. The second sequence contains the source files, that are tracked by the VCS. If a source file is not in the second sequence, then it's considered to be untracked. A source file can either be or not be in any of these two sequences.
Your task is to calculate two values: the number of source files of the project, that are both tracked and ignored, and the number of source files of the project, that are both untracked and unignored.
------ 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 the test case description contains three integers N, M and K denoting the number of source files in the project, the number of ignored source files and the number of tracked source files.
The second line contains M distinct integers denoting the sequence A of ignored source files. The sequence is strictly increasing.
The third line contains K distinct integers denoting the sequence B of tracked source files. The sequence is strictly increasing.
------ Output ------
For each test case, output a single line containing two integers: the number of the source files, that are both tracked and ignored, and the number of the source files, that are both untracked and unignored.
------ Constraints ------
$1 β€ T β€ 100$
$1 β€ M, K β€ N β€ 100$
$1 β€ A_{1} < A_{2} < ... < A_{M} β€ N$
$1 β€ B_{1} < B_{2} < ... < B_{K} β€ N$
----- Sample Input 1 ------
2
7 4 6
1 4 6 7
1 2 3 4 6 7
4 2 2
1 4
3 4
----- Sample Output 1 ------
4 1
1 1
----- explanation 1 ------
In the first test case, the source files {1, 4, 6, 7} are both tracked and ignored, the source file {5} is both untracked and unignored.
In the second test case, the source file {4} is both tracked and ignored, the source file {2} is both untracked and unignored.
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 huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.
You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.
You are also given two integers $0 \le y < x < n$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$.
-----Input-----
The first line of the input contains three integers $n, x, y$ ($0 \le y < x < n \le 2 \cdot 10^5$) β the length of the number and the integers $x$ and $y$, respectively.
The second line of the input contains one decimal number consisting of $n$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.
-----Output-----
Print one integer β the minimum number of operations you should perform to obtain the number having remainder $10^y$ modulo $10^x$. In other words, the obtained number should have remainder $10^y$ when divided by $10^x$.
-----Examples-----
Input
11 5 2
11010100101
Output
1
Input
11 5 1
11010100101
Output
3
-----Note-----
In the first example the number will be $11010100100$ after performing one operation. It has remainder $100$ modulo $100000$.
In the second example the number will be $11010100010$ after performing three operations. It has remainder $10$ modulo $100000$.
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.
Maya writes weekly articles to a well known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he doesn't like to just give them away. He texts Maya a number and she needs to find out the hidden word.
The words can contain only the letter: "a", "b", "d", "e", "i", "l", "m", "n", "o", and "t".
Luckily, Maya has the key:
"a" - 6
"b" - 1
"d" - 7
"e" - 4
"i" - 3
"l" - 2
"m" - 9
"n" - 8
"o" - 0
"t" - 5
You can help Maya by writing a function that will take a number between 100 and 999999 and return a string with the word.
The input is always a number, contains only the numbers in the key.
The output should be always a string with one word, all lowercase.
Maya won't forget to thank you at the end of her article :)
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.
If you draw a few infinitely long straight lines on an infinitely wide plane, this plane will be divided into several areas. For example, if you draw a straight line, the plane will be divided into two areas. Even if you draw the same number of straight lines, the number of areas obtained will differ depending on how you draw. For example, if you draw two straight lines in parallel, you get three areas, and if you draw two straight lines perpendicular to each other, you get four areas.
<image>
Create a program that outputs the maximum number of regions that can be obtained by drawing n straight lines.
Input
Given multiple datasets. Each dataset is given n (1 β€ n β€ 10,000) on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each dataset, output the maximum number of divisions on one line.
Example
Input
1
3
Output
2
7
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.
Mr. E Ven only likes even length words.
Please create a translator so that he doesn't have to hear those pesky odd length words.
For some reason he also hates punctuation, he likes his sentences to flow.
Your translator should take in a string and output it with all odd length words having an extra letter (the last letter in the word). It should also remove all punctuation (.,?!) as well as any underscores (_).
"How did we end up here? We go?"
translated becomes->
"Howw didd we endd up here We go"
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 17:00, special agent Jack starts to escape from the enemy camp. There is a cliff in between the camp and the nearest safety zone. Jack has to climb the almost vertical cliff by stepping his feet on the blocks that cover the cliff. The cliff has slippery blocks where Jack has to spend time to take each step. He also has to bypass some blocks that are too loose to support his weight. Your mission is to write a program that calculates the minimum time to complete climbing.
Figure D-1 shows an example of cliff data that you will receive. The cliff is covered with square blocks. Jack starts cliff climbing from the ground under the cliff, by stepping his left or right foot on one of the blocks marked with 'S' at the bottom row. The numbers on the blocks are the "slippery levels". It takes t time units for him to safely put his foot on a block marked with t, where 1 β€ t β€ 9. He cannot put his feet on blocks marked with 'X'. He completes the climbing when he puts either of his feet on one of the blocks marked with 'T' at the top row.
<image>
Figure D-1: Example of Cliff Data
Jack's movement must meet the following constraints. After putting his left (or right) foot on a block, he can only move his right (or left, respectively) foot. His left foot position (lx, ly) and his right foot position (rx, ry) should satisfy lx < rx
and | lx - rx | + | ly - ry | β€ 3
. This implies that, given a position of his left foot in Figure D-2 (a), he has to place his right foot on one of the nine blocks marked with blue color. Similarly, given a position of his right foot in Figure D-2 (b), he has to place his left foot on one of the nine blocks marked with blue color.
<image>
Figure D-2: Possible Placements of Feet
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. Each dataset is formatted as follows:
> w h
> s(1,1) ... s(1,w)
> s(2,1) ... s(2,w)
> ...
> s(h,1) ... s(h,w)
>
The integers w and h are the width and the height of the matrix data of the cliff. You may assume 2 β€ w β€ 30 and 5 β€ h β€ 60. Each of the following h lines consists of w characters delimited by a space. The character s(y, x) represents the state of the block at position (x, y) as follows:
* 'S': Jack can start cliff climbing from this block.
* 'T': Jack finishes climbing when he reaches this block.
* 'X': Jack cannot put his feet on this block.
* '1' - '9' (= t): Jack has to spend t time units to put either of his feet on this block.
You can assume that it takes no time to put a foot on a block marked with 'S' or 'T'.
Output
For each dataset, print a line only having a decimal integer indicating the minimum time required for the cliff climbing, when Jack can complete it. Otherwise, print a line only having "-1" for the dataset. Each line should not have any characters other than these numbers.
Example
Input
6 6
4 4 X X T T
4 7 8 2 X 7
3 X X X 1 8
1 2 X X X 6
1 1 2 4 4 7
S S 2 3 X X
2 10
T 1
1 X
1 X
1 X
1 1
1 X
1 X
1 1
1 X
S S
2 10
T X
1 X
1 X
1 X
1 1
1 X
1 X
1 1
1 X
S S
10 10
T T T T T T T T T T
X 2 X X X X X 3 4 X
9 8 9 X X X 2 9 X 9
7 7 X 7 3 X X 8 9 X
8 9 9 9 6 3 X 5 X 5
8 9 9 9 6 X X 5 X 5
8 6 5 4 6 8 X 5 X 5
8 9 3 9 6 8 X 5 X 5
8 3 9 9 6 X X X 5 X
S S S S S S S S S S
10 7
2 3 2 3 2 3 2 3 T T
1 2 3 2 3 2 3 2 3 2
3 2 3 2 3 2 3 2 3 4
3 2 3 2 3 2 3 2 3 5
3 2 3 1 3 2 3 2 3 5
2 2 3 2 4 2 3 2 3 5
S S 2 3 2 1 2 3 2 3
0 0
Output
12
5
-1
22
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.
There are n positive integers a_1, a_2, ..., a_n. For the one move you can choose any even value c and divide by two all elements that equal c.
For example, if a=[6,8,12,6,3,12] and you choose c=6, and a is transformed into a=[3,8,12,3,3,12] after the move.
You need to find the minimal number of moves for transforming a to an array of only odd integers (each element shouldn't be divisible by 2).
Input
The first line of the input contains one integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow.
The first line of a test case contains n (1 β€ n β€ 2β
10^5) β the number of integers in the sequence a. The second line contains positive integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The sum of n for all test cases in the input doesn't exceed 2β
10^5.
Output
For t test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by 2).
Example
Input
4
6
40 6 40 3 20 1
1
1024
4
2 4 8 16
3
3 1 7
Output
4
10
4
0
Note
In the first test case of the example, the optimal sequence of moves can be as follows:
* before making moves a=[40, 6, 40, 3, 20, 1];
* choose c=6;
* now a=[40, 3, 40, 3, 20, 1];
* choose c=40;
* now a=[20, 3, 20, 3, 20, 1];
* choose c=20;
* now a=[10, 3, 10, 3, 10, 1];
* choose c=10;
* now a=[5, 3, 5, 3, 5, 1] β all numbers are odd.
Thus, all numbers became odd after 4 moves. In 3 or fewer moves, you cannot make them all odd.
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 kata is from check py.checkio.org
You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0.
Let's look at a few examples:
* array = [1, 2, 3, 4] and N = 2, then the result is 3^2 == 9;
* array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -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.
We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j).
Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares.
Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game.
When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.
The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.
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 official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 β€ i β€ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.
Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.
To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.
Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.
Input
The first input line contains two integers n and m (1 β€ n β€ 105; 1 β€ m β€ 106) β the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 β€ ti, Ti, xi, costi β€ 106). The numbers in the lines are separated by single spaces.
Output
Print the only integer β the minimum number of roubles the organizers will have to spend to transport all schoolchildren.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
2 10
30 35 1 100
20 35 10 10
Output
120
Input
3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000
Output
200065
Note
In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.
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.
Nezzar has $n$ balls, numbered with integers $1, 2, \ldots, n$. Numbers $a_1, a_2, \ldots, a_n$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $a_i \leq a_{i+1}$ for all $1 \leq i < n$.
Nezzar wants to color the balls using the minimum number of colors, such that the following holds.
For any color, numbers on balls will form a strictly increasing sequence if he keeps balls with this chosen color and discards all other balls.
Note that a sequence with the length at most $1$ is considered as a strictly increasing sequence.
Please help Nezzar determine the minimum number of colors.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) β the number of testcases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 100$).
The second line of each test case contains $n$ integers $a_1,a_2,\ldots,a_n$ ($1 \le a_i \le n$). It is guaranteed that $a_1 \leq a_2 \leq \ldots \leq a_n$.
-----Output-----
For each test case, output the minimum number of colors Nezzar can use.
-----Examples-----
Input
5
6
1 1 1 2 3 4
5
1 1 2 2 3
4
2 2 2 2
3
1 2 3
1
1
Output
3
2
4
1
1
-----Note-----
Let's match each color with some numbers. Then:
In the first test case, one optimal color assignment is $[1,2,3,3,2,1]$.
In the second test case, one optimal color assignment is $[1,2,1,2,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.
We, the researchers who discovered and investigated the ancient nation Iwashiro, finally discovered the temple in the center of Iwashiro. A lithograph dedicated to the god of Iwashiro was stored in the temple. On the lithograph, two strings were written, one for each sentence and one for the spell.
In Iwashiro, how many times a spell appears in a sentence has an important meaning. However, it is considered that all the characters contained in the spell appear in order, and some of them appear in the sentence in a discrete manner once. For example, if the sentence is "abab" and the spell is "ab", then "ab" appears three times in "abab", including non-continuous ones (three ways: abab, abab, and abab).
Create a program that prints how many times a spell appears in a sentence when it is given a sentence and a spell.
Input
The input is given in the following format.
t
b b
The first line is given the string t that represents the text written on the lithograph. The second line is given the string b that represents the spell written on the lithograph. Both strings are composed of only lowercase letters and have a length of 1 or more and 1000 or less.
Output
Prints how many times a spell appears in a sentence on one line. However, the value to be output can be very large, so instead output the remainder divided by 1,000,000,007.
Examples
Input
abab
ab
Output
3
Input
aaaabaaaabaaaabaaaab
aaaaa
Output
4368
Input
data
structure
Output
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.
Boolean Expression Compressor
You are asked to build a compressor for Boolean expressions that transforms expressions to the shortest form keeping their meaning.
The grammar of the Boolean expressions has terminals `0` `1` `a` `b` `c` `d` `-` `^` `*` `(` `)`, start symbol <E> and the following production rule:
> <E> ::= `0` | `1` | `a` | `b` | `c` | `d` | `-`<E> | `(`<E>`^`<E>`)` | `(`<E>`*`<E>`)`
Letters `a`, `b`, `c` and `d` represent Boolean variables that have values of either `0` or `1`. Operators are evaluated as shown in the Table below. In other words, `-` means negation (NOT), `^` means exclusive disjunction (XOR), and `*` means logical conjunction (AND).
Table: Evaluations of operators
<image>
Write a program that calculates the length of the shortest expression that evaluates equal to the given expression with whatever values of the four variables.
For example, `0`, that is the first expression in the sample input, cannot be shortened further. Therefore the shortest length for this expression is 1.
For another example, `(a*(1*b))`, the second in the sample input, always evaluates equal to `(a*b)` and `(b*a)`, which are the shortest. The output for this expression, thus, should be `5`.
Input
The input consists of multiple datasets. A dataset consists of one line, containing an expression conforming to the grammar described above. The length of the expression is less than or equal to 16 characters.
The end of the input is indicated by a line containing one Β`.`Β (period). The number of datasets in the input is at most 200.
Output
For each dataset, output a single line containing an integer which is the length of the shortest expression that has the same value as the given expression for all combinations of values in the variables.
Sample Input
0
(a*(1*b))
(1^a)
(-(-a*-b)*a)
(a^(b^(c^d)))
.
Output for the Sample Input
1
5
2
1
13
Example
Input
0
(a*(1*b))
(1^a)
(-(-a*-b)*a)
(a^(b^(c^d)))
.
Output
1
5
2
1
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.
Snuke is visiting a shop in Tokyo called 109 to buy some logs.
He wants n logs: one of length 1, one of length 2, ..., and one of length n.
The shop has n+1 logs in stock: one of length 1, one of length 2, \dots, and one of length n+1. Each of these logs is sold for 1 yen (the currency of Japan).
He can cut these logs as many times as he wants after buying them. That is, he can get k logs of length L_1, \dots, L_k from a log of length L, where L = L_1 + \dots + L_k. He can also throw away unwanted logs.
Snuke wants to spend as little money as possible to get the logs he wants.
Find the minimum amount of money needed to get n logs of length 1 to n.
-----Constraints-----
- 1 \leq n \leq 10^{18}
-----Input-----
Input is given from Standard Input in the following format:
n
-----Output-----
Print the minimum amount of money needed to get n logs of length 1 to n.
-----Sample Input-----
4
-----Sample Output-----
3
One way to get the logs he wants with 3 yen is:
- Buy logs of length 2, 4, and 5.
- Cut the log of length 5 into two logs of length 1 each and a log of length 3.
- Throw away one of the logs of length 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.
You are given a string $s$ consisting of $n$ lowercase Latin letters.
You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.
String $s = s_1 s_2 \dots s_n$ is lexicographically smaller than string $t = t_1 t_2 \dots t_m$ if $n < m$ and $s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$ or there exists a number $p$ such that $p \le min(n, m)$ and $s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$ and $s_p < t_p$.
For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) β the length of $s$.
The second line of the input contains exactly $n$ lowercase Latin letters β the string $s$.
-----Output-----
Print one string β the smallest possible lexicographically string that can be obtained by removing at most one character from the string $s$.
-----Examples-----
Input
3
aaa
Output
aa
Input
5
abcda
Output
abca
-----Note-----
In the first example you can remove any character of $s$ to obtain the string "aa".
In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".
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 positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2 + 3 + 5 + 7 + 11 + 13, 11 + 13 + 17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20.
Your mission is to write a program that reports the number of representations for the given positive integer.
Input
The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero.
Output
The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output.
Example
Input
2
3
17
41
20
666
12
53
0
Output
1
1
2
3
0
0
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.
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $n$ players arranged in a circle, so that for all $j$ such that $2 \leq j \leq n$, player $j - 1$ is to the left of the player $j$, and player $j$ is to the right of player $j - 1$. Additionally, player $n$ is to the left of player $1$, and player $1$ is to the right of player $n$.
Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $0$, $1$, or $2$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $1$ other player, then they should logically attack that player in response. If instead a player is being attacked by $0$ or $2$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.
Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $n$ players in the game to make them instead attack another player Β β i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left.
Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The descriptions of the test cases follows.
The first line of each test case contains one integer $n$ ($3 \leq n \leq 2 \cdot 10^5$) Β β the amount of players (and therefore beds) in this game of Bed Wars.
The second line of each test case contains a string $s$ of length $n$. The $j$-th character of $s$ is equal to L if the $j$-th player is attacking the player to their left, and R if the $j$-th player is attacking the player to their right.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy.
It can be proven that it is always possible for Omkar to achieve this under the given constraints.
-----Example-----
Input
5
4
RLRL
6
LRRRRL
8
RLLRRRLL
12
LLLLRRLRRRLL
5
RRRRR
Output
0
1
1
3
2
-----Note-----
In the first test case, players $1$ and $2$ are attacking each other, and players $3$ and $4$ are attacking each other. Each player is being attacked by exactly $1$ other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer $0$.
In the second test case, not every player acts logically: for example, player $3$ is attacked only by player $2$, but doesn't attack him in response. Omkar can talk to player $3$ to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer $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.
Notice that the memory limit is non-standard.
Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.
All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the i-th opening bracket he remembers the segment [l_{i}, r_{i}], containing the distance to the corresponding closing bracket.
Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [l_{i}, r_{i}].
Help Arthur restore his favorite correct bracket sequence!
-----Input-----
The first line contains integer n (1 β€ n β€ 600), the number of opening brackets in Arthur's favorite correct bracket sequence.
Next n lines contain numbers l_{i} and r_{i} (1 β€ l_{i} β€ r_{i} < 2n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one.
The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right.
-----Output-----
If it is possible to restore the correct bracket sequence by the given data, print any possible choice.
If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line "IMPOSSIBLE" (without the quotes).
-----Examples-----
Input
4
1 1
1 1
1 1
1 1
Output
()()()()
Input
3
5 5
3 3
1 1
Output
((()))
Input
3
5 5
3 3
2 2
Output
IMPOSSIBLE
Input
3
2 3
1 4
1 4
Output
(())()
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.
Wherever the destination is, whoever we meet, let's render this song together.
On a Cartesian coordinate plane lies a rectangular stage of size w Γ h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.
On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups: Vertical: stands at (x_{i}, 0), moves in positive y direction (upwards); Horizontal: stands at (0, y_{i}), moves in positive x direction (rightwards). [Image]
According to choreography, the i-th dancer should stand still for the first t_{i} milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on. [Image]
Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.
-----Input-----
The first line of input contains three space-separated positive integers n, w and h (1 β€ n β€ 100 000, 2 β€ w, h β€ 100 000) β the number of dancers and the width and height of the stage, respectively.
The following n lines each describes a dancer: the i-th among them contains three space-separated integers g_{i}, p_{i}, and t_{i} (1 β€ g_{i} β€ 2, 1 β€ p_{i} β€ 99 999, 0 β€ t_{i} β€ 100 000), describing a dancer's group g_{i} (g_{i} = 1 β vertical, g_{i} = 2 β horizontal), position, and waiting time. If g_{i} = 1 then p_{i} = x_{i}; otherwise p_{i} = y_{i}. It's guaranteed that 1 β€ x_{i} β€ w - 1 and 1 β€ y_{i} β€ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
-----Output-----
Output n lines, the i-th of which contains two space-separated integers (x_{i}, y_{i}) β the stopping position of the i-th dancer in the input.
-----Examples-----
Input
8 10 8
1 1 10
1 4 13
1 7 1
1 8 2
2 2 0
2 5 14
2 6 0
2 6 1
Output
4 8
10 5
8 8
10 6
10 2
1 8
7 8
10 6
Input
3 2 3
1 1 2
2 1 1
1 1 5
Output
1 3
2 1
1 3
-----Note-----
The first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure. [Image]
In the second example, no dancers collide.
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 ask you to select some number of positive integers, and calculate the sum of them.
It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.
Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.
If the objective is achievable, print YES. Otherwise, print NO.
-----Constraints-----
- 1 β€ A β€ 100
- 1 β€ B β€ 100
- 0 β€ C < B
-----Input-----
Input is given from Standard Input in the following format:
A B C
-----Output-----
Print YES or NO.
-----Sample Input-----
7 5 1
-----Sample Output-----
YES
For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 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.
Given an integer N, let us consider a triangle of numbers of N lines in which a number a_{11} appears in the first line, two numbers a_{21} and a_{22} appear in the second line, three numbers a_{31}, a_{32} and a_{33} appear in the third line, etc. In general, i numbers a_{i1}, a_{i2} \dots a_{ii} appear in the i^{th} line for all 1 β€ i β€ N. Develop a program that will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
on each path the next number is located on the row below, more precisely either directly below or below and one place to the right.
Warning: large Input/Output data, be careful with certain languages
------ Input Format ------
- The first line of the input contains an integer T, the number of test cases.
- Then T test cases follow. Each test case starts with an integer N, the number of rows. Then N lines follow where in i^{th} line contains i integers a_{i1}, a_{i2} \dots a_{ii}.
------ Output Format ------
For each test case print the maximum path sum in a separate line.
------ Constraints ------
$1 β€ T β€ 1000$
$1 β€ N < 100$
$0 β€ a_{ij} < 100$
----- Sample Input 1 ------
2
3
1
2 1
1 2 3
4
1
1 2
4 1 2
2 3 1 1
----- Sample Output 1 ------
5
9
----- explanation 1 ------
Test case 1:
There are a total of $4$ paths
- $(1,1) \rightarrow (2, 1) \rightarrow (3, 1)$ with sum equal to $4$.
- $(1,1) \rightarrow (2, 1) \rightarrow (3, 2)$ with sum equal to $5$.
- $(1,1) \rightarrow (2, 2) \rightarrow (3, 2)$ with sum equal to $4$.
- $(1,1) \rightarrow (2, 2) \rightarrow (3, 3)$ with sum equal to $5$.
Therefore, the maximum sum over all paths is equal to $5$.
Test case 2:
There are a total of $8$ paths
- $(1,1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (4, 1)$ with sum equal to $8$.
- $(1,1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (4, 2)$ with sum equal to $9$.
- $(1,1) \rightarrow (2, 1) \rightarrow (3, 2) \rightarrow (4, 2)$ with sum equal to $7$.
- $(1,1) \rightarrow (2, 1) \rightarrow (3, 2) \rightarrow (4, 3)$ with sum equal to $4$.
- $(1,1) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (4, 2)$ with sum equal to $7$.
- $(1,1) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (4, 3)$ with sum equal to $5$.
- $(1,1) \rightarrow (2, 2) \rightarrow (3, 3) \rightarrow (4, 3)$ with sum equal to $6$.
- $(1,1) \rightarrow (2, 2) \rightarrow (3, 3) \rightarrow (4, 4)$ with sum equal to $6$.
Therefore, the maximum sum over all paths is equal to $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.
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to a_{i}. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.
-----Input-----
The first line contains one integer n (1 β€ n β€ 360) Β β the number of pieces into which the delivered pizza was cut.
The second line contains n integers a_{i} (1 β€ a_{i} β€ 360) Β β the angles of the sectors into which the pizza was cut. The sum of all a_{i} is 360.
-----Output-----
Print one integer Β β the minimal difference between angles of sectors that will go to Vasya and Petya.
-----Examples-----
Input
4
90 90 90 90
Output
0
Input
3
100 100 160
Output
40
Input
1
360
Output
360
Input
4
170 30 150 10
Output
0
-----Note-----
In first sample Vasya can take 1 and 2 pieces, Petya can take 3 and 4 pieces. Then the answer is |(90 + 90) - (90 + 90)| = 0.
In third sample there is only one piece of pizza that can be taken by only one from Vasya and Petya. So the answer is |360 - 0| = 360.
In fourth sample Vasya can take 1 and 4 pieces, then Petya will take 2 and 3 pieces. So the answer is |(170 + 10) - (30 + 150)| = 0.
Picture explaning fourth sample:
[Image]
Both red and green sectors consist of two adjacent pieces of pizza. So Vasya can take green sector, then Petya will take red sector.
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.
One day, the teacher came up with the following game.
The game uses n cards with one number from 1 to 10 and proceeds as follows.
1. The teacher pastes n cards on the blackboard in a horizontal row so that the numbers can be seen, and declares an integer k (k β₯ 1) to the students. For n cards arranged in a horizontal row, let Ck be the maximum product of k consecutive cards. Also, let Ck'when the teachers line up.
2. Students consider increasing Ck by looking at the row of cards affixed in 1. If the Ck can be increased by swapping two cards, the student's grade will increase by Ck --Ck'points. End the game when someone gets a grade.
Your job is to write a program that fills in a row of cards arranged by the teacher and outputs the maximum grades the student can get. However, if you can only lower Ck by selecting any two of them and exchanging them (Ck --Ck'<0), output the string "NO GAME" (without quotation marks).
<image>
When the cards arranged by the teacher are 7, 2, 3, 5. By exchanging 7 and 3 at this time, the student gets a maximum of 35 -15 = 20 grade points.
Hint
In the sample, C2'= 35, and no matter which two sheets are rearranged from here, the maximum value of C2 does not exceed 35. Therefore, students can get a maximum of 0 grades.
Constraints
* All inputs are integers
* 2 β€ n β€ 100
* 1 β€ k β€ 5
* k β€ n
* 1 β€ ci β€ 10 (1 β€ i β€ n)
* The number of test cases does not exceed 100.
Input
The input consists of multiple test cases. One test case follows the format below.
n k
c1
c2
c3
...
cn
n is the number of cards the teacher arranges, and k is the integer to declare. Also, ci (1 β€ i β€ n) indicates the number written on the card. Also, suppose that the teacher pastes it on the blackboard sideways in this order. The end of the input is indicated by a line where two 0s are separated by a single space.
Output
Print the maximum grade or string "NO GAME" (without quotation marks) that students will get on one line for each test case.
Example
Input
4 2
2
3
7
5
0 0
Output
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.
You are visiting a large electronics store to buy a refrigerator and a microwave.
The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen.
You have M discount tickets. With the i-th ticket ( 1 \le i \le M ), you can get a discount of c_i yen from the total price when buying the x_i-th refrigerator and the y_i-th microwave together. Only one ticket can be used at a time.
You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.
Constraints
* All values in input are integers.
* 1 \le A \le 10^5
* 1 \le B \le 10^5
* 1 \le M \le 10^5
* 1 \le a_i , b_i , c_i \le 10^5
* 1 \le x_i \le A
* 1 \le y_i \le B
* c_i \le a_{x_i} + b_{y_i}
Input
Input is given from Standard Input in the following format:
A B M
a_1 a_2 ... a_A
b_1 b_2 ... b_B
x_1 y_1 c_1
\vdots
x_M y_M c_M
Output
Print the answer.
Examples
Input
2 3 1
3 3
3 3 3
1 2 1
Output
5
Input
1 1 2
10
10
1 1 5
1 1 10
Output
10
Input
2 2 1
3 5
3 5
2 2 2
Output
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.
Hands that shed innocent blood!
There are n guilty people in a line, the i-th of them holds a claw with length L_{i}. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j β₯ i - L_{i}.
You are given lengths of the claws. You need to find the total number of alive people after the bell rings.
-----Input-----
The first line contains one integer n (1 β€ n β€ 10^6) β the number of guilty people.
Second line contains n space-separated integers L_1, L_2, ..., L_{n} (0 β€ L_{i} β€ 10^9), where L_{i} is the length of the i-th person's claw.
-----Output-----
Print one integer β the total number of alive people after the bell rings.
-----Examples-----
Input
4
0 1 0 10
Output
1
Input
2
0 0
Output
2
Input
10
1 1 3 0 0 0 2 1 0 3
Output
3
-----Note-----
In first sample the last person kills everyone in front of him.
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.
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.
They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.
Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.
-----Constraints-----
- 2 \leq N \leq 2 \times 10^5
- -10^{9} \leq a_i \leq 10^{9}
- a_i is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{N}
-----Output-----
Print the answer.
-----Sample Input-----
6
1 2 3 4 5 6
-----Sample Output-----
1
If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.
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 Japan, temperature is usually expressed using the Celsius (β) scale. In America, they used the Fahrenheit (β) scale instead. $20$ degrees Celsius is roughly equal to $68$ degrees Fahrenheit. A phrase such as "Todayβs temperature is $68$ degrees" is commonly encountered while you are in America.
A value in Fahrenheit can be converted to Celsius by first subtracting $32$ and then multiplying by $\frac{5}{9}$. A simplified method may be used to produce a rough estimate: first subtract $30$ and then divide by $2$. Using the latter method, $68$ Fahrenheit is converted to $19$ Centigrade, i.e., $\frac{(68-30)}{2}$.
Make a program to convert Fahrenheit to Celsius using the simplified method: $C = \frac{F - 30}{2}$.
Input
The input is given in the following format.
$F$
The input line provides a temperature in Fahrenheit $F$ ($30 \leq F \leq 100$), which is an integer divisible by $2$.
Output
Output the converted Celsius temperature in a line.
Examples
Input
68
Output
19
Input
50
Output
10
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 planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.
Find the minimum total fare when the optimal choices are made for trains and buses.
-----Constraints-----
- 1 \leq A \leq 1 000
- 1 \leq B \leq 1 000
- 1 \leq C \leq 1 000
- 1 \leq D \leq 1 000
- All input values are integers.
-----Input-----
Input is given from Standard Input in the following format:
A
B
C
D
-----Output-----
Print the minimum total fare.
-----Sample Input-----
600
300
220
420
-----Sample Output-----
520
The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.
Therefore, the minimum total fare is 300 + 220 = 520 yen.
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 time no story, no theory. The examples below show you how to write function `accum`:
**Examples:**
```
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"
```
The parameter of accum is a string which includes only letters from `a..z` and `A..Z`.
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 two friends. You want to present each of them several positive integers. You want to present cnt_1 numbers to the first friend and cnt_2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.
In addition, the first friend does not like the numbers that are divisible without remainder by prime number x. The second one does not like the numbers that are divisible without remainder by prime number y. Of course, you're not going to present your friends numbers they don't like.
Your task is to find such minimum number v, that you can form presents using numbers from a set 1, 2, ..., v. Of course you may choose not to present some numbers at all.
A positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.
-----Input-----
The only line contains four positive integers cnt_1, cnt_2, x, y (1 β€ cnt_1, cnt_2 < 10^9; cnt_1 + cnt_2 β€ 10^9; 2 β€ x < y β€ 3Β·10^4)Β β the numbers that are described in the statement. It is guaranteed that numbers x, y are prime.
-----Output-----
Print a single integer β the answer to the problem.
-----Examples-----
Input
3 1 2 3
Output
5
Input
1 3 2 3
Output
4
-----Note-----
In the first sample you give the set of numbers {1, 3, 5} to the first friend and the set of numbers {2} to the second friend. Note that if you give set {1, 3, 5} to the first friend, then we cannot give any of the numbers 1, 3, 5 to the second friend.
In the second sample you give the set of numbers {3} to the first friend, and the set of numbers {1, 2, 4} to the second friend. Thus, the answer to the problem 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.
Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.
For permutation p = p_0, p_1, ..., p_{n}, Polo has defined its beauty β number $(0 \oplus p_{0}) +(1 \oplus p_{1}) + \cdots +(n \oplus p_{n})$.
Expression $x \oplus y$ means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal β as "xor".
Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.
-----Input-----
The single line contains a positive integer n (1 β€ n β€ 10^6).
-----Output-----
In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m.
If there are several suitable permutations, you are allowed to print any of them.
-----Examples-----
Input
4
Output
20
0 2 1 4 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.
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials.
He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally:
Let a0, a1, ..., an denote the coefficients, so <image>. Then, a polynomial P(x) is valid if all the following conditions are satisfied:
* ai is integer for every i;
* |ai| β€ k for every i;
* an β 0.
Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) β 0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ.
Input
The first line contains two integers n and k (1 β€ n β€ 200 000, 1 β€ k β€ 109) β the degree of the polynomial and the limit for absolute values of coefficients.
The second line contains n + 1 integers a0, a1, ..., an (|ai| β€ k, an β 0) β describing a valid polynomial <image>. It's guaranteed that P(2) β 0.
Output
Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0.
Examples
Input
3 1000000000
10 -9 -3 5
Output
3
Input
3 12
10 -9 -3 5
Output
2
Input
2 20
14 -7 19
Output
0
Note
In the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3.
Limak can change one coefficient in three ways:
1. He can set a0 = - 10. Then he would get Q(x) = - 10 - 9x - 3x2 + 5x3 and indeed Q(2) = - 10 - 18 - 12 + 40 = 0.
2. Or he can set a2 = - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0.
3. Or he can set a1 = - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0.
In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time.
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.
It is winter now, and Max decided it's about time he watered the garden.
The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed x_{i}), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed x_{i} is turned on, then after one second has passed, the bed x_{i} will be watered; after two seconds have passed, the beds from the segment [x_{i} - 1, x_{i} + 1] will be watered (if they exist); after j seconds have passed (j is an integer number), the beds from the segment [x_{i} - (j - 1), x_{i} + (j - 1)] will be watered (if they exist). Nothing changes during the seconds, so, for example, we can't say that the segment [x_{i} - 2.5, x_{i} + 2.5] will be watered after 2.5 seconds have passed; only the segment [x_{i} - 2, x_{i} + 2] will be watered at that moment.
$\left. \begin{array}{|c|c|c|c|c|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline \end{array} \right.$ The garden from test 1. White colour denotes a garden bed without a tap, red colour β a garden bed with a tap.
$\left. \begin{array}{|c|c|c|c|c|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline \end{array} \right.$ The garden from test 1 after 2 seconds have passed after turning on the tap. White colour denotes an unwatered garden bed, blue colour β a watered bed.
Max wants to turn on all the water taps at the same moment, and now he wonders, what is the minimum number of seconds that have to pass after he turns on some taps until the whole garden is watered. Help him to find the answer!
-----Input-----
The first line contains one integer t β the number of test cases to solve (1 β€ t β€ 200).
Then t test cases follow. The first line of each test case contains two integers n and k (1 β€ n β€ 200, 1 β€ k β€ n) β the number of garden beds and water taps, respectively.
Next line contains k integers x_{i} (1 β€ x_{i} β€ n) β the location of i-th water tap. It is guaranteed that for each $i \in [ 2 ; k ]$ condition x_{i} - 1 < x_{i} holds.
It is guaranteed that the sum of n over all test cases doesn't exceed 200.
Note that in hacks you have to set t = 1.
-----Output-----
For each test case print one integer β the minimum number of seconds that have to pass after Max turns on some of the water taps, until the whole garden is watered.
-----Example-----
Input
3
5 1
3
3 3
1 2 3
4 1
1
Output
3
1
4
-----Note-----
The first example consists of 3 tests:
There are 5 garden beds, and a water tap in the bed 3. If we turn it on, then after 1 second passes, only bed 3 will be watered; after 2 seconds pass, beds [1, 3] will be watered, and after 3 seconds pass, everything will be watered. There are 3 garden beds, and there is a water tap in each one. If we turn all of them on, then everything will be watered after 1 second passes. There are 4 garden beds, and only one tap in the bed 1. It will take 4 seconds to water, for example, bed 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.
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.
The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 β€ i β€ n - 1) on every floor x, where a β€ x β€ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building.
[Image]
The picture illustrates the first example.
You have given k pairs of locations (t_{a}, f_{a}), (t_{b}, f_{b}): floor f_{a} of tower t_{a} and floor f_{b} of tower t_{b}. For each pair you need to determine the minimum walking time between these locations.
-----Input-----
The first line of the input contains following integers:
n: the number of towers in the building (1 β€ n β€ 10^8), h: the number of floors in each tower (1 β€ h β€ 10^8), a and b: the lowest and highest floor where it's possible to move between adjacent towers (1 β€ a β€ b β€ h), k: total number of queries (1 β€ k β€ 10^4).
Next k lines contain description of the queries. Each description consists of four integers t_{a}, f_{a}, t_{b}, f_{b} (1 β€ t_{a}, t_{b} β€ n, 1 β€ f_{a}, f_{b} β€ h). This corresponds to a query to find the minimum travel time between f_{a}-th floor of the t_{a}-th tower and f_{b}-th floor of the t_{b}-th tower.
-----Output-----
For each query print a single integer: the minimum walking time between the locations in minutes.
-----Example-----
Input
3 6 2 3 3
1 2 1 3
1 4 3 4
1 2 2 3
Output
1
4
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.
We have a rectangular grid of squares 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. On this grid, there is a piece, which is initially placed at square (s_r,s_c).
Takahashi and Aoki will play a game, where each player has a string of length N. Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: `L`, `R`, `U` and `D`.
The game consists of N steps. The i-th step proceeds as follows:
* First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.
* Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.
Here, to move the piece in the direction of `L`, `R`, `U` and `D`, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.
Takahashi wants to remove the piece from the grid in one of the N steps. Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid. Determine if the piece will remain on the grid at the end of the game when both players play optimally.
Constraints
* 2 \leq H,W \leq 2 \times 10^5
* 2 \leq N \leq 2 \times 10^5
* 1 \leq s_r \leq H
* 1 \leq s_c \leq W
* |S|=|T|=N
* S and T consists of the four kinds of letters `L`, `R`, `U` and `D`.
Input
Input is given from Standard Input in the following format:
H W N
s_r s_c
S
T
Output
If the piece will remain on the grid at the end of the game, print `YES`; otherwise, print `NO`.
Examples
Input
2 3 3
2 2
RRL
LUD
Output
YES
Input
4 3 5
2 2
UDRRR
LLDUD
Output
NO
Input
5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD
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.
For an array $b$ of length $m$ we define the function $f$ as $ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $
where $\oplus$ is bitwise exclusive OR.
For example, $f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$
You are given an array $a$ and a few queries. Each query is represented as two integers $l$ and $r$. The answer is the maximum value of $f$ on all continuous subsegments of the array $a_l, a_{l+1}, \ldots, a_r$.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 5000$)Β β the length of $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$)Β β the elements of the array.
The third line contains a single integer $q$ ($1 \le q \le 100\,000$)Β β the number of queries.
Each of the next $q$ lines contains a query represented as two integers $l$, $r$ ($1 \le l \le r \le n$).
-----Output-----
Print $q$ linesΒ β the answers for the queries.
-----Examples-----
Input
3
8 4 1
2
2 3
1 2
Output
5
12
Input
6
1 2 4 8 16 32
4
1 6
2 5
3 4
1 2
Output
60
30
12
3
-----Note-----
In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.
In second sample, optimal segment for first query are $[3,6]$, for second query β $[2,5]$, for third β $[3,4]$, for fourth β $[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.
At Akabeko Elementary School, all the students participate in a slightly unusual jogging. Students run their own lap courses at their own pace. After going around each of your courses, you will be returned to elementary school. How many laps do they all meet at the same time in elementary school after they all start elementary school at the same time?
Enter the number of students n, the distance d (km) per lap of each student's course, and the running speed v (km / hour) of each student. To do this, create a program that outputs how many laps each student has made. Please note that each student will not run more than 231-1 laps.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
d1 v1
d2 v2
::
dn vn
The first line gives the number of students n (2 β€ n β€ 10). The next n lines give the distance di (1 β€ di β€ 10000) and the running speed vi (1 β€ vi β€ 10000) for one lap of the course of the i-th student.
The number of datasets does not exceed 2000.
Output
Outputs the number of laps for each student for each input dataset. Please output the number of laps of each student on one line according to the order of input.
Example
Input
2
4 3
5 4
5
789 289
166 46
9 4
617 252
972 303
2
8 5
32 20
0
Output
15
16
1598397732
1209243492
1939462992
1782294192
1360317793
1
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.
Now I have a card with n numbers on it. Consider arranging some or all of these appropriately to make numbers. Find the number obtained by adding all the numbers created at this time.
For example, if you have 1 and 2, you will get 4 numbers 1, 2, 12, 21 so the total number is 36. Even if the same numbers are produced as a result of arranging them, if they are arranged differently, they are added separately. For example, if you have a card called 1 and a card called 11, there are two ways to arrange them so that they are 111, but add them as different ones. There are no leading zero cards among the cards, and we do not accept numbers that lead to zero reading. Output the answer divided by 1,000,000,007.
Input
The input is given in the form:
> n
> a1
> a2
> ...
> an
>
The first line contains n (1 β€ n β€ 200), which represents the number of cards, and the next n lines contain the number ai (0 β€ ai <10000) on each card. Also, the same number is never written on multiple cards.
Output
Output the sum of all the numbers you can make divided by 1,000,000,007 on one line.
Examples
Input
2
1
2
Output
36
Input
2
1
11
Output
234
Input
4
0
4
7
8
Output
135299
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 **bouncy number** is a positive integer whose digits neither increase nor decrease. For example, `1235` is an increasing number, `5321` is a decreasing number, and `2351` is a bouncy number. By definition, all numbers under `100` are non-bouncy, and `101` is the first bouncy number. To complete this kata, you must write a function that takes a number and determines if it is bouncy.
Input numbers will always be positive integers, but it never hurts to throw in some error handling : )
For clarification, the bouncy numbers between `100` and `125` are: `101, 102, 103, 104, 105, 106, 107, 108, 109, 120, and 121`.
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.