question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
A crop circle suddenly appeared on the vast agricultural land of Argentina. A total of n crop circles were confirmed, including overlapping, popping, large, and small ones.
When a mystery hunter tried to capture the whole picture of a crop circle from the air, he found it difficult to show the beautiful pattern in the image because the outline of each circle was not clear.
Therefore, the mystery hunter proposed to emphasize the contour by installing a string of special material along the contour.
The part where the string is installed is the part on the circumference of one crop circle that is not included in any other crop circle.
The film crew asked you to create a program to measure the required string length. Enter the center coordinates and radius of each crop circle and create a program to report the length of the string to be installed.
For reference, the first and second cases of the input / output examples are shown in FIGS. 1 and 2, respectively. The part of the string is shown by a thick line.
<image>
Figure 1
<image>
Figure 2
Constraints
* n β€ 100
* -1000 β€ xi, yi β€ 1000
* 0 <ri β€ 100
Input
Multiple datasets are given as input. Each dataset is given in the following format:
n (number of crop circles: integer)
x1 y1 r1 (center coordinates and radius of the first circle: real numbers separated by blanks)
x2 y2 r2 (center coordinates and radius of the second circle: real numbers separated by blanks)
..
..
xn yn rn (center coordinates and radius of the nth circle: real numbers separated by blanks)
When n is 0, it indicates the end of input.
Output
Output the string length on one line for each dataset. The output may contain an error of 0.000001 or less.
Example
Input
4
6 4 2
4 7 3
7 10 3
13 6 1
4
7 4 2
4 7 3
7 10 3
11 6 3
0
Output
39.664699289572
45.627024663706
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules.
There are mines on the field, for each the coordinates of its location are known ($x_i, y_i$). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates all mines vertically and horizontally at a distance of $k$ (two perpendicular lines). As a result, we get an explosion on the field in the form of a "plus" symbol ('+'). Thus, one explosion can cause new explosions, and so on.
Also, Polycarp can detonate anyone mine every second, starting from zero seconds. After that, a chain reaction of explosions also takes place. Mines explode instantly and also instantly detonate other mines according to the rules described above.
Polycarp wants to set a new record and asks you to help him calculate in what minimum number of seconds all mines can be detonated.
-----Input-----
The first line of the input contains an integer $t$ ($1 \le t \le 10^4$) β the number of test cases in the test.
An empty line is written in front of each test suite.
Next comes a line that contains integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $0 \le k \le 10^9$) β the number of mines and the distance that hit by mines during the explosion, respectively.
Then $n$ lines follow, the $i$-th of which describes the $x$ and $y$ coordinates of the $i$-th mine and the time until its explosion ($-10^9 \le x, y \le 10^9$, $0 \le timer \le 10^9$). It is guaranteed that all mines have different coordinates.
It is guaranteed that the sum of the values $n$ over all test cases in the test does not exceed $2 \cdot 10^5$.
-----Output-----
Print $t$ lines, each of the lines must contain the answer to the corresponding set of input data β the minimum number of seconds it takes to explode all the mines.
-----Examples-----
Input
3
5 0
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
5 2
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
6 1
1 -1 3
0 -1 9
0 1 7
-1 0 1
-1 1 9
-1 -1 7
Output
2
1
0
-----Note-----
Picture from examples
First example:
$0$ second: we explode a mine at the cell $(2, 2)$, it does not detonate any other mine since $k=0$.
$1$ second: we explode the mine at the cell $(0, 1)$, and the mine at the cell $(0, 0)$ explodes itself.
$2$ second: we explode the mine at the cell $(1, 1)$, and the mine at the cell $(1, 0)$ explodes itself.
Second example:
$0$ second: we explode a mine at the cell $(2, 2)$ we get:
$1$ second: the mine at coordinate $(0, 0)$ explodes and since $k=2$ the explosion detonates mines at the cells $(0, 1)$ and $(1, 0)$, and their explosions detonate the mine at the cell $(1, 1)$ and there are no mines left on the field.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's call a list of positive integers $a_0, a_1, ..., a_{n-1}$ a power sequence if there is a positive integer $c$, so that for every $0 \le i \le n-1$ then $a_i = c^i$.
Given a list of $n$ positive integers $a_0, a_1, ..., a_{n-1}$, you are allowed to: Reorder the list (i.e. pick a permutation $p$ of $\{0,1,...,n - 1\}$ and change $a_i$ to $a_{p_i}$), then Do the following operation any number of times: pick an index $i$ and change $a_i$ to $a_i - 1$ or $a_i + 1$ (i.e. increment or decrement $a_i$ by $1$) with a cost of $1$.
Find the minimum cost to transform $a_0, a_1, ..., a_{n-1}$ into a power sequence.
-----Input-----
The first line contains an integer $n$ ($3 \le n \le 10^5$).
The second line contains $n$ integers $a_0, a_1, ..., a_{n-1}$ ($1 \le a_i \le 10^9$).
-----Output-----
Print the minimum cost to transform $a_0, a_1, ..., a_{n-1}$ into a power sequence.
-----Examples-----
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
-----Note-----
In the first example, we first reorder $\{1, 3, 2\}$ into $\{1, 2, 3\}$, then increment $a_2$ to $4$ with cost $1$ to get a power sequence $\{1, 2, 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.
Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
-----Input-----
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000)Β β the starting and ending equilateral triangle side lengths respectively.
-----Output-----
Print a single integerΒ β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
-----Examples-----
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
-----Note-----
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do $(6,6,6) \rightarrow(6,6,3) \rightarrow(6,4,3) \rightarrow(3,4,3) \rightarrow(3,3,3)$.
In the second sample test, Memory can do $(8,8,8) \rightarrow(8,8,5) \rightarrow(8,5,5) \rightarrow(5,5,5)$.
In the third sample test, Memory can do: $(22,22,22) \rightarrow(7,22,22) \rightarrow(7,22,16) \rightarrow(7,10,16) \rightarrow(7,10,4) \rightarrow$
$(7,4,4) \rightarrow(4,4,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.
We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:
- For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.
- There is an edge between Vertex X and Vertex Y.
For each k=1,2,...,N-1, solve the problem below:
- Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.
-----Constraints-----
- 3 \leq N \leq 2 \times 10^3
- 1 \leq X,Y \leq N
- X+1 < Y
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N X Y
-----Output-----
For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.
-----Sample Input-----
5 2 4
-----Sample Output-----
5
4
1
0
The graph in this input is as follows:
There are five pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 1: (1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5).
There are four pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 2: (1,3)\,,(1,4)\,,(2,5)\,,(3,5).
There is one pair (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 3: (1,5).
There are no pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j 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.
Create a program that converts the date expressed in the Christian era to the Japanese calendar using the era name and outputs the date. The input is three integers, as shown in the example, in the order year, month, and day. Convert this as shown in the sample output. If the date before the Meiji era is entered, please display "pre-meiji".
The first year of each year will be output as "1 year" instead of "first year".
Era | Period
--- | ---
meiji | 1868. 9. 8 ~ 1912. 7.29
taisho | 1912. 7.30 ~ 1926.12.24
showa | 1926.12.25 ~ 1989. 1. 7
heisei | 1989. 1. 8 ~
input
Multiple data are given. As each data, three integers representing year, month and day are given on one line separated by blanks.
Please process until the end of the input. The number of data does not exceed 50.
output
Output the blank-separated era, year, month, day, or "pre-meiji" on one line.
Example
Input
2005 9 3
1868 12 2
1868 9 7
Output
heisei 17 9 3
meiji 1 12 2
pre-meiji
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.
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.
<image>
Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.
Input
The first line contains a single integer n (0 β€ n β€ 1018) β the number of full years when the plant grew.
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.
Output
Print a single integer β the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).
Examples
Input
1
Output
3
Input
2
Output
10
Note
The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third 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.
Make a program that takes a value (x) and returns "Bang" if the number is divisible by 3, "Boom" if it is divisible by 5, "BangBoom" if it divisible by 3 and 5, and "Miss" if it isn't divisible by any of them.
Note: Your program should only return one value
Ex: Input: 105 --> Output: "BangBoom"
Ex: Input: 9 --> Output: "Bang"
Ex:Input: 25 --> Output: "Boom"
Write your solution by modifying this code:
```python
def multiple(x):
```
Your solution should implemented in the function "multiple". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are N points on the circumference of a circle centered at (0,0) in an xy-plane. The coordinates of the i-th point are (\cos(\frac{2\pi T_i}{L}),\sin(\frac{2\pi T_i}{L})).
Three distinct points will be chosen uniformly at random from these N points. Find the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points.
Constraints
* 3 \leq N \leq 3000
* N \leq L \leq 10^9
* 0 \leq T_i \leq L-1
* T_i<T_{i+1}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N L
T_1
:
T_N
Output
Print the expected x- and y-coordinates of the center of the circle inscribed in the triangle formed by the chosen points. Your output will be considered correct when the absolute or relative error is at most 10^{-9}.
Examples
Input
3 4
0
1
3
Output
0.414213562373095 -0.000000000000000
Input
4 8
1
3
5
6
Output
-0.229401949926902 -0.153281482438188
Input
10 100
2
11
35
42
54
69
89
91
93
99
Output
0.352886583546338 -0.109065017701873
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.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 β€ n β€ 10
* 1 β€ ai β€ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
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.
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, `atcoder`, `zscoder` and `agc` are diverse words while `gotou` and `connect` aren't diverse words.
Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.
Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.
Constraints
* 1 \leq |S| \leq 26
* S is a diverse word.
Input
Input is given from Standard Input in the following format:
S
Output
Print the next word that appears after S in the dictionary, or `-1` if it doesn't exist.
Examples
Input
atcoder
Output
atcoderb
Input
abc
Output
abcd
Input
zyxwvutsrqponmlkjihgfedcba
Output
-1
Input
abcdefghijklmnopqrstuvwzyx
Output
abcdefghijklmnopqrstuvx
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 pair of numbers has a unique LCM but a single number can be the LCM of more than one possible
pairs. For example `12` is the LCM of `(1, 12), (2, 12), (3,4)` etc. For a given positive integer N, the number of different integer pairs with LCM is equal to N can be called the LCM cardinality of that number N. In this kata your job is to find out the LCM cardinality of a number.
Write your solution by modifying this code:
```python
def lcm_cardinality(n):
```
Your solution should implemented in the function "lcm_cardinality". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).
Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.
-----Input-----
The first line of the input contains n (2 β€ n β€ 1000) β number of bidders. The second line contains n distinct integer numbers p_1, p_2, ... p_{n}, separated by single spaces (1 β€ p_{i} β€ 10000), where p_{i} stands for the price offered by the i-th bidder.
-----Output-----
The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.
-----Examples-----
Input
2
5 7
Output
2 5
Input
3
10 2 8
Output
1 8
Input
6
3 8 2 9 4 14
Output
6 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.
Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.
You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.
-----Constraints-----
- 111 \leq n \leq 999
- n is an integer consisting of digits 1 and 9.
-----Input-----
Input is given from Standard Input in the following format:
n
-----Output-----
Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.
-----Sample Input-----
119
-----Sample Output-----
991
Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.
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.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level $n$ as a rooted tree constructed as described below.
A rooted dead bush of level $1$ is a single vertex. To construct an RDB of level $i$ we, at first, construct an RDB of level $i-1$, then for each vertex $u$: if $u$ has no children then we will add a single child to it; if $u$ has one child then we will add two children to it; if $u$ has more than one child, then we will skip it.
[Image] Rooted Dead Bushes of level $1$, $2$ and $3$.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
[Image] The center of the claw is the vertex with label $1$.
Lee has a Rooted Dead Bush of level $n$. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $10^9+7$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$)Β β the number of test cases.
Next $t$ lines contain test casesΒ β one per line.
The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^6$)Β β the level of Lee's RDB.
-----Output-----
For each test case, print a single integerΒ β the maximum number of yellow vertices Lee can make modulo $10^9 + 7$.
-----Example-----
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
-----Note-----
It's easy to see that the answer for RDB of level $1$ or $2$ is $0$.
The answer for RDB of level $3$ is $4$ since there is only one claw we can choose: $\{1, 2, 3, 4\}$.
The answer for RDB of level $4$ is $4$ since we can choose either single claw $\{1, 3, 2, 4\}$ or single claw $\{2, 7, 5, 6\}$. There are no other claws in the RDB of level $4$ (for example, we can't choose $\{2, 1, 7, 6\}$, since $1$ is not a child of center vertex $2$).
$\therefore$ Rooted Dead Bush of level 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.
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:
All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting.
Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad?
-----Input-----
The first line of input contains two integer numbers $n$ and $k$ ($1 \le n \le 10^{9}$, $0 \le k \le 2\cdot10^5$), where $n$ denotes total number of pirates and $k$ is the number of pirates that have any coins.
The next $k$ lines of input contain integers $a_i$ and $b_i$ ($1 \le a_i \le n$, $1 \le b_i \le 10^{9}$), where $a_i$ denotes the index of the pirate sitting at the round table ($n$ and $1$ are neighbours) and $b_i$ the total number of coins that pirate $a_i$ has at the start of the game.
-----Output-----
Print $1$ if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations.
Print $-1$ if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations.
-----Examples-----
Input
4 2
1 2
2 2
Output
1
Input
6 2
2 3
4 1
Output
1
Input
3 2
1 1
2 2
Output
-1
-----Note-----
In the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting 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.
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) β (0, 1) β (0, 2) β (1, 2) β (1, 1) β (0, 1) β ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.
Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.
To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) β (0, 1) β (0, 0) cannot occur in a valid grid path.
One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.
Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.
Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
Input
The first line of the input contains a single integer n (2 β€ n β€ 1 000 000) β the length of the paths.
The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') β the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".
The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') β the second grid path.
Output
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
Examples
Input
7
NNESWW
SWSWSW
Output
YES
Input
3
NN
SS
Output
NO
Note
In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.
In the second sample, no sequence of moves can get both marbles to the end.
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 a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures
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
I started a part-time job at the rental DVD shop "NEO". First of all, I decided to study the fee system of this store.
There are three types of rental DVDs, old, semi-new, and new, and the rental fee for one DVD is a yen, b yen, and c yen, respectively. The set rental shown below can be applied multiple times at the time of accounting.
* Select a few DVDs for which set rental has not yet been applied.
* If the number of selected DVDs is d or more, the total price of the selected DVDs exceeds (the number of selected DVDs) * e yen, rent them for (the number of selected DVDs) * e yen. You can.
* If the number of selected DVDs is less than d, and the total price of the selected DVDs exceeds d * e yen, you can rent them for d * e yen.
* If the above does not apply, the selected DVD will be rented at the regular rate.
Here I noticed a problem. The set rental is not applied automatically when you go to the cash register, but is applied manually. This may result in the application of suboptimal set rentals (which can be cheaper). This can lead to complaints. I hate complaints, so I decided to create a program that calculates the price when the set rental is optimally applied.
Constraints
The input satisfies the following conditions.
* All values ββcontained in the input are integers
* 0 <a <b <e <c β€ 1000
* 0 <d β€ 100000
* 0 β€ na, nb, nc β€ 100000
* 0 <na + nb + nc
* No more than 100 datasets
Input
The input consists of multiple datasets. Each dataset is represented below. The first line is given five integers a, b, c, d, e separated by spaces. The number of rentals is given on the second line. The three integers na, nb, nc are given separated by spaces. Represents the number of old, semi-new, and new DVDs, respectively. The end of the input consists of 5 zeros.
a b c d e
na nb nc
Output
For each dataset, output the charge when the set rental is optimally applied on one line.
Example
Input
70 100 340 4 200
1 1 4
70 100 340 4 200
0 1 3
70 100 340 4 200
1 1 2
0 0 0 0 0
Output
970
800
800
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.
Complete the function that accepts a string parameter, and reverses each word in the string. **All** spaces in the string should be retained.
## Examples
```
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
```
Write your solution by modifying this code:
```python
def reverse_words(text):
```
Your solution should implemented in the function "reverse_words". The i
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 railroad in Takahashi Kingdom. The railroad consists of N sections, numbered 1, 2, ..., N, and N+1 stations, numbered 0, 1, ..., N. Section i directly connects the stations i-1 and i. A train takes exactly A_i minutes to run through section i, regardless of direction. Each of the N sections is either single-tracked over the whole length, or double-tracked over the whole length. If B_i = 1, section i is single-tracked; if B_i = 2, section i is double-tracked. Two trains running in opposite directions can cross each other on a double-tracked section, but not on a single-tracked section. Trains can also cross each other at a station.
Snuke is creating the timetable for this railroad. In this timetable, the trains on the railroad run every K minutes, as shown in the following figure. Here, bold lines represent the positions of trains running on the railroad. (See Sample 1 for clarification.)
<image>
When creating such a timetable, find the minimum sum of the amount of time required for a train to depart station 0 and reach station N, and the amount of time required for a train to depart station N and reach station 0. It can be proved that, if there exists a timetable satisfying the conditions in this problem, this minimum sum is always an integer.
Formally, the times at which trains arrive and depart must satisfy the following:
* Each train either departs station 0 and is bound for station N, or departs station N and is bound for station 0.
* Each train takes exactly A_i minutes to run through section i. For example, if a train bound for station N departs station i-1 at time t, the train arrives at station i exactly at time t+A_i.
* Assume that a train bound for station N arrives at a station at time s, and departs the station at time t. Then, the next train bound for station N arrives at the station at time s+K, and departs the station at time t+K. Additionally, the previous train bound for station N arrives at the station at time s-K, and departs the station at time t-K. This must also be true for trains bound for station 0.
* Trains running in opposite directions must not be running on the same single-tracked section (except the stations at both ends) at the same time.
Constraints
* 1 \leq N \leq 100000
* 1 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* A_i is an integer.
* B_i is either 1 or 2.
Input
The input is given from Standard Input in the following format:
N K
A_1 B_1
A_2 B_2
:
A_N B_N
Output
Print an integer representing the minimum sum of the amount of time required for a train to depart station 0 and reach station N, and the amount of time required for a train to depart station N and reach station 0. If it is impossible to create a timetable satisfying the conditions, print -1 instead.
Examples
Input
3 10
4 1
3 1
4 1
Output
26
Input
1 10
10 1
Output
-1
Input
6 4
1 1
1 1
1 1
1 1
1 1
1 1
Output
12
Input
20 987654321
129662684 2
162021979 1
458437539 1
319670097 2
202863355 1
112218745 1
348732033 1
323036578 1
382398703 1
55854389 1
283445191 1
151300613 1
693338042 2
191178308 2
386707193 1
204580036 1
335134457 1
122253639 1
824646518 2
902554792 2
Output
14829091348
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.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m β the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β the numbers of students tied by the i-th lace (1 β€ a, b β€ n, a β b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number β the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students β in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is 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.
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.
The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).
Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.
At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.
It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.
Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.
-----Input-----
The first line contains one integer n (1 β€ n β€ 50) β the length of the hidden word.
The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed.
The third line contains an integer m (1 β€ m β€ 1000) β the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves β n-letter strings of lowercase Latin letters. All words are distinct.
It is guaranteed that the hidden word appears as one of the given m words. Before the current move Polycarp has told exactly the letters which are currently revealed.
-----Output-----
Output the single integer β the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero.
-----Examples-----
Input
4
a**d
2
abcd
acbd
Output
2
Input
5
lo*er
2
lover
loser
Output
0
Input
3
a*a
2
aaa
aba
Output
1
-----Note-----
In the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed.
The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word.
In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns.
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.
Maga and Alex are good at string manipulation problems. Just now they have faced a problem related to string. But it is not a standard string problem. They have no idea to solve it. They need your help.
A string is called unique if all characters of string are distinct.
String s_1 is called subsequence of string s_2 if s_1 can be produced from s_2 by removing some characters of s_2.
String s_1 is stronger than s_2 if s_1 is lexicographically greater than s_2.
You are given a string. Your task is to find the strongest unique string which is subsequence of given string.
Input:
first line contains length of string.
second line contains the string.
Output:
Output the strongest unique string which is subsequence of given string.
Constraints:
1 β€ |S| β€ 100000
All letters are lowercase English letters.
SAMPLE INPUT
5
abvzx
SAMPLE OUTPUT
zx
Explanation
Select all subsequence of the string and sort them in ascending order. The greatest of all is zx.
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 Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.
In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.
The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.
Input
The first line contains integer n (1 β€ n β€ 103) β the boulevard's length in tiles.
The second line contains n space-separated integers ai β the number of days after which the i-th tile gets destroyed (1 β€ ai β€ 103).
Output
Print a single number β the sought number of days.
Examples
Input
4
10 3 5 10
Output
5
Input
5
10 2 8 3 5
Output
5
Note
In the first sample the second tile gets destroyed after day three, and the only path left is 1 β 3 β 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.
In the second sample path 1 β 3 β 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals n (n is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first n / 2 digits) equals the sum of digits in the second half (the sum of the last n / 2 digits). Check if the given ticket is lucky.
Input
The first line contains an even integer n (2 β€ n β€ 50) β the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly n β the ticket number. The number may contain leading zeros.
Output
On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes).
Examples
Input
2
47
Output
NO
Input
4
4738
Output
NO
Input
4
4774
Output
YES
Note
In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 β 7).
In the second sample the ticket number is not the lucky number.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that A follows Z. For example, shifting A by 2 results in C (A \to B \to C), and shifting Y by 3 results in B (Y \to Z \to A \to B).
-----Constraints-----
- 0 \leq N \leq 26
- 1 \leq |S| \leq 10^4
- S consists of uppercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
N
S
-----Output-----
Print the string resulting from shifting each character of S by N in alphabetical order.
-----Sample Input-----
2
ABCXYZ
-----Sample Output-----
CDEZAB
Note that A follows 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.
While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000.
If the quantity and price per item are input, write a program to calculate the total expenses.
------ Input Format ------
The first line contains an integer T, total number of test cases. Then follow T lines, each line contains integers quantity and price.
------ Output Format ------
For each test case, output the total expenses while purchasing items, in a new line.
------ Constraints ------
1 β€ T β€ 1000
1 β€ quantity,price β€ 100000
----- Sample Input 1 ------
3
100 120
10 20
1200 20
----- Sample Output 1 ------
12000.000000
200.000000
21600.000000
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 beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.
Input
Input data contains the only number n (1 β€ n β€ 109).
Output
Output the only number β answer to the problem.
Examples
Input
10
Output
2
Note
For n = 10 the answer includes numbers 1 and 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 are given $n$ lengths of segments that need to be placed on an infinite axis with coordinates.
The first segment is placed on the axis so that one of its endpoints lies at the point with coordinate $0$. Let's call this endpoint the "start" of the first segment and let's call its "end" as that endpoint that is not the start.
The "start" of each following segment must coincide with the "end" of the previous one. Thus, if the length of the next segment is $d$ and the "end" of the previous one has the coordinate $x$, the segment can be placed either on the coordinates $[x-d, x]$, and then the coordinate of its "end" is $x - d$, or on the coordinates $[x, x+d]$, in which case its "end" coordinate is $x + d$.
The total coverage of the axis by these segments is defined as their overall union which is basically the set of points covered by at least one of the segments. It's easy to show that the coverage will also be a segment on the axis. Determine the minimal possible length of the coverage that can be obtained by placing all the segments on the axis without changing their order.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 1000$) β the number of test cases.
The next $2t$ lines contain descriptions of the test cases.
The first line of each test case description contains an integer $n$ ($1 \le n \le 10^4$) β the number of segments. The second line of the description contains $n$ space-separated integers $a_i$ ($1 \le a_i \le 1000$) β lengths of the segments in the same order they should be placed on the axis.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^4$.
-----Output-----
Print $t$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer β the minimal possible length of the axis coverage.
-----Examples-----
Input
6
2
1 3
3
1 2 3
4
6 2 3 9
4
6 8 4 5
7
1 2 4 6 7 7 3
8
8 6 5 1 2 2 3 6
Output
3
3
9
9
7
8
-----Note-----
In the third sample test case the segments should be arranged as follows: $[0, 6] \rightarrow [4, 6] \rightarrow [4, 7] \rightarrow [-2, 7]$. As you can see, the last segment $[-2, 7]$ covers all the previous ones, and the total length of coverage is $9$.
In the fourth sample test case the segments should be arranged as $[0, 6] \rightarrow [-2, 6] \rightarrow [-2, 2] \rightarrow [2, 7]$. The union of these segments also occupies the area $[-2, 7]$ and has the length of $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.
Here is a very simple variation of the game backgammon, named βMinimal Backgammonβ. The game is played by only one player, using only one of the dice and only one checker (the token used by the player).
The game board is a line of (N + 1) squares labeled as 0 (the start) to N (the goal). At the beginning, the checker is placed on the start (square 0). The aim of the game is to bring the checker to the goal (square N). The checker proceeds as many squares as the roll of the dice. The dice generates six integers from 1 to 6 with equal probability.
The checker should not go beyond the goal. If the roll of the dice would bring the checker beyond the goal, the checker retreats from the goal as many squares as the excess. For example, if the checker is placed at the square (N - 3), the roll "5" brings the checker to the square (N - 2), because the excess beyond the goal is 2. At the next turn, the checker proceeds toward the goal as usual.
Each square, except the start and the goal, may be given one of the following two special instructions.
* Lose one turn (labeled "L" in Figure 2) If the checker stops here, you cannot move the checker in the next turn.
* Go back to the start (labeled "B" in Figure 2)
If the checker stops here, the checker is brought back to the start.
<image>
Figure 2: An example game
Given a game board configuration (the size N, and the placement of the special instructions), you are requested to compute the probability with which the game succeeds within a given number of turns.
Input
The input consists of multiple datasets, each containing integers in the following format.
N T L B
Lose1
...
LoseL
Back1
...
BackB
N is the index of the goal, which satisfies 5 β€ N β€ 100. T is the number of turns. You are requested to compute the probability of success within T turns. T satisfies 1 β€ T β€ 100. L is the number of squares marked βLose one turnβ, which satisfies 0 β€ L β€ N - 1. B is the number of squares marked βGo back to the startβ, which satisfies 0 β€ B β€ N - 1. They are separated by a space.
Losei's are the indexes of the squares marked βLose one turnβ, which satisfy 1 β€ Losei β€ N - 1. All Losei's are distinct, and sorted in ascending order. Backi's are the indexes of the squares marked βGo back to the startβ, which satisfy 1 β€ Backi β€ N - 1. All Backi's are distinct, and sorted in ascending order. No numbers occur both in Losei's and Backi's.
The end of the input is indicated by a line containing four zeros separated by a space.
Output
For each dataset, you should answer the probability with which the game succeeds within the given number of turns. The output should not contain an error greater than 0.00001.
Example
Input
6 1 0 0
7 1 0 0
7 2 0 0
6 6 1 1
2
5
7 10 0 6
1
2
3
4
5
6
0 0 0 0
Output
0.166667
0.000000
0.166667
0.619642
0.000000
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 kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0. During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right. That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i. The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible. Find the earliest possible time to reach coordinate X.
Constraints
* X is an integer.
* 1β€Xβ€10^9
Input
The input is given from Standard Input in the following format:
X
Output
Print the earliest possible time for the kangaroo to reach coordinate X.
Examples
Input
6
Output
3
Input
2
Output
2
Input
11
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.
Input
The input is given from standard input in the following format.
> $H \ W$ $a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}$ $a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}$ $\vdots \ \ \ \ \ \ \ \ \ \ \vdots \ \ \ \ \ \ \ \ \ \ \vdots$ $a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}$
Output
* Print the maximum number of souvenirs they can get.
Constraints
* $1 \le H, W \le 200$
* $0 \le a_{i, j} \le 10^5$
Subtasks
Subtask 1 [ 50 points ]
* The testcase in the subtask satisfies $1 \le H \le 2$.
Subtask 2 [ 80 points ]
* The testcase in the subtask satisfies $1 \le H \le 3$.
Subtask 3 [ 120 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 7$.
Subtask 4 [ 150 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 30$.
Subtask 5 [ 200 points ]
* There are no additional constraints.
Output
* Print the maximum number of souvenirs they can get.
Constraints
* $1 \le H, W \le 200$
* $0 \le a_{i, j} \le 10^5$
Subtasks
Subtask 1 [ 50 points ]
* The testcase in the subtask satisfies $1 \le H \le 2$.
Subtask 2 [ 80 points ]
* The testcase in the subtask satisfies $1 \le H \le 3$.
Subtask 3 [ 120 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 7$.
Subtask 4 [ 150 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 30$.
Subtask 5 [ 200 points ]
* There are no additional constraints.
Input
The input is given from standard input in the following format.
> $H \ W$ $a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}$ $a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}$ $\vdots \ \ \ \ \ \ \ \ \ \ \vdots \ \ \ \ \ \ \ \ \ \ \vdots$ $a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}$
Examples
Input
3 3
1 0 5
2 2 3
4 2 4
Output
21
Input
6 6
1 2 3 4 5 6
8 6 9 1 2 0
3 1 4 1 5 9
2 6 5 3 5 8
1 4 1 4 2 1
2 7 1 8 2 8
Output
97
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.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 β€ n, w β€ 2Β·105) β the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 β€ ai β€ 109) β the heights of the towers in the bears' wall. The third line contains w integers bi (1 β€ bi β€ 109) β the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<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's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer β as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored.
Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal).
The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall. [Image]
In the given coordinate system you are given: y_1, y_2 β the y-coordinates of the side pillars of the goalposts of robo-Wallace's opponents; y_{w} β the y-coordinate of the wall to which Robo-Wallace is aiming; x_{b}, y_{b} β the coordinates of the ball's position when it is hit; r β the radius of the ball.
A goal is scored when the center of the ball crosses the OY axis in the given coordinate system between (0, y_1) and (0, y_2). The ball moves along a straight line. The ball's hit on the wall is perfectly elastic (the ball does not shrink from the hit), the angle of incidence equals the angle of reflection. If the ball bounces off the wall not to the goal, that is, if it hits the other wall or the goal post, then the opposing team catches the ball and Robo-Wallace starts looking for miscalculation and gets dysfunctional. Such an outcome, if possible, should be avoided. We assume that the ball touches an object, if the distance from the center of the ball to the object is no greater than the ball radius r.
-----Input-----
The first and the single line contains integers y_1, y_2, y_{w}, x_{b}, y_{b}, r (1 β€ y_1, y_2, y_{w}, x_{b}, y_{b} β€ 10^6; y_1 < y_2 < y_{w}; y_{b} + r < y_{w}; 2Β·r < y_2 - y_1).
It is guaranteed that the ball is positioned correctly in the field, doesn't cross any wall, doesn't touch the wall that Robo-Wallace is aiming at. The goal posts can't be located in the field corners.
-----Output-----
If Robo-Wallace can't score a goal in the described manner, print "-1" (without the quotes). Otherwise, print a single number x_{w} β the abscissa of his point of aiming.
If there are multiple points of aiming, print the abscissa of any of them. When checking the correctness of the answer, all comparisons are made with the permissible absolute error, equal to 10^{ - 8}.
It is recommended to print as many characters after the decimal point as possible.
-----Examples-----
Input
4 10 13 10 3 1
Output
4.3750000000
Input
1 4 6 2 2 1
Output
-1
Input
3 10 15 17 9 2
Output
11.3333333333
-----Note-----
Note that in the first and third samples other correct values of abscissa x_{w} are also possible.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.
The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?
-----Constraints-----
- -40 \leq X \leq 40
- X is an integer.
-----Input-----
Input is given from Standard Input in the following format:
X
-----Output-----
Print Yes if you will turn on the air conditioner; print No otherwise.
-----Sample Input-----
25
-----Sample 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.
On a chessboard with a width of $10^9$ and a height of $10^9$, the rows are numbered from bottom to top from $1$ to $10^9$, and the columns are numbered from left to right from $1$ to $10^9$. Therefore, for each cell of the chessboard you can assign the coordinates $(x,y)$, where $x$ is the column number and $y$ is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left cornerΒ β a cell with coordinates $(1,1)$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namelyΒ β on the upper side of the field (that is, in any cell that is in the row with number $10^9$).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number $x$. Such spells create an infinite blocking line between the columns $x$ and $x+1$. Horizontal. Each of these is defined by three numbers $x_1$, $x_2$, $y$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $y$ and in columns from $x_1$ to $x_2$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
[Image]
An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $(r_0,c_0)$ into the cell $(r_1,c_1)$ only under the condition that $r_1 = r_0$ or $c_1 = c_0$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
-----Input-----
The first line contains two integers $n$ and $m$ ($0 \le n,m \le 10^5$)Β β the number of vertical and horizontal spells.
Each of the following $n$ lines contains one integer $x$ ($1 \le x < 10^9$)Β β the description of the vertical spell. It will create a blocking line between the columns of $x$ and $x+1$.
Each of the following $m$ lines contains three integers $x_1$, $x_2$ and $y$ ($1 \le x_{1} \le x_{2} \le 10^9$, $1 \le y < 10^9$)Β β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number $y$, in columns from $x_1$ to $x_2$ inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
-----Output-----
In a single line print one integerΒ β the minimum number of spells the rook needs to remove so it can get from the cell $(1,1)$ to at least one cell in the row with the number $10^9$
-----Examples-----
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
-----Note-----
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
[Image] Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
$m$ Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
[Image] Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
[Image] Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
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 counts and reports the number of each alphabetical letter. Ignore the case of characters.
Constraints
* The number of characters in the sentence < 1200
Input
A sentence in English is given in several lines.
Output
Prints the number of alphabetical letters in the following format:
a : The number of 'a'
b : The number of 'b'
c : The number of 'c'
.
.
z : The number of 'z'
Example
Input
This is a pen.
Output
a : 1
b : 0
c : 0
d : 0
e : 1
f : 0
g : 0
h : 1
i : 2
j : 0
k : 0
l : 0
m : 0
n : 1
o : 0
p : 1
q : 0
r : 0
s : 2
t : 1
u : 0
v : 0
w : 0
x : 0
y : 0
z : 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.
The string $s$ is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet.
As long as the string length is greater than $1$, the following operation can be performed on it: select any two adjacent letters in the string $s$ and delete them from the string. For example, from the string "lemma" in one operation, you can get any of the four strings: "mma", "lma", "lea" or "lem" In particular, in one operation, the length of the string reduces by $2$.
Formally, let the string $s$ have the form $s=s_1s_2 \dots s_n$ ($n>1$). During one operation, you choose an arbitrary index $i$ ($1 \le i < n$) and replace $s=s_1s_2 \dots s_{i-1}s_{i+2} \dots s_n$.
For the given string $s$ and the letter $c$, determine whether it is possible to make such a sequence of operations that in the end the equality $s=c$ will be true? In other words, is there such a sequence of operations that the process will end with a string of length $1$, which consists of the letter $c$?
-----Input-----
The first line of input data contains an integer $t$ ($1 \le t \le 10^3$) β the number of input test cases.
The descriptions of the $t$ cases follow. Each test case is represented by two lines:
string $s$, which has an odd length from $1$ to $49$ inclusive and consists of lowercase letters of the Latin alphabet;
is a string containing one letter $c$, where $c$ is a lowercase letter of the Latin alphabet.
-----Output-----
For each test case in a separate line output:
YES, if the string $s$ can be converted so that $s=c$ is true;
NO otherwise.
You can output YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive response).
-----Examples-----
Input
5
abcde
c
abcde
b
x
y
aaaaaaaaaaaaaaa
a
contest
t
Output
YES
NO
NO
YES
YES
-----Note-----
In the first test case, $s$="abcde". You need to get $s$="c". For the first operation, delete the first two letters, we get $s$="cde". In the second operation, we delete the last two letters, so we get the expected value of $s$="c".
In the third test case, $s$="x", it is required to get $s$="y". Obviously, this cannot be done.
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.
Andi and Budi were given an assignment to tidy up their bookshelf of $n$ books. Each book is represented by the book title β a string $s_i$ numbered from $1$ to $n$, each with length $m$. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending.
Settling their fight, they decided to combine their idea and sort it asc-desc-endingly, where the odd-indexed characters will be compared ascendingly, and the even-indexed characters will be compared descendingly.
A string $a$ occurs before a string $b$ in asc-desc-ending order if and only if in the first position where $a$ and $b$ differ, the following holds:
if it is an odd position, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$;
if it is an even position, the string $a$ has a letter that appears later in the alphabet than the corresponding letter in $b$.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \leq n \cdot m \leq 10^6$).
The $i$-th of the next $n$ lines contains a string $s_i$ consisting of $m$ uppercase Latin letters β the book title. The strings are pairwise distinct.
-----Output-----
Output $n$ integers β the indices of the strings after they are sorted asc-desc-endingly.
-----Examples-----
Input
5 2
AA
AB
BB
BA
AZ
Output
5 2 1 3 4
-----Note-----
The following illustrates the first example.
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.
Hr0d1y has $q$ queries on a binary string $s$ of length $n$. A binary string is a string containing only characters '0' and '1'.
A query is described by a pair of integers $l_i$, $r_i$ $(1 \leq l_i \lt r_i \leq n)$.
For each query, he has to determine whether there exists a good subsequence in $s$ that is equal to the substring $s[l_i\ldots r_i]$.
A substring $s[i\ldots j]$ of a string $s$ is the string formed by characters $s_i s_{i+1} \ldots s_j$.
String $a$ is said to be a subsequence of string $b$ if $a$ can be obtained from $b$ by deleting some characters without changing the order of the remaining characters.
A subsequence is said to be good if it is not contiguous and has length $\ge 2$. For example, if $s$ is "1100110", then the subsequences $s_1s_2s_4$ ("1100110") and $s_1s_5s_7$ ("1100110") are good, while $s_1s_2s_3$ ("1100110") is not good.
Can you help Hr0d1y answer each query?
-----Input-----
The first line of the input contains a single integer $t$ ($1\leq t \leq 100$) β the number of test cases. The description of each test case is as follows.
The first line contains two integers $n$ ($2 \leq n \leq 100$) and $q$ ($1\leq q \leq 100$) β the length of the string and the number of queries.
The second line contains the string $s$.
The $i$-th of the next $q$ lines contains two integers $l_i$ and $r_i$ ($1 \leq l_i \lt r_i \leq n$).
-----Output-----
For each test case, output $q$ lines. The $i$-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring $s[l_i...r_i]$, and "NO" otherwise.
You may print each letter in any case (upper or lower).
-----Examples-----
Input
2
6 3
001000
2 4
1 3
3 5
4 2
1111
1 4
2 3
Output
YES
NO
YES
NO
YES
-----Note-----
In the first test case,
$s[2\ldots 4] = $ "010". In this case $s_1s_3s_5$ ("001000") and $s_2s_3s_6$ ("001000") are good suitable subsequences, while $s_2s_3s_4$ ("001000") is not good.
$s[1\ldots 3] = $ "001". No suitable good subsequence exists.
$s[3\ldots 5] = $ "100". Here $s_3s_5s_6$ ("001000") is a suitable good subsequence.
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.
To write a research paper, you should definitely follow the structured format. This format, in many cases, is strictly defined, and students who try to write their papers have a hard time with it.
One of such formats is related to citations. If you refer several pages of a material, you should enumerate their page numbers in ascending order. However, enumerating many page numbers waste space, so you should use the following abbreviated notation:
When you refer all pages between page a and page b (a < b), you must use the notation "a-b". For example, when you refer pages 1, 2, 3, 4, you must write "1-4" not "1 2 3 4". You must not write, for example, "1-2 3-4", "1-3 4", "1-3 2-4" and so on. When you refer one page and do not refer the previous and the next page of that page, you can write just the number of that page, but you must follow the notation when you refer successive pages (more than or equal to 2). Typically, commas are used to separate page numbers, in this problem we use space to separate the page numbers.
You, a kind senior, decided to write a program which generates the abbreviated notation for your junior who struggle with the citation.
Constraints
* 1 β€ n β€ 50
Input
Input consists of several datasets.
The first line of the dataset indicates the number of pages n.
Next line consists of n integers. These integers are arranged in ascending order and they are differ from each other.
Input ends when n = 0.
Output
For each dataset, output the abbreviated notation in a line. Your program should not print extra space. Especially, be careful about the space at the end of line.
Example
Input
5
1 2 3 5 6
3
7 8 9
0
Output
1-3 5-6
7-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.
For given an integer $n$, print all permutations of $\\{1, 2, ..., n\\}$ in lexicographic order.
Constraints
* $1 \leq n \leq 9$
Input
An integer $n$ is given in a line.
Output
Print each permutation in a line in order. Separate adjacency elements by a space character.
Examples
Input
2
Output
1 2
2 1
Input
3
Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 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.
Today an outstanding event is going to happen in the forestΒ β hedgehog Filya will come to his old fried Sonya!
Sonya is an owl and she sleeps during the day and stay awake from minute l_1 to minute r_1 inclusive. Also, during the minute k she prinks and is unavailable for Filya.
Filya works a lot and he plans to visit Sonya from minute l_2 to minute r_2 inclusive.
Calculate the number of minutes they will be able to spend together.
-----Input-----
The only line of the input contains integers l_1, r_1, l_2, r_2 and k (1 β€ l_1, r_1, l_2, r_2, k β€ 10^18, l_1 β€ r_1, l_2 β€ r_2), providing the segments of time for Sonya and Filya and the moment of time when Sonya prinks.
-----Output-----
Print one integerΒ β the number of minutes Sonya and Filya will be able to spend together.
-----Examples-----
Input
1 10 9 20 1
Output
2
Input
1 100 50 200 75
Output
50
-----Note-----
In the first sample, they will be together during minutes 9 and 10.
In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a positive integer $n$. Since $n$ may be very large, you are given its binary representation.
You should compute the number of triples $(a,b,c)$ with $0 \leq a,b,c \leq n$ such that $a \oplus b$, $b \oplus c$, and $a \oplus c$ are the sides of a non-degenerate triangle.
Here, $\oplus$ denotes the bitwise XOR operation .
You should output the answer modulo $998\,244\,353$.
Three positive values $x$, $y$, and $z$ are the sides of a non-degenerate triangle if and only if $x+y>z$, $x+z>y$, and $y+z>x$.
-----Input-----
The first and only line contains the binary representation of an integer $n$ ($0 < n < 2^{200000}$) without leading zeros.
For example, the string 10 is the binary representation of the number $2$, while the string 1010 represents the number $10$.
-----Output-----
Print one integer β the number of triples $(a,b,c)$ satisfying the conditions described in the statement modulo $998\,244\,353$.
-----Examples-----
Input
101
Output
12
Input
1110
Output
780
Input
11011111101010010
Output
141427753
-----Note-----
In the first test case, $101_2=5$.
The triple $(a, b, c) = (0, 3, 5)$ is valid because $(a\oplus b, b\oplus c, c\oplus a) = (3, 6, 5)$ are the sides of a non-degenerate triangle.
The triple $(a, b, c) = (1, 2, 4)$ is valid because $(a\oplus b, b\oplus c, c\oplus a) = (3, 6, 5)$ are the sides of a non-degenerate triangle.
The $6$ permutations of each of these two triples are all the valid triples, thus the answer is $12$.
In the third test case, $11\,011\,111\,101\,010\,010_2=114\,514$. The full answer (before taking the modulo) is $1\,466\,408\,118\,808\,164$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N. Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:
* Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq A_i,B_i \leq 10^9
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
If the objective is achievable, print `Yes`; if it is not, print `No`.
Examples
Input
3
1 3 2
1 2 3
Output
Yes
Input
3
1 2 3
2 2 2
Output
No
Input
6
3 1 2 6 3 4
2 2 8 3 4 3
Output
Yes
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 special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer.
The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows:
```Haskell
2 = 2^0 * 3^0 + 1
3 = 2^1 * 3^0 + 1
5 = 2^2 * 3^0 + 1
7 = 2^1 * 3^1 + 1
13 = 2^2 * 3^1 + 1
..and so on
```
You will be given a range and your task is to return the number of primes that have this property. For example, `solve(0,15) = 5`, because there are only `5` such primes `>= 0 and < 15`; they are `2,3,5,7,13`. The upper limit of the tests will not exceed `1,500,000`.
More examples in the test cases.
Good luck!
If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
Write your solution by modifying this code:
```python
def solve(x, y):
```
Your solution should implemented in the function "solve". The i
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 problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" β people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy.
Input
The only line of the input contains an integer between 1 and 5, inclusive. All tests for this problem are different. The contents of the test case doesn't need to be equal to its index.
Output
The only line of the output contains an integer between 1 and 3, inclusive.
Examples
Note
This problem has no samples, since there so few test cases.
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 Little Elephant has got a problem β somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.
The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.
Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.
Input
The first line contains a single integer n (2 β€ n β€ 105) β the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, β array a.
Note that the elements of the array are not necessarily distinct numbers.
Output
In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise.
Examples
Input
2
1 2
Output
YES
Input
3
3 2 1
Output
YES
Input
4
4 3 2 1
Output
NO
Note
In the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES".
In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES".
In the third sample we can't sort the array in more than one swap operation, so the answer is "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.
This is an interactive problem.
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.
Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 β€ x β€ m, where Natasha knows the number m. Besides, x and m are positive integers.
Natasha can ask the rocket questions. Every question is an integer y (1 β€ y β€ m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken β it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.
In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, β¦, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, β¦, (n-1)-th, n-th, β¦. If the current element is 1, the rocket answers correctly, if 0 β lies. Natasha doesn't know the sequence p, but she knows its length β n.
You can ask the rocket no more than 60 questions.
Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.
Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).
Input
The first line contains two integers m and n (1 β€ m β€ 10^9, 1 β€ n β€ 30) β the maximum distance to Mars and the number of elements in the sequence p.
Interaction
You can ask the rocket no more than 60 questions.
To ask a question, print a number y (1β€ yβ€ m) and an end-of-line character, then do the operation flush and read the answer to the question.
If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.
If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.
You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.
To flush the output buffer you can use (after printing a query and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking
Use the following format for hacking:
In the first line, print 3 integers m,n,x (1β€ xβ€ mβ€ 10^9, 1β€ nβ€ 30) β the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.
In the second line, enter n numbers, each of which is equal to 0 or 1 β sequence p.
The hacked solution will not have access to the number x and sequence p.
Example
Input
5 2
1
-1
-1
1
0
Output
1
2
4
5
3
Note
In the example, hacking would look like this:
5 2 3
1 0
This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...
Really:
on the first query (1) the correct answer is 1, the rocket answered correctly: 1;
on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;
on the third query (4) the correct answer is -1, the rocket answered correctly: -1;
on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;
on the fifth query (3) the correct and incorrect answer is 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.
Monocarp is the coach of the Berland State University programming teams. He decided to compose a problemset for a training session for his teams.
Monocarp has $n$ problems that none of his students have seen yet. The $i$-th problem has a topic $a_i$ (an integer from $1$ to $n$) and a difficulty $b_i$ (an integer from $1$ to $n$). All problems are different, that is, there are no two tasks that have the same topic and difficulty at the same time.
Monocarp decided to select exactly $3$ problems from $n$ problems for the problemset. The problems should satisfy at least one of two conditions (possibly, both):
the topics of all three selected problems are different;
the difficulties of all three selected problems are different.
Your task is to determine the number of ways to select three problems for the problemset.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 50000$) β the number of testcases.
The first line of each testcase contains an integer $n$ ($3 \le n \le 2 \cdot 10^5$) β the number of problems that Monocarp have.
In the $i$-th of the following $n$ lines, there are two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le n$) β the topic and the difficulty of the $i$-th problem.
It is guaranteed that there are no two problems that have the same topic and difficulty at the same time.
The sum of $n$ over all testcases doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print the number of ways to select three training problems that meet either of the requirements described in the statement.
-----Examples-----
Input
2
4
2 4
3 4
2 1
1 3
5
1 5
2 4
3 3
4 2
5 1
Output
3
10
-----Note-----
In the first example, you can take the following sets of three problems:
problems $1$, $2$, $4$;
problems $1$, $3$, $4$;
problems $2$, $3$, $4$.
Thus, the number of ways is equal to three.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You've been collecting change all day, and it's starting to pile up in your pocket, but you're too lazy to see how much you've found.
Good thing you can code!
Create ```change_count()``` to return a dollar amount of how much change you have!
Valid types of change include:
```
penny: 0.01
nickel: 0.05
dime: 0.10
quarter: 0.25
dollar: 1.00
```
```if:python
These amounts are already preloaded as floats into the `CHANGE` dictionary for you to use!
```
```if:ruby
These amounts are already preloaded as floats into the `CHANGE` hash for you to use!
```
```if:javascript
These amounts are already preloaded as floats into the `CHANGE` object for you to use!
```
```if:php
These amounts are already preloaded as floats into the `CHANGE` (a constant) associative array for you to use!
```
You should return the total in the format ```$x.xx```.
Examples:
```python
change_count('nickel penny dime dollar') == '$1.16'
change_count('dollar dollar quarter dime dime') == '$2.45'
change_count('penny') == '$0.01'
change_count('dime') == '$0.10'
```
Warning, some change may amount to over ```$10.00```!
Write your solution by modifying this code:
```python
def change_count(change):
```
Your solution should implemented in the function "change_count". The i
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γ`a = 1, b = 2, c = 3 ... z = 26`
Then `l + o + v + e = 54`
and `f + r + i + e + n + d + s + h + i + p = 108`
So `friendship` is twice stronger than `love` :-)
The input will always be in lowercase and never be empty.
Write your solution by modifying this code:
```python
def words_to_marks(s):
```
Your solution should implemented in the function "words_to_marks". The i
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.
Shortest Common Non-Subsequence
A subsequence of a sequence $P$ is a sequence that can be derived from the original sequence $P$ by picking up some or no elements of $P$ preserving the order. For example, "ICPC" is a subsequence of "MICROPROCESSOR".
A common subsequence of two sequences is a subsequence of both sequences. The famous longest common subsequence problem is finding the longest of common subsequences of two given sequences.
In this problem, conversely, we consider the shortest common non-subsequence problem: Given two sequences consisting of 0 and 1, your task is to find the shortest sequence also consisting of 0 and 1 that is a subsequence of neither of the two sequences.
Input
The input consists of a single test case with two lines. Both lines are sequences consisting only of 0 and 1. Their lengths are between 1 and 4000, inclusive.
Output
Output in one line the shortest common non-subsequence of two given sequences. If there are two or more such sequences, you should output the lexicographically smallest one. Here, a sequence $P$ is lexicographically smaller than another sequence $Q$ of the same length if there exists $k$ such that $P_1 = Q_1, ... , P_{k-1} = Q_{k-1}$, and $P_k < Q_k$, where $S_i$ is the $i$-th character of a sequence $S$.
Sample Input 1
0101
1100001
Sample Output 1
0010
Sample Input 2
101010101
010101010
Sample Output 2
000000
Sample Input 3
11111111
00000000
Sample Output 3
01
Example
Input
0101
1100001
Output
0010
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.
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
<image>
You should count, how many there are pairs of integers (a, b) (0 β€ a, b) which satisfy the system.
Input
A single line contains two integers n, m (1 β€ n, m β€ 1000) β the parameters of the system. The numbers on the line are separated by a space.
Output
On a single line print the answer to the problem.
Examples
Input
9 3
Output
1
Input
14 28
Output
1
Input
4 20
Output
0
Note
In the first sample the suitable pair is integers (3, 0). In the second sample the suitable pair is integers (3, 5). In the third sample there is no suitable pair.
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:
* #### Complete the pattern, using the special character ```β β‘```
* #### In this kata, we draw some histogram of the sound performance of ups and downs.
# # Rules:
- parameter ```waves``` The value of sound waves, an array of number, all number in array >=0.
- return a string, ```β ``` represents the sound waves, and ```β‘``` represents the blank part, draw the histogram from bottom to top.
# # Example:
```
draw([1,2,3,4])
β‘β‘β‘β
β‘β‘β β
β‘β β β
β β β β
draw([1,2,3,3,2,1])
β‘β‘β β β‘β‘
β‘β β β β β‘
β β β β β β
draw([1,2,3,3,2,1,1,2,3,4,5,6,7])
β‘β‘β‘β‘β‘β‘β‘β‘β‘β‘β‘β‘β
β‘β‘β‘β‘β‘β‘β‘β‘β‘β‘β‘β β
β‘β‘β‘β‘β‘β‘β‘β‘β‘β‘β β β
β‘β‘β‘β‘β‘β‘β‘β‘β‘β β β β
β‘β‘β β β‘β‘β‘β‘β β β β β
β‘β β β β β‘β‘β β β β β β
β β β β β β β β β β β β β
draw([5,3,1,2,4,6,5,4,2,3,5,2,1])
β‘β‘β‘β‘β‘β β‘β‘β‘β‘β‘β‘β‘
β β‘β‘β‘β‘β β β‘β‘β‘β β‘β‘
β β‘β‘β‘β β β β β‘β‘β β‘β‘
β β β‘β‘β β β β β‘β β β‘β‘
β β β‘β β β β β β β β β β‘
β β β β β β β β β β β β β
draw([1,0,1,0,1,0,1,0])
β β‘β β‘β β‘β β‘
```
Write your solution by modifying this code:
```python
def draw(waves):
```
Your solution should implemented in the function "draw". The i
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.
Seiji Hayashi had been a professor of the Nisshinkan Samurai School in the domain of Aizu for a long time in the 18th century. In order to reward him for his meritorious career in education, Katanobu Matsudaira, the lord of the domain of Aizu, had decided to grant him a rectangular estate within a large field in the Aizu Basin. Although the size (width and height) of the estate was strictly specified by the lord, he was allowed to choose any location for the estate in the field. Inside the field which had also a rectangular shape, many Japanese persimmon trees, whose fruit was one of the famous products of the Aizu region known as 'Mishirazu Persimmon', were planted. Since persimmon was Hayashi's favorite fruit, he wanted to have as many persimmon trees as possible in the estate given by the lord.
For example, in Figure 1, the entire field is a rectangular grid whose width and height are 10 and 8 respectively. Each asterisk (*) represents a place of a persimmon tree. If the specified width and height of the estate are 4 and 3 respectively, the area surrounded by the solid line contains the most persimmon trees. Similarly, if the estate's width is 6 and its height is 4, the area surrounded by the dashed line has the most, and if the estate's width and height are 3 and 4 respectively, the area surrounded by the dotted line contains the most persimmon trees. Note that the width and height cannot be swapped; the sizes 4 by 3 and 3 by 4 are different, as shown in Figure 1.
<image>
---
Figure 1: Examples of Rectangular Estates
Your task is to find the estate of a given size (width and height) that contains the largest number of persimmon trees.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> N
> W` `H
> x1` `y1
> x2` `y2
> ...
> xN` `yN
> S` `T
>
N is the number of persimmon trees, which is a positive integer less than 500. W and H are the width and the height of the entire field respectively. You can assume that both W and H are positive integers whose values are less than 100. For each i (1 <= i <= N), xi and yi are coordinates of the i-th persimmon tree in the grid. Note that the origin of each coordinate is 1. You can assume that 1 <= xi <= W and 1 <= yi <= H, and no two trees have the same positions. But you should not assume that the persimmon trees are sorted in some order according to their positions. Lastly, S and T are positive integers of the width and height respectively of the estate given by the lord. You can also assume that 1 <= S <= W and 1 <= T <= H.
The end of the input is indicated by a line that solely contains a zero.
Output
For each data set, you are requested to print one line containing the maximum possible number of persimmon trees that can be included in an estate of the given size.
Example
Input
16
10 8
2 2
2 5
2 7
3 3
3 8
4 2
4 5
4 8
6 4
6 7
7 5
7 8
8 1
8 4
9 6
10 3
4 3
8
6 4
1 2
2 1
2 4
3 4
4 2
5 3
6 1
6 2
3 2
0
Output
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.
problem
There are many $ N $ colored balls of different weights in the queue. The queue is in ascending order from the beginning: $ 1,2,3, \ dots, N-1, N, 1,2,3, \ dots, N-1, N, 1,2,3, \ dots $ The balls are lined up, followed by the balls of color $ N $, followed by the balls of color $ 1 $. Balls of the same color weigh the same, and balls of color $ i $ weigh $ A_i $.
From this state, take out $ M $ of balls from the beginning of the queue and repeat the process of grouping them. Then stop forming groups when the total number of balls of each color removed from the cue is equal. Please note that the cue contains a sufficient number of balls and the cue will not be empty by the time you stop forming groups.
For example, when $ N = 8, M = 2 $, there are 4 groups of {color 1, color 2}, {color 3, color 4}, {color 5, color 6}, {color 7, color 8}. (At this time, there is one ball of each color). When $ N = 4, M = 3 $, {color 1, color 2, color 3}, {color 4, color 1, color 2}, {color 3, color 4, color 1}, {color 2, color There will be a $ 4 $ group of 3, colors 4} (there are 3 balls of each color each).
At this time, in each group, the difference between the maximum value and the minimum value of the weight of the balls included is called the weight range of that group. Output the sum of the weight ranges for each group.
output
Print the answer in one line. Also, output a line break at the end.
Example
Input
8 2
23 61 57 13 91 41 79 41
Output
170
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 not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.
He took a checkered white square piece of paper, consisting of n Γ n cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.
Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist.
Input
The first line contains two integers n and m (1 β€ n β€ 1000, 1 β€ m β€ min(nΒ·n, 105)) β the size of the squared piece of paper and the number of moves, correspondingly.
Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1 β€ xi, yi β€ n) β the number of row and column of the square that gets painted on the i-th move.
All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom.
Output
On a single line print the answer to the problem β the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1.
Examples
Input
4 11
1 1
1 2
1 3
2 2
2 3
1 4
2 4
3 4
3 2
3 3
4 1
Output
10
Input
4 12
1 1
1 2
1 3
2 2
2 3
1 4
2 4
3 4
3 2
4 2
4 1
3 1
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
##Task:
You have to write a function `add` which takes two binary numbers as strings and returns their sum as a string.
##Note:
* You are `not allowed to convert binary to decimal & vice versa`.
* The sum should contain `No leading zeroes`.
##Examples:
```
add('111','10'); => '1001'
add('1101','101'); => '10010'
add('1101','10111') => '100100'
```
Write your solution by modifying this code:
```python
def add(a,b):
```
Your solution should implemented in the function "add". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled.
Alice received a set of Toy Trainβ’ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
-----Input-----
The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100$; $1 \leq m \leq 200$) β the number of stations and the number of candies, respectively.
The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) β the station that initially contains candy $i$ and the destination station of the candy, respectively.
-----Output-----
In the first and only line, print $n$ space-separated integers, the $i$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $i$.
-----Examples-----
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
-----Note-----
Consider the second sample.
If the train started at station $1$, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the first candy. Proceed to station $1$. This step takes $1$ second. Load the second candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the second candy. Proceed to station $1$. This step takes $1$ second. Load the third candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the third candy.
Hence, the train needs $5$ seconds to complete the tasks.
If the train were to start at station $2$, however, it would need to move to station $1$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $5+1 = 6$ seconds.
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.
Find the last element of the given argument(s).
## Examples
```python
last([1, 2, 3, 4]) ==> 4
last("xyz") ==> "z"
last(1, 2, 3, 4) ==> 4
```
In **javascript** and **CoffeeScript** a **list** will be an `array`, a `string` or the list of `arguments`.
(courtesy of [haskell.org](http://www.haskell.org/haskellwiki/99_questions/1_to_10))
Write your solution by modifying this code:
```python
def last(*args):
```
Your solution should implemented in the function "last". The i
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 a function which takes a string, and returns its hash value.
Algorithm steps:
* `a` := sum of the ascii values of the input characters
* `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...)
* `c` := (`a` OR `b`) AND ((NOT `a`) shift left by 2 bits)
* `d` := `c` XOR (32 * (`total_number_of_spaces` + 1))
* return `d`
**Note**: OR, AND, NOT, XOR are bitwise operations.
___
### Examples
```
input = "a"
a = 97
b = 0
result = 64
input = "ca"
a = 196
b = -2
result = -820
```
___
Give an example why this hashing algorithm is bad?
Write your solution by modifying this code:
```python
def string_hash(s):
```
Your solution should implemented in the function "string_hash". The i
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.
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.
This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.
-----Input-----
The first line contains a non-empty string, that contains only lowercase English letters β the user name. This string contains at most 100 letters.
-----Output-----
If it is a female by our hero's method, print "CHAT WITH HER!" (without the quotes), otherwise, print "IGNORE HIM!" (without the quotes).
-----Examples-----
Input
wjmzbmr
Output
CHAT WITH HER!
Input
xiaodao
Output
IGNORE HIM!
Input
sevenkplus
Output
CHAT WITH HER!
-----Note-----
For the first example. There are 6 distinct characters in "wjmzbmr". These characters are: "w", "j", "m", "z", "b", "r". So wjmzbmr is a female and you should print "CHAT WITH HER!".
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 some country live wizards. They love to ride trolleybuses.
A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it leaves at the moment of time ti seconds, can go at a speed of no greater than vi meters per second, and accelerate with an acceleration no greater than a meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.
Despite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.
You, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine.
Input
The first input line contains three space-separated integers n, a, d (1 β€ n β€ 105, 1 β€ a, d β€ 106) β the number of trolleybuses, their maximum acceleration and the distance from the depot to the final station, correspondingly.
Next n lines contain pairs of integers ti vi (0 β€ t1 < t2... < tn - 1 < tn β€ 106, 1 β€ vi β€ 106) β the time when the i-th trolleybus leaves the depot and its maximum speed, correspondingly. The numbers in the lines are separated by spaces.
Output
For each trolleybus print a single line the time it arrives to the final station. Print the times for the trolleybuses in the order in which the trolleybuses are given in the input. The answer will be accepted if the absolute or relative error doesn't exceed 10 - 4.
Examples
Input
3 10 10000
0 10
5 11
1000 1
Output
1000.5000000000
1000.5000000000
11000.0500000000
Input
1 2 26
28 29
Output
33.0990195136
Note
In the first sample the second trolleybus will catch up with the first one, that will happen at distance 510.5 meters from the depot. The trolleybuses will go the remaining 9489.5 meters together at speed 10 meters per second. As a result, both trolleybuses will arrive to the final station by the moment of time 1000.5 seconds. The third trolleybus will not catch up with them. It will arrive to the final station by the moment of time 11000.05 seconds.
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.
Simple interest on a loan is calculated by simply taking the initial amount (the principal, p) and multiplying it by a rate of interest (r) and the number of time periods (n).
Compound interest is calculated by adding the interest after each time period to the amount owed, then calculating the next interest payment based on the principal PLUS the interest from all previous periods.
Given a principal *p*, interest rate *r*, and a number of periods *n*, return an array [total owed under simple interest, total owed under compound interest].
```
EXAMPLES:
interest(100,0.1,1) = [110,110]
interest(100,0.1,2) = [120,121]
interest(100,0.1,10) = [200,259]
```
Round all answers to the nearest integer. Principal will always be an integer between 0 and 9999; interest rate will be a decimal between 0 and 1; number of time periods will be an integer between 0 and 49.
---
More on [Simple interest, compound interest and continuous interest](https://betterexplained.com/articles/a-visual-guide-to-simple-compound-and-continuous-interest-rates/)
Write your solution by modifying this code:
```python
def interest(p,r,n):
```
Your solution should implemented in the function "interest". The i
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.
*Based on this Numberphile video: https://www.youtube.com/watch?v=Wim9WJeDTHQ*
---
Multiply all the digits of a nonnegative integer `n` by each other, repeating with the product until a single digit is obtained. The number of steps required is known as the **multiplicative persistence**.
Create a function that calculates the individual results of each step, not including the original number, but including the single digit, and outputs the result as a list/array. If the input is a single digit, return an empty list/array.
## Examples
```
per(1) = []
per(10) = [0]
// 1*0 = 0
per(69) = [54, 20, 0]
// 6*9 = 54 --> 5*4 = 20 --> 2*0 = 0
per(277777788888899) = [4996238671872, 438939648, 4478976, 338688, 27648, 2688, 768, 336, 54, 20, 0]
// 2*7*7*7*7*7*7*8*8*8*8*8*8*9*9 = 4996238671872 --> 4*9*9*6*2*3*8*6*7*1*8*7*2 = 4478976 --> ...
```
Write your solution by modifying this code:
```python
def per(n):
```
Your solution should implemented in the function "per". The i
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.
Chefs from all over the globe gather each year for an international convention. Each chef represents some country. Please, note that more than one chef can represent a country.
Each of them presents their best dish to the audience. The audience then sends emails to a secret and secure mail server, with the subject being the name of the chef whom they wish to elect as the "Chef of the Year".
You will be given the list of the subjects of all the emails. Find the country whose chefs got the most number of votes, and also the chef who got elected as the "Chef of the Year" (the chef who got the most number of votes).
Note 1
If several countries got the maximal number of votes, consider the country with the lexicographically smaller name among them to be a winner. Similarly if several chefs got the maximal number of votes, consider the chef with the lexicographically smaller name among them to be a winner.
Note 2
The string A = a1a2...an is called lexicographically smaller then the string B = b1b2...bm in the following two cases:
- there exists index i β€ min{n, m} such that aj = bj for 1 β€ j < i and ai < bi;
- A is a proper prefix of B, that is, n < m and aj = bj for 1 β€ j β€ n.
The characters in strings are compared by their ASCII codes.
Refer to function strcmp in C or to standard comparator < for string data structure in C++ for details.
-----Input-----
The first line of the input contains two space-separated integers N and M denoting the number of chefs and the number of emails respectively. Each of the following N lines contains two space-separated strings, denoting the name of the chef and his country respectively. Each of the following M lines contains one string denoting the subject of the email.
-----Output-----
Output should consist of two lines. The first line should contain the name of the country whose chefs got the most number of votes. The second line should contain the name of the chef who is elected as the "Chef of the Year".
-----Constraints-----
- 1 β€ N β€ 10000 (104)
- 1 β€ M β€ 100000 (105)
- Each string in the input contains only letters of English alphabets (uppercase or lowercase)
- Each string in the input has length not exceeding 10
- All chef names will be distinct
- Subject of each email will coincide with the name of one of the chefs
-----Example 1-----
Input:
1 3
Leibniz Germany
Leibniz
Leibniz
Leibniz
Output:
Germany
Leibniz
-----Example 2-----
Input:
4 5
Ramanujan India
Torricelli Italy
Gauss Germany
Lagrange Italy
Ramanujan
Torricelli
Torricelli
Ramanujan
Lagrange
Output:
Italy
Ramanujan
-----Example 3-----
Input:
2 2
Newton England
Euclid Greece
Newton
Euclid
Output:
England
Euclid
-----Explanation-----
Example 1. Here we have only one chef Leibniz and he is from Germany. Clearly, all votes are for him. So Germany is the country-winner and Leibniz is the "Chef of the Year".
Example 2. Here we have chefs Torricelli and Lagrange from Italy, chef Ramanujan from India and chef Gauss from Germany. Torricelli got 2 votes, while Lagrange got one vote. Hence the Italy got 3 votes in all. Ramanujan got also 2 votes. And so India got 2 votes in all. Finally Gauss got no votes leaving Germany without votes. So the country-winner is Italy without any ties. But we have two chefs with 2 votes: Torricelli and Ramanujan. But since the string "Ramanujan" is lexicographically smaller than "Torricelli", then Ramanujan is the "Chef of the Year".
Example 3. Here we have two countries with 1 vote: England and Greece. Since the string "England" is lexicographically smaller than "Greece", then England is the country-winner. Next, we have two chefs with 1 vote: Newton and Euclid. Since the string "Euclid" is lexicographically smaller than "Newton", then Euclid is the "Chef of the Year".
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.
Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times the words `"Sand"`, `"Water"`, `"Fish"`, and `"Sun"` appear without overlapping (regardless of the case).
## Examples
```python
sum_of_a_beach("WAtErSlIde") ==> 1
sum_of_a_beach("GolDeNSanDyWateRyBeaChSuNN") ==> 3
sum_of_a_beach("gOfIshsunesunFiSh") ==> 4
sum_of_a_beach("cItYTowNcARShoW") ==> 0
```
Write your solution by modifying this code:
```python
def sum_of_a_beach(beach):
```
Your solution should implemented in the function "sum_of_a_beach". The i
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.
Maksim walks on a Cartesian plane. Initially, he stands at the point $(0, 0)$ and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point $(0, 0)$, he can go to any of the following points in one move: $(1, 0)$; $(0, 1)$; $(-1, 0)$; $(0, -1)$.
There are also $n$ distinct key points at this plane. The $i$-th point is $p_i = (x_i, y_i)$. It is guaranteed that $0 \le x_i$ and $0 \le y_i$ and there is no key point $(0, 0)$.
Let the first level points be such points that $max(x_i, y_i) = 1$, the second level points be such points that $max(x_i, y_i) = 2$ and so on. Maksim wants to visit all the key points. But he shouldn't visit points of level $i + 1$ if he does not visit all the points of level $i$. He starts visiting the points from the minimum level of point from the given set.
The distance between two points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$ where $|v|$ is the absolute value of $v$.
Maksim wants to visit all the key points in such a way that the total distance he walks will be minimum possible. Your task is to find this distance.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
-----Input-----
The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of key points.
Each of the next $n$ lines contains two integers $x_i$, $y_i$ ($0 \le x_i, y_i \le 10^9$) β $x$-coordinate of the key point $p_i$ and $y$-coordinate of the key point $p_i$. It is guaranteed that all the points are distinct and the point $(0, 0)$ is not in this set.
-----Output-----
Print one integer β the minimum possible total distance Maksim has to travel if he needs to visit all key points in a way described above.
-----Examples-----
Input
8
2 2
1 4
2 3
3 1
3 4
1 1
4 3
1 2
Output
15
Input
5
2 1
1 0
2 0
3 2
0 3
Output
9
-----Note-----
The picture corresponding to the first example: [Image]
There is one of the possible answers of length $15$.
The picture corresponding to the second example: [Image]
There is one of the possible answers of length $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.
Ayush, Ashish and Vivek are busy preparing a new problem for the next Codeforces round and need help checking if their test cases are valid.
Each test case consists of an integer $n$ and two arrays $a$ and $b$, of size $n$. If after some (possibly zero) operations described below, array $a$ can be transformed into array $b$, the input is said to be valid. Otherwise, it is invalid.
An operation on array $a$ is: select an integer $k$ $(1 \le k \le \lfloor\frac{n}{2}\rfloor)$ swap the prefix of length $k$ with the suffix of length $k$
For example, if array $a$ initially is $\{1, 2, 3, 4, 5, 6\}$, after performing an operation with $k = 2$, it is transformed into $\{5, 6, 3, 4, 1, 2\}$.
Given the set of test cases, help them determine if each one is valid or invalid.
-----Input-----
The first line contains one integer $t$ $(1 \le t \le 500)$Β β the number of test cases. The description of each test case is as follows.
The first line of each test case contains a single integer $n$ $(1 \le n \le 500)$Β β the size of the arrays.
The second line of each test case contains $n$ integers $a_1$, $a_2$, ..., $a_n$ $(1 \le a_i \le 10^9)$ β elements of array $a$.
The third line of each test case contains $n$ integers $b_1$, $b_2$, ..., $b_n$ $(1 \le b_i \le 10^9)$ β elements of array $b$.
-----Output-----
For each test case, print "Yes" if the given input is valid. Otherwise print "No".
You may print the answer in any case.
-----Example-----
Input
5
2
1 2
2 1
3
1 2 3
1 2 3
3
1 2 4
1 3 4
4
1 2 3 2
3 1 2 2
3
1 2 3
1 3 2
Output
yes
yes
No
yes
No
-----Note-----
For the first test case, we can swap prefix $a[1:1]$ with suffix $a[2:2]$ to get $a=[2, 1]$.
For the second test case, $a$ is already equal to $b$.
For the third test case, it is impossible since we cannot obtain $3$ in $a$.
For the fourth test case, we can first swap prefix $a[1:1]$ with suffix $a[4:4]$ to obtain $a=[2, 2, 3, 1]$. Now we can swap prefix $a[1:2]$ with suffix $a[3:4]$ to obtain $a=[3, 1, 2, 2]$.
For the fifth test case, it is impossible to convert $a$ to $b$.
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.
Variation of this nice kata, the war has expanded and become dirtier and meaner; both even and odd numbers will fight with their pointy `1`s. And negative integers are coming into play as well, with, Γ§a va sans dire, a negative contribution (think of them as spies or saboteurs).
Again, three possible outcomes: `odds win`, `evens win` and `tie`.
Examples:
```python
bits_war([1,5,12]) => "odds win" #1+101 vs 1100, 3 vs 2
bits_war([7,-3,20]) => "evens win" #111-11 vs 10100, 3-2 vs 2
bits_war([7,-3,-2,6]) => "tie" #111-11 vs -1+110, 3-2 vs -1+2
```
Write your solution by modifying this code:
```python
def bits_war(numbers):
```
Your solution should implemented in the function "bits_war". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata we are focusing on the Numpy python package. You must write a function called `looper` which takes three integers `start, stop and number` as input and returns a list from `start` to `stop` with `number` total values in the list. Five examples are shown below:
```
looper(1, 5, 1) = [1.0]
looper(1, 5, 2) = [1.0, 5.0]
looper(1, 5, 3) = [1.0, 3.0, 5.0]
looper(1, 5, 4) = [1.0, 2.333333333333333, 3.6666666666666665, 5.0]
looper(1, 5, 5) = [1.0, 2.0, 3.0, 4.0, 5.0]
```
Write your solution by modifying this code:
```python
def looper(start, stop, number):
```
Your solution should implemented in the function "looper". The i
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.
Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a β€ x β€ b and x is divisible by k.
-----Input-----
The only line contains three space-separated integers k, a and b (1 β€ k β€ 10^18; - 10^18 β€ a β€ b β€ 10^18).
-----Output-----
Print the required number.
-----Examples-----
Input
1 1 10
Output
10
Input
2 -4 4
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.
The Fair Nut likes kvass very much. On his birthday parents presented him $n$ kegs of kvass. There are $v_i$ liters of kvass in the $i$-th keg. Each keg has a lever. You can pour your glass by exactly $1$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $s$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.
Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $s$ liters of kvass.
-----Input-----
The first line contains two integers $n$ and $s$ ($1 \le n \le 10^3$, $1 \le s \le 10^{12}$)Β β the number of kegs and glass volume.
The second line contains $n$ integers $v_1, v_2, \ldots, v_n$ ($1 \le v_i \le 10^9$)Β β the volume of $i$-th keg.
-----Output-----
If the Fair Nut cannot pour his glass by $s$ liters of kvass, print $-1$. Otherwise, print a single integerΒ β how much kvass in the least keg can be.
-----Examples-----
Input
3 3
4 3 5
Output
3
Input
3 4
5 3 4
Output
2
Input
3 7
1 2 3
Output
-1
-----Note-----
In the first example, the answer is $3$, the Fair Nut can take $1$ liter from the first keg and $2$ liters from the third keg. There are $3$ liters of kvass in each keg.
In the second example, the answer is $2$, the Fair Nut can take $3$ liters from the first keg and $1$ liter from the second keg.
In the third example, the Fair Nut can't pour his cup by $7$ liters, so the answer 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.
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.
Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.
Input
The first line contains a single number n (2 β€ n β€ 1000) β the number of the tram's stops.
Then n lines follow, each contains two integers ai and bi (0 β€ ai, bi β€ 1000) β the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement.
* The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, <image>. This particularly means that a1 = 0.
* At the last stop, all the passengers exit the tram and it becomes empty. More formally, <image>.
* No passenger will enter the train at the last stop. That is, bn = 0.
Output
Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).
Examples
Input
4
0 3
2 5
4 2
4 0
Output
6
Note
For the first example, a capacity of 6 is sufficient:
* At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3.
* At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now.
* At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now.
* Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints.
Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.
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 Fair Nut is going to travel to the Tree Country, in which there are $n$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $u$ and go by a simple path to city $v$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.
A filling station is located in every city. Because of strange law, Nut can buy only $w_i$ liters of gasoline in the $i$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.
He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 3 \cdot 10^5$)Β β the number of cities.
The second line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \leq w_{i} \leq 10^9$)Β β the maximum amounts of liters of gasoline that Nut can buy in cities.
Each of the next $n - 1$ lines describes road and contains three integers $u$, $v$, $c$ ($1 \leq u, v \leq n$, $1 \leq c \leq 10^9$, $u \ne v$), where $u$ and $v$Β β cities that are connected by this road and $c$Β β its length.
It is guaranteed that graph of road connectivity is a tree.
-----Output-----
Print one numberΒ β the maximum amount of gasoline that he can have at the end of the path.
-----Examples-----
Input
3
1 3 3
1 2 2
1 3 2
Output
3
Input
5
6 3 2 5 0
1 2 10
2 3 3
2 4 1
1 5 1
Output
7
-----Note-----
The optimal way in the first example is $2 \to 1 \to 3$. [Image]
The optimal way in the second example is $2 \to 4$. [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.
For two sequences S and T of length N consisting of 0 and 1, let us define f(S, T) as follows:
- Consider repeating the following operation on S so that S will be equal to T. f(S, T) is the minimum possible total cost of those operations.
- Change S_i (from 0 to 1 or vice versa). The cost of this operation is D \times C_i, where D is the number of integers j such that S_j \neq T_j (1 \leq j \leq N) just before this change.
There are 2^N \times (2^N - 1) pairs (S, T) of different sequences of length N consisting of 0 and 1. Compute the sum of f(S, T) over all of those pairs, modulo (10^9+7).
-----Constraints-----
- 1 \leq N \leq 2 \times 10^5
- 1 \leq C_i \leq 10^9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
C_1 C_2 \cdots C_N
-----Output-----
Print the sum of f(S, T), modulo (10^9+7).
-----Sample Input-----
1
1000000000
-----Sample Output-----
999999993
There are two pairs (S, T) of different sequences of length 2 consisting of 0 and 1, as follows:
- S = (0), T = (1): by changing S_1 to 1, we can have S = T at the cost of 1000000000, so f(S, T) = 1000000000.
- S = (1), T = (0): by changing S_1 to 0, we can have S = T at the cost of 1000000000, so f(S, T) = 1000000000.
The sum of these is 2000000000, and we should print it modulo (10^9+7), that is, 999999993.
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 $n \times n$ square grid and an integer $k$. Put an integer in each cell while satisfying the conditions below. All numbers in the grid should be between $1$ and $k$ inclusive. Minimum number of the $i$-th row is $1$ ($1 \le i \le n$). Minimum number of the $j$-th column is $1$ ($1 \le j \le n$).
Find the number of ways to put integers in the grid. Since the answer can be very large, find the answer modulo $(10^{9} + 7)$. [Image] These are the examples of valid and invalid grid when $n=k=2$.
-----Input-----
The only line contains two integers $n$ and $k$ ($1 \le n \le 250$, $1 \le k \le 10^{9}$).
-----Output-----
Print the answer modulo $(10^{9} + 7)$.
-----Examples-----
Input
2 2
Output
7
Input
123 456789
Output
689974806
-----Note-----
In the first example, following $7$ cases are possible. [Image]
In the second example, make sure you print the answer modulo $(10^{9} + 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.
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.
To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.
Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
-----Input-----
The first line contains a single integer nΒ β the length of the sequence of games (1 β€ n β€ 10^5).
The second line contains n space-separated integers a_{i}. If a_{i} = 1, then the i-th serve was won by Petya, if a_{i} = 2, then the i-th serve was won by Gena.
It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
-----Output-----
In the first line print a single number kΒ β the number of options for numbers s and t.
In each of the following k lines print two integers s_{i} and t_{i}Β β the option for numbers s and t. Print the options in the order of increasing s_{i}, and for equal s_{i}Β β in the order of increasing t_{i}.
-----Examples-----
Input
5
1 2 1 2 1
Output
2
1 3
3 1
Input
4
1 1 1 1
Output
3
1 4
2 2
4 1
Input
4
1 2 1 2
Output
0
Input
8
2 1 2 1 1 1 1 1
Output
3
1 6
2 3
6 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.
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with $n$ rows and $m$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $1$. For example, park with $n=m=2$ has $12$ streets.
You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).
[Image] The park sizes are: $n=4$, $m=5$. The lighted squares are marked yellow. Please note that all streets have length $1$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit.
Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) β the number of test cases in the input. Then $t$ test cases follow.
Each test case is a line containing two integers $n$, $m$ ($1 \le n, m \le 10^4$) β park sizes.
-----Output-----
Print $t$ answers to the test cases. Each answer must be a single integer β the minimum number of lanterns that are required to light all the squares.
-----Example-----
Input
5
1 1
1 3
2 2
3 3
5 3
Output
1
2
2
5
8
-----Note-----
Possible optimal arrangement of the lanterns for the $2$-nd test case of input data example: [Image]
Possible optimal arrangement of the lanterns for the $3$-rd test case of input data example: [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.
Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you)Β β who knows?
Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r), Mike can instantly tell the value of $\operatorname{max}_{i = l}^{r} a_{i}$ while !Mike can instantly tell the value of $\operatorname{min}_{i = l} b_{i}$.
Now suppose a robot (you!) asks them all possible different queries of pairs of integers (l, r) (1 β€ l β€ r β€ n) (so he will make exactly n(n + 1) / 2 queries) and counts how many times their answers coincide, thus for how many pairs $\operatorname{max}_{i = l}^{r} a_{i} = \operatorname{min}_{i = l} b_{i}$ is satisfied.
How many occasions will the robot count?
-----Input-----
The first line contains only integer n (1 β€ n β€ 200 000).
The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^9 β€ a_{i} β€ 10^9)Β β the sequence a.
The third line contains n integer numbers b_1, b_2, ..., b_{n} ( - 10^9 β€ b_{i} β€ 10^9)Β β the sequence b.
-----Output-----
Print the only integer numberΒ β the number of occasions the robot will count, thus for how many pairs $\operatorname{max}_{i = l}^{r} a_{i} = \operatorname{min}_{i = l} b_{i}$ is satisfied.
-----Examples-----
Input
6
1 2 3 2 1 4
6 7 1 2 3 2
Output
2
Input
3
3 3 3
1 1 1
Output
0
-----Note-----
The occasions in the first sample case are:
1.l = 4,r = 4 since max{2} = min{2}.
2.l = 4,r = 5 since max{2, 1} = min{2, 3}.
There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always 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.
Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
-----Input-----
The firt line of the input contains integers n, m, s and t (2 β€ n β€ 1000, 1 β€ m β€ 1000, 1 β€ s, t β€ n, s β t)Β β the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers u_{i} and v_{i} (1 β€ u_{i}, v_{i} β€ n, u_{i} β v_{i}), meaning that this road connects junctions u_{i} and v_{i} directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
-----Output-----
Print one integerΒ β the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
-----Examples-----
Input
5 4 1 5
1 2
2 3
3 4
4 5
Output
0
Input
5 4 3 5
1 2
2 3
3 4
4 5
Output
5
Input
5 6 1 5
1 2
1 3
1 4
4 5
3 5
2 5
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.
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a_1, a_2, ..., a_{n}, then after we apply the described operation, the sequence transforms into a_1, a_2, ..., a_{n}[, a_1, a_2, ..., a_{l}] (the block in the square brackets must be repeated c times).
A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
-----Input-----
The first line contains integer m (1 β€ m β€ 10^5) β the number of stages to build a sequence.
Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer x_{i} (1 β€ x_{i} β€ 10^5) β the number to add. Type 2 means copying a prefix of length l_{i} to the end c_{i} times, in this case the line further contains two integers l_{i}, c_{i} (1 β€ l_{i} β€ 10^5, 1 β€ c_{i} β€ 10^4), l_{i} is the length of the prefix, c_{i} is the number of copyings. It is guaranteed that the length of prefix l_{i} is never larger than the current length of the sequence.
The next line contains integer n (1 β€ n β€ 10^5) β the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print the elements that Sereja is interested in, in the order in which their numbers occur in the input.
-----Examples-----
Input
6
1 1
1 2
2 2 1
1 3
2 5 2
1 4
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Output
1 2 1 2 3 1 2 1 2 3 1 2 1 2 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.
Ancient Egyptians are known to have used a large set of symbols $\sum$ to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S_1 and S_2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set $\sum$ have equal probability for being in the position of any erased symbol.
Fifa challenged Fafa to calculate the probability that S_1 is lexicographically greater than S_2. Can you help Fafa with this task?
You know that $|\sum|= m$, i.Β e. there were m distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to m in alphabet order. A word x is lexicographically greater than a word y of the same length, if the words are same up to some position, and then the word x has a larger character, than the word y.
We can prove that the probability equals to some fraction $P / Q$, where P and Q are coprime integers, and $Q \neq 0 \text{mod}(10^{9} + 7)$. Print as the answer the value $R = P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, i.Β e. such a non-negative integer less than 10^9 + 7, such that $R \cdot Q \equiv P \operatorname{mod}(10^{9} + 7)$, where $a \equiv b \text{mod}(m)$ means that a and b give the same remainders when divided by m.
-----Input-----
The first line contains two integers n and m (1 β€ n, m β€ 10^5) β the length of each of the two words and the size of the alphabet $\sum$, respectively.
The second line contains n integers a_1, a_2, ..., a_{n} (0 β€ a_{i} β€ m) β the symbols of S_1. If a_{i} = 0, then the symbol at position i was erased.
The third line contains n integers representing S_2 with the same format as S_1.
-----Output-----
Print the value $P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, where P and Q are coprime and $P / Q$ is the answer to the problem.
-----Examples-----
Input
1 2
0
1
Output
500000004
Input
1 2
1
0
Output
0
Input
7 26
0 15 12 9 13 0 14
11 1 0 13 15 12 0
Output
230769233
-----Note-----
In the first sample, the first word can be converted into (1) or (2). The second option is the only one that will make it lexicographically larger than the second word. So, the answer to the problem will be $\frac{1}{2} \operatorname{mod}(10^{9} + 7)$, that is 500000004, because $(500000004 \cdot 2) \operatorname{mod}(10^{9} + 7) = 1$.
In the second example, there is no replacement for the zero in the second word that will make the first one lexicographically larger. So, the answer to the problem is $\frac{0}{1} \operatorname{mod}(10^{9} + 7)$, that is 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 given a tree (an undirected connected graph without cycles) and an integer $s$.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $s$. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
-----Input-----
The first line contains two integer numbers $n$ and $s$ ($2 \leq n \leq 10^5$, $1 \leq s \leq 10^9$) β the number of vertices in the tree and the sum of edge weights.
Each of the following $nβ1$ lines contains two space-separated integer numbers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) β the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
-----Output-----
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $s$.
Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$.
Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is considered correct if $\frac {|a-b|} {max(1, b)} \leq 10^{-6}$.
-----Examples-----
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
-----Note-----
In the first example it is necessary to put weights like this: [Image]
It is easy to see that the diameter of this tree is $2$. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this: [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.
Is the number even?
If the numbers is even return `true`. If it's odd, return `false`.
Oh yeah... the following symbols/commands have been disabled!
use of ```%```
use of ```.even?``` in Ruby
use of ```mod``` in Python
Write your solution by modifying this code:
```python
def is_even(n):
```
Your solution should implemented in the function "is_even". The i
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 random string consisting of numbers, letters, symbols, you need to sum up the numbers in the string.
Note:
- Consecutive integers should be treated as a single number. eg, `2015` should be treated as a single number `2015`, NOT four numbers
- All the numbers should be treaded as positive integer. eg, `11-14` should be treated as two numbers `11` and `14`. Same as `3.14`, should be treated as two numbers `3` and `14`
- If no number was given in the string, it should return `0`
Example:
```
str = "In 2015, I want to know how much does iPhone 6+ cost?"
```
The numbers are `2015`, `6`
Sum is `2021`.
Write your solution by modifying this code:
```python
def sum_from_string(string):
```
Your solution should implemented in the function "sum_from_string". The i
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 is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains $a$ stones, the second of them contains $b$ stones and the third of them contains $c$ stones.
Each time she can do one of two operations: take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones).
She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $0$ stones. Can you help her?
-----Input-----
The first line contains one integer $t$ ($1 \leq t \leq 100$) Β β the number of test cases. Next $t$ lines describe test cases in the following format:
Line contains three non-negative integers $a$, $b$ and $c$, separated by spaces ($0 \leq a,b,c \leq 100$)Β β the number of stones in the first, the second and the third heap, respectively.
In hacks it is allowed to use only one test case in the input, so $t = 1$ should be satisfied.
-----Output-----
Print $t$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer Β β the maximum possible number of stones that Alice can take after making some operations.
-----Example-----
Input
3
3 4 5
1 0 5
5 3 2
Output
9
0
6
-----Note-----
For the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $9$. It is impossible to make some operations to take more than $9$ stones, so the answer is $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.
From the divine land of heaven came to earth a fruit known as Magic fruit.Unfortunately the fruit was found by two friends X and Y.
After lot of fighting,they came to the conclusion that they will share the fruit if and only if when they can divide it into two even weighing parts without wasting any part of fruit. Given weight of the fruit tell them if they can share it.
Input
The first (and the only) input line contains integer number w (1ββ€βwββ€β100) β the weight of the magic fruit.
Output
Print YES, if the boys can divide the magic fruit into two parts, each of them weighing even number of kilos; and NO in the opposite case.
SAMPLE INPUT
8
SAMPLE OUTPUT
YES
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.
Some examples of beautiful numbers: 1_2 (1_10); 110_2 (6_10); 1111000_2 (120_10); 111110000_2 (496_10).
More formally, the number is beautiful iff there exists some positive integer k such that the number is equal to (2^{k} - 1) * (2^{k} - 1).
Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find it!
-----Input-----
The only line of input contains one number n (1 β€ n β€ 10^5) β the number Luba has got.
-----Output-----
Output one number β the greatest beautiful divisor of Luba's number. It is obvious that the answer always exists.
-----Examples-----
Input
3
Output
1
Input
992
Output
496
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 two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word. The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can assume both words will contain the dividing letter.
## Examples
```python
string_merge("hello", "world", "l") ==> "held"
string_merge("coding", "anywhere", "n") ==> "codinywhere"
string_merge("jason", "samson", "s") ==> "jasamson"
string_merge("wonderful", "people", "e") ==> "wondeople"
```
Write your solution by modifying this code:
```python
def string_merge(string1, string2, letter):
```
Your solution should implemented in the function "string_merge". The i
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.
Ridbit starts with an integer $n$.
In one move, he can perform one of the following operations:
divide $n$ by one of its proper divisors, or
subtract $1$ from $n$ if $n$ is greater than $1$.
A proper divisor is a divisor of a number, excluding itself. For example, $1$, $2$, $4$, $5$, and $10$ are proper divisors of $20$, but $20$ itself is not.
What is the minimum number of moves Ridbit is required to make to reduce $n$ to $1$?
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 1000$) β the number of test cases.
The only line of each test case contains a single integer $n$ ($1 \leq n \leq 10^9$).
-----Output-----
For each test case, output the minimum number of moves required to reduce $n$ to $1$.
-----Examples-----
Input
6
1
2
3
4
6
9
Output
0
1
2
2
2
3
-----Note-----
For the test cases in the example, $n$ may be reduced to $1$ using the following operations in sequence
$1$
$2 \xrightarrow{} 1$
$3 \xrightarrow{} 2 \xrightarrow{} 1$
$4 \xrightarrow{} 2 \xrightarrow{} 1$
$6 \xrightarrow{} 2 \xrightarrow{} 1$
$9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 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.
Problem
You brought a flat, holeless donut with a $ W $ horizontal $ H $ vertical $ H $ rectangle for ACPC.
Place this donut on the $ 2 $ dimension plane coordinate $ (0,0) $ with the center of the donut so that the side of length H and the $ y $ axis are parallel.
On the ACPC $ 1 $ day you ate a donut that was in the range of $ w $ vertical $ h $ centered on the coordinates ($ x $, $ y $).
If you want to eat the same amount on the $ 2 $ and $ 3 $ days, divide the donut by a straight line passing through the coordinates $ (0,0) $, and the sum of the donut areas in the area on one side of the straight line is on the other side I want it to be equal to the sum of the donut areas in the area of.
Find one slope of such a straight line.
Constraints
The input satisfies the following conditions.
* $ 1 \ lt h \ lt H \ lt 10 ^ 6 $
* $ 1 \ lt w \ lt W \ lt 10 ^ 6 $
* $ 1 \ le y \ le (h / 2 + H-1)-H / 2 $
* $ 1 \ le x \ le (w / 2 + W-1)-W / 2 $
* $ W $, $ H $, $ w $, $ h $ are even numbers
Input
The input is given in the following format.
$ W $ $ H $ $ w $ $ h $ $ x $ $ y $
Output
Output the slope of a straight line in one line. If the absolute error or relative error is $ 10 ^ {-6} $ or less, the answer is correct.
Examples
Input
6000 5000 20 10 400 300
Output
0.75
Input
10 10 8 8 8 8
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.
Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $n$ problems of distinct difficulty, the difficulties are numbered from $1$ to $n$.
To hold a round Arkady needs $n$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $1$ to $n$ and puts it into the problems pool.
At each moment when Arkady can choose a set of $n$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.
You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10^5$)Β β the number of difficulty levels and the number of problems Arkady created.
The second line contains $m$ integers $a_1, a_2, \ldots, a_m$ ($1 \le a_i \le n$)Β β the problems' difficulties in the order Arkady created them.
-----Output-----
Print a line containing $m$ digits. The $i$-th digit should be $1$ if Arkady held the round after creation of the $i$-th problem, and $0$ otherwise.
-----Examples-----
Input
3 11
2 3 1 2 2 2 3 2 2 3 1
Output
00100000001
Input
4 8
4 1 3 3 2 3 3 3
Output
00001000
-----Note-----
In the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m β€ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.
Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.
Help the Beaver to write a program that will encrypt messages in the described manner.
Input
The first input line contains three integers n, m and c, separated by single spaces.
The second input line contains n integers ai (0 β€ ai < c), separated by single spaces β the original message.
The third input line contains m integers bi (0 β€ bi < c), separated by single spaces β the encryption key.
The input limitations for getting 30 points are:
* 1 β€ m β€ n β€ 103
* 1 β€ c β€ 103
The input limitations for getting 100 points are:
* 1 β€ m β€ n β€ 105
* 1 β€ c β€ 103
Output
Print n space-separated integers β the result of encrypting the original message.
Examples
Input
4 3 2
1 1 1 1
1 1 1
Output
0 1 1 0
Input
3 1 5
1 2 3
4
Output
0 1 2
Note
In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
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 very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number t_{i}: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.
Initially, Petya was in one of the rooms at minute 0, he didn't write down number t_0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
-----Input-----
The first line contains a single integer n (1 β€ n β€ 2Β·10^5) β then number of notes in Petya's logbook.
The second line contains n non-negative integers t_1, t_2, ..., t_{n} (0 β€ t_{i} < i) β notes in the logbook.
-----Output-----
In the only line print a single integer β the minimum possible number of rooms in Paris catacombs.
-----Examples-----
Input
2
0 0
Output
2
Input
5
0 1 0 1 3
Output
3
-----Note-----
In the first sample, sequence of rooms Petya visited could be, for example 1 β 1 β 2, 1 β 2 β 1 or 1 β 2 β 3. The minimum possible number of rooms is 2.
In the second sample, the sequence could be 1 β 2 β 3 β 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.
One of the oddest traditions of the town of Gameston may be that even the town mayor of the next term is chosen according to the result of a game. When the expiration of the term of the mayor approaches, at least three candidates, including the mayor of the time, play a game of pebbles, and the winner will be the next mayor.
The rule of the game of pebbles is as follows. In what follows, n is the number of participating candidates.
Requisites A round table, a bowl, and plenty of pebbles. Start of the Game A number of pebbles are put into the bowl; the number is decided by the Administration Commission using some secret stochastic process. All the candidates, numbered from 0 to n-1 sit around the round table, in a counterclockwise order. Initially, the bowl is handed to the serving mayor at the time, who is numbered 0. Game Steps When a candidate is handed the bowl and if any pebbles are in it, one pebble is taken out of the bowl and is kept, together with those already at hand, if any. If no pebbles are left in the bowl, the candidate puts all the kept pebbles, if any, into the bowl. Then, in either case, the bowl is handed to the next candidate to the right. This step is repeated until the winner is decided. End of the Game When a candidate takes the last pebble in the bowl, and no other candidates keep any pebbles, the game ends and that candidate with all the pebbles is the winner.
A math teacher of Gameston High, through his analysis, concluded that this game will always end within a finite number of steps, although the number of required steps can be very large.
Input
The input is a sequence of datasets. Each dataset is a line containing two integers n and p separated by a single space. The integer n is the number of the candidates including the current mayor, and the integer p is the total number of the pebbles initially put in the bowl. You may assume 3 β€ n β€ 50 and 2 β€ p β€ 50.
With the settings given in the input datasets, the game will end within 1000000 (one million) steps.
The end of the input is indicated by a line containing two zeros separated by a single space.
Output
The output should be composed of lines corresponding to input datasets in the same order, each line of which containing the candidate number of the winner. No other characters should appear in the output.
Sample Input
3 2
3 3
3 50
10 29
31 32
50 2
50 50
0 0
Output for the Sample Input
1
0
1
5
30
1
13
Example
Input
3 2
3 3
3 50
10 29
31 32
50 2
50 50
0 0
Output
1
0
1
5
30
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.
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.
Graph is given as the array f_0, f_1, ..., f_{n} - 1, where f_{i} β the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w_0, w_1, ..., w_{n} - 1, where w_{i} β the arc weight from i to f_{i}. [Image] The graph from the first sample test.
Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers s_{i} and m_{i}, where: s_{i} β the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i; m_{i} β the minimal weight from all arcs on the path with length k which starts from the vertex i.
The length of the path is the number of arcs on this path.
-----Input-----
The first line contains two integers n, k (1 β€ n β€ 10^5, 1 β€ k β€ 10^10). The second line contains the sequence f_0, f_1, ..., f_{n} - 1 (0 β€ f_{i} < n) and the third β the sequence w_0, w_1, ..., w_{n} - 1 (0 β€ w_{i} β€ 10^8).
-----Output-----
Print n lines, the pair of integers s_{i}, m_{i} in each line.
-----Examples-----
Input
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3 4 0
4 1 2 14 3
Output
7 1
17 1
19 2
21 3
8 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 matrix, consisting of n rows and m columns. The rows are numbered top to bottom, the columns are numbered left to right.
Each cell of the matrix can be either free or locked.
Let's call a path in the matrix a staircase if it:
* starts and ends in the free cell;
* visits only free cells;
* has one of the two following structures:
1. the second cell is 1 to the right from the first one, the third cell is 1 to the bottom from the second one, the fourth cell is 1 to the right from the third one, and so on;
2. the second cell is 1 to the bottom from the first one, the third cell is 1 to the right from the second one, the fourth cell is 1 to the bottom from the third one, and so on.
In particular, a path, consisting of a single cell, is considered to be a staircase.
Here are some examples of staircases:
<image>
Initially all the cells of the matrix are free.
You have to process q queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.
Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
Input
The first line contains three integers n, m and q (1 β€ n, m β€ 1000; 1 β€ q β€ 10^4) β the sizes of the matrix and the number of queries.
Each of the next q lines contains two integers x and y (1 β€ x β€ n; 1 β€ y β€ m) β the description of each query.
Output
Print q integers β the i-th value should be equal to the number of different staircases after i queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.
Examples
Input
2 2 8
1 1
1 1
1 1
2 2
1 1
1 2
2 1
1 1
Output
5
10
5
2
5
3
1
0
Input
3 4 10
1 4
1 2
2 3
1 2
2 3
3 2
1 3
3 4
1 3
3 1
Output
49
35
24
29
49
39
31
23
29
27
Input
1000 1000 2
239 634
239 634
Output
1332632508
1333333000
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.