question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the assignment of teams of a piece in an n character string, where each character is A or B.
2. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change A to B and B to A). He can do this step at most once.
3. Alice will get all the pieces marked A and Bob will get all the pieces marked B.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input
The first line contains integer n (1 β€ n β€ 5Β·105) β the number of game pieces.
The second line contains n integers pi (1 β€ pi β€ 109) β the strength of the i-th piece.
The third line contains n characters A or B β the assignment of teams after the first step (after Alice's step).
Output
Print the only integer a β the maximum strength Bob can achieve.
Examples
Input
5
1 2 3 4 5
ABABA
Output
11
Input
5
1 2 3 4 5
AAAAA
Output
15
Input
1
1
B
Output
1
Note
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 a sequence a of n integers between 1 and m, inclusive, denote f(a) as the number of distinct subsequences of a (including the empty subsequence).
You are given two positive integers n and m. Let S be the set of all sequences of length n consisting of numbers from 1 to m. Compute the sum f(a) over all a in S modulo 109 + 7.
Input
The only line contains two integers n and m (1 β€ n, m β€ 106) β the number of elements in arrays and the upper bound for elements.
Output
Print the only integer c β the desired sum modulo 109 + 7.
Examples
Input
1 3
Output
6
Input
2 2
Output
14
Input
3 3
Output
174
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.
For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.
Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.
Katya had no problems with completing this task. Will you do the same?
Input
The only line of the input contains single integer n (1 β€ n β€ 109) β the length of some side of a right triangle.
Output
Print two integers m and k (1 β€ m, k β€ 1018), such that n, m and k form a Pythagorean triple, in the only line.
In case if there is no any Pythagorean triple containing integer n, print - 1 in the only line. If there are many answers, print any of them.
Examples
Input
3
Output
4 5
Input
6
Output
8 10
Input
1
Output
-1
Input
17
Output
144 145
Input
67
Output
2244 2245
Note
<image>
Illustration for the first sample.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers A = [a1, a2, ..., an] and B = [b1, b2, ..., bn] of length n each which he uses to ask people some quite peculiar questions.
To test you on how good are you at spotting inequality in life, he wants you to find an "unfair" subset of the original sequence. To be more precise, he wants you to select k numbers P = [p1, p2, ..., pk] such that 1 β€ pi β€ n for 1 β€ i β€ k and elements in P are distinct. Sequence P will represent indices of elements that you'll select from both sequences. He calls such a subset P "unfair" if and only if the following conditions are satisfied: 2Β·(ap1 + ... + apk) is greater than the sum of all elements from sequence A, and 2Β·(bp1 + ... + bpk) is greater than the sum of all elements from the sequence B. Also, k should be smaller or equal to <image> because it will be to easy to find sequence P if he allowed you to select too many elements!
Mike guarantees you that a solution will always exist given the conditions described above, so please help him satisfy his curiosity!
Input
The first line contains integer n (1 β€ n β€ 105) β the number of elements in the sequences.
On the second line there are n space-separated integers a1, ..., an (1 β€ ai β€ 109) β elements of sequence A.
On the third line there are also n space-separated integers b1, ..., bn (1 β€ bi β€ 109) β elements of sequence B.
Output
On the first line output an integer k which represents the size of the found subset. k should be less or equal to <image>.
On the next line print k integers p1, p2, ..., pk (1 β€ pi β€ n) β the elements of sequence P. You can print the numbers in any order you want. Elements in sequence P should be distinct.
Example
Input
5
8 7 4 8 3
4 2 5 3 7
Output
3
1 4 5
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.
Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.
So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.
Input
The first line of input file contains a positive integer q (1 β€ q β€ 100 000) β the number of graphs Ivan needs to construct.
Then q lines follow, i-th line contains one positive integer ni (1 β€ ni β€ 2Β·109) β the number of vertices in i-th graph.
Note that in hacks you have to use q = 1.
Output
Output q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.
Example
Input
3
3
4
6
Output
2
3
6
Note
In the first example it is possible to construct these graphs:
1. 1 - 2, 1 - 3;
2. 1 - 2, 1 - 3, 2 - 4;
3. 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Γ m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:
1. All cells in a set have the same color.
2. Every two cells in a set share row or column.
Input
The first line of input contains integers n and m (1 β€ n, m β€ 50) β the number of rows and the number of columns correspondingly.
The next n lines of input contain descriptions of rows. There are m integers, separated by spaces, in each line. The number equals 0 if the corresponding cell is colored white and equals 1 if the corresponding cell is colored black.
Output
Output single integer β the number of non-empty sets from the problem description.
Examples
Input
1 1
0
Output
1
Input
2 3
1 0 1
0 1 0
Output
8
Note
In the second example, there are six one-element sets. Additionally, there are two two-element sets, the first one consists of the first and the third cells of the first row, the second one consists of the first and the third cells of the second row. To sum up, there are 8 sets.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* β you can add an asterisk to the right of the existing type X β that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite β to any type of X, which is a pointer, you can add an ampersand β that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types β void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator β the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and Ρ β to void**.
The next query typedef redefines b β it is now equal to &b = &void* = void. At that, the Ρ type doesn't change.
After that the Ρ type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.
Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.
The definition of a rooted tree can be found [here](https://goo.gl/1dqvzz).
Input
The first line contains one integer n β the number of vertices in the tree (3 β€ n β€ 1 000). Each of the next n - 1 lines contains one integer pi (1 β€ i β€ n - 1) β the index of the parent of the i + 1-th vertex (1 β€ pi β€ i).
Vertex 1 is the root. It's guaranteed that the root has at least 2 children.
Output
Print "Yes" if the tree is a spruce and "No" otherwise.
Examples
Input
4
1
1
1
Output
Yes
Input
7
1
1
1
2
2
2
Output
No
Input
8
1
1
1
1
3
3
3
Output
Yes
Note
The first example:
<image>
The second example:
<image>
It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.
The third example:
<image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms.
Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)).
Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs.
Input
The first line of the input contains single integer n (1 β€ n β€ 105) β the number of moves in the walking sequence.
The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.
Output
On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.
Examples
Input
1
U
Output
0
Input
6
RURUUR
Output
1
Input
7
URRRUUU
Output
2
Note
The figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at which Fafa have to pay silver coins.
<image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 following process.
There is a platform with n columns. 1 Γ 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.
When all of the n columns have at least one square in them, the bottom row is being removed. You will receive 1 point for this, and all the squares left will fall down one row.
You task is to calculate the amount of points you will receive.
Input
The first line of input contain 2 integer numbers n and m (1 β€ n, m β€ 1000) β the length of the platform and the number of the squares.
The next line contain m integer numbers c_1, c_2, ..., c_m (1 β€ c_i β€ n) β column in which i-th square will appear.
Output
Print one integer β the amount of points you will receive.
Example
Input
3 9
1 1 2 2 2 3 1 2 3
Output
2
Note
In the sample case the answer will be equal to 2 because after the appearing of 6-th square will be removed one row (counts of the squares on the platform will look like [2~ 3~ 1], and after removing one row will be [1~ 2~ 0]).
After the appearing of 9-th square counts will be [2~ 3~ 1], and after removing one row it will look like [1~ 2~ 0].
So the answer will be equal to 2.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second.
Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 β€ l_i < r_i β€ a).
There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 β€ x_i β€ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas.
During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i β€ x and x + 1 β€ r_i).
The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.
Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.
Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.
Input
The first line contains three integers a, n and m (1 β€ a, m β€ 2000, 1 β€ n β€ βa/2β) β the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.
Each of the next n lines contains two integers l_i and r_i (0 β€ l_i < r_i β€ a) β the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i.
Each of the next m lines contains two integers x_i and p_i (0 β€ x_i β€ a, 1 β€ p_i β€ 10^5) β the location and the weight of the i-th umbrella.
Output
Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.
Examples
Input
10 2 4
3 7
8 10
0 10
3 4
8 1
1 2
Output
14
Input
10 1 1
0 9
0 5
Output
45
Input
10 1 1
0 9
1 5
Output
-1
Note
In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14).
In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Monk learned about priority queues recently and asked his teacher for an interesting problem. So his teacher came up with a simple problem. He now has an integer array A. For each index i, he wants to find the product of the largest, second largest and the third largest integer in the range [1,i].
Note: Two numbers can be the same value-wise but they should be distinct index-wise.
Input:
The first line contains an integer N, denoting the number of elements in the array A.
The next line contains N space separated integers, each denoting the ith integer of the array A.
Output:
Print the answer for each index in each line. If there is no second largest or third largest number in the array A upto that index, then print "-1", without the quotes.
Constraints:
1 β€ N β€ 100000
0 β€ A[i] β€ 1000000
SAMPLE INPUT
5
1 2 3 4 5
SAMPLE OUTPUT
-1
-1
6
24
60
Explanation
There are 5 integers 1,2,3,4 and 5.
For the first two indexes, since the number of elements is less than 3, so -1 is printed.
For the third index, the top 3 numbers are 3,2 and 1 whose product is 6.
For the fourth index, the top 3 numbers are 4,3, and 2 whose product is 24.
For the fifth index, the top 3 numbers are 5,4 and 3 whose product is 60.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 in a class of Computer Networks, little Roy learned to calculate Hamming Distance between two strings of equal length.
During practical session, Roy's teacher gave him a string of length L with all distinct characters. Teacher asked him to find the number of permutations of the string such that the hamming distance between the original string and permuted string is maximum.
Roy seeks your help to answer the question.
Input:
First line of input will contain integer L, length of given string.
Second line of input will contain a string of length L.
Output:
Print in a single line the number of such permutations.
Since the answer can be very large output it modulo 1000000007
Constraints:
1 β€ L β€ 94
String is made of characters whose [ASCII value][2] fall within the range [33,126]
SAMPLE INPUT
3
#$%
SAMPLE OUTPUT
2
Explanation
Possible permutations of #$% are:
[1] #$%
[2] #%$
[3] $#%
[4] $%#
[5] %#$
[6] %$#
Out of these [4] and [5] result in maximum hamming distance. Hence the output is 2.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have N logs of lengths A_1,A_2,\cdots A_N.
We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.
Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_1 A_2 \cdots A_N
Output
Print an integer representing the answer.
Examples
Input
2 3
7 9
Output
4
Input
3 0
3 4 5
Output
5
Input
10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202
Output
292638192
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have N+M balls, each of which has an integer written on it.
It is known that:
* The numbers written on N of the balls are even.
* The numbers written on M of the balls are odd.
Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.
It can be shown that this count does not depend on the actual values written on the balls.
Constraints
* 0 \leq N,M \leq 100
* 2 \leq N+M
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
Output
Print the answer.
Examples
Input
2 1
Output
1
Input
4 3
Output
9
Input
1 1
Output
0
Input
13 3
Output
81
Input
0 3
Output
3
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.
When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).
In how many ways can the knight reach the square (X, Y)?
Find the number of ways modulo 10^9 + 7.
Constraints
* 1 \leq X \leq 10^6
* 1 \leq Y \leq 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.
Examples
Input
3 3
Output
2
Input
2 2
Output
0
Input
999999 999999
Output
151840682
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.
Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.
It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.
Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.
Can Kizahashi complete all the jobs in time? If he can, print `Yes`; if he cannot, print `No`.
Constraints
* All values in input are integers.
* 1 \leq N \leq 2 \times 10^5
* 1 \leq A_i, B_i \leq 10^9 (1 \leq i \leq N)
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
.
.
.
A_N B_N
Output
If Kizahashi can complete all the jobs in time, print `Yes`; if he cannot, print `No`.
Examples
Input
5
2 4
1 9
1 8
4 9
3 12
Output
Yes
Input
3
334 1000
334 1000
334 1000
Output
No
Input
30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720
Output
Yes
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 will play a one-player game using a number line and N pieces.
First, we place each of these pieces at some integer coordinate.
Here, multiple pieces can be placed at the same coordinate.
Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:
Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.
Note that the coordinates where we initially place the pieces are already regarded as visited.
Find the minimum number of moves required to achieve the objective.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* -10^5 \leq X_i \leq 10^5
* X_1, X_2, ..., X_M are all different.
Input
Input is given from Standard Input in the following format:
N M
X_1 X_2 ... X_M
Output
Find the minimum number of moves required to achieve the objective.
Examples
Input
2 5
10 12 1 2 14
Output
5
Input
3 7
-10 -3 0 9 -100 2 17
Output
19
Input
100 1
-100000
Output
0
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Infinity has a string S consisting of digits from `1` to `9`. Each time the date changes, this string changes as follows:
* Each occurrence of `2` in S is replaced with `22`. Similarly, each `3` becomes `333`, `4` becomes `4444`, `5` becomes `55555`, `6` becomes `666666`, `7` becomes `7777777`, `8` becomes `88888888` and `9` becomes `999999999`. `1` remains as `1`.
For example, if S is `1324`, it becomes `1333224444` the next day, and it becomes `133333333322224444444444444444` the day after next. You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?
Constraints
* S is a string of length between 1 and 100 (inclusive).
* K is an integer between 1 and 10^{18} (inclusive).
* The length of the string after 5 \times 10^{15} days is at least K.
Input
Input is given from Standard Input in the following format:
S
K
Output
Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.
Examples
Input
1214
4
Output
2
Input
3
157
Output
3
Input
299792458
9460730472580800
Output
2
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Cosmic market, commonly known as Kozumike, is the largest coterie spot sale in the universe. Doujin lovers of all genres gather at Kozumike. In recent years, the number of visitors to Kozumike has been increasing. If everyone can enter from the beginning, it will be very crowded and dangerous, so admission is restricted immediately after the opening. Only a certain number of people can enter at the same time as the opening. Others have to wait for a while before entering.
However, if you decide to enter the venue on a first-come, first-served basis, some people will line up all night from the day before. Many of Kozumike's participants are minors, and there are security issues, so it is not very good to decide on a first-come, first-served basis. For that reason, Kozumike can play some kind of game among the participants, and the person who survives the game gets the right to enter first. To be fair, we use highly random games every year.
I plan to participate in Kozumike again this time. I have a douujinshi that I really want to get at this Kozumike. A doujinshi distributed by a popular circle, which deals with the magical girl anime that became a hot topic this spring. However, this circle is very popular and its distribution ends immediately every time. It would be almost impossible to get it if you couldn't enter at the same time as the opening. Of course, there is no doubt that it will be available at douujin shops at a later date. But I can't put up with it until then. I have to get it on the day of Kozumike with any hand. Unfortunately, I've never been the first to enter Kozumike.
According to Kozumike's catalog, this time we will select the first person to enter in the following games. First, the first r Γ c of the participants sit in any of the seats arranged like the r Γ c grid. You can choose the location on a first-come, first-served basis, so there are many options if you go early. The game starts when r Γ c people sit down. In this game, all people in a seat in a row (row) are instructed to sit or stand a certain number of times. If a person who is already seated is instructed to sit down, just wait. The same is true for those who are standing up. The column (row) to which this instruction is issued and the content of the instruction are randomly determined by roulette. Only those who stand up after a certain number of instructions will be able to enter the venue first. Participants are not informed of the number of instructions, so they do not know when the game will end. So at some point neither standing nor sitting knows if they can enter first. That's why the catalog emphasizes that you can enjoy the thrill.
At 1:00 pm the day before Kozumike, I got all the data about this year's game. According to the information I got, the number of times this instruction, q, has already been decided. On the contrary, all the instructions for q times have already been decided. It is said that it has a high degree of randomness, but that was a lie. I don't know why it was decided in advance. But this information seems to me a godsend.
If the game is played according to this data, you will know all the seating locations where you can enter first. In the worst case, let's say all the participants except me had this information. Even in such a case, you should know the number of arrivals at the latest to enter the venue first. However, it seems impossible to analyze this instruction by hand from now on because it is too much. No matter how hard I try, I can't make it in time for Kozumike.
So I decided to leave this calculation to you. You often participate in programming contests and you should be good at writing math programs like this. Of course I wouldn't ask you to do it for free. According to the catalog, this year's Kozumike will be attended by a circle that publishes a doujinshi about programming contests. If I can enter at the same time as the opening, I will get the douujinshi as a reward and give it to you. Well, I'll take a nap for about 5 hours from now on. In the meantime, I believe you will give me an answer.
Input
The input consists of multiple cases. Each case is given in the following format.
r c q
A0 B0 order0
A1 B1 order1
..
..
..
Aq-1 Bq-1 orderq-1
When Ai = 0, the orderi instruction is executed for the Bi line.
When Ai = 1, the orderi instruction is executed for the Bi column.
When orderi = 0, all people in the specified row or column are seated.
When orderi = 1, make everyone stand in the specified row or column.
The end of the input is given by r = 0 c = 0 q = 0.
The input value satisfies the following conditions.
1 β€ r β€ 50,000
1 β€ c β€ 50,000
1 β€ q β€ 50,000
orderi = 0 or 1
When Ai = 0
0 β€ Bi <r
When Ai = 1
0 β€ Bi <c
The number of test cases does not exceed 100
Output
In the worst case, print out in one line how many times you should arrive to get the right to enter the venue first.
Example
Input
5 5 5
0 0 1
0 0 0
0 2 0
1 2 1
0 0 0
5 5 5
1 4 0
0 1 1
0 4 1
1 3 0
0 3 1
5 5 5
1 0 0
0 3 0
1 2 1
0 4 0
0 1 1
0 0 0
Output
4
13
8
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them.
One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats with magical fences running between the piles. She said βYour cats are shut away in the fences until they become ugly old cats.β like a curse and went away.
Nicholas tried to break the fences with a hummer, but the fences are impregnable against his effort. He went to a church and asked a priest help. The priest looked for how to destroy the magical fences in books and found they could be destroyed by holy water. The Required amount of the holy water to destroy a fence was proportional to the length of the fence. The holy water was, however, fairly expensive. So he decided to buy exactly the minimum amount of the holy water required to save all his cats. How much holy water would be required?
Input
The input has the following format:
N M
x1 y1 .
.
.
xN yN p1 q1
.
.
.
pM qM
The first line of the input contains two integers N (2 β€ N β€ 10000) and M (1 β€ M). N indicates the number of magical piles and M indicates the number of magical fences. The following N lines describe the coordinates of the piles. Each line contains two integers xi and yi (-10000 β€ xi, yi β€ 10000). The following M lines describe the both ends of the fences. Each line contains two integers pj and qj (1 β€ pj, qj β€ N). It indicates a fence runs between the pj-th pile and the qj-th pile.
You can assume the following:
* No Piles have the same coordinates.
* A pile doesnβt lie on the middle of fence.
* No Fences cross each other.
* There is at least one cat in each enclosed area.
* It is impossible to destroy a fence partially.
* A unit of holy water is required to destroy a unit length of magical fence.
Output
Output a line containing the minimum amount of the holy water required to save all his cats. Your program may output an arbitrary number of digits after the decimal point. However, the absolute error should be 0.001 or less.
Examples
Input
3 3
0 0
3 0
0 4
1 2
2 3
3 1
Output
3.000
Input
4 3
0 0
-100 0
100 0
0 100
1 2
1 3
1 4
Output
0.000
Input
6 7
2 0
6 0
8 2
6 3
0 5
1 7
1 2
2 3
3 4
4 1
5 1
5 4
5 6
Output
7.236
Input
6 6
0 0
0 1
1 0
30 0
0 40
30 40
1 2
2 3
3 1
4 5
5 6
6 4
Output
31.000
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Statement
You are now participating in the Summer Training Camp for Programming Contests with your friend Jiro, who is an enthusiast of the ramen chain SIRO. Since every SIRO restaurant has its own tasteful ramen, he wants to try them at as many different restaurants as possible in the night. He doesn't have plenty of time tonight, however, because he has to get up early in the morning tomorrow to join a training session. So he asked you to find the maximum number of different restaurants to which he would be able to go to eat ramen in the limited time.
There are $n$ railway stations in the city, which are numbered $1$ through $n$. The station $s$ is the nearest to the camp venue. $m$ pairs of stations are directly connected by the railway: you can move between the stations $a_i$ and $b_i$ in $c_i$ minutes in the both directions. Among the stations, there are $l$ stations where a SIRO restaurant is located nearby. There is at most one SIRO restaurant around each of the stations, and there are no restaurants near the station $s$. It takes $e_i$ minutes for Jiro to eat ramen at the restaurant near the station $j_i$.
It takes only a negligibly short time to go back and forth between a station and its nearby SIRO restaurant. You can also assume that Jiro doesn't have to wait for the ramen to be served in the restaurants.
Jiro is now at the station $s$ and have to come back to the station in $t$ minutes. How many different SIRO's can he taste?
Input
The input is a sequence of datasets. The number of the datasets does not exceed $100$. Each dataset is formatted as follows:
> $n$ $m$ $l$ $s$ $t$
> $a_1$ $b_1$ $c_1$
> :
> :
> $a_m$ $b_m$ $c_m$
> $j_1$ $e_1$
> :
> :
> $j_l$ $e_l$
The first line of each dataset contains five integers:
* $n$ for the number of stations,
* $m$ for the number of directly connected pairs of stations,
* $l$ for the number of SIRO restaurants,
* $s$ for the starting-point station, and
* $t$ for the time limit for Jiro.
Each of the following $m$ lines contains three integers:
* $a_i$ and $b_i$ for the connected stations, and
* $c_i$ for the time it takes to move between the two stations.
Each of the following $l$ lines contains two integers:
* $j_i$ for the station where a SIRO restaurant is located, and
* $e_i$ for the time it takes for Jiro to eat at the restaurant.
The end of the input is indicated by a line with five zeros, which is not included in the datasets.
The datasets satisfy the following constraints:
* $2 \le n \le 300$
* $1 \le m \le 5{,}000$
* $1 \le l \le 16$
* $1 \le s \le n$
* $1 \le t \le 100{,}000$
* $1 \le a_i, b_i \le n$
* $1 \le c_i \le 1{,}000$
* $1 \le j_i \le n$
* $1 \le e_i \le 15$
* $s \ne j_i$
* $j_i$'s are distinct.
* $a_i \ne b_i$
* $(a_i, b_i) \ne (a_j, b_j)$ and $(a_i, b_i) \ne (b_j, a_j)$ for any $i \ne j$
Note that there may be some stations not reachable from the starting point $s$.
Output
For each data set, output the maximum number of different restaurants where Jiro can go within the time limit.
Sample Input
2 1 1 1 10
1 2 3
2 4
2 1 1 1 9
1 2 3
2 4
4 2 2 4 50
1 2 5
3 4 5
2 15
3 15
4 6 3 1 29
1 2 20
3 2 10
4 1 5
3 1 5
2 4 3
3 4 4
2 1
4 5
3 3
0 0 0 0 0
Output for the Sample Input
1
0
1
3
Example
Input
2 1 1 1 10
1 2 3
2 4
2 1 1 1 9
1 2 3
2 4
4 2 2 4 50
1 2 5
3 4 5
2 15
3 15
4 6 3 1 29
1 2 20
3 2 10
4 1 5
3 1 5
2 4 3
3 4 4
2 1
4 5
3 3
0 0 0 0 0
Output
1
0
1
3
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Points:10
The Indian Heights School believes that learning with the aid of technology is the fastest way to do so. It is a pioneer in innovation and virtual classrooms in the country. Keeping in accordance with its practices, the school wants to integrate software and automate various functions at the classroom level.
As college students, your team volunteered for this assignment and your proposal has been accepted by the school's director. Each day the class teacher picks a random number of students to delegate them duties for the day such as wiping the board, managing the class, maintaining the display boards and so on. But sometimes the students complain about being picked more frequently than the others. Thus the teacher wants to know the number of ways to pick a certain number of students out of the total class. Your job is to help her do so...
Input:
The first line consists of total no of test cases.
Each test case consists of one line containing two integers(space separated) a β₯ 1(i.e. total students) and 0 β€ b β€ a (i.e. number of students to be picked).
Output:
For each test case, print one line containing the required number. This number will always fit into an integer, i.e. it will be less than 2^31.
Example:
Input:
2
5 3
10 5
Output:
10
252
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n points on the plane, (x_1,y_1), (x_2,y_2), β¦, (x_n,y_n).
You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
Input
First line contains one integer n (1 β€ n β€ 10^5).
Each of the next n lines contains two integers x_i and y_i (1 β€ x_i,y_i β€ 10^9).
Output
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
Examples
Input
3
1 1
1 2
2 1
Output
3
Input
4
1 1
1 2
2 1
2 2
Output
4
Note
Illustration for the first example: <image>
Illustration for the second example: <image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 took n videos, the duration of the i-th video is a_i seconds. The videos are listed in the chronological order, i.e. the 1-st video is the earliest, the 2-nd video is the next, ..., the n-th video is the last.
Now Polycarp wants to publish exactly k (1 β€ k β€ n) posts in Instabram. Each video should be a part of a single post. The posts should preserve the chronological order, it means that the first post should contain one or more of the earliest videos, the second post should contain a block (one or more videos) going next and so on. In other words, if the number of videos in the j-th post is s_j then:
* s_1+s_2+...+s_k=n (s_i>0),
* the first post contains the videos: 1, 2, ..., s_1;
* the second post contains the videos: s_1+1, s_1+2, ..., s_1+s_2;
* the third post contains the videos: s_1+s_2+1, s_1+s_2+2, ..., s_1+s_2+s_3;
* ...
* the k-th post contains videos: n-s_k+1,n-s_k+2,...,n.
Polycarp is a perfectionist, he wants the total duration of videos in each post to be the same.
Help Polycarp to find such positive integer values s_1, s_2, ..., s_k that satisfy all the conditions above.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 10^5). The next line contains n positive integer numbers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^4), where a_i is the duration of the i-th video.
Output
If solution exists, print "Yes" in the first line. Print k positive integers s_1, s_2, ..., s_k (s_1+s_2+...+s_k=n) in the second line. The total duration of videos in each post should be the same. It can be easily proven that the answer is unique (if it exists).
If there is no solution, print a single line "No".
Examples
Input
6 3
3 3 1 4 1 6
Output
Yes
2 3 1
Input
3 3
1 1 1
Output
Yes
1 1 1
Input
3 3
1 1 2
Output
No
Input
3 1
1 10 100
Output
Yes
3
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is β_{i = 1}^{n} dist(i, v) β
a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 β€ n β€ 2 β
10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 β€ u_i, v_i β€ n, u_i β v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer β the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 β
9 + 1 β
4 + 0 β
1 + 3 β
7 + 3 β
10 + 4 β
1 + 4 β
6 + 4 β
5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool permutation p_1, p_2, ..., p_n of length n. It is very disappointing, but he forgot this permutation. He only remembers the array q_1, q_2, ..., q_{n-1} of length n-1, where q_i=p_{i+1}-p_i.
Given n and q=q_1, q_2, ..., q_{n-1}, help Polycarp restore the invented permutation.
Input
The first line contains the integer n (2 β€ n β€ 2β
10^5) β the length of the permutation to restore. The second line contains n-1 integers q_1, q_2, ..., q_{n-1} (-n < q_i < n).
Output
Print the integer -1 if there is no such permutation of length n which corresponds to the given array q. Otherwise, if it exists, print p_1, p_2, ..., p_n. Print any such permutation if there are many of them.
Examples
Input
3
-2 1
Output
3 1 2
Input
5
1 1 1 1
Output
1 2 3 4 5
Input
4
-1 2 2
Output
-1
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a garden consisting entirely of grass and weeds. Your garden is described by an n Γ m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either grass or weeds. For example, a 4 Γ 5 garden may look as follows (empty cells denote grass):
<image>
You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell (1, 1). At any moment of time you are facing a certain direction β either left or right. And initially, you face right.
In one move you can do either one of these:
1) Move one cell in the direction that you are facing.
* if you are facing right: move from cell (r, c) to cell (r, c + 1)
<image>
* if you are facing left: move from cell (r, c) to cell (r, c - 1)
<image>
2) Move one cell down (that is, from cell (r, c) to cell (r + 1, c)), and change your direction to the opposite one.
* if you were facing right previously, you will face left
<image>
* if you were facing left previously, you will face right
<image>
You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move.
What is the minimum number of moves required to mow all the weeds?
Input
The first line contains two integers n and m (1 β€ n, m β€ 150) β the number of rows and columns respectively. Then follow n lines containing m characters each β the content of the grid. "G" means that this cell contains grass. "W" means that this cell contains weeds.
It is guaranteed that the top-left corner of the grid will contain grass.
Output
Print a single number β the minimum number of moves required to mow all the weeds.
Examples
Input
4 5
GWGGW
GGWGG
GWGGG
WGGGG
Output
11
Input
3 3
GWW
WWW
WWG
Output
7
Input
1 1
G
Output
0
Note
For the first example, this is the picture of the initial state of the grid:
<image>
A possible solution is by mowing the weeds as illustrated below:
<image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a given picture with size w Γ h. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:
* A "+" shape has one center nonempty cell.
* There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction.
* All other cells are empty.
Find out if the given picture has single "+" shape.
Input
The first line contains two integers h and w (1 β€ h, w β€ 500) β the height and width of the picture.
The i-th of the next h lines contains string s_{i} of length w consisting "." and "*" where "." denotes the empty space and "*" denotes the non-empty space.
Output
If the given picture satisfies all conditions, print "YES". Otherwise, print "NO".
You can output each letter in any case (upper or lower).
Examples
Input
5 6
......
..*...
.****.
..*...
..*...
Output
YES
Input
3 5
..*..
****.
.*...
Output
NO
Input
7 7
.......
...*...
..****.
...*...
...*...
.......
.*.....
Output
NO
Input
5 6
..**..
..**..
******
..**..
..**..
Output
NO
Input
3 7
.*...*.
***.***
.*...*.
Output
NO
Input
5 10
..........
..*.......
.*.******.
..*.......
..........
Output
NO
Note
In the first example, the given picture contains one "+".
In the second example, two vertical branches are located in a different column.
In the third example, there is a dot outside of the shape.
In the fourth example, the width of the two vertical branches is 2.
In the fifth example, there are two shapes.
In the sixth example, there is an empty space inside of the shape.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point x. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach x.
Input
The input data consists of only one integer x ( - 109 β€ x β€ 109).
Output
Output the minimal number of jumps that Jack requires to reach x.
Examples
Input
2
Output
3
Input
6
Output
3
Input
0
Output
0
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 define a balanced multiset the following way. Write down the sum of all elements of the multiset in its decimal representation. For each position of that number check if the multiset includes at least one element such that the digit of the element and the digit of the sum at that position are the same. If that holds for every position, then the multiset is balanced. Otherwise it's unbalanced.
For example, multiset \{20, 300, 10001\} is balanced and multiset \{20, 310, 10001\} is unbalanced:
<image>
The red digits mark the elements and the positions for which these elements have the same digit as the sum. The sum of the first multiset is 10321, every position has the digit required. The sum of the second multiset is 10331 and the second-to-last digit doesn't appear in any number, thus making the multiset unbalanced.
You are given an array a_1, a_2, ..., a_n, consisting of n integers.
You are asked to perform some queries on it. The queries can be of two types:
* 1~i~x β replace a_i with the value x;
* 2~l~r β find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, ..., a_r with the minimum sum, or report that no unbalanced subset exists.
Note that the empty multiset is balanced.
For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5) β the number of elements in the array and the number of queries, respectively.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i < 10^9).
Each of the following m lines contains a query of one of two types:
* 1~i~x (1 β€ i β€ n, 1 β€ x < 10^9) β replace a_i with the value x;
* 2~l~r (1 β€ l β€ r β€ n) β find the unbalanced subset of the multiset of the numbers a_l, a_{l + 1}, ..., a_r with the lowest sum, or report that no unbalanced subset exists.
It is guaranteed that there is at least one query of the second type.
Output
For each query of the second type print the lowest sum of the unbalanced subset. Print -1 if no unbalanced subset exists.
Example
Input
4 5
300 10001 20 20
2 1 3
1 1 310
2 1 3
2 3 3
2 3 4
Output
-1
330
-1
40
Note
All the subsets of multiset \{20, 300, 10001\} are balanced, thus the answer is -1.
The possible unbalanced subsets in the third query are \{20, 310\} and \{20, 310, 10001\}. The lowest sum one is \{20, 310\}. Note that you are asked to choose a subset, not a subsegment, thus the chosen elements might not be adjancent in the array.
The fourth query includes only the empty subset and subset \{20\}. Both of them are balanced.
The last query includes the empty subset and the subsets \{20\}, \{20\} and \{20, 20\}. Only \{20, 20\} is unbalanced, its sum is 40. Note that you are asked to choose a multiset, thus it might include equal elements.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.
You must paint a fence which consists of 10^{100} planks in two colors in the following way (suppose planks are numbered from left to right from 0):
* if the index of the plank is divisible by r (such planks have indices 0, r, 2r and so on) then you must paint it red;
* if the index of the plank is divisible by b (such planks have indices 0, b, 2b and so on) then you must paint it blue;
* if the index is divisible both by r and b you can choose the color to paint the plank;
* otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it).
Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are k consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.
The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.
Input
The first line contains single integer T (1 β€ T β€ 1000) β the number of test cases.
The next T lines contain descriptions of test cases β one per line. Each test case contains three integers r, b, k (1 β€ r, b β€ 10^9, 2 β€ k β€ 10^9) β the corresponding coefficients.
Output
Print T words β one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.
Example
Input
4
1 1 2
2 10 4
5 2 3
3 2 2
Output
OBEY
REBEL
OBEY
OBEY
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.
The exam consists of n problems that can be solved in T minutes. Thus, the exam begins at time 0 and ends at time T. Petya can leave the exam at any integer time from 0 to T, inclusive.
All problems are divided into two types:
* easy problems β Petya takes exactly a minutes to solve any easy problem;
* hard problems β Petya takes exactly b minutes (b > a) to solve any hard problem.
Thus, if Petya starts solving an easy problem at time x, then it will be solved at time x+a. Similarly, if at a time x Petya starts to solve a hard problem, then it will be solved at time x+b.
For every problem, Petya knows if it is easy or hard. Also, for each problem is determined time t_i (0 β€ t_i β€ T) at which it will become mandatory (required). If Petya leaves the exam at time s and there is such a problem i that t_i β€ s and he didn't solve it, then he will receive 0 points for the whole exam. Otherwise (i.e if he has solved all such problems for which t_i β€ s) he will receive a number of points equal to the number of solved problems. Note that leaving at time s Petya can have both "mandatory" and "non-mandatory" problems solved.
For example, if n=2, T=5, a=2, b=3, the first problem is hard and t_1=3 and the second problem is easy and t_2=2. Then:
* if he leaves at time s=0, then he will receive 0 points since he will not have time to solve any problems;
* if he leaves at time s=1, he will receive 0 points since he will not have time to solve any problems;
* if he leaves at time s=2, then he can get a 1 point by solving the problem with the number 2 (it must be solved in the range from 0 to 2);
* if he leaves at time s=3, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them;
* if he leaves at time s=4, then he will receive 0 points since at this moment both problems will be mandatory, but he will not be able to solve both of them;
* if he leaves at time s=5, then he can get 2 points by solving all problems.
Thus, the answer to this test is 2.
Help Petya to determine the maximal number of points that he can receive, before leaving the exam.
Input
The first line contains the integer m (1 β€ m β€ 10^4) β the number of test cases in the test.
The next lines contain a description of m test cases.
The first line of each test case contains four integers n, T, a, b (2 β€ n β€ 2β
10^5, 1 β€ T β€ 10^9, 1 β€ a < b β€ 10^9) β the number of problems, minutes given for the exam and the time to solve an easy and hard problem, respectively.
The second line of each test case contains n numbers 0 or 1, separated by single space: the i-th number means the type of the i-th problem. A value of 0 means that the problem is easy, and a value of 1 that the problem is hard.
The third line of each test case contains n integers t_i (0 β€ t_i β€ T), where the i-th number means the time at which the i-th problem will become mandatory.
It is guaranteed that the sum of n for all test cases does not exceed 2β
10^5.
Output
Print the answers to m test cases. For each set, print a single integer β maximal number of points that he can receive, before leaving the exam.
Example
Input
10
3 5 1 3
0 0 1
2 1 4
2 5 2 3
1 0
3 2
1 20 2 4
0
16
6 20 2 5
1 1 0 1 0 0
0 8 2 9 11 6
4 16 3 6
1 0 1 1
8 3 5 6
6 20 3 6
0 1 0 0 1 0
20 11 3 20 16 17
7 17 1 6
1 1 0 1 0 0 0
1 7 0 11 10 15 10
6 17 2 6
0 0 1 0 0 1
7 6 3 7 10 12
5 17 2 5
1 1 1 1 0
17 11 10 6 4
1 1 1 2
0
1
Output
3
2
1
0
1
4
0
1
2
1
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
* The length of t does not exceed the length of s.
* t is a palindrome.
* There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 1000), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
Note
In the first test, the string s = "a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because:
* Its length is 9, which does not exceed the length of the string s, which equals 11.
* It is a palindrome.
* "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s".
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).
For any integer k and positive integer n, let kmod n denote the remainder when k is divided by n. More formally, r=kmod n is the smallest non-negative integer such that k-r is divisible by n. It always holds that 0β€ kmod nβ€ n-1. For example, 100mod 12=4 and (-1337)mod 3=1.
Then the shuffling works as follows. There is an array of n integers a_0,a_1,β¦,a_{n-1}. Then for each integer k, the guest in room k is moved to room number k+a_{kmod n}.
After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.
Input
Each test consists of multiple test cases. The first line contains a single integer t (1β€ tβ€ 10^4) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains a single integer n (1β€ nβ€ 2β
10^5) β the length of the array.
The second line of each test case contains n integers a_0,a_1,β¦,a_{n-1} (-10^9β€ a_iβ€ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 2β
10^5.
Output
For each test case, output a single line containing "YES" if there is exactly one guest assigned to each room after the shuffling process, or "NO" otherwise. You can print each letter in any case (upper or lower).
Example
Input
6
1
14
2
1 -1
4
5 5 5 1
3
3 2 1
2
0 1
5
-239 -2 -100 -3 -11
Output
YES
YES
YES
NO
NO
YES
Note
In the first test case, every guest is shifted by 14 rooms, so the assignment is still unique.
In the second test case, even guests move to the right by 1 room, and odd guests move to the left by 1 room. We can show that the assignment is still unique.
In the third test case, every fourth guest moves to the right by 1 room, and the other guests move to the right by 5 rooms. We can show that the assignment is still unique.
In the fourth test case, guests 0 and 1 are both assigned to room 3.
In the fifth test case, guests 1 and 2 are both assigned to room 2.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array a[0 β¦ n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 β€ i β€ n - 1) the equality i mod 2 = a[i] mod 2 holds, where x mod 2 is the remainder of dividing x by 2.
For example, the arrays [0, 5, 2, 1] and [0, 17, 0, 3] are good, and the array [2, 4, 6, 7] is bad, because for i=1, the parities of i and a[i] are different: i mod 2 = 1 mod 2 = 1, but a[i] mod 2 = 4 mod 2 = 0.
In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).
Find the minimum number of moves in which you can make the array a good, or say that this is not possible.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases in the test. Then t test cases follow.
Each test case starts with a line containing an integer n (1 β€ n β€ 40) β the length of the array a.
The next line contains n integers a_0, a_1, β¦, a_{n-1} (0 β€ a_i β€ 1000) β the initial array.
Output
For each test case, output a single integer β the minimum number of moves to make the given array a good, or -1 if this is not possible.
Example
Input
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
Output
2
1
-1
0
Note
In the first test case, in the first move, you can swap the elements with indices 0 and 1, and in the second move, you can swap the elements with indices 2 and 3.
In the second test case, in the first move, you need to swap the elements with indices 0 and 1.
In the third test case, you cannot make the array good.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
In the beginning, uncle Bogdan wrote on a board a positive integer x consisting of n digits. After that, he wiped out x and wrote integer k instead, which was the concatenation of binary representations of digits x consists of (without leading zeroes). For example, let x = 729, then k = 111101001 (since 7 = 111, 2 = 10, 9 = 1001).
After some time, uncle Bogdan understood that he doesn't know what to do with k and asked Denis to help. Denis decided to wipe last n digits of k and named the new number as r.
As a result, Denis proposed to find such integer x of length n that r (as number) is maximum possible. If there are multiple valid x then Denis is interested in the minimum one.
All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?
Note: in this task, we compare integers (x or k) as numbers (despite what representations they are written in), so 729 < 1999 or 111 < 1000.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
Next t lines contain test cases β one per test case. The one and only line of each test case contains the single integer n (1 β€ n β€ 10^5) β the length of the integer x you need to find.
It's guaranteed that the sum of n from all test cases doesn't exceed 2 β
10^5.
Output
For each test case, print the minimum integer x of length n such that obtained by Denis number r is maximum possible.
Example
Input
2
1
3
Output
8
998
Note
In the second test case (with n = 3), if uncle Bogdan had x = 998 then k = 100110011000. Denis (by wiping last n = 3 digits) will obtain r = 100110011.
It can be proved that the 100110011 is the maximum possible r Denis can obtain and 998 is the minimum x to obtain it.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.
He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space):
### ..# .#. #..
.#. ### .#. ###
.#. ..# ### #..
Simon faced a quite natural challenge: placing in the given n Γ m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.
Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
Input
The only line contains two space-separated integers n and m β the sizes of the warehouse (1 β€ n, m β€ 9).
Output
In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.
Examples
Input
3 3
Output
1
AAA
.A.
.A.
Input
5 6
Output
4
A..C..
AAAC..
ABCCCD
.B.DDD
BBB..D
Input
2 2
Output
0
..
..
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
Alice and Bob are playing a game. There is nΓ n grid, initially empty. We refer to the cell in row i and column j by (i, j) for 1β€ i, jβ€ n. There is an infinite supply of tokens that come in 3 colors labelled 1, 2, and 3.
The game proceeds with turns as follows. Each turn begins with Alice naming one of the three colors, let's call it a. Then, Bob chooses a color bβ a, chooses an empty cell, and places a token of color b on that cell.
We say that there is a conflict if there exist two adjacent cells containing tokens of the same color. Two cells are considered adjacent if they share a common edge.
If at any moment there is a conflict, Alice wins. Otherwise, if n^2 turns are completed (so that the grid becomes full) without any conflicts, Bob wins.
We have a proof that Bob has a winning strategy. Play the game as Bob and win.
The interactor is adaptive. That is, Alice's color choices can depend on Bob's previous moves.
Interaction
The interaction begins by reading a single integer n (2β€ nβ€ 100) β the size of the grid.
The turns of the game follow. You should begin each turn by reading an integer a (1β€ aβ€ 3) β Alice's chosen color.
Then you must print three integers b,i,j (1β€ bβ€ 3,bβ a, 1β€ i,jβ€ n) β denoting that Bob puts a token of color b in the cell (i, j). The cell (i, j) must not contain a token from a previous turn. If your move is invalid or loses the game, the interaction is terminated and you will receive a Wrong Answer verdict.
After n^2 turns have been completed, make sure to exit immediately to avoid getting unexpected verdicts.
After printing something do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
Hack Format
To hack, use the following format.
The first line contains a single integer n (2β€ nβ€ 100).
The second line contains n^2 integers a_1,β¦,a_{n^2} (1β€ a_iβ€ 3), where a_i denotes Alice's color on the i-th turn.
The interactor might deviate from the list of colors in your hack, but only if it forces Bob to lose.
Example
Input
2
1
2
1
3
Output
2 1 1
3 1 2
3 2 1
1 2 2
Note
The final grid from the sample is pictured below. Bob wins because there are no two adjacent cells with tokens of the same color. $$$\begin{matrix}2&3\\\3&1\end{matrix}$$$
The sample is only given to demonstrate the input and output format. It is not guaranteed to represent an optimal strategy for Bob or the real behavior of the interactor.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.
The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti β the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.
When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:
* the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n),
* the sum of the ti values of the remaining sculptures is maximized.
Help the Vice Rector to analyze the criticism β find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.
Input
The first input line contains an integer n (3 β€ n β€ 20000) β the initial number of sculptures. The second line contains a sequence of integers t1, t2, ..., tn, ti β the degree of the i-th sculpture's attractiveness ( - 1000 β€ ti β€ 1000). The numbers on the line are separated by spaces.
Output
Print the required maximum sum of the sculptures' attractiveness.
Examples
Input
8
1 2 -3 4 -5 5 2 3
Output
14
Input
6
1 -2 3 -4 5 -6
Output
9
Input
6
1 2 3 4 5 6
Output
21
Note
In the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 ΠΈ 3.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.
Find the volume fraction of orange juice in the final drink.
Input
The first input line contains a single integer n (1 β€ n β€ 100) β the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0 β€ pi β€ 100) β the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space.
Output
Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10 - 4.
Examples
Input
3
50 50 100
Output
66.666666666667
Input
4
0 25 50 75
Output
37.500000000000
Note
Note to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal <image> milliliters. The total cocktail's volume equals 3Β·x milliliters, so the volume fraction of the juice in the cocktail equals <image>, that is, 66.(6) percent.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).
<image>
Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).
Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of dice in the tower.
The second line contains an integer x (1 β€ x β€ 6) β the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 β€ ai, bi β€ 6; ai β bi) β the numbers Bob sees on the two sidelong faces of the i-th dice in the tower.
Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.
Output
Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).
Examples
Input
3
6
3 2
5 4
2 4
Output
YES
Input
3
3
2 6
4 1
5 3
Output
NO
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly n. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the OX axis to the left along the roof and the OY axis β up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles Ξ±1 and Ξ±2 to the OX axis.
<image>
Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles Ξ±1 and Ξ±2 to the OX axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star.
<image>
As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules.
Your task is to find the maximum number of stars m that the Donkey's chain can contain.
Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number m of stars in the chain.
Input
The first line contains an integer n (1 β€ n β€ 105) β the number of stars. The second line contains simple fractions representing relationships "a/b c/d", such that <image> and <image> (0 β€ a, b, c, d β€ 105; <image>; <image>; <image>). The given numbers a, b, c, d are integers.
Next n lines contain pairs of integers xi, yi (1 β€ xi, yi β€ 105)β the stars' coordinates.
It is guaranteed that all stars have distinct coordinates.
Output
In a single line print number m β the answer to the problem.
Examples
Input
15
1/3 2/1
3 1
6 2
4 2
2 5
4 5
6 6
3 4
1 6
2 1
7 4
9 3
5 3
1 3
15 5
12 4
Output
4
Note
In the sample the longest chain the Donkey can build consists of four stars. Note that the Donkey can't choose the stars that lie on the rays he imagines.
<image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 β€ w2 β€ ... β€ wk holds.
Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?
Input
The first line contains three integers n, m, k (1 β€ n, m β€ 105, 1 β€ k β€ 109) β the number of fish caught by Alice and Bob respectively, and the number of fish species.
The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob.
Note that one may have caught more than one fish for a same species.
Output
Output "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise.
Examples
Input
3 3 3
2 2 2
1 1 3
Output
YES
Input
4 7 9
5 2 7 3
3 5 2 7 3 8 7
Output
NO
Note
In the first sample, if w1 = 1, w2 = 2, w3 = 2.5, then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5.
In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bobβs fish is always not less than the total weight of Aliceβs fish.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 new TV game on BerTV. In this game two players get a number A consisting of 2n digits. Before each turn players determine who will make the next move. Each player should make exactly n moves. On it's turn i-th player takes the leftmost digit of A and appends it to his or her number Si. After that this leftmost digit is erased from A. Initially the numbers of both players (S1 and S2) are Β«emptyΒ». Leading zeroes in numbers A, S1, S2 are allowed. In the end of the game the first player gets S1 dollars, and the second gets S2 dollars.
One day Homer and Marge came to play the game. They managed to know the number A beforehand. They want to find such sequence of their moves that both of them makes exactly n moves and which maximizes their total prize. Help them.
Input
The first line contains integer n (1 β€ n β€ 18). The second line contains integer A consisting of exactly 2n digits. This number can have leading zeroes.
Output
Output the line of 2n characters Β«HΒ» and Β«MΒ» β the sequence of moves of Homer and Marge, which gives them maximum possible total prize. Each player must make exactly n moves. If there are several solutions, output any of them.
Examples
Input
2
1234
Output
HHMM
Input
2
9911
Output
HMHM
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 β€ li β€ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ..., n. Formally, he want to find the number of distinct numbers among ali, ali + 1, ..., an.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.
Input
The first line contains two integers n and m (1 β€ n, m β€ 105). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 105) β the array elements.
Next m lines contain integers l1, l2, ..., lm. The i-th line contains integer li (1 β€ li β€ n).
Output
Print m lines β on the i-th line print the answer to the number li.
Examples
Input
10 10
1 2 3 4 1 2 3 4 100000 99999
1
2
3
4
5
6
7
8
9
10
Output
6
6
6
6
6
5
4
3
2
1
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Inna loves sweets very much. She has n closed present boxes lines up in a row in front of her. Each of these boxes contains either a candy (Dima's work) or nothing (Sereja's work). Let's assume that the boxes are numbered from 1 to n, from left to right.
As the boxes are closed, Inna doesn't know which boxes contain candies and which boxes contain nothing. Inna chose number k and asked w questions to Dima to find that out. Each question is characterised by two integers li, ri (1 β€ li β€ ri β€ n; r - l + 1 is divisible by k), the i-th question is: "Dima, is that true that among the boxes with numbers from li to ri, inclusive, the candies lie only in boxes with numbers li + k - 1, li + 2k - 1, li + 3k - 1, ..., ri?"
Dima hates to say "no" to Inna. That's why he wonders, what number of actions he will have to make for each question to make the answer to the question positive. In one action, Dima can either secretly take the candy from any box or put a candy to any box (Dima has infinitely many candies). Help Dima count the number of actions for each Inna's question.
Please note that Dima doesn't change the array during Inna's questions. That's why when you calculate the number of operations for the current question, please assume that the sequence of boxes didn't change.
Input
The first line of the input contains three integers n, k and w (1 β€ k β€ min(n, 10), 1 β€ n, w β€ 105). The second line contains n characters. If the i-th box contains a candy, the i-th character of the line equals 1, otherwise it equals 0.
Each of the following w lines contains two integers li and ri (1 β€ li β€ ri β€ n) β the description of the i-th question. It is guaranteed that ri - li + 1 is divisible by k.
Output
For each question, print a single number on a single line β the minimum number of operations Dima needs to make the answer to the question positive.
Examples
Input
10 3 3
1010100011
1 3
1 6
4 9
Output
1
3
2
Note
For the first question, you need to take a candy from the first box to make the answer positive. So the answer is 1.
For the second question, you need to take a candy from the first box, take a candy from the fifth box and put a candy to the sixth box. The answer is 3.
For the third question, you need to take a candy from the fifth box and put it to the sixth box. The answer is 2.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.
There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.
The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?
Input
The first line contains two space-separated integers n and k (1 β€ k β€ n β€ 100) β the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1, a2, ..., an (16 β€ ai β€ 32768); number ai denotes the maximum data transfer speed on the i-th computer.
Output
Print a single integer β the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.
Examples
Input
3 2
40 20 30
Output
30
Input
6 4
100 20 40 20 50 50
Output
40
Note
In the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother.
As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b.
Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.
You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
Input
The first line contains two space-separated integers n, m (1 β€ n, m β€ 105). The second line will contain n space-separated integers representing content of the array a (1 β€ ai β€ 109). The third line will contain m space-separated integers representing content of the array b (1 β€ bi β€ 109).
Output
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
Examples
Input
2 2
2 3
3 5
Output
3
Input
3 2
1 2 3
3 4
Output
4
Input
3 2
4 5 6
1 2
Output
0
Note
In example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.
In example 3, you don't need to do any operation, Devu's condition is already satisfied.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Notice that the memory limit is non-standard.
Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.
All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the i-th opening bracket he remembers the segment [li, ri], containing the distance to the corresponding closing bracket.
Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [li, ri].
Help Arthur restore his favorite correct bracket sequence!
Input
The first line contains integer n (1 β€ n β€ 600), the number of opening brackets in Arthur's favorite correct bracket sequence.
Next n lines contain numbers li and ri (1 β€ li β€ ri < 2n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one.
The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right.
Output
If it is possible to restore the correct bracket sequence by the given data, print any possible choice.
If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line "IMPOSSIBLE" (without the quotes).
Examples
Input
4
1 1
1 1
1 1
1 1
Output
()()()()
Input
3
5 5
3 3
1 1
Output
((()))
Input
3
5 5
3 3
2 2
Output
IMPOSSIBLE
Input
3
2 3
1 4
1 4
Output
(())()
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.
We will call person a a subordinates of another person b, if either b is an immediate supervisor of a, or the immediate supervisor of a is a subordinate to person b. In particular, subordinates of the head are all other employees of the company.
To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer ai, where i is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.
The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.
Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.
Input
The first line contains integer n (1 β€ n β€ 2Β·105) β the number of workers of the Big Software Company.
Then n lines follow, describing the company employees. The i-th line contains two integers pi, ai (1 β€ ai β€ 105) β the number of the person who is the i-th employee's immediate superior and i-th employee's efficiency. For the director p1 = - 1, for all other people the condition 1 β€ pi < i is fulfilled.
Output
Print a single integer β the maximum possible efficiency of the workgroup.
Examples
Input
7
-1 3
1 2
1 1
1 4
4 5
4 3
5 2
Output
17
Note
In the sample test the most effective way is to make a workgroup from employees number 1, 2, 4, 5, 6.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array of positive integers a1, a2, ..., an Γ T of length n Γ T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array.
Input
The first line contains two space-separated integers: n, T (1 β€ n β€ 100, 1 β€ T β€ 107). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 300).
Output
Print a single number β the length of a sought sequence.
Examples
Input
4 3
3 1 4 2
Output
5
Note
The array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction <image> as a sum of three distinct positive fractions in form <image>.
Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that <image>. Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.
If there is no such answer, print -1.
Input
The single line contains single integer n (1 β€ n β€ 104).
Output
If the answer exists, print 3 distinct numbers x, y and z (1 β€ x, y, z β€ 109, x β y, x β z, y β z). Otherwise print -1.
If there are multiple answers, print any of them.
Examples
Input
3
Output
2 7 42
Input
7
Output
7 8 56
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them.
The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playing field. The field can be considered infinite.
Let's take a look at the battle unit called an "Archer". Each archer has a parameter "shot range". It's a positive integer that determines the radius of the circle in which the archer can hit a target. The center of the circle coincides with the center of the cell in which the archer stays. A cell is considered to be under the archerβs fire if and only if all points of this cell, including border points are located inside the circle or on its border.
The picture below shows the borders for shot ranges equal to 3, 4 and 5. The archer is depicted as A.
<image>
Find the number of cells that are under fire for some archer.
Input
The first and only line of input contains a single positive integer k β the archer's shot range (1 β€ k β€ 106).
Output
Print the single number, the number of cells that are under fire.
Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator).
Examples
Input
3
Output
7
Input
4
Output
13
Input
5
Output
19
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.
More formally, the guys take turns giving each other one candy more than they received in the previous turn.
This continued until the moment when one of them couldnβt give the right amount of candy. Candies, which guys got from each other, they donβt consider as their own. You need to know, who is the first who canβt give the right amount of candy.
Input
Single line of input data contains two space-separated integers a, b (1 β€ a, b β€ 109) β number of Vladik and Valera candies respectively.
Output
Pring a single line "Vladikββ in case, if Vladik first who canβt give right amount of candy, or "Valeraββ otherwise.
Examples
Input
1 1
Output
Valera
Input
7 6
Output
Vladik
Note
Illustration for first test case:
<image>
Illustration for second test case:
<image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 very important person has a piece of paper in the form of a rectangle a Γ b.
Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi Γ yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).
A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?
Input
The first line contains three integer numbers n, a and b (1 β€ n, a, b β€ 100).
Each of the next n lines contain two numbers xi, yi (1 β€ xi, yi β€ 100).
Output
Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.
Examples
Input
2 2 2
1 2
2 1
Output
4
Input
4 10 9
2 3
1 1
5 10
9 11
Output
56
Input
3 10 10
6 6
7 7
20 5
Output
0
Note
In the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.
In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.
In the third example there is no such pair of seals that they both can fit on a piece of paper.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets.
Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.
Determine the maximum possible number of large bouquets Vasya can make.
Input
The first line contains a single positive integer n (1 β€ n β€ 105) β the number of initial bouquets.
The second line contains a sequence of integers a1, a2, ..., an (1 β€ ai β€ 106) β the number of flowers in each of the initial bouquets.
Output
Print the maximum number of large bouquets Vasya can make.
Examples
Input
5
2 3 4 2 7
Output
2
Input
6
2 2 6 8 6 12
Output
0
Input
3
11 4 10
Output
1
Note
In the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme.
In the second example it is not possible to form a single bouquet with odd number of flowers.
In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Aarav has just graduated from the university. Now he is going to travel along his country. More precisely: there are N cities with integer coordinates. His plan is to travel between each pair of the cities.
The distance between city A with coordinates (x1, y1) and city B with coordinates (x2, y2) is equal to |x1 - x2| + |y1 - y2|.
Now he is interested in the total distance between all the pairs of the cities.
Input
The first line contains one integer N.
The following N lines contain two separated integers (xi, yi) each - coordinates of the corresponding city.
Output
Output one integer - the answer to the question.
As this number can be very big - output it modulo 10^9 + 7.
Constraints
1 β€ N β€ 200 000
|xi|, |yi| β€ 10^9
SAMPLE INPUT
4
-1 5
1 6
3 5
2 3
SAMPLE OUTPUT
22
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Each digit of a number is represented by a cluster of adjacent X, with spaces between neighboring clusters. The digit is determined by the number of X in the cluster. For example, the number 243 would be represented by the following pattern
-XX-XXXX-XXX-
So to represent 0 the pattern will be -- (2 dashes without any X in between).
Given a string as input you have to output the corresponding number.
NOTE - All the number will fit into 32 bit integer. And string does not contain 10 consecutive 'X's.
First line contains number of test cases.
The first line of every test case contains one string.
Constraints-
1 β€ t β€ 30
3 β€ string length β€ 50
SAMPLE INPUT
2
-XX-XXXX-XXX-
-XX--XXXX---XXX-
SAMPLE OUTPUT
243
204003
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N points on the 2D plane, i-th of which is located on (x_i, y_i). There can be multiple points that share the same coordinate. What is the maximum possible Manhattan distance between two distinct points?
Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq x_i,y_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_N y_N
Output
Print the answer.
Examples
Input
3
1 1
2 4
3 2
Output
4
Input
2
1 1
1 1
Output
0
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).
Constraints
* 1 \leq N \leq 10^5
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of positive integers less than or equal to N that have an odd number of digits.
Examples
Input
11
Output
9
Input
136
Output
46
Input
100000
Output
90909
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
* The string does not contain characters other than `A`, `C`, `G` and `T`.
* The string does not contain `AGC` as a substring.
* The condition above cannot be violated by swapping two adjacent characters once.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.
Examples
Input
3
Output
61
Input
4
Output
230
Input
100
Output
388130742
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i.
In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y).
We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* 1 \leq B_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
A_2 B_2
:
A_N B_N
Output
Print the minimum total weight of the edges in such a cycle.
Examples
Input
3
1 5
4 2
6 3
Output
7
Input
4
1 5
2 6
3 7
4 8
Output
10
Input
6
19 92
64 64
78 48
57 33
73 6
95 73
Output
227
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 long seat of width X centimeters. There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters.
We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two people, and between the end of the seat and a person.
At most how many people can sit on the seat?
Constraints
* All input values are integers.
* 1 \leq X, Y, Z \leq 10^5
* Y+2Z \leq X
Input
Input is given from Standard Input in the following format:
X Y Z
Output
Print the answer.
Examples
Input
13 3 1
Output
3
Input
12 3 1
Output
2
Input
100000 1 1
Output
49999
Input
64146 123 456
Output
110
Input
64145 123 456
Output
109
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 frequency operation in the conversion operation of a finite number sequence. The conversion result of the sequence $ S = \\ {s_1, s_2, ... s_n \\} $ is a sequence of the same length. If the result is $ C = \\ {c_1, c_2, ..., c_n \\} $, then $ c_i $ represents the number of $ s_i $ in the sequence $ S $.
For example, if $ S = \\ {3,4,1,5,9,2,6,5,3 \\} $, then $ C = {2,1,1,2,1,1,1,2, It will be 2} $. Furthermore, if you perform a frequency operation on this sequence $ C $, you will get $ P = \\ {4,5,5,4,5,5,5,4,4 \\} $. This sequence does not change with the frequency operation. Such a sequence $ P $ is called a fixed point of the sequence $ S $. It is known that the fixed point can be obtained by repeating the appearance frequency operation for any sequence.
The example below shows the procedure for frequency manipulation. Let the first row be the sequence $ S $, the second row be the sequence $ C $, and the last row be the sequence $ P $. Since there are 3 same numbers as the first element ($ s_1 = 2 $) of the sequence $ S $, the first element $ c_1 $ of the sequence $ C $ is 3 and the same number as the next element ($ s_2 = 7 $). Since there are two, $ c_2 = 2 $, and so on, count the number and find $ c_i $.
<image>
Enter the sequence length $ n $ and the sequence $ S $, and write a program that outputs the fixed point sequence $ P $ and the minimum number of occurrence frequency operations performed to obtain $ P $. ..
Input
Given multiple datasets. Each dataset is given in the following format:
$ n $
$ s_1 $ $ s_2 $ ... $ s_n $
The first row is given the integer $ n $ ($ n \ leq 12 $), which represents the length of the sequence. In the second row, the integer $ s_i $ ($ 1 \ leq s_i \ leq 100 $) representing the elements of the sequence $ S $ is given, separated by blanks.
Input ends with 0 single line. The number of datasets does not exceed 200.
Output
For each dataset, the minimum number of occurrence frequency operations (integer) in the first row, the sequence of fixed points corresponding to the second row $ P $ element $ p_1 $, $ p_2 $, ..., $ p_n Please output $ separated by blanks.
Example
Input
10
4 5 1 1 4 5 12 3 5 4
0
Output
3
6 6 4 4 6 6 4 4 6 6
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mobile phones are equipped with a function that displays input candidates in order to efficiently input texts such as emails. This records frequently used words and presents words that have the entered letters as initial letters as input candidates. For example, if you usually enter the word "computer" a lot, just enter "c" and "computer" will be presented as a candidate. Let's create the basic part of such a feature.
Create a program that inputs sentences and letters and outputs words that have the letters as the first letter in the order of the number of occurrences. However, if there are multiple words with the same number of occurrences, they are output in lexicographic order. Output up to 5 words. If the corresponding word does not exist, output "NA".
input
Given multiple datasets. The end of the input is represented by a single zero. Each dataset is given in the following format:
n
line1
line2
::
linen
k
The first line is given the number of lines of text n (1 β€ n β€ 10). The text is given on the next n lines. The text consists of half-width lowercase letters and half-width spaces, and the number of characters in one line is 1 to 1024 characters. Words separated by spaces are between 1 and 20 characters.
The first letter k is given in the following line as a half-width alphabetic character.
The number of datasets does not exceed 100.
output
For each dataset, it prints a word or "NA" with the specified letter as the first letter.
Example
Input
1
ben likes bananas the best among many fruits because bananas are sweet and cheap
b
1
winners get to visit aizu and the university of aizu and make many friends as well
a
3
ask alex about
the answer for the
assignment on android apps
a
2
programming is both
a sport and an intellectual puzzle
c
0
Output
bananas because ben best
aizu and as
about alex android answer apps
NA
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two players, A and B, play the game using cards with numbers from 0 to 9. First, the two arrange the given n cards face down in a horizontal row. After that, the two players turn their cards face up one by one from the left, and the owner of the card with the larger number takes the two cards. At this time, the sum of the numbers written on the two cards shall be the score of the player who took the card. However, if the same number is written on the two open cards, it is a draw and each player takes one of his own cards.
For example, consider the case where the hands of A and B are arranged as shown in the following input examples 1 to 3. However, the input file consists of n + 1 lines, the first line contains the number of cards n for each player, and the i + 1 line (i = 1, 2, ..., n) is A. The numbers on the i-th card from the left and the numbers on the i-th card from the left of B are written in this order, with a blank as the delimiter. That is, from the second row onward of the input file, the left column represents the sequence of A cards, and the right column represents the sequence of B cards. At this time, the scores of A and B after the end of the game are shown in the corresponding output examples, respectively.
Create a program that outputs the score of A and the score of B when the game corresponding to the input file ends on one line with a space as a delimiter in this order. However, n β€ 10000.
Input example 1 | Input example 2 | Input example 3
--- | --- | ---
3 | 3 | 3
9 1 | 9 1 | 9 1
5 4 | 5 4 | 5 5
0 8 | 1 0 | 1 8
Output example 1 | Output example 2 | Output example 3
19 8 | 20 0 | 15 14
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each dataset, the score of A and the score of B are output on one line.
Input example
3
9 1
5 4
0 8
3
9 1
5 4
Ten
3
9 1
5 5
1 8
0
Output example
19 8
20 0
15 14
Insert a line break after the output of each dataset (after the score of B).
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
Example
Input
3
9 1
5 4
0 8
3
9 1
5 4
1 0
3
9 1
5 5
1 8
0
Output
19 8
20 0
15 14
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Professor Random, known for his research on randomized algorithms, is now conducting an experiment on biased dice. His experiment consists of dropping a number of dice onto a plane, one after another from a fixed position above the plane. The dice fall onto the plane or dice already there, without rotating, and may roll and fall according to their property. Then he observes and records the status of the stack formed on the plane, specifically, how many times each number appears on the faces visible from above. All the dice have the same size and their face numbering is identical, which we show in Figure C-1.
<image>
Figure C-1: Numbering of a die
The dice have very special properties, as in the following.
(1) Ordinary dice can roll in four directions, but the dice used in this experiment never roll in the directions of faces 1, 2 and 3; they can only roll in the directions of faces 4, 5 and 6. In the situation shown in Figure C-2, our die can only roll to one of two directions.
<image>
Figure C-2: An ordinary die and a biased die
(2) The die can only roll when it will fall down after rolling, as shown in Figure C-3. When multiple possibilities exist, the die rolls towards the face with the largest number among those directions it can roll to.
<image>
Figure C-3: A die can roll only when it can fall
(3) When a die rolls, it rolls exactly 90 degrees, and then falls straight down until its bottom face touches another die or the plane, as in the case [B] or [C] of Figure C-4.
(4) After rolling and falling, the die repeatedly does so according to the rules (1) to (3) above.
<image>
Figure C-4: Example stacking of biased dice
For example, when we drop four dice all in the same orientation, 6 at the top and 4 at the front, then a stack will be formed as shown in Figure C-4.
<image>
Figure C-5: Example records
After forming the stack, we count the numbers of faces with 1 through 6 visible from above and record them. For example, in the left case of Figure C-5, the record will be "0 2 1 0 0 0", and in the right case, "0 1 1 0 0 1".
Input
The input consists of several datasets each in the following format.
> n
> t1 f1
> t2 f2
> ...
> tn fn
>
Here, n (1 β€ n β€ 100) is an integer and is the number of the dice to be dropped. ti and fi (1 β€ ti, fi β€ 6) are two integers separated by a space and represent the numbers on the top and the front faces of the i-th die, when it is released, respectively.
The end of the input is indicated by a line containing a single zero.
Output
For each dataset, output six integers separated by a space. The integers represent the numbers of faces with 1 through 6 correspondingly, visible from above. There may not be any other characters in the output.
Sample Input
4
6 4
6 4
6 4
6 4
2
5 3
5 3
8
4 2
4 2
4 2
4 2
4 2
4 2
4 2
4 2
6
4 6
1 5
2 3
5 3
2 4
4 2
0
Output for the Sample Input
0 1 1 0 0 1
1 0 0 0 1 0
1 2 2 1 0 0
2 3 0 0 0 0
Example
Input
4
6 4
6 4
6 4
6 4
2
5 3
5 3
8
4 2
4 2
4 2
4 2
4 2
4 2
4 2
4 2
6
4 6
1 5
2 3
5 3
2 4
4 2
0
Output
0 1 1 0 0 1
1 0 0 0 1 0
1 2 2 1 0 0
2 3 0 0 0 0
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 goddess of programming is reviewing a thick logbook, which is a yearly record of visitors to her holy altar of programming. The logbook also records her visits at the altar.
The altar attracts programmers from all over the world because one visitor is chosen every year and endowed with a gift of miracle programming power by the goddess. The endowed programmer is chosen from those programmers who spent the longest time at the altar during the goddess's presence. There have been enthusiastic visitors who spent very long time at the altar but failed to receive the gift because the goddess was absent during their visits.
Now, your mission is to write a program that finds how long the programmer to be endowed stayed at the altar during the goddess's presence.
Input
The input is a sequence of datasets. The number of datasets is less than 100. Each dataset is formatted as follows.
n
M1/D1 h1:m1e1 p1
M2/D2 h2:m2e2 p2
.
.
.
Mn/Dn hn:mnen pn
The first line of a dataset contains a positive even integer, n β€ 1000, which denotes the number of lines of the logbook. This line is followed by n lines of space-separated data, where Mi/Di identifies the month and the day of the visit, hi:mi represents the time of either the entrance to or exit from the altar, ei is either I for entrance, or O for exit, and pi identifies the visitor.
All the lines in the logbook are formatted in a fixed-column format. Both the month and the day in the month are represented by two digits. Therefore April 1 is represented by 04/01 and not by 4/1. The time is described in the 24-hour system, taking two digits for the hour, followed by a colon and two digits for minutes, 09:13 for instance and not like 9:13. A programmer is identified by an ID, a unique number using three digits. The same format is used to indicate entrance and exit of the goddess, whose ID is 000.
All the lines in the logbook are sorted in ascending order with respect to date and time. Because the altar is closed at midnight, the altar is emptied at 00:00. You may assume that each time in the input is between 00:01 and 23:59, inclusive.
A programmer may leave the altar just after entering it. In this case, the entrance and exit time are the same and the length of such a visit is considered 0 minute. You may assume for such entrance and exit records, the line that corresponds to the entrance appears earlier in the input than the line that corresponds to the exit. You may assume that at least one programmer appears in the logbook.
The end of the input is indicated by a line containing a single zero.
Output
For each dataset, output the total sum of the blessed time of the endowed programmer. The blessed time of a programmer is the length of his/her stay at the altar during the presence of the goddess. The endowed programmer is the one whose total blessed time is the longest among all the programmers. The output should be represented in minutes. Note that the goddess of programming is not a programmer.
Example
Input
14
04/21 09:00 I 000
04/21 09:00 I 001
04/21 09:15 I 002
04/21 09:30 O 001
04/21 09:45 O 000
04/21 10:00 O 002
04/28 09:00 I 003
04/28 09:15 I 000
04/28 09:30 I 004
04/28 09:45 O 004
04/28 10:00 O 000
04/28 10:15 O 003
04/29 20:00 I 002
04/29 21:30 O 002
20
06/01 09:00 I 001
06/01 09:15 I 002
06/01 09:15 I 003
06/01 09:30 O 002
06/01 10:00 I 000
06/01 10:15 O 001
06/01 10:30 I 002
06/01 10:45 O 002
06/01 11:00 I 001
06/01 11:15 O 000
06/01 11:30 I 002
06/01 11:45 O 001
06/01 12:00 O 002
06/01 12:15 I 000
06/01 12:30 I 002
06/01 12:45 O 000
06/01 13:00 I 000
06/01 13:15 O 000
06/01 13:30 O 002
06/01 13:45 O 003
0
Output
45
120
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Nathan O. Davis is challenging a kind of shooter game. In this game, enemies emit laser beams from outside of the screen. A laser beam is a straight line with a certain thickness. Nathan moves a circular-shaped machine within the screen, in such a way it does not overlap a laser beam. As in many shooters, the machine is destroyed when the overlap happens.
Nathan is facing an uphill stage. Many enemies attack simultaneously in this stage, so eventually laser beams fill out almost all of the screen. Surprisingly, it is even possible he has no "safe area" on the screen. In other words, the machine cannot survive wherever it is located in some cases.
The world is as kind as it is cruel! There is a special item that helps the machine to survive any dangerous situation, even if it is exposed in a shower of laser beams, for some seconds. In addition, another straight line (called "a warning line") is drawn on the screen for a few seconds before a laser beam is emit along that line.
The only problem is that Nathan has a little slow reflexes. He often messes up the timing to use the special item. But he knows a good person who can write a program to make up his slow reflexes - it's you! So he asked you for help.
Your task is to write a program to make judgement whether he should use the item or not, for given warning lines and the radius of the machine.
Input
The input is a sequence of datasets. Each dataset corresponds to one situation with warning lines in the following format:
W H N R
x1,1 y1,1 x1,2 y1,2 t1
x2,1 y2,1 x2,2 y2,2 t2
...
xN,1 yN,1 xN,2 yN,2 tN
The first line of a dataset contains four integers W, H, N and R (2 < W β€ 640, 2 < H β€ 480, 0 β€ N β€ 100 and 0 < R < min{W, H}/2). The first two integers W and H indicate the width and height of the screen, respectively. The next integer N represents the number of laser beams.
The last integer R indicates the radius of the machine. It is guaranteed that the output would remain unchanged if the radius of the machine would become larger by 10-5 than R.
The following N lines describe the N warning lines. The (i+1)-th line of the dataset corresponds to the i-th warning line, which is represented as a straight line which passes through two given different coordinates (xi,1, yi,1 ) and (xi,2 , yi,2 ). The last integer ti indicates the thickness of the laser beam corresponding to the i-th warning line.
All given coordinates (x, y) on the screen are a pair of integers (0 β€ x β€ W, 0 β€ y β€ H). Note that, however, the machine is allowed to be located at non-integer coordinates during the play.
The input is terminated by a line with four zeros. This line should not be processed.
Output
For each case, print "Yes" in a line if there is a safe area, or print "No" otherwise.
Example
Input
100 100 1 1
50 0 50 100 50
640 480 1 1
0 0 640 480 100
0 0 0 0
Output
No
Yes
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 range search problem consists of a set of attributed records S to determine which records from S intersect with a given range.
For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set.
Constraints
* 0 β€ n β€ 500,000
* 0 β€ q β€ 20,000
* -1,000,000,000 β€ x, y, sx, tx, sy, ty β€ 1,000,000,000
* sx β€ tx
* sy β€ ty
* For each query, the number of points which are within the range is less than or equal to 100.
Input
n
x0 y0
x1 y1
:
xn-1 yn-1
q
sx0 tx0 sy0 ty0
sx1 tx1 sy1 ty1
:
sxq-1 txq-1 syq-1 tyq-1
The first integer n is the number of points. In the following n lines, the coordinate of the i-th point is given by two integers xi and yi.
The next integer q is the number of queries. In the following q lines, each query is given by four integers, sxi, txi, syi, tyi.
Output
For each query, report IDs of points such that sxi β€ x β€ txi and syi β€ y β€ tyi. The IDs should be reported in ascending order. Print an ID in a line, and print a blank line at the end of output for the each query.
Example
Input
6
2 1
2 2
4 2
6 2
3 3
5 4
2
2 4 0 4
4 10 2 5
Output
0
1
2
4
2
3
5
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya has got a magic matrix a of size n Γ m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.
Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.
After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.
Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to β{(i_1-i_2)^2 + (j_1-j_2)^2}.
Calculate the expected value of the Vasya's final score.
It can be shown that the answer can be represented as P/Q, where P and Q are coprime integer numbers, and Q notβ‘ 0~(mod ~ 998244353). Print the value P β
Q^{-1} modulo 998244353.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 1 000) β the number of rows and the number of columns in the matrix a.
The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, ..., a_{im} ~ (0 β€ a_{ij} β€ 10^9).
The following line contains two integers r and c (1 β€ r β€ n, 1 β€ c β€ m) β the index of row and the index of column where the chip is now.
Output
Print the expected value of Vasya's final score in the format described in the problem statement.
Examples
Input
1 4
1 1 2 1
1 3
Output
2
Input
2 3
1 5 7
2 3 1
1 2
Output
665496238
Note
In the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to (1^2 + 2^2+ 1^2)/(3) = 2.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 Γ 8, but it still is N Γ N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number 1 (you can choose which one). Then you want to reach square 2 (possibly passing through some other squares in process), then square 3 and so on until you reach square N^2. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
Input
The first line contains a single integer N (3 β€ N β€ 10) β the size of the chessboard.
Each of the next N lines contains N integers A_{i1}, A_{i2}, ..., A_{iN} (1 β€ A_{ij} β€ N^2) β the numbers written on the squares of the i-th row of the board.
It is guaranteed that all A_{ij} are pairwise distinct.
Output
The only line should contain two integers β the number of steps in the best answer and the number of replacement moves in it.
Example
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
Note
Here are the steps for the first example (the starting piece is a knight):
1. Move to (3, 2)
2. Move to (1, 3)
3. Move to (3, 2)
4. Replace the knight with a rook
5. Move to (3, 1)
6. Move to (3, 3)
7. Move to (3, 2)
8. Move to (2, 2)
9. Move to (2, 3)
10. Move to (2, 1)
11. Move to (1, 1)
12. Move to (1, 2)
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.
Input
The first line contains integers n and k (1 β€ n,k β€ 10^5), the length of the array and the number of operations you should perform.
The second line contains n space-separated integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9), the elements of the array.
Output
Print the minimum non-zero element before each operation in a new line.
Examples
Input
3 5
1 2 3
Output
1
1
1
0
0
Input
4 2
10 3 5 3
Output
3
2
Note
In the first sample:
In the first step: the array is [1,2,3], so the minimum non-zero element is 1.
In the second step: the array is [0,1,2], so the minimum non-zero element is 1.
In the third step: the array is [0,0,1], so the minimum non-zero element is 1.
In the fourth and fifth step: the array is [0,0,0], so we printed 0.
In the second sample:
In the first step: the array is [10,3,5,3], so the minimum non-zero element is 3.
In the second step: the array is [7,0,2,0], so the minimum non-zero element is 2.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 at the lesson of mathematics, Petya learns about the digital root.
The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.
Let's denote the digital root of x as S(x). Then S(5)=5, S(38)=S(3+8=11)=S(1+1=2)=2, S(10)=S(1+0=1)=1.
As a homework Petya got n tasks of the form: find k-th positive number whose digital root is x.
Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all n tasks from Petya's homework.
Input
The first line contains a single integer n (1 β€ n β€ 10^3) β the number of tasks in Petya's homework. The next n lines contain two integers k_i (1 β€ k_i β€ 10^{12}) and x_i (1 β€ x_i β€ 9) β i-th Petya's task in which you need to find a k_i-th positive number, the digital root of which is x_i.
Output
Output n lines, i-th line should contain a single integer β the answer to the i-th problem.
Example
Input
3
1 5
5 2
3 1
Output
5
38
19
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible.
There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are closed, and there is one stone on every manhole. There is exactly one coin under every manhole, and to win the game Nastya should pick all the coins. Initially Nastya stands near the k-th manhole from the left. She is thinking what to do.
In one turn, Nastya can do one of the following:
* if there is at least one stone on the manhole Nastya stands near, throw exactly one stone from it onto any other manhole (yes, Nastya is strong).
* go to a neighboring manhole;
* if there are no stones on the manhole Nastya stays near, she can open it and pick the coin from it. After it she must close the manhole immediately (it doesn't require additional moves).
<image> The figure shows the intermediate state of the game. At the current position Nastya can throw the stone to any other manhole or move left or right to the neighboring manholes. If she were near the leftmost manhole, she could open it (since there are no stones on it).
Nastya can leave the room when she picks all the coins. Monsters are everywhere, so you need to compute the minimum number of moves Nastya has to make to pick all the coins.
Note one time more that Nastya can open a manhole only when there are no stones onto it.
Input
The first and only line contains two integers n and k, separated by space (2 β€ n β€ 5000, 1 β€ k β€ n) β the number of manholes and the index of manhole from the left, near which Nastya stays initially. Initially there is exactly one stone near each of the n manholes.
Output
Print a single integer β minimum number of moves which lead Nastya to pick all the coins.
Examples
Input
2 2
Output
6
Input
4 2
Output
13
Input
5 1
Output
15
Note
Let's consider the example where n = 2, k = 2. Nastya should play as follows:
* At first she throws the stone from the second manhole to the first. Now there are two stones on the first manhole.
* Then she opens the second manhole and pick the coin from it.
* Then she goes to the first manhole, throws two stones by two moves to the second manhole and then opens the manhole and picks the coin from it.
So, 6 moves are required to win.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles.
Misha has to buy exactly k shovels. Each shovel can be bought no more than once.
Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset.
There are also m special offers in the shop. The j-th of them is given as a pair (x_j, y_j), and it means that if Misha buys exactly x_j shovels during one purchase then y_j most cheapest of them are for free (i.e. he will not pay for y_j most cheapest shovels during the current purchase).
Misha can use any offer any (possibly, zero) number of times, but he cannot use more than one offer during one purchase (but he can buy shovels without using any offers).
Your task is to calculate the minimum cost of buying k shovels, if Misha buys them optimally.
Input
The first line of the input contains three integers n, m and k (1 β€ n, m β€ 2 β
10^5, 1 β€ k β€ min(n, 2000)) β the number of shovels in the shop, the number of special offers and the number of shovels Misha has to buy, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^5), where a_i is the cost of the i-th shovel.
The next m lines contain special offers. The j-th of them is given as a pair of integers (x_i, y_i) (1 β€ y_i β€ x_i β€ n) and means that if Misha buys exactly x_i shovels during some purchase, then he can take y_i most cheapest of them for free.
Output
Print one integer β the minimum cost of buying k shovels if Misha buys them optimally.
Examples
Input
7 4 5
2 5 4 2 6 3 1
2 1
6 5
2 1
3 1
Output
7
Input
9 4 8
6 8 5 1 8 1 1 2 1
9 2
8 4
5 3
9 7
Output
17
Input
5 1 4
2 5 7 4 6
5 4
Output
17
Note
In the first example Misha can buy shovels on positions 1 and 4 (both with costs 2) during the first purchase and get one of them for free using the first or the third special offer. And then he can buy shovels on positions 3 and 6 (with costs 4 and 3) during the second purchase and get the second one for free using the first or the third special offer. Then he can buy the shovel on a position 7 with cost 1. So the total cost is 4 + 2 + 1 = 7.
In the second example Misha can buy shovels on positions 1, 2, 3, 4 and 8 (costs are 6, 8, 5, 1 and 2) and get three cheapest (with costs 5, 1 and 2) for free. And then he can buy shovels on positions 6, 7 and 9 (all with costs 1) without using any special offers. So the total cost is 6 + 8 + 1 + 1 + 1 = 17.
In the third example Misha can buy four cheapest shovels without using any special offers and get the total cost 17.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Authors guessed an array a consisting of n integers; each integer is not less than 2 and not greater than 2 β
10^5. You don't know the array a, but you know the array b which is formed from it with the following sequence of operations:
1. Firstly, let the array b be equal to the array a;
2. Secondly, for each i from 1 to n:
* if a_i is a prime number, then one integer p_{a_i} is appended to array b, where p is an infinite sequence of prime numbers (2, 3, 5, ...);
* otherwise (if a_i is not a prime number), the greatest divisor of a_i which is not equal to a_i is appended to b;
3. Then the obtained array of length 2n is shuffled and given to you in the input.
Here p_{a_i} means the a_i-th prime number. The first prime p_1 = 2, the second one is p_2 = 3, and so on.
Your task is to recover any suitable array a that forms the given array b. It is guaranteed that the answer exists (so the array b is obtained from some suitable array a). If there are multiple answers, you can print any.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a.
The second line of the input contains 2n integers b_1, b_2, ..., b_{2n} (2 β€ b_i β€ 2750131), where b_i is the i-th element of b. 2750131 is the 199999-th prime number.
Output
In the only line of the output print n integers a_1, a_2, ..., a_n (2 β€ a_i β€ 2 β
10^5) in any order β the array a from which the array b can be obtained using the sequence of moves given in the problem statement. If there are multiple answers, you can print any.
Examples
Input
3
3 5 2 3 2 4
Output
3 4 2
Input
1
2750131 199999
Output
199999
Input
1
3 6
Output
6
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 β
n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from left to right.
<image>
Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all 2n students (there are no additional constraints), and a team can consist of any number of students.
Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.
Input
The first line of the input contains a single integer n (1 β€ n β€ 10^5) β the number of students in each row.
The second line of the input contains n integers h_{1, 1}, h_{1, 2}, β¦, h_{1, n} (1 β€ h_{1, i} β€ 10^9), where h_{1, i} is the height of the i-th student in the first row.
The third line of the input contains n integers h_{2, 1}, h_{2, 2}, β¦, h_{2, n} (1 β€ h_{2, i} β€ 10^9), where h_{2, i} is the height of the i-th student in the second row.
Output
Print a single integer β the maximum possible total height of players in a team Demid can choose.
Examples
Input
5
9 3 5 7 3
5 8 1 4 5
Output
29
Input
3
1 2 9
10 1 1
Output
19
Input
1
7
4
Output
7
Note
In the first example Demid can choose the following team as follows:
<image>
In the second example Demid can choose the following team as follows:
<image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n.
The graph is considered harmonious if and only if the following property holds:
* For every triple of integers (l, m, r) such that 1 β€ l < m < r β€ n, if there exists a path going from node l to node r, then there exists a path going from node l to node m.
In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l < r), then we should able to reach nodes (l+1), (l+2), β¦, (r-1) too.
What is the minimum number of edges we need to add to make the graph harmonious?
Input
The first line contains two integers n and m (3 β€ n β€ 200\ 000 and 1 β€ m β€ 200\ 000).
The i-th of the next m lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n, u_i β v_i), that mean that there's an edge between nodes u and v.
It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).
Output
Print the minimum number of edges we have to add to the graph to make it harmonious.
Examples
Input
14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12
Output
1
Input
200000 3
7 9
9 8
4 5
Output
0
Note
In the first example, the given graph is not harmonious (for instance, 1 < 6 < 7, node 1 can reach node 7 through the path 1 β 2 β 7, but node 1 can't reach node 6). However adding the edge (2, 4) is sufficient to make it harmonious.
In the second example, the given graph is already harmonious.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j (1 β€ j β€ n-2), that s_{j}s_{j+1}s_{j+2}="one" or s_{j}s_{j+1}s_{j+2}="two".
For example:
* Polycarp does not like strings "oneee", "ontwow", "twone" and "oneonetwo" (they all have at least one substring "one" or "two"),
* Polycarp likes strings "oonnee", "twwwo" and "twnoe" (they have no substrings "one" and "two").
Polycarp wants to select a certain set of indices (positions) and remove all letters on these positions. All removals are made at the same time.
For example, if the string looks like s="onetwone", then if Polycarp selects two indices 3 and 6, then "onetwone" will be selected and the result is "ontwne".
What is the minimum number of indices (positions) that Polycarp needs to select to make the string liked? What should these positions be?
Input
The first line of the input contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Next, the test cases are given.
Each test case consists of one non-empty string s. Its length does not exceed 1.5β
10^5. The string s consists only of lowercase Latin letters.
It is guaranteed that the sum of lengths of all lines for all input data in the test does not exceed 1.5β
10^6.
Output
Print an answer for each test case in the input in order of their appearance.
The first line of each answer should contain r (0 β€ r β€ |s|) β the required minimum number of positions to be removed, where |s| is the length of the given line. The second line of each answer should contain r different integers β the indices themselves for removal in any order. Indices are numbered from left to right from 1 to the length of the string. If r=0, then the second line can be skipped (or you can print empty). If there are several answers, print any of them.
Examples
Input
4
onetwone
testme
oneoneone
twotwo
Output
2
6 3
0
3
4 1 7
2
1 4
Input
10
onetwonetwooneooonetwooo
two
one
twooooo
ttttwo
ttwwoo
ooone
onnne
oneeeee
oneeeeeeetwooooo
Output
6
18 11 12 1 6 21
1
1
1
3
1
2
1
6
0
1
4
0
1
1
2
1 11
Note
In the first example, answers are:
* "onetwone",
* "testme" β Polycarp likes it, there is nothing to remove,
* "oneoneone",
* "twotwo".
In the second example, answers are:
* "onetwonetwooneooonetwooo",
* "two",
* "one",
* "twooooo",
* "ttttwo",
* "ttwwoo" β Polycarp likes it, there is nothing to remove,
* "ooone",
* "onnne" β Polycarp likes it, there is nothing to remove,
* "oneeeee",
* "oneeeeeeetwooooo".
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string s starting from the l-th character and ending with the r-th character as s[l ... r]. The characters of each string are numbered from 1.
We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.
Binary string a is considered reachable from binary string b if there exists a sequence s_1, s_2, ..., s_k such that s_1 = a, s_k = b, and for every i β [1, k - 1], s_i can be transformed into s_{i + 1} using exactly one operation. Note that k can be equal to 1, i. e., every string is reachable from itself.
You are given a string t and q queries to it. Each query consists of three integers l_1, l_2 and len. To answer each query, you have to determine whether t[l_1 ... l_1 + len - 1] is reachable from t[l_2 ... l_2 + len - 1].
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the length of string t.
The second line contains one string t (|t| = n). Each character of t is either 0 or 1.
The third line contains one integer q (1 β€ q β€ 2 β
10^5) β the number of queries.
Then q lines follow, each line represents a query. The i-th line contains three integers l_1, l_2 and len (1 β€ l_1, l_2 β€ |t|, 1 β€ len β€ |t| - max(l_1, l_2) + 1) for the i-th query.
Output
For each query, print either YES if t[l_1 ... l_1 + len - 1] is reachable from t[l_2 ... l_2 + len - 1], or NO otherwise. You may print each letter in any register.
Example
Input
5
11011
3
1 3 3
1 4 2
1 2 3
Output
Yes
Yes
No
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token.
Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table:
* ">" β 1000,
* "<" β 1001,
* "+" β 1010,
* "-" β 1011,
* "." β 1100,
* "," β 1101,
* "[" β 1110,
* "]" β 1111.
Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system β this is the Unary program equivalent to the original Brainfuck one.
You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo 1000003 (106 + 3).
Input
The input will consist of a single line p which gives a Brainfuck program. String p will contain between 1 and 100 characters, inclusive. Each character of p will be "+", "-", "[", "]", "<", ">", "." or ",".
Output
Output the size of the equivalent Unary program modulo 1000003 (106 + 3).
Examples
Input
,.
Output
220
Input
++++[>,.<-]
Output
61425
Note
To write a number n in unary numeral system, one simply has to write 1 n times. For example, 5 written in unary system will be 11111.
In the first example replacing Brainfuck commands with binary code will give us 1101 1100. After we concatenate the codes, we'll get 11011100 in binary system, or 220 in decimal. That's exactly the number of tokens in the equivalent Unary program.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is an undirected tree of n vertices, connected by n-1 bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex a and its tail is at vertex b. The snake's body occupies all vertices on the unique simple path between a and b.
The snake wants to know if it can reverse itself β that is, to move its head to where its tail started, and its tail to where its head started. Unfortunately, the snake's movements are restricted to the tree's structure.
In an operation, the snake can move its head to an adjacent vertex not currently occupied by the snake. When it does this, the tail moves one vertex closer to the head, so that the length of the snake remains unchanged. Similarly, the snake can also move its tail to an adjacent vertex not currently occupied by the snake. When it does this, the head moves one unit closer to the tail.
<image> Let's denote a snake position by (h,t), where h is the index of the vertex with the snake's head, t is the index of the vertex with the snake's tail. This snake can reverse itself with the movements (4,7)β (5,1)β (4,2)β (1, 3)β (7,2)β (8,1)β (7,4).
Determine if it is possible to reverse the snake with some sequence of operations.
Input
The first line contains a single integer t (1β€ tβ€ 100) β the number of test cases. The next lines contain descriptions of test cases.
The first line of each test case contains three integers n,a,b (2β€ nβ€ 10^5,1β€ a,bβ€ n,aβ b).
Each of the next n-1 lines contains two integers u_i,v_i (1β€ u_i,v_iβ€ n,u_iβ v_i), indicating an edge between vertices u_i and v_i. It is guaranteed that the given edges form a tree.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, output "YES" if it is possible for the snake to reverse itself, or "NO" otherwise.
Example
Input
4
8 4 7
1 2
2 3
1 4
4 5
4 6
1 7
7 8
4 3 2
4 3
1 2
2 3
9 3 5
1 2
2 3
3 4
1 5
5 6
6 7
1 8
8 9
16 15 12
1 2
2 3
1 4
4 5
5 6
6 7
4 8
8 9
8 10
10 11
11 12
11 13
13 14
10 15
15 16
Output
YES
NO
NO
YES
Note
The first test case is pictured above.
In the second test case, the tree is a path. We can show that the snake cannot reverse itself.
In the third test case, we can show that the snake cannot reverse itself.
In the fourth test case, an example solution is:
(15,12)β (16,11)β (15,13)β (10,14)β (8,13)β (4,11)β (1,10)
β (2,8)β (3,4)β (2,5)β (1,6)β (4,7)β (8,6)β (10,5)
β (11,4)β (13,8)β (14,10)β (13,15)β (11,16)β (12,15).
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 square of size 10^6 Γ 10^6 on the coordinate plane with four points (0, 0), (0, 10^6), (10^6, 0), and (10^6, 10^6) as its vertices.
You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.
Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.
Input
The first line contains two integers n and m (0 β€ n, m β€ 10^5) β the number of horizontal segments and the number of vertical segments.
The next n lines contain descriptions of the horizontal segments. The i-th line contains three integers y_i, lx_i and rx_i (0 < y_i < 10^6; 0 β€ lx_i < rx_i β€ 10^6), which means the segment connects (lx_i, y_i) and (rx_i, y_i).
The next m lines contain descriptions of the vertical segments. The i-th line contains three integers x_i, ly_i and ry_i (0 < x_i < 10^6; 0 β€ ly_i < ry_i β€ 10^6), which means the segment connects (x_i, ly_i) and (x_i, ry_i).
It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.
Output
Print the number of pieces the square is divided into after drawing all the segments.
Example
Input
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
Output
7
Note
The sample is like this:
<image>
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way:
* Consider a graph on k nodes, with numbers from b_1 to b_k written on them.
* For every i from 1 to k: find such j (1 β€ j β€ k, jβ i), for which (b_i β b_j) is the smallest among all such j, where β denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph.
* We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles).
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
You can find an example below (the picture corresponding to the first test case).
Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.
However, sequence (0, 1, 5, 2) is good.
<image>
You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?
It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
Input
The first line contains a single integer n (2 β€ n β€ 200,000) β length of the sequence.
The second line contains n distinct non-negative integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the sequence.
Output
You should output exactly one integer β the minimum possible number of elements to remove in order to make the remaining sequence good.
Examples
Input
5
0 1 5 2 6
Output
1
Input
7
6 9 8 7 3 5 2
Output
2
Note
Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.
It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array a_1, a_2, β¦, a_n consisting of n positive integers and a positive integer m.
You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.
Let's call an array m-divisible if for each two adjacent numbers in the array (two numbers on the positions i and i+1 are called adjacent for each i) their sum is divisible by m. An array of one element is m-divisible.
Find the smallest number of m-divisible arrays that a_1, a_2, β¦, a_n is possible to divide into.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
The first line of each test case contains two integers n, m (1 β€ n β€ 10^5, 1 β€ m β€ 10^5).
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9).
It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 10^5.
Output
For each test case print the answer to the problem.
Example
Input
4
6 4
2 2 8 6 9 4
10 8
1 1 1 5 2 4 4 8 6 7
1 1
666
2 2
2 4
Output
3
6
1
1
Note
In the first test case we can divide the elements as follows:
* [4, 8]. It is a 4-divisible array because 4+8 is divisible by 4.
* [2, 6, 2]. It is a 4-divisible array because 2+6 and 6+2 are divisible by 4.
* [9]. It is a 4-divisible array because it consists of one element.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if:
* in one move you can go to any of the four adjacent cells sharing a side;
* visiting the cell F is forbidden (it is an obstacle).
Input
The first line contains an integer t (1 β€ t β€ 10^4) β the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers x_A, y_A (1 β€ x_A, y_A β€ 1000) β coordinates of the start cell A. The second one contains two integers x_B, y_B (1 β€ x_B, y_B β€ 1000) β coordinates of the finish cell B. The third one contains two integers x_F, y_F (1 β€ x_F, y_F β€ 1000) β coordinates of the forbidden cell F. All cells are distinct.
Coordinate x corresponds to the column number and coordinate y corresponds to the row number (see the pictures below).
Output
Output t lines. The i-th line should contain the answer for the i-th test case: the length of the shortest path from the cell A to the cell B if the cell F is not allowed to be visited.
Example
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
Note
<image> An example of a possible shortest path for the first test case. <image> An example of a possible shortest path for the second test case.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following:
function rangeIncrement(l, r)
for i := l .. r do
a[i] = a[i] + 1
Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105.
Before calls of function rangeIncrement(l, r) all array elements equal zero.
Input
The first input line contains a single integer n (1 β€ n β€ 105) β the length of the array a[1... n].
The second line contains its integer space-separated elements, a[1], a[2], ..., a[n] (0 β€ a[i] β€ 105) after some series of function calls rangeIncrement(l, r).
It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r).
Output
Print on the first line t β the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105.
Then print t lines β the descriptions of function calls, one per line. Each line should contain two integers li, ri (1 β€ li β€ ri β€ n) β the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order.
If there are multiple solutions, you are allowed to print any of them.
Examples
Input
6
1 2 1 1 4 1
Output
5
2 2
5 5
5 5
5 5
1 6
Input
5
1 0 1 0 1
Output
3
1 1
3 3
5 5
Note
The first sample requires a call for the entire array, and four additional calls:
* one for the segment [2,2] (i.e. the second element of the array),
* three for the segment [5,5] (i.e. the fifth element of the array).
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.
At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.
Input
The single line contains four integers x, y, a, b (1 β€ a β€ x β€ 100, 1 β€ b β€ y β€ 100). The numbers on the line are separated by a space.
Output
In the first line print integer n β the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di β the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order.
Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.
Examples
Input
3 2 1 1
Output
3
2 1
3 1
3 2
Input
2 4 2 2
Output
0
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
Input
The first line contains number n (1 β€ n β€ 100). Next n lines contains the dominoes. Each of these lines contains two numbers β the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
Output
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of n lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "β" (if you need to turn it).
Examples
Input
5
1 2
2 4
2 4
6 4
2 1
Output
2 -
1 -
5 -
3 +
4 -
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.
And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure:
* if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively);
* if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code;
* if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits.
* The length of the safe code coincides with the length of the hint.
For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".
After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.
At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...
Input
The first line contains string s β the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.
The input limits for scoring 30 points are (subproblem A1):
* 1 β€ |s| β€ 5.
The input limits for scoring 100 points are (subproblems A1+A2):
* 1 β€ |s| β€ 105.
Here |s| means the length of string s.
Output
Print the number of codes that match the given hint.
Examples
Input
AJ
Output
81
Input
1?AA
Output
100
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider a table G of size n Γ m such that G(i, j) = GCD(i, j) for all 1 β€ i β€ n, 1 β€ j β€ m. GCD(a, b) is the greatest common divisor of numbers a and b.
You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1 β€ i β€ n and 1 β€ j β€ m - k + 1 should exist that G(i, j + l - 1) = al for all 1 β€ l β€ k.
Determine if the sequence a occurs in table G.
Input
The first line contains three space-separated integers n, m and k (1 β€ n, m β€ 1012; 1 β€ k β€ 10000). The second line contains k space-separated integers a1, a2, ..., ak (1 β€ ai β€ 1012).
Output
Print a single word "YES", if the given sequence occurs in table G, otherwise print "NO".
Examples
Input
100 100 5
5 2 1 2 1
Output
YES
Input
100 8 5
5 2 1 2 1
Output
NO
Input
100 100 7
1 2 3 4 5 6 7
Output
NO
Note
Sample 1. The tenth row of table G starts from sequence {1, 2, 1, 2, 5, 2, 1, 2, 1, 10}. As you can see, elements from fifth to ninth coincide with sequence a.
Sample 2. This time the width of table G equals 8. Sequence a doesn't occur there.
The input will be give
Read the inputs from 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.