question large_stringlengths 265 13.2k |
|---|
Solve the programming task below in a Python markdown code block.
Captain Jack Sparrow and Davy Jones are having a furious sword fight to gain the key to the chest containing Davy Jones' heart. Jack wants to kill Davy Jones and live forever as the captain of The Flying Dutchman. On the other hand, Davy Jones wants to save himself from death.
A string is hanging between them. With each strike of a sword, they can strike down any one character from the string. If at any point of time before striking down a character, either of them is able to make a palindrome from the characters of the string (any anagram of the string) , he can strike down the entire string in one shot and defeat his opponent. It is known that Jack gets the first chance to strike and strikes are made alternatively by both of them.
Given the string that is hanging between them, determine who wins the fight provided that both fight to achieve their target i.e. fight optimally.
Input
The first line of each file contains T, the number of test cases.
Each of the next T line contains a string S consisting of only lower case characters (a-z).
Output
For each test case, print in a new line the winner of the sword fight - "JACK" or
"DAVY JONES" (quotes for clarity only).
Constraints
1 β€ T β€ 100
1 β€ length of string S β€ 100000
NOTE
There is partial marking for this question.
SAMPLE INPUT
2
aba
abca
SAMPLE OUTPUT
JACK
DAVY JONES
Explanation
For 2nd test case if Jack wants to win then by playing optimally he removes 'a' from the string. Else 'aca' or 'aba' will be formed by removing 'b' or 'c' respectively, which can be cut in one go as they are palindromes by Davy Jones where he would win. So Davy Jones will be left with 'bca'. Now all are distinct characters, in which he removes any one of the three. In next turn Jack removes another character and finally Davy Jones gets only single character where he wins.
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.
Panda is fond of numbers. Given a number, he subtracts it with squares of any one particular digit of that number to get new numbers. This operation can be applied any number of times (possibly zero) till he obtains a pandatic number. If he is able to reach to a pandatic number then he wins. A pandatic number is a number which can be expressed in the form A^A, where A is a positive integer.
Input Format:
The first line will contain T, the number of test cases.
Then T lines follow, each containing an integer N.
Output Format:
For each test case, output whether it's possible for panda to reach a pandatic number by doing the operations as described. If it's possible print "Yes" (without quotes), otherwise print "No" (without quotes).
Constraints:
Subtask 1: (10 points)
1 β€ T β€ 10^3
1 β€ N β€ 10^3
Subtask 2: (90 points)
1 β€ T β€ 10^5
1 β€ N β€ 10^6
SAMPLE INPUT
3
1
3
13
SAMPLE OUTPUT
Yes
No
Yes
Explanation
Case 1: 1 is a pandatic number, hence the answer is "Yes".
Case 2: 3 is not a pandatic number, the answer for this is "No". 3 - 3^3 = -6 is also not a "pandatic number". Hence the final answer is "No".
Case 3: 13 is not a pandatic number.
13 - 1^2 = 12 is not a pandatic number.
13 - 3^2 = 4 is a pandatic number.
.
.
.
Hence the final answer is "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.
A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:
* In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.
For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.
You are given a positive integer K. Find the K-th smallest lunlun number.
Constraints
* 1 \leq K \leq 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
K
Output
Print the answer.
Examples
Input
15
Output
23
Input
1
Output
1
Input
13
Output
21
Input
100000
Output
3234566667
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 a tree G with N vertices. The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.
Consider painting the edges in G with some number of colors. We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.
Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.
Constraints
* 2 \le N \le 10^5
* 1 \le a_i \lt b_i \le N
* All values in input are integers.
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}
Output
Print N lines.
The first line should contain K, the number of colors used.
The (i+1)-th line (1 \le i \le N-1) should contain c_i, the integer representing the color of the i-th edge, where 1 \le c_i \le K must hold.
If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.
Examples
Input
3
1 2
2 3
Output
2
1
2
Input
8
1 2
2 3
2 4
2 5
4 7
5 6
6 8
Output
4
1
2
3
4
1
1
2
Input
6
1 2
1 3
1 4
1 5
1 6
Output
5
1
2
3
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.
You are given a 4-character string S consisting of uppercase English letters. Determine if S consists of exactly two kinds of characters which both appear twice in S.
Constraints
* The length of S is 4.
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If S consists of exactly two kinds of characters which both appear twice in S, print `Yes`; otherwise, print `No`.
Examples
Input
ASSA
Output
Yes
Input
STOP
Output
No
Input
FFEE
Output
Yes
Input
FREE
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.
You are given a permutation of 1,2,...,N: p_1,p_2,...,p_N. Determine if the state where p_i=i for every i can be reached by performing the following operation any number of times:
* Choose three elements p_{i-1},p_{i},p_{i+1} (2\leq i\leq N-1) such that p_{i-1}>p_{i}>p_{i+1} and reverse the order of these three.
Constraints
* 3 \leq N \leq 3 Γ 10^5
* p_1,p_2,...,p_N is a permutation of 1,2,...,N.
Input
Input is given from Standard Input in the following format:
N
p_1
:
p_N
Output
If the state where p_i=i for every i can be reached by performing the operation, print `Yes`; otherwise, print `No`.
Examples
Input
5
5
2
1
4
3
Output
Yes
Input
4
3
2
4
1
Output
No
Input
7
3
2
1
6
5
4
7
Output
Yes
Input
6
5
3
4
1
2
6
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.
There are N holes in a two-dimensional plane. The coordinates of the i-th hole are (x_i,y_i).
Let R=10^{10^{10^{10}}}. Ringo performs the following operation:
* Randomly choose a point from the interior of a circle of radius R centered at the origin, and put Snuke there. Snuke will move to the hole with the smallest Euclidean distance from the point, and fall into that hole. If there are multiple such holes, the hole with the smallest index will be chosen.
For every i (1 \leq i \leq N), find the probability that Snuke falls into the i-th hole.
Here, the operation of randomly choosing a point from the interior of a circle of radius R is defined as follows:
* Pick two real numbers x and y independently according to uniform distribution on [-R,R].
* If x^2+y^2\leq R^2, the point (x,y) is chosen. Otherwise, repeat picking the real numbers x,y until the condition is met.
Constraints
* 2 \leq N \leq 100
* |x_i|,|y_i| \leq 10^6(1\leq i\leq N)
* All given points are pairwise distinct.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
:
x_N y_N
Output
Print N real numbers. The i-th real number must represent the probability that Snuke falls into the i-th hole.
The output will be judged correct when, for all output values, the absolute or relative error is at most 10^{-5}.
Examples
Input
2
0 0
1 1
Output
0.5
0.5
Input
5
0 0
2 8
4 5
2 6
3 10
Output
0.43160120892732328768
0.03480224363653196956
0.13880483535586193855
0.00000000000000000000
0.39479171208028279727
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 in charge of controlling a dam. The dam can store at most L liters of water. Initially, the dam is empty. Some amount of water flows into the dam every morning, and any amount of water may be discharged every night, but this amount needs to be set so that no water overflows the dam the next morning.
It is known that v_i liters of water at t_i degrees Celsius will flow into the dam on the morning of the i-th day. You are wondering about the maximum possible temperature of water in the dam at noon of each day, under the condition that there needs to be exactly L liters of water in the dam at that time. For each i, find the maximum possible temperature of water in the dam at noon of the i-th day. Here, consider each maximization separately, that is, the amount of water discharged for the maximization of the temperature on the i-th day, may be different from the amount of water discharged for the maximization of the temperature on the j-th day (jβ i).
Also, assume that the temperature of water is not affected by anything but new water that flows into the dam. That is, when V_1 liters of water at T_1 degrees Celsius and V_2 liters of water at T_2 degrees Celsius are mixed together, they will become V_1+V_2 liters of water at \frac{T_1*V_1+T_2*V_2}{V_1+V_2} degrees Celsius, and the volume and temperature of water are not affected by any other factors.
Constraints
* 1β€ N β€ 5*10^5
* 1β€ L β€ 10^9
* 0β€ t_i β€ 10^9(1β€iβ€N)
* 1β€ v_i β€ L(1β€iβ€N)
* v_1 = L
* L, each t_i and v_i are integers.
Input
Input is given from Standard Input in the following format:
N L
t_1 v_1
t_2 v_2
:
t_N v_N
Output
Print N lines. The i-th line should contain the maximum temperature such that it is possible to store L liters of water at that temperature in the dam at noon of the i-th day.
Each of these values is accepted if the absolute or relative error is at most 10^{-6}.
Examples
Input
3 10
10 10
20 5
4 3
Output
10.0000000
15.0000000
13.2000000
Input
4 15
0 15
2 5
3 6
4 4
Output
0.0000000
0.6666667
1.8666667
2.9333333
Input
4 15
1000000000 15
9 5
8 6
7 4
Output
1000000000.0000000
666666669.6666666
400000005.0000000
293333338.8666667
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 prime number n (11, 19, 23, etc.) that divides by 4 and has 3 has an interesting property. The results of calculating the remainder of the square of a natural number (1, 2, ..., n -1) of 1 or more and less than n divided by n are the same, so they are different from each other. The number is (n -1) / 2.
The set of numbers thus obtained has special properties. From the resulting set of numbers, choose two different a and b and calculate the difference. If the difference is negative, add n to the difference. If the result is greater than (n -1) / 2, subtract the difference from n.
For example, when n = 11, the difference between 1 and 9 is 1 β 9 = β8 β β8 + n = β8 + 11 = 3. The difference between 9 and 1 is also 9 β1 = 8 β n β 8 = 11 β 8 = 3, which is the same value 3. This difference can be easily understood by writing 0, 1, Β·Β·Β·, n -1 on the circumference and considering the shorter arc between the two numbers. (See the figure below)
<image>
The "difference" in the numbers thus obtained is either 1, 2, ..., (n -1) / 2, and appears the same number of times.
[Example] When n = 11, it will be as follows.
1. Calculate the remainder of the square of the numbers from 1 to n-1 divided by n.
12 = 1 β 1
22 = 4 β 4
32 = 9 β 9
42 = 16 β 5
52 = 25 β 3
62 = 36 β 3
72 = 49 β 5
82 = 64 β 9
92 = 81 β 4
102 = 100 β 1
2. Calculation of "difference" between a and b
1. Calculate the difference between different numbers for 1, 3, 4, 5, 9 obtained in 1.
2. If the calculation result is negative, add n = 11.
3. In addition, if the result of the calculation is greater than (n-1) / 2 = 5, subtract from n = 11.
3. Find the number of appearances
Count the number of occurrences of the calculation results 1, 2, 3, 4, and 5, respectively.
From these calculation results, we can see that 1, 2, 3, 4, and 5 appear four times. This property is peculiar to a prime number that is 3 when divided by 4, and this is not the case with a prime number that is 1 when divided by 4. To confirm this, a program that takes an odd number n of 10000 or less as an input, executes the calculation as shown in the example (finds the frequency of the difference of the square that is too much divided by n), and outputs the number of occurrences. Please create.
Input
Given multiple datasets. One integer n (n β€ 10000) is given on one row for each dataset. The input ends with a line containing one 0.
Output
For each data set, output the frequency of occurrence in the following format.
Number of occurrences (integer) of (a, b) where the difference between the squares of the remainder is 1
The number of occurrences (integer) of (a, b) where the difference between the squares of the remainder is 2
::
::
The number of occurrences (integer) of (a, b) where the difference between the squares of the remainder is (n-1) / 2
Example
Input
11
15
0
Output
4
4
4
4
4
2
2
4
2
4
4
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.
One of the games that uses the Hyakunin Isshu tag is "Buddhist turning". It is a simple game that uses only picture cards, so it is widely enjoyed. There are various derivative types of rules, but the shaved turn considered here is performed by N participants according to the following rules.
* Use a total of 100 cards, including 64 "men", 15 "boys", and 21 "princesses".
* Turn the bill over so that you can't see the picture and mix well to make a "bill pile".
* Draw one card from the first participant in order. After the Nth person, repeat from the first person.
* If the drawn card is a man, the person who draws will get the card.
* If the drawn card is a shaven, the person who draws puts all the cards he has, including that card, into the "field".
* If the drawn card is a princess, the person who draws gets all the cards in play, including that card.
* When there are no more cards in the bill pile, the game ends, and the person with the most cards wins.
Given the number of participants and the order of the cards piled up in the bill pile, the number of cards each participant has at the end of the game is arranged in ascending order, and the number of cards remaining in the field is shown. Create a program to output.
input
The input consists of multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
N
c1c2 ... c100
Each dataset has two rows, and the first row is given the integer N (2 β€ N β€ 10) representing the number of participants. The next line is given a character string that represents the arrangement of the bills piled up in the bill pile. The letter ci represents the i-th drawn tag, where M is a man, S is a shaven, and L is a princess. There is no space between each character.
The number of datasets does not exceed 100.
output
For each data set, the sequence of the number of cards at the end of the game is output on one line. As the number of cards, the number of cards that each participant has is arranged in ascending order, and then the number of cards remaining in the field is output. Separate each number of bills with one blank. Do not print blanks at the end of the line.
Example
Input
2
SSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
2
SSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMSL
5
MMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSMLMSMMMMMMMSMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM
0
Output
42 58 0
0 100 0
0 0 3 10 59 28
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 playing with J using the Midakuji. The Amida lottery consists of n vertical bars and m horizontal bars. The vertical bars are numbered from 1 to n in order from the left, and the vertical bar i The positive integer si is written at the bottom of.
<image>
Figure 3-1 Example of Amidakuji (n = 4, m = 5, s1 = 20, s2 = 80, s3 = 100, s4 = 50)
The integer written at the bottom of the vertical bar i, which is reached by following the path from the top of the vertical bar i, is the score when the vertical bar i is selected. For example, in Fig. 3-1 the vertical bar 1 is selected. And the score is 80 points, and if the vertical bar 2 is selected, the score is 100 points.
<image>
Figure 3-2 Example of how to follow the road
Mr. J decides to choose a series of k books from vertical bar 1 to vertical bar k. The total score when selecting those k vertical bars is J's score. However, you are in the Amidakuji You can select one horizontal bar and delete that horizontal bar from the Amidakuji. (You do not have to delete it.) If you delete one horizontal bar, the vertical bar in the deleted Amidakuji will be displayed vertically. J's score is the total of the points when selecting k consecutive vertical bars from bar 1 to vertical bar k.
Given the shape of the Amida lottery and the number of vertical bars k that J chooses as input, create a program that finds the minimum value of J's score.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, four integers n, m, h, k are written separated by blanks. N (2 β€ n β€ 1000) is the number of vertical bars, and m (1 β€ m β€ 100000) is the horizontal bar. H (2 β€ h β€ 1000) represents the length of the vertical bar, and k (1 β€ k β€ n) represents the number of vertical bars you choose.
The following n lines contain the score written at the bottom of the vertical bar. The first line (1 β€ i β€ n) contains the positive integer si. Also, s1 + s2 + ... + sn β€ 2000000000 = 2 Γ 109.
The following m lines indicate the position of the horizontal bar. The horizontal bars are numbered from 1 to m. The first line (1 β€ i β€ m) is the horizontal bar i. The two integers ai, bi (1 β€ ai β€ n --1, 1 β€ bi β€ h --1) representing the position are separated by blanks, and the horizontal bar i connects the vertical bar ai and the vertical bar ai + 1. , Indicates that the distance from the top edge of the horizontal bar i is bi. However, no two horizontal bars share an endpoint.
Of the scoring data, 20% of the points will have the lowest score for Mr. J if the horizontal bar is not deleted. Also, 30% of the points will satisfy n β€ 20, m β€ 30, h β€ 10. 60% of the points are m β€ 1000.
The end of the input is indicated by a line containing four zeros. The number of datasets does not exceed 10.
output
For each dataset, output the minimum score of Mr. J on one line.
Examples
Input
4 5 7 2
20
80
100
50
1 1
2 6
2 3
1 5
3 1
2 2 5 1
10
20
1 1
1 3
0 0 0 0
Output
100
10
Input
None
Output
None
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.
Honestly, a rabbit does not matter.
There is a rabbit playing a stage system action game. In this game, every stage has a difficulty level. The rabbit, which always needs challenges, basically wants to play more difficult stages than he has ever played. However, he sometimes needs rest too. So, to compromise, he admitted to play T or less levels easier stages than the preceding one.
How many ways are there to play all the stages at once, while honoring the convention above? Maybe the answer will be a large number. So, let me know the answer modulo 1,000,000,007.
Input
The first line of input contains two integers N and T (1 β€ N β€ 100,000, 1 β€ T β€ 10,000). N is the number of stages, and T is the compromise level.
The following N lines describe the difficulty levels of each stage. The i-th line contains one integer Di (1 β€ Di β€ 100,000), which is the difficulty level of the i-th stage.
Output
Calculate how many ways to play all the stages at once there are. Print the answer modulo 1,000,000,007 in a line.
Examples
Input
3 1
1
2
3
Output
4
Input
5 3
9
2
6
8
8
Output
24
Input
5 7
9
9
9
1
5
Output
48
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.
D - Medical Inspection
Problem Statement
The government has declared a state of emergency due to the MOFU syndrome epidemic in your country. Persons in the country suffer from MOFU syndrome and cannot get out of bed in the morning. You are a programmer working for the Department of Health. You have to take prompt measures.
The country consists of n islands numbered from 1 to n and there are ocean liners between some pair of islands. The Department of Health decided to establish the quarantine stations in some islands and restrict an infected person's moves to prevent the expansion of the epidemic. To carry out this plan, there must not be any liner such that there is no quarantine station in both the source and the destination of the liner. The problem is the department can build at most K quarantine stations due to the lack of budget.
Your task is to calculate whether this objective is possible or not. And if it is possible, you must calculate the minimum required number of quarantine stations.
Input
The test case starts with a line containing three integers N (2 \leq N \leq 3{,}000), M (1 \leq M \leq 30{,}000) and K (1 \leq K \leq 32). Each line in the next M lines contains two integers a_i (1 \leq a_i \leq N) and b_i (1 \leq b_i \leq N). This represents i-th ocean liner connects island a_i and b_i. You may assume a_i \neq b_i for all i, and there are at most one ocean liner between all the pairs of islands.
Output
If there is no way to build quarantine stations that satisfies the objective, print "Impossible" (without quotes). Otherwise, print the minimum required number of quarantine stations.
Sample Input 1
3 3 2
1 2
2 3
3 1
Output for the Sample Input 1
2
Sample Input 2
3 3 1
1 2
2 3
3 1
Output for the Sample Input 2
Impossible
Sample Input 3
7 6 5
1 3
2 4
3 5
4 6
5 7
6 2
Output for the Sample Input 3
4
Sample Input 4
10 10 10
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Output for the Sample Input 4
4
Example
Input
3 3 2
1 2
2 3
3 1
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.
A pitch-black room
When I woke up, Mr. A was in a pitch-black room. Apparently, Mr. A got lost in a dungeon consisting of N rooms. You couldn't know which room A got lost in, but fortunately he got a map of the dungeon. Let's show A the way to go and lead to a bright room.
It is known that M of the N rooms are pitch black, and the D_1, D_2, ..., and D_Mth rooms are pitch black, respectively. Also, there are exactly K one-way streets from all the rooms in order, and the roads from the i-th room are v_ {i, 1}, v_ {i, 2}, ..., v_ {i, respectively. , K} Connected to the third room. You can follow the a_1, a_2, ..., a_lth roads in order from the room you are in for Mr. A. However, when Mr. A reaches the bright room, he ignores the subsequent instructions. You cannot know the information of the room where Mr. A is currently before and after the instruction, so you must give the instruction sequence so that you can reach the bright room no matter which room you are in. Answer the length of the shortest of such instructions.
Constraints
* 2 β€ N β€ 100
* 1 β€ M β€ min (16, N β 1)
* 1 β€ K β€ N
* 1 β€ D_i β€ N
* D_i are all different
* 1 β€ v_ {i, j} β€ N
* All dark rooms can reach at least one bright room
Input Format
Input is given from standard input in the following format.
NMK
D_1 D_2 ... D_M
v_ {1,1} v_ {1,2} ... v_ {1,K}
v_ {2,1} v_ {2,2} ... v_ {2, K}
...
v_ {N, 1} v_ {N, 2} ... v_ {N, K}
Output Format
Print the answer in one line.
Sample Input 1
4 2 2
1 2
twenty four
3 1
4 2
13
Sample Output 1
2
<image>
If you give the instruction 1, 1
* If A's initial position is room 1, the second move will reach room 3.
* If A's initial position is room 2, the first move will reach room 3.
Sample Input 2
3 2 2
1 2
twenty three
1 2
twenty one
Sample Output 2
3
<image>
If you give instructions 2, 1, 2
* If A's initial position is room 1, the first move will reach room 3.
* If A's initial position is room 2, the third move will reach room 3.
Sample Input 3
6 3 3
one two Three
4 1 1
2 5 2
3 3 6
4 4 4
5 5 5
6 6 6
Sample Output 3
3
<image>
Beware of unconnected cases and cases with self-edges and multiple edges.
Example
Input
4 2 2
1 2
2 4
3 1
4 2
1 3
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.
The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$.
Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$.
Constraints
* $1 \leq n \leq 100$
* $1 \leq r, c \leq 100$
Input
In the first line, an integer $n$ is given. In the following $n$ lines, the dimension of matrix $M_i$ ($i = 1...n$) is given by two integers $r$ and $c$ which respectively represents the number of rows and columns of $M_i$.
Output
Print the minimum number of scalar multiplication in a line.
Example
Input
6
30 35
35 15
15 5
5 10
10 20
20 25
Output
15125
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 given two sides of a triangle a and b and the angle C between them, calculate the following properties:
* S: Area of the triangle
* L: The length of the circumference of the triangle
* h: The height of the triangle with side a as a bottom edge
Input
The length of a, the length of b and the angle C are given in integers.
Output
Print S, L and h in a line respectively. The output should not contain an absolute error greater than 10-4.
Example
Input
4 3 90
Output
6.00000000
12.00000000
3.00000000
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 [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) algorithm is defined as follows.
1. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new [queue](http://gg.gg/queue_en) containing only vertex 1, mark the vertex 1 as used.
2. Extract a vertex v from the head of the queue q.
3. Print the index of vertex v.
4. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q.
5. If the queue is not empty, continue from step 2.
6. Otherwise finish.
Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.
In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The [tree](http://gg.gg/tree_en) is an undirected graph, such that there is exactly one simple path between any two vertices.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) which denotes the number of nodes in the tree.
The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 β€ x, y β€ n) β the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree.
The last line contains n distinct integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n) β the sequence to check.
Output
Print "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
4
1 2
1 3
2 4
1 2 3 4
Output
Yes
Input
4
1 2
1 3
2 4
1 2 4 3
Output
No
Note
Both sample tests have the same tree in them.
In this tree, there are two valid BFS orderings:
* 1, 2, 3, 4,
* 1, 3, 2, 4.
The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
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 Morse code, an letter of English alphabet is represented as a string of some length from 1 to 4. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".
Because there are 2^1+2^2+2^3+2^4 = 30 strings with length 1 to 4 containing only "0" and/or "1", not all of them correspond to one of the 26 English letters. In particular, each string of "0" and/or "1" of length at most 4 translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".
You will work with a string S, which is initially empty. For m times, either a dot or a dash will be appended to S, one at a time. Your task is to find and report, after each of these modifications to string S, the number of non-empty sequences of English letters that are represented with some substring of S in Morse code.
Since the answers can be incredibly tremendous, print them modulo 10^9 + 7.
Input
The first line contains an integer m (1 β€ m β€ 3 000) β the number of modifications to S.
Each of the next m lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to S.
Output
Print m lines, the i-th of which being the answer after the i-th modification to S.
Examples
Input
3
1
1
1
Output
1
3
7
Input
5
1
0
1
0
1
Output
1
4
10
22
43
Input
9
1
1
0
0
0
1
1
0
1
Output
1
3
10
24
51
109
213
421
833
Note
Let us consider the first sample after all characters have been appended to S, so S is "111".
As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of S in Morse code, therefore, are as follows.
1. "T" (translates into "1")
2. "M" (translates into "11")
3. "O" (translates into "111")
4. "TT" (translates into "11")
5. "TM" (translates into "111")
6. "MT" (translates into "111")
7. "TTT" (translates into "111")
Although unnecessary for this task, a conversion table from English alphabets into Morse code can be found [here](https://en.wikipedia.org/wiki/Morse_code).
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.
Codefortia is a small island country located somewhere in the West Pacific. It consists of n settlements connected by m bidirectional gravel roads. Curiously enough, the beliefs of the inhabitants require the time needed to pass each road to be equal either to a or b seconds. It's guaranteed that one can go between any pair of settlements by following a sequence of roads.
Codefortia was recently struck by the financial crisis. Therefore, the king decided to abandon some of the roads so that:
* it will be possible to travel between each pair of cities using the remaining roads only,
* the sum of times required to pass each remaining road will be minimum possible (in other words, remaining roads must form minimum spanning tree, using the time to pass the road as its weight),
* among all the plans minimizing the sum of times above, the time required to travel between the king's residence (in settlement 1) and the parliament house (in settlement p) using the remaining roads only will be minimum possible.
The king, however, forgot where the parliament house was. For each settlement p = 1, 2, ..., n, can you tell what is the minimum time required to travel between the king's residence and the parliament house (located in settlement p) after some roads are abandoned?
Input
The first line of the input contains four integers n, m, a and b (2 β€ n β€ 70, n - 1 β€ m β€ 200, 1 β€ a < b β€ 10^7) β the number of settlements and gravel roads in Codefortia, and two possible travel times. Each of the following lines contains three integers u, v, c (1 β€ u, v β€ n, u β v, c β \\{a, b\}) denoting a single gravel road between the settlements u and v, which requires c minutes to travel.
You can assume that the road network is connected and has no loops or multiedges.
Output
Output a single line containing n integers. The p-th of them should denote the minimum possible time required to travel from 1 to p after the selected roads are abandoned. Note that for each p you can abandon a different set of roads.
Examples
Input
5 5 20 25
1 2 25
2 3 25
3 4 20
4 5 20
5 1 20
Output
0 25 60 40 20
Input
6 7 13 22
1 2 13
2 3 13
1 4 22
3 4 13
4 5 13
5 6 13
6 1 13
Output
0 13 26 39 26 13
Note
The minimum possible sum of times required to pass each road in the first example is 85 β exactly one of the roads with passing time 25 must be abandoned. Note that after one of these roads is abandoned, it's now impossible to travel between settlements 1 and 3 in time 50.
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 sequence of digits of length 2^k [a_1, a_2, β¦, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0β€ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}β₯ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.
Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth β¦, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).
Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, β¦, a_{2^k}]) denote the number of candies we get in this process.
For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:
After the first operation the sequence becomes [(8 + 7)mod 10, (3 + 1)mod 10, (7 + 0)mod 10, (9 + 4)mod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 β₯ 10 and 9 + 4 β₯ 10.
After the second operation the sequence becomes [(5 + 4)mod 10, (7 + 3)mod 10] = [9, 0], and we get one more candy as 7 + 3 β₯ 10.
After the final operation sequence becomes [(9 + 0) mod 10] = [9].
Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.
You are given a sequence of digits of length n s_1, s_2, β¦ s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, β¦, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the length of the sequence.
The second line contains n digits s_1, s_2, β¦, s_n (0 β€ s_i β€ 9).
The third line contains a single integer q (1 β€ q β€ 10^5) β the number of queries.
Each of the next q lines contains two integers l_i, r_i (1 β€ l_i β€ r_i β€ n) β i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.
Output
Output q lines, in i-th line output single integer β f([s_{l_i}, s_{l_i + 1}, β¦, s_{r_i}]), answer to the i-th query.
Examples
Input
8
8 7 3 1 7 0 9 4
3
1 8
2 5
7 7
Output
3
1
0
Input
6
0 1 2 3 3 5
3
1 2
1 4
3 6
Output
0
0
1
Note
The first example illustrates an example from the statement.
f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] β [(7 + 3)mod 10, (1 + 7)mod 10] = [0, 8] and one candy as 7 + 3 β₯ 10 β [(0 + 8) mod 10] = [8], so we get only 1 candy.
f([9]) = 0 as we don't perform operations with 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.
Let us define a magic grid to be a square matrix of integers of size n Γ n, satisfying the following conditions.
* All integers from 0 to (n^2 - 1) inclusive appear in the matrix exactly once.
* [Bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of all elements in a row or a column must be the same for each row and column.
You are given an integer n which is a multiple of 4. Construct a magic grid of size n Γ n.
Input
The only line of input contains an integer n (4 β€ n β€ 1000). It is guaranteed that n is a multiple of 4.
Output
Print a magic grid, i.e. n lines, the i-th of which contains n space-separated integers, representing the i-th row of the grid.
If there are multiple answers, print any. We can show that an answer always exists.
Examples
Input
4
Output
8 9 1 13
3 12 7 5
0 2 4 11
6 10 15 14
Input
8
Output
19 55 11 39 32 36 4 52
51 7 35 31 12 48 28 20
43 23 59 15 0 8 16 44
3 47 27 63 24 40 60 56
34 38 6 54 17 53 9 37
14 50 30 22 49 5 33 29
2 10 18 46 41 21 57 13
26 42 62 58 1 45 25 61
Note
In the first example, XOR of each row and each column is 13.
In the second example, XOR of each row and each column 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.
Let's call two strings s and t anagrams of each other if it is possible to rearrange symbols in the string s to get a string, equal to t.
Let's consider two strings s and t which are anagrams of each other. We say that t is a reducible anagram of s if there exists an integer k β₯ 2 and 2k non-empty strings s_1, t_1, s_2, t_2, ..., s_k, t_k that satisfy the following conditions:
1. If we write the strings s_1, s_2, ..., s_k in order, the resulting string will be equal to s;
2. If we write the strings t_1, t_2, ..., t_k in order, the resulting string will be equal to t;
3. For all integers i between 1 and k inclusive, s_i and t_i are anagrams of each other.
If such strings don't exist, then t is said to be an irreducible anagram of s. Note that these notions are only defined when s and t are anagrams of each other.
For example, consider the string s = "gamegame". Then the string t = "megamage" is a reducible anagram of s, we may choose for example s_1 = "game", s_2 = "gam", s_3 = "e" and t_1 = "mega", t_2 = "mag", t_3 = "e":
<image>
On the other hand, we can prove that t = "memegaga" is an irreducible anagram of s.
You will be given a string s and q queries, represented by two integers 1 β€ l β€ r β€ |s| (where |s| is equal to the length of the string s). For each query, you should find if the substring of s formed by characters from the l-th to the r-th has at least one irreducible anagram.
Input
The first line contains a string s, consisting of lowercase English characters (1 β€ |s| β€ 2 β
10^5).
The second line contains a single integer q (1 β€ q β€ 10^5) β the number of queries.
Each of the following q lines contain two integers l and r (1 β€ l β€ r β€ |s|), representing a query for the substring of s formed by characters from the l-th to the r-th.
Output
For each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.
Examples
Input
aaaaa
3
1 1
2 4
5 5
Output
Yes
No
Yes
Input
aabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
Output
No
Yes
Yes
Yes
No
No
Note
In the first sample, in the first and third queries, the substring is "a", which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand, in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s_1 = "a", s_2 = "aa", t_1 = "a", t_2 = "aa" to show that it is a reducible anagram.
In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
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 two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 1000) β the number of test cases.
The only line of each test case contains two integers n and d (2 β€ n, d β€ 5000) β the number of vertices in the tree and the required sum of depths of all vertices.
It is guaranteed that the sum of n and the sum of d both does not exceed 5000 (β n β€ 5000, β d β€ 5000).
Output
For each test case, print the answer.
If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n-1 integers p_2, p_3, ..., p_n in the second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print should describe some binary tree.
Example
Input
3
5 7
10 19
10 18
Output
YES
1 2 1 3
YES
1 2 3 3 9 9 2 1 6
NO
Note
Pictures corresponding to the first and the second test cases of the example:
<image>
<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 playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has a_i health.
You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by 1 (deals 1 damage to it). Furthermore, when the health of some monster i becomes 0 or less than 0, it dies and explodes, dealing b_i damage to the next monster (monster i + 1, if i < n, or monster 1, if i = n). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.
You have to calculate the minimum number of bullets you have to fire to kill all n monsters in the circle.
Input
The first line contains one integer T (1 β€ T β€ 150000) β the number of test cases.
Then the test cases follow, each test case begins with a line containing one integer n (2 β€ n β€ 300000) β the number of monsters. Then n lines follow, each containing two integers a_i and b_i (1 β€ a_i, b_i β€ 10^{12}) β the parameters of the i-th monster in the circle.
It is guaranteed that the total number of monsters in all test cases does not exceed 300000.
Output
For each test case, print one integer β the minimum number of bullets you have to fire to kill all of the monsters.
Example
Input
1
3
7 15
2 14
5 3
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.
You are given an undirected graph without self-loops or multiple edges which consists of n vertices and m edges. Also you are given three integers n_1, n_2 and n_3.
Can you label each vertex with one of three numbers 1, 2 or 3 in such way, that:
1. Each vertex should be labeled by exactly one number 1, 2 or 3;
2. The total number of vertices with label 1 should be equal to n_1;
3. The total number of vertices with label 2 should be equal to n_2;
4. The total number of vertices with label 3 should be equal to n_3;
5. |col_u - col_v| = 1 for each edge (u, v), where col_x is the label of vertex x.
If there are multiple valid labelings, print any of them.
Input
The first line contains two integers n and m (1 β€ n β€ 5000; 0 β€ m β€ 10^5) β the number of vertices and edges in the graph.
The second line contains three integers n_1, n_2 and n_3 (0 β€ n_1, n_2, n_3 β€ n) β the number of labels 1, 2 and 3, respectively. It's guaranteed that n_1 + n_2 + n_3 = n.
Next m lines contan description of edges: the i-th line contains two integers u_i, v_i (1 β€ u_i, v_i β€ n; u_i β v_i) β the vertices the i-th edge connects. It's guaranteed that the graph doesn't contain self-loops or multiple edges.
Output
If valid labeling exists then print "YES" (without quotes) in the first line. In the second line print string of length n consisting of 1, 2 and 3. The i-th letter should be equal to the label of the i-th vertex.
If there is no valid labeling, print "NO" (without quotes).
Examples
Input
6 3
2 2 2
3 1
5 4
2 5
Output
YES
112323
Input
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
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.
You are given an array a consisting of n positive integers.
Initially, you have an integer x = 0. During one move, you can do one of the following two operations:
1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1).
2. Just increase x by 1 (x := x + 1).
The first operation can be applied no more than once to each i from 1 to n.
Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by k (the value k is given).
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and k (1 β€ n β€ 2 β
10^5; 1 β€ k β€ 10^9) β the length of a and the required divisior. The second line of the test case contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of moves required to obtain such an array that each its element is divisible by k.
Example
Input
5
4 3
1 2 1 3
10 6
8 7 1 8 3 7 5 10 8 9
5 10
20 100 50 20 100500
10 25
24 24 24 24 24 24 24 24 24 24
8 8
1 2 3 4 5 6 7 8
Output
6
18
0
227
8
Note
Consider the first test case of the example:
1. x=0, a = [1, 2, 1, 3]. Just increase x;
2. x=1, a = [1, 2, 1, 3]. Add x to the second element and increase x;
3. x=2, a = [1, 3, 1, 3]. Add x to the third element and increase x;
4. x=3, a = [1, 3, 3, 3]. Add x to the fourth element and increase x;
5. x=4, a = [1, 3, 3, 6]. Just increase x;
6. x=5, a = [1, 3, 3, 6]. Add x to the first element and increase x;
7. x=6, a = [6, 3, 3, 6]. We obtained the required array.
Note that you can't add x to the same element more than 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.
Ziota found a video game called "Monster Invaders".
Similar to every other shooting RPG game, "Monster Invaders" involves killing monsters and bosses with guns.
For the sake of simplicity, we only consider two different types of monsters and three different types of guns.
Namely, the two types of monsters are:
* a normal monster with 1 hp.
* a boss with 2 hp.
And the three types of guns are:
* Pistol, deals 1 hp in damage to one monster, r_1 reloading time
* Laser gun, deals 1 hp in damage to all the monsters in the current level (including the boss), r_2 reloading time
* AWP, instantly kills any monster, r_3 reloading time
The guns are initially not loaded, and the Ziota can only reload 1 gun at a time.
The levels of the game can be considered as an array a_1, a_2, β¦, a_n, in which the i-th stage has a_i normal monsters and 1 boss. Due to the nature of the game, Ziota cannot use the Pistol (the first type of gun) or AWP (the third type of gun) to shoot the boss before killing all of the a_i normal monsters.
If Ziota damages the boss but does not kill it immediately, he is forced to move out of the current level to an arbitrary adjacent level (adjacent levels of level i (1 < i < n) are levels i - 1 and i + 1, the only adjacent level of level 1 is level 2, the only adjacent level of level n is level n - 1). Ziota can also choose to move to an adjacent level at any time. Each move between adjacent levels are managed by portals with d teleportation time.
In order not to disrupt the space-time continuum within the game, it is strictly forbidden to reload or shoot monsters during teleportation.
Ziota starts the game at level 1. The objective of the game is rather simple, to kill all the bosses in all the levels. He is curious about the minimum time to finish the game (assuming it takes no time to shoot the monsters with a loaded gun and Ziota has infinite ammo on all the three guns). Please help him find this value.
Input
The first line of the input contains five integers separated by single spaces: n (2 β€ n β€ 10^6) β the number of stages, r_1, r_2, r_3 (1 β€ r_1 β€ r_2 β€ r_3 β€ 10^9) β the reload time of the three guns respectively, d (1 β€ d β€ 10^9) β the time of moving between adjacent levels.
The second line of the input contains n integers separated by single spaces a_1, a_2, ..., a_n (1 β€ a_i β€ 10^6, 1 β€ i β€ n).
Output
Print one integer, the minimum time to finish the game.
Examples
Input
4 1 3 4 3
3 2 5 1
Output
34
Input
4 2 4 4 1
4 5 1 2
Output
31
Note
In the first test case, the optimal strategy is:
* Use the pistol to kill three normal monsters and AWP to kill the boss (Total time 1β
3+4=7)
* Move to stage two (Total time 7+3=10)
* Use the pistol twice and AWP to kill the boss (Total time 10+1β
2+4=16)
* Move to stage three (Total time 16+3=19)
* Use the laser gun and forced to move to either stage four or two, here we move to stage four (Total time 19+3+3=25)
* Use the pistol once, use AWP to kill the boss (Total time 25+1β
1+4=30)
* Move back to stage three (Total time 30+3=33)
* Kill the boss at stage three with the pistol (Total time 33+1=34)
Note that here, we do not finish at level n, but when all the bosses are killed.
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 order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers a and b and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of (a β x) + (b β x) for any given x, where β denotes the [bitwise XOR operation](http://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 10^{4}). Description of the test cases follows.
The only line of each test case contains two integers a and b (1 β€ a, b β€ 10^{9}).
Output
For each testcase, output the smallest possible value of the given expression.
Example
Input
6
6 12
4 9
59 832
28 14
4925 2912
1 1
Output
10
13
891
18
6237
0
Note
For the first test case Sana can choose x=4 and the value will be (6 β 4) + (12 β 4) = 2 + 8 = 10. It can be shown that this is the smallest possible value.
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.
Only a few know that Pan and Apollo weren't only battling for the title of the GOAT musician. A few millenniums later, they also challenged each other in math (or rather in fast calculations). The task they got to solve is the following:
Let x_1, x_2, β¦, x_n be the sequence of n non-negative integers. Find this value: $$$β_{i=1}^n β_{j=1}^n β_{k=1}^n (x_i \& x_j) β
(x_j | x_k)$$$
Here \& denotes the [bitwise and,](https://en.wikipedia.org/wiki/Bitwise_operation#AND) and | denotes the [bitwise or.](https://en.wikipedia.org/wiki/Bitwise_operation#OR)
Pan and Apollo could solve this in a few seconds. Can you do it too? For convenience, find the answer modulo 10^9 + 7.
Input
The first line of the input contains a single integer t (1 β€ t β€ 1 000) denoting the number of test cases, then t test cases follow.
The first line of each test case consists of a single integer n (1 β€ n β€ 5 β
10^5), the length of the sequence. The second one contains n non-negative integers x_1, x_2, β¦, x_n (0 β€ x_i < 2^{60}), elements of the sequence.
The sum of n over all test cases will not exceed 5 β
10^5.
Output
Print t lines. The i-th line should contain the answer to the i-th text case.
Example
Input
8
2
1 7
3
1 2 4
4
5 5 5 5
5
6 2 2 1 0
1
0
1
1
6
1 12 123 1234 12345 123456
5
536870912 536870911 1152921504606846975 1152921504606846974 1152921504606846973
Output
128
91
1600
505
0
1
502811676
264880351
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 was gifted an array a of length n. Polycarp considers an array beautiful if there exists a number C, such that each number in the array occurs either zero or C times. Polycarp wants to remove some elements from the array a to make it beautiful.
For example, if n=6 and a = [1, 3, 2, 1, 4, 2], then the following options are possible to make the array a array beautiful:
* Polycarp removes elements at positions 2 and 5, array a becomes equal to [1, 2, 1, 2];
* Polycarp removes elements at positions 1 and 6, array a becomes equal to [3, 2, 1, 4];
* Polycarp removes elements at positions 1, 2 and 6, array a becomes equal to [2, 1, 4];
Help Polycarp determine the minimum number of elements to remove from the array a to make it beautiful.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of one integer n (1 β€ n β€ 2 β
10^5) β the length of the array a.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β array a.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output one integer β the minimum number of elements that Polycarp has to remove from the array a to make it beautiful.
Example
Input
3
6
1 3 2 1 4 2
4
100 100 4 100
8
1 2 3 3 3 2 6 6
Output
2
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.
A sequence of n non-negative integers (n β₯ 2) a_1, a_2, ..., a_n is called good if for all i from 1 to n-1 the following condition holds true: $$$a_1 \: \& \: a_2 \: \& \: ... \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: ... \: \& \: a_n, where \&$$$ denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
You are given an array a of size n (n β₯ 2). Find the number of permutations p of numbers ranging from 1 to n, for which the sequence a_{p_1}, a_{p_2}, ... ,a_{p_n} is good. Since this number can be large, output it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 10^4), denoting the number of test cases.
The first line of each test case contains a single integer n (2 β€ n β€ 2 β
10^5) β the size of the array.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^9) β the elements of the array.
It is guaranteed that the sum of n over all test cases doesn't exceed 2 β
10^5.
Output
Output t lines, where the i-th line contains the number of good permutations in the i-th test case modulo 10^9 + 7.
Example
Input
4
3
1 1 1
5
1 2 3 4 5
5
0 2 0 3 0
4
1 3 5 1
Output
6
0
36
4
Note
In the first test case, since all the numbers are equal, whatever permutation we take, the sequence is good. There are a total of 6 permutations possible with numbers from 1 to 3: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].
In the second test case, it can be proved that no permutation exists for which the sequence is good.
In the third test case, there are a total of 36 permutations for which the sequence is good. One of them is the permutation [1,5,4,2,3] which results in the sequence s=[0,0,3,2,0]. This is a good sequence because
* s_1 = s_2 \: \& \: s_3 \: \& \: s_4 \: \& \: s_5 = 0,
* s_1 \: \& \: s_2 = s_3 \: \& \: s_4 \: \& \: s_5 = 0,
* s_1 \: \& \: s_2 \: \& \: s_3 = s_4 \: \& \: s_5 = 0,
* s_1 \: \& \: s_2 \: \& \: s_3 \: \& \: s_4 = s_5 = 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 new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as single character '/'.
A path called normalized if it contains the smallest possible number of characters '/'.
Your task is to transform a given path to the normalized form.
Input
The first line of the input contains only lowercase Latin letters and character '/' β the path to some directory. All paths start with at least one character '/'. The length of the given line is no more than 100 characters, it is not empty.
Output
The path in normalized form.
Examples
Input
//usr///local//nginx/sbin
Output
/usr/local/nginx/sbin
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 cows have just learned what a primitive root is! Given a prime p, a primitive root <image> is an integer x (1 β€ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is.
Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots <image>.
Input
The input contains a single line containing an integer p (2 β€ p < 2000). It is guaranteed that p is a prime.
Output
Output on a single line the number of primitive roots <image>.
Examples
Input
3
Output
1
Input
5
Output
2
Note
The only primitive root <image> is 2.
The primitive roots <image> are 2 and 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.
Petya wrote a programme on C++ that calculated a very interesting function f(n). Petya ran the program with a certain value of n and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had the result. However while Petya was drinking tea, a sly virus managed to destroy the input file so that Petya can't figure out for which value of n the program was run. Help Petya, carry out the inverse function!
Mostly, the program consists of a function in C++ with the following simplified syntax:
* function ::= int f(int n) {operatorSequence}
* operatorSequence ::= operator | operator operatorSequence
* operator ::= return arithmExpr; | if (logicalExpr) return arithmExpr;
* logicalExpr ::= arithmExpr > arithmExpr | arithmExpr < arithmExpr | arithmExpr == arithmExpr
* arithmExpr ::= sum
* sum ::= product | sum + product | sum - product
* product ::= multiplier | product * multiplier | product / multiplier
* multiplier ::= n | number | f(arithmExpr)
* number ::= 0|1|2|... |32767
The whitespaces in a operatorSequence are optional.
Thus, we have a function, in which body there are two kinds of operators. There is the operator "return arithmExpr;" that returns the value of the expression as the value of the function, and there is the conditional operator "if (logicalExpr) return arithmExpr;" that returns the value of the arithmetical expression when and only when the logical expression is true. Guaranteed that no other constructions of C++ language β cycles, assignment operators, nested conditional operators etc, and other variables except the n parameter are used in the function. All the constants are integers in the interval [0..32767].
The operators are performed sequentially. After the function has returned a value other operators in the sequence are not performed. Arithmetical expressions are performed taking into consideration the standard priority of the operations. It means that first all the products that are part of the sum are calculated. During the calculation of the products the operations of multiplying and division are performed from the left to the right. Then the summands are summed, and the addition and the subtraction are also performed from the left to the right. Operations ">" (more), "<" (less) and "==" (equals) also have standard meanings.
Now you've got to pay close attention! The program is compiled with the help of 15-bit Berland C++ compiler invented by a Berland company BerSoft, that's why arithmetical operations are performed in a non-standard way. Addition, subtraction and multiplication are performed modulo 32768 (if the result of subtraction is negative, then 32768 is added to it until the number belongs to the interval [0..32767]). Division "/" is a usual integer division where the remainder is omitted.
Examples of arithmetical operations:
<image>
Guaranteed that for all values of n from 0 to 32767 the given function is performed correctly. That means that:
1. Division by 0 never occures.
2. When performing a function for the value n = N recursive calls of the function f may occur only for the parameter value of 0, 1, ..., N - 1. Consequently, the program never has an infinite recursion.
3. As the result of the sequence of the operators, the function always returns a value.
We have to mention that due to all the limitations the value returned by the function f is independent from either global variables or the order of performing the calculations of arithmetical expressions as part of the logical one, or from anything else except the value of n parameter. That's why the f function can be regarded as a function in its mathematical sense, i.e. as a unique correspondence between any value of n from the interval [0..32767] and a value of f(n) from the same interval.
Given the value of f(n), and you should find n. If the suitable n value is not unique, you should find the maximal one (from the interval [0..32767]).
Input
The first line has an integer f(n) from the interval [0..32767]. The next lines have the description of the function f. In the description can be found extra spaces and line breaks (see the examples) which, of course, canβt break key words int, if, return and numbers. The size of input data canβt exceed 100 bytes.
Output
Output a single number β the answer to the problem. If thereβs no answer, output "-1" (without quotes).
Examples
Input
17
int f(int n)
{
if (n < 100) return 17;
if (n > 99) return 27;
}
Output
99
Input
13
int f(int n)
{
if (n == 0) return 0;
return f(n - 1) + 1;
}
Output
13
Input
144
int f(int n)
{
if (n == 0) return 0;
if (n == 1) return n;
return f(n - 1) + f(n - 2);
}
Output
24588
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.
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy β she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of leaves Alyona has found. The next n lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.
Output
Output the single number β the number of Alyona's leaves.
Examples
Input
5
birch yellow
maple red
birch yellow
maple yellow
maple green
Output
4
Input
3
oak yellow
oak yellow
oak yellow
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.
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
* the queen's weight is 9,
* the rook's weight is 5,
* the bishop's weight is 3,
* the knight's weight is 3,
* the pawn's weight is 1,
* the king's weight isn't considered in evaluating position.
The player's weight equals to the sum of weights of all his pieces on the board.
As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
Input
The input contains eight lines, eight characters each β the board's description.
The white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters.
The white pieces are denoted as follows: the queen is represented is 'Q', the rook β as 'R', the bishop β as'B', the knight β as 'N', the pawn β as 'P', the king β as 'K'.
The black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively.
An empty square of the board is marked as '.' (a dot).
It is not guaranteed that the given chess position can be achieved in a real game. Specifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.
Output
Print "White" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, print "Black" if the weight of the black pieces is more than the weight of the white pieces and print "Draw" if the weights of the white and black pieces are equal.
Examples
Input
...QK...
........
........
........
........
........
........
...rk...
Output
White
Input
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR
Output
Draw
Input
rppppppr
...k....
........
........
........
........
K...Q...
........
Output
Black
Note
In the first test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals 5.
In the second test sample the weights of the positions of the black and the white pieces are equal to 39.
In the third test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals to 16.
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 Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:
We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti.
As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.
It's time for Susie to go to bed, help her find such string p or state that it is impossible.
Input
The first line contains string s of length n.
The second line contains string t of length n.
The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.
Output
Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes).
If there are multiple possible answers, print any of them.
Examples
Input
0001
1011
Output
0011
Input
000
111
Output
impossible
Note
In the first sample different answers are possible, namely β 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.
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 teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = kiΒ·x + bi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1 < x2. In other words, is it true that there are 1 β€ i < j β€ n and x', y', such that:
* y' = ki * x' + bi, that is, point (x', y') belongs to the line number i;
* y' = kj * x' + bj, that is, point (x', y') belongs to the line number j;
* x1 < x' < x2, that is, point (x', y') lies inside the strip bounded by x1 < x2.
You can't leave Anton in trouble, can you? Write a program that solves the given task.
Input
The first line of the input contains an integer n (2 β€ n β€ 100 000) β the number of lines in the task given to Anton. The second line contains integers x1 and x2 ( - 1 000 000 β€ x1 < x2 β€ 1 000 000) defining the strip inside which you need to find a point of intersection of at least two lines.
The following n lines contain integers ki, bi ( - 1 000 000 β€ ki, bi β€ 1 000 000) β the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two i β j it is true that either ki β kj, or bi β bj.
Output
Print "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes).
Examples
Input
4
1 2
1 2
1 0
0 1
0 2
Output
NO
Input
2
1 3
1 0
-1 3
Output
YES
Input
2
1 3
1 0
0 2
Output
YES
Input
2
1 3
1 0
0 3
Output
NO
Note
In the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it.
<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.
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward).
<image>
Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.
Input
The first line of the input contains a single number n (1 β€ n β€ 26) β the number of colors of beads. The second line contains after n positive integers ai β the quantity of beads of i-th color. It is guaranteed that the sum of ai is at least 2 and does not exceed 100 000.
Output
In the first line print a single number β the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace.
Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.
Examples
Input
3
4 2 1
Output
1
abacaba
Input
1
4
Output
4
aaaa
Input
2
1 1
Output
0
ab
Note
In the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.
In the second sample there is only one way to compose a necklace.
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 positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?
Input
The first line of the input contains two integers s and x (2 β€ s β€ 1012, 0 β€ x β€ 1012), the sum and bitwise xor of the pair of positive integers, respectively.
Output
Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.
Examples
Input
9 5
Output
4
Input
3 3
Output
2
Input
5 2
Output
0
Note
In the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2).
In the second sample, the only solutions are (1, 2) and (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.
Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.
Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.
Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.
Input
The first line contains two integers n and k (1 β€ n, k β€ 500) β the number of coins and the price of the chocolate, respectively.
Next line will contain n integers c1, c2, ..., cn (1 β€ ci β€ 500) β the values of Pari's coins.
It's guaranteed that one can make value k using these coins.
Output
First line of the output must contain a single integer qβ the number of suitable values x. Then print q integers in ascending order β the values that Arya can make for some subset of coins of Pari that pays for the chocolate.
Examples
Input
6 18
5 6 1 10 12 2
Output
16
0 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18
Input
3 50
25 25 50
Output
3
0 25 50
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.
Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!
Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).
The little walrus's text looks in the following manner:
TEXT ::= SENTENCE | SENTENCE SPACE TEXT
SENTENCE ::= WORD SPACE SENTENCE | WORD END
END ::= {'.', '?', '!'}
WORD ::= LETTER | LETTER WORD
LETTER ::= {'a'..'z', 'A'..'Z'}
SPACE ::= ' '
SPACE stands for the symbol of a space.
So, how many messages did Fangy send?
Input
The first line contains an integer n, which is the size of one message (2 β€ n β€ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.
Output
On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.
Examples
Input
25
Hello. I am a little walrus.
Output
2
Input
2
How are you?
Output
Impossible
Input
19
Hello! Do you like fish? Why?
Output
3
Note
Let's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".
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 famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.
As before, the chessboard is a square-checkered board with the squares arranged in a 8 Γ 8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.
Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.
It goes without saying that in such business one should economize on everything β for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
Input
The input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character β for a square painted black.
It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).
Output
Output the only number β the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.
Examples
Input
WWWBWWBW
BBBBBBBB
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
Output
3
Input
WWWWWWWW
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
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.
Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens.
All characters in this game are lowercase English letters. There are two players: Mister B and his competitor.
Initially the players have a string s consisting of the first a English letters in alphabetical order (for example, if a = 5, then s equals to "abcde").
The players take turns appending letters to string s. Mister B moves first.
Mister B must append exactly b letters on each his move. He can arbitrary choose these letters. His opponent adds exactly a letters on each move.
Mister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string s of length a and generates a string t of length a such that all letters in the string t are distinct and don't appear in the considered suffix. From multiple variants of t lexicographically minimal is chosen (if a = 4 and the suffix is "bfdd", the computer chooses string t equal to "aceg"). After that the chosen string t is appended to the end of s.
Mister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string s on the segment between positions l and r, inclusive. Letters of string s are numerated starting from 1.
Input
First and only line contains four space-separated integers: a, b, l and r (1 β€ a, b β€ 12, 1 β€ l β€ r β€ 109) β the numbers of letters each player appends and the bounds of the segment.
Output
Print one integer β the minimum possible number of different letters in the segment from position l to position r, inclusive, in string s.
Examples
Input
1 1 1 8
Output
2
Input
4 2 2 6
Output
3
Input
3 7 4 6
Output
1
Note
In the first sample test one of optimal strategies generate string s = "abababab...", that's why answer is 2.
In the second sample test string s = "abcdbcaefg..." can be obtained, chosen segment will look like "bcdbc", that's why answer is 3.
In the third sample test string s = "abczzzacad..." can be obtained, chosen, segment will look like "zzz", that's why answer is 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.
Recently Luba bought a monitor. Monitor is a rectangular matrix of size n Γ m. But then she started to notice that some pixels cease to work properly. Luba thinks that the monitor will become broken the first moment when it contains a square k Γ k consisting entirely of broken pixels. She knows that q pixels are already broken, and for each of them she knows the moment when it stopped working. Help Luba to determine when the monitor became broken (or tell that it's still not broken even after all q pixels stopped working).
Input
The first line contains four integer numbers n, m, k, q (1 β€ n, m β€ 500, 1 β€ k β€ min(n, m), 0 β€ q β€ nΒ·m) β the length and width of the monitor, the size of a rectangle such that the monitor is broken if there is a broken rectangle with this size, and the number of broken pixels.
Each of next q lines contain three integer numbers xi, yi, ti (1 β€ xi β€ n, 1 β€ yi β€ m, 0 β€ t β€ 109) β coordinates of i-th broken pixel (its row and column in matrix) and the moment it stopped working. Each pixel is listed at most once.
We consider that pixel is already broken at moment ti.
Output
Print one number β the minimum moment the monitor became broken, or "-1" if it's still not broken after these q pixels stopped working.
Examples
Input
2 3 2 5
2 1 8
2 2 8
1 2 1
1 3 4
2 3 2
Output
8
Input
3 3 2 5
1 2 2
2 2 1
2 3 5
3 2 10
2 1 100
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.
Vova promised himself that he would never play computer games... But recently Firestorm β a well-known game developing company β published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.
Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.
Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.
The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?
Take a look at the notes if you think you haven't understood the problem completely.
Input
The first line contains two integer numbers n and m (1 β€ n β€ 105, 0 β€ m β€ 105) β the number of characters in Overcity and the number of pairs of friends.
The second line contains n integer numbers ci (0 β€ ci β€ 109) β the amount of gold i-th character asks to start spreading the rumor.
Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 β€ xi, yi β€ n, xi β yi). It is guaranteed that each pair is listed at most once.
Output
Print one number β the minimum amount of gold Vova has to spend in order to finish the quest.
Examples
Input
5 2
2 5 3 4 8
1 4
4 5
Output
10
Input
10 0
1 2 3 4 5 6 7 8 9 10
Output
55
Input
10 5
1 6 2 7 3 8 4 9 5 10
1 2
3 4
5 6
7 8
9 10
Output
15
Note
In the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.
In the second example Vova has to bribe everyone.
In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
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.
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.
Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.
You are given a word s. Can you predict what will it become after correction?
In this problem letters a, e, i, o, u and y are considered to be vowels.
Input
The first line contains one integer n (1 β€ n β€ 100) β the number of letters in word s before the correction.
The second line contains a string s consisting of exactly n lowercase Latin letters β the word before the correction.
Output
Output the word s after the correction.
Examples
Input
5
weird
Output
werd
Input
4
word
Output
word
Input
5
aaeaa
Output
a
Note
Explanations of the examples:
1. There is only one replace: weird <image> werd;
2. No replace needed since there are no two consecutive vowels;
3. aaeaa <image> aeaa <image> aaa <image> aa <image> a.
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 lunch time at the Vibrant Gujarat Summit and all the investors are called for the executive lunch. When Bruce reached the lunch area, he found that the waiter was taking out bowls from a big box containing some amount of golden bowls and other bronze bowls. The bowls were taken out at random. Each dish contains exactly one bowl. Bruce and Robin are the first ones to receive the dishes.
Bruce believes that there is a 50/50 chance in everything. He tells Robin that the there is a 50% chance of both of them receiving a golden bowl. Robin is confused and doesn't know how is that possible. He asks Bruce what makes him think so. Bruce says that he would have to find the answer himself and so in order to make things interesting he tells Robin the total number of bowls the waiter has in the box. All Robin has to do is now find the number of golden bowls there should be in the box in order for it to be a 50% probability.
Input:
Only one integer number, N, telling the number of bowls in the box.
Output:
The number of golden bowls required for it to be a 50% probability of both of them receiving a golden bowl.
Constraints:
1 β€ N β€ 10^15
SAMPLE INPUT
21
SAMPLE OUTPUT
15
Explanation
As Bruce and Robin are the first ones to receive the bowls, if there are 15 golden bowls then the probability for the first person to get a golden one is 15/21 and the second one is 14/20.
(15/21)*(14/20) = 0.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.
Monk visits Biksy, the largest trading market in the land. Biksy has traders from all over the world.
There are a total of N items indexed from 1 to N, that are traded in the market by a total of M dealers. Each trader is characterized by three integers, say i, j, C , meaning that the trader will take i'th item from you and give you j'th item and C units of money. A negative value of C signifies that, in order to get j'th item from the trader, you will have to give i'th item and C units of money. Note that there can be multiple dealers who deal with the same pair of items and some crazy dealers might trade the same item as well i.e. (i = j).
Monk visits Biksy having the item number 1. He collects the data of all the traders and wants to know if there is way by which he can become infinity rich if he acts smart! i.e. if there are a series of profits, repeating which, will always increase the number of units of money with him! Help Monk find the answer to this question. Note that Monk can go to any dealer any number of times.
Input:
First line contains an integer T. T test cases follow.
First line of each test case contains two space-separated integers N, M
Next M lines contain three space-separated integers i, j and C, the characteristics of the traders.
Output:
Print "Yes"(without the quotes) if such a way exists, "No"(without the quotes) otherwise.
Print the answer to each test case in a new line.
Constraints:
1 β€ T β€ 10
1 β€ N β€ 100
1 β€ M β€ 1000
1 β€ i, j β€ N
-1000 β€ C β€ 1000
SAMPLE INPUT
2
5 6
1 2 2
2 3 -1
3 4 -7
4 5 0
2 3 -7
3 5 6
5 8
1 5 10
2 3 -6
5 2 5
4 5 9
1 5 1
2 4 -10
2 3 -2
4 1 1
SAMPLE OUTPUT
No
Yes
Explanation
For the first test case, there is no such way possible.
For the second test case, Monk starts with item 1.
Trades it for 5th item gaining 10 units.
Trades 5th for 2nd gaining 5 units.
Trades 2nd for 4th losing 10 units.
Trades 4th for 1st gaining 1 unit.
Thereby, gaining 6 units in this process and it can be repeated indefinitely to make Monk infinitely rich!
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.
Definition:
Roy's boolean function (RBF) is True, if number of the positive integers less than or equal to N that are relatively prime to N, is prime; else False.
In other words, let Z be the number of integers K in the range 1 β€ K β€ N for which the greatest common divisor gcd(N, K) = 1. If Z is prime then RBF is True else it is False.
Given an integer N, your task is to find if its RBF value.
Input:
First line contains T - number of test cases.
Each of next T lines contain an integer N.
Output:
Print RBF value of each N in a new line i.e. "TRUE" or "FALSE" (quotes are only for clarity)
Constraints:
1 β€ T β€ 10
1 β€ N β€ 100000
Note: In case you're wondering, 1 is NOT a prime number :)
SAMPLE INPUT
4
2
3
4
5SAMPLE OUTPUT
FALSE
TRUE
TRUE
FALSEExplanation
For N=4, numbers β€ 4 and relatively prime to 4 are 1 and 3. So there are 2 numbers that are relatively prime to 4. Since 2 is a prime. RBF is TRUE.
For N=5, numbers β€ 5 and relatively prime to 5 are 1,2,3 and 4. So there are 4 numbers that are relatively prime to 5. Since 4 is not a prime, RBF is FALSE.
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.
With the T20 world cup going on, a list of batsmen was prepared with their country code and their T20I career runs.
The list contains data of N batsmen (country-code and runs).
Number of countries may range from 1 to N and each country has its unique code.
The list is pretty unorganized. Virat and Maxwell do not like it. They decided to group all the players belonging to same country together.
Virat likes arranging stuffs in ascending order and wants the data list to be sorted in ascending order, while Maxwell prefers descending order.
As they are good friends, they mutually agreed that country codes should be sorted in ascending order and for each country code, the runs of all the batsmen for that particular country should be sorted in descending order.
As the mighty clash between Australia and India is going to start shortly, Virat and Maxwell don't have the time to organize the list. Can you help them to sort the list, the way they want?
(See test cases for clarification)
INPUT:
First line contains a integer N, the number of Batsmen.
Next N lines, contains two integers separated by space, country-code and runs of the ith batsmen . (1 β€ i β€ N)
OUTPUT :
Print N lines containing two integers, i.e. country-code and runs of the batsmen, sorted in the order Virat and Maxwell wants.
CONSTRAINS
1 β€ N β€ 1000006
0 β€ Runs β€ 10^9
Disclaimer : All country-codes and runs are fictional and has no relation and significance with real life.
SAMPLE INPUT
5
4 12
2 1
3 10
2 7
2 5
SAMPLE OUTPUT
2 7
2 5
2 1
3 10
4 12
Explanation
Country '4' has one player with runs '12',
Country '3' has one player with run '10',
Country '2' has three players with runs '1' , '7' and '5' .
Countries are sorted in increasing order 2 -> 2 -> 2 -> 3 -> 4.
The players for each country should have runs in descending order, so final output is
(2,7) (2,5), (2,1) , (3,10), (4,12).
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 buy a product for N yen (the currency of Japan) at a shop.
If we use only 1000-yen bills to pay the price, how much change will we receive?
Assume we use the minimum number of bills required.
Constraints
* 1 \leq N \leq 10000
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the amount of change as an integer.
Examples
Input
1900
Output
100
Input
3000
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.
Does \sqrt{a} + \sqrt{b} < \sqrt{c} hold?
Constraints
* 1 \leq a, b, c \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
a \ b \ c
Output
If \sqrt{a} + \sqrt{b} < \sqrt{c}, print `Yes`; otherwise, print `No`.
Examples
Input
2 3 9
Output
No
Input
2 3 10
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 have two indistinguishable pieces placed on a number line. Both pieces are initially at coordinate 0. (They can occupy the same position.)
We can do the following two kinds of operations:
* Choose a piece and move it to the right (the positive direction) by 1.
* Move the piece with the smaller coordinate to the position of the piece with the greater coordinate. If two pieces already occupy the same position, nothing happens, but it still counts as doing one operation.
We want to do a total of N operations of these kinds in some order so that one of the pieces will be at coordinate A and the other at coordinate B. Find the number of ways to move the pieces to achieve it. The answer can be enormous, so compute the count modulo 998244353.
Two ways to move the pieces are considered different if and only if there exists an integer i (1 \leq i \leq N) such that the set of the coordinates occupied by the pieces after the i-th operation is different in those two ways.
Constraints
* 1 \leq N \leq 10^7
* 0 \leq A \leq B \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the number of ways to move the pieces to achieve our objective, modulo 998244353.
Examples
Input
5 1 3
Output
4
Input
10 0 0
Output
1
Input
10 4 6
Output
197
Input
1000000 100000 200000
Output
758840509
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 weights indexed 1 to N. The mass of the weight indexed i is W_i.
We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.
Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.
Constraints
* 2 \leq N \leq 100
* 1 \leq W_i \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
W_1 W_2 ... W_{N-1} W_N
Output
Print the minimum possible absolute difference of S_1 and S_2.
Examples
Input
3
1 2 3
Output
0
Input
4
1 3 1 1
Output
2
Input
8
27 23 76 2 3 5 62 52
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.
For a positive integer n, let us define f(n) as the number of digits in base 10.
You are given an integer S. Count the number of the pairs of positive integers (l, r) (l \leq r) such that f(l) + f(l + 1) + ... + f(r) = S, and find the count modulo 10^9 + 7.
Constraints
* 1 \leq S \leq 10^8
Input
Input is given from Standard Input in the following format:
S
Output
Print the answer.
Examples
Input
1
Output
9
Input
2
Output
98
Input
123
Output
460191684
Input
36018
Output
966522825
Input
1000
Output
184984484
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 points (x_i,y_i) located on a two-dimensional plane. Consider a subset S of the N points that forms a convex polygon. Here, we say a set of points S forms a convex polygon when there exists a convex polygon with a positive area that has the same set of vertices as S. All the interior angles of the polygon must be strictly less than 180Β°.
cddb0c267926c2add885ca153c47ad8a.png
For example, in the figure above, {A,C,E} and {B,D,E} form convex polygons; {A,C,D,E}, {A,B,C,E}, {A,B,C}, {D,E} and {} do not.
For a given set S, let n be the number of the points among the N points that are inside the convex hull of S (including the boundary and vertices). Then, we will define the score of S as 2^{n-|S|}.
Compute the scores of all possible sets S that form convex polygons, and find the sum of all those scores.
However, since the sum can be extremely large, print the sum modulo 998244353.
Constraints
* 1β€Nβ€200
* 0β€x_i,y_i<10^4 (1β€iβ€N)
* If iβ j, x_iβ x_j or y_iβ y_j.
* x_i and y_i are integers.
Input
The 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 sum of all the scores modulo 998244353.
Examples
Input
4
0 0
0 1
1 0
1 1
Output
5
Input
5
0 0
0 1
0 2
0 3
1 1
Output
11
Input
1
3141 2718
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.
Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.
In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".
The current time is A o'clock, and a contest will begin in exactly B hours. When will the contest begin? Answer in 24-hour time.
Constraints
* 0 \leq A,B \leq 23
* A and B are integers.
Input
The input is given from Standard Input in the following format:
A B
Output
Print the hour of the starting time of the contest in 24-hour time.
Examples
Input
9 12
Output
21
Input
19 0
Output
19
Input
23 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.
There is a double-track line (up and down are separate lines and pass each other everywhere). There are 11 stations on this line, including the terminal station, and each station is called by the section number shown in the figure.
<image>
Trains depart from both terminal stations on this line at the same time and run without stopping along the way. Create a program that reads the length of each section and the speed of the two trains and outputs the number of the section where the trains pass each other in each case. However, if you pass each other just at the station, the smaller number of the section numbers on both sides will be output. In addition, the length of the train and the length of the station cannot be ignored.
Input
Multiple datasets are given. Each dataset is given in the following format.
l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, v1, v2
li (1 β€ li β€ 2,000) is an integer representing the length (km) of the interval i. v1 is the speed of the train departing from the terminal station on the section 1 side (km / h), and v2 is the speed of the train departing from the terminal station on the section 10 side (km / h) (1 β€ v1, v2) β€ 2,000).
The number of datasets does not exceed 50.
Output
For each data set, the number of the section where the train passes is output on one line.
Example
Input
1,1,1,1,1,1,1,1,1,1,40,60
1,1,1,1,1,3,3,3,3,3,50,50
10,10,10,10,10,10,10,10,10,10,50,49
Output
4
7
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.
Create a program that inputs the vertex information of two polygons inscribed in one circle and outputs the magnitude relationship of their areas.
Assume that each vertex of the X-side is numbered counterclockwise from 1 to X (the figure shows an example when X = 4). However, the given polygon assumes that the center of the circle is contained inside, and the data on the position of vertex i is the angle v (1 β€ v <180) of the central angle measured counterclockwise from vertex i to vertex i + 1. Integer). Regarding the magnitude relationship to be output, 1 (half-width number) when the area of ββthe first polygon is large, 2 (half-width number) when the area of ββthe second polygon is large, and when the areas are the same, Please output 0 (half-width number).
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
m
v1
v2
::
vm β1
n
v1
v2
::
vn β 1
The first line gives the number of vertices of the first polygon m (3 β€ m β€ 50), and the following m β 1 line gives the information vi (1 β€ vi <180) of the vertices i of the first polygon. ..
The following line gives the number of vertices n (3 β€ n β€ 50) of the second polygon, and the following n β 1 line gives the information vi (1 β€ vi <180) for the vertices i of the second polygon.
The number of datasets does not exceed 200.
Output
Outputs the magnitude relationship (half-width numbers) for each data set on one line.
Example
Input
4
30
125
75
4
30
125
75
5
30
125
75
65
4
30
125
75
4
30
125
75
6
30
50
50
25
75
0
Output
0
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.
Addition is easy to calculate by hand, but if some numbers are missing, is it easy to fill in the missing numbers? For example, in the following long division, if there is a condition that the numbers 1 to 9 appear only once, how many numbers will fit in the C and E squares? In this case, 8 is correct for C and 5 is correct for E. An operation that lacks some numbers in this way is called worm-eaten calculation.
<image>
The condition that the numbers 1 to 9 appear only once remains the same, and if more numbers are missing as shown below, is there only one way to fill in the correct numbers? In fact, it is not always decided in one way.
<image>
Create a program that outputs how many correct filling methods are available when the information of each cell from A to I is given in the form of worm-eaten calculation as shown in the above figure.
Input
The input is given in the following format.
A B C D E F G H I
One line is given the information of the numbers in the cells from A to I of the worm-eaten calculation. However, when the given value is -1, it means that the number in that square is missing. Values ββother than -1 are any of the integers from 1 to 9 and there is no duplication between them.
Output
Outputs how many correct filling methods are available on one line.
Examples
Input
7 6 -1 1 -1 9 2 3 4
Output
1
Input
7 6 5 1 8 9 2 3 4
Output
0
Input
-1 -1 -1 -1 -1 -1 8 4 6
Output
12
Input
-1 -1 -1 -1 -1 -1 -1 -1 -1
Output
168
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
The JOI building is a combination of regular hexagons with a side of 1 meter as shown in the figure. As Christmas is approaching, JOI decided to decorate the walls of the building with illuminations. However, since it is useless to illuminate the parts that cannot be seen from the outside, we decided to decorate only the walls that can be reached from the outside without passing through the building.
<image>
Figure: Example of JOI building layout
The figure above is an example of the layout of JOI's buildings as seen from above. The numbers in the regular hexagon represent the coordinates. A gray regular hexagon represents a place with a building, and a white regular hexagon represents a place without a building. In this example, the part indicated by the solid red line is the wall surface to be decorated with illumination, and the total length of the wall surface is 64 meters.
Given a map showing the layout of JOI's buildings, create a program to find the total length of the walls to decorate. However, the outside of the map can be freely moved, and it is not possible to pass between adjacent buildings.
input
Two integers W and H (1 β€ W β€ 100, 1 β€ H β€ 100) are written on the first line of the input file, separated by blanks. The following line H describes the layout of the JOI building. On the first line of i + (1 β€ i β€ H), W integers are written separated by blanks, and the jth (1 β€ j β€ W) integer is a regular hexagon with coordinates (j, i). It is 1 when there is a building in, and 0 when there is no building. Also, the input data given always has one or more buildings.
The map is described by the following rules.
* The westernmost regular hexagon in the northernmost row of the map is the coordinates (1, 1).
* The eastern adjacent regular hexagon adjacent to the regular hexagon with coordinates (x, y) is the coordinates (x + 1, y).
* When y is odd, the coordinates of the southwestern regular hexagon adjacent to the regular hexagon of coordinates (x, y) are (x, y + 1).
* When y is even, the coordinates of the southeastern regular hexagon adjacent to the regular hexagon of coordinates (x, y) are (x, y + 1).
output
Output the total length of the walls to be decorated with illuminations in one line.
Input / output example
Input example 1
8 4
0 1 0 1 0 1 1 1
0 1 1 0 0 1 0 0
1 0 1 0 1 1 1 1 1
0 1 1 0 1 0 1 0
Output example 1
64
Input / output example 1 corresponds to the example in the problem statement, and the total length of the wall surface decorated with illumination is 64 meters.
Input example 2
8 5
0 1 1 1 0 1 1 1
0 1 0 0 1 1 0 0
1 0 0 1 1 1 1 1 1
0 1 0 1 1 0 1 0
0 1 1 0 1 1 0 0
Output example 2
56
The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics.
Example
Input
8 4
0 1 0 1 0 1 1 1
0 1 1 0 0 1 0 0
1 0 1 0 1 1 1 1
0 1 1 0 1 0 1 0
Output
64
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.
Yokoβs math homework today was to calculate areas of polygons in the xy-plane. Vertices are all aligned to grid points (i.e. they have integer coordinates).
Your job is to help Yoko, not good either at math or at computer programming, get her home- work done. A polygon is given by listing the coordinates of its vertices. Your program should approximate its area by counting the number of unit squares (whose vertices are also grid points) intersecting the polygon. Precisely, a unit square βintersects the polygonβ if and only if the in- tersection of the two has non-zero area. In the figure below, dashed horizontal and vertical lines are grid lines, and solid lines are edges of the polygon. Shaded unit squares are considered inter- secting the polygon. Your program should output 55 for this polygon (as you see, the number of shaded unit squares is 55).
<image>
Figure 1: A polygon and unit squares intersecting it
Input
The input file describes polygons one after another, followed by a terminating line that only contains a single zero.
A description of a polygon begins with a line containing a single integer, m (β₯ 3), that gives the number of its vertices. It is followed by m lines, each containing two integers x and y, the coordinates of a vertex. The x and y are separated by a single space. The i-th of these m lines gives the coordinates of the i-th vertex (i = 1, ... , m). For each i = 1, ... , m - 1, the i-th vertex and the (i + 1)-th vertex are connected by an edge. The m-th vertex and the first vertex are also connected by an edge (i.e., the curve is closed). Edges intersect only at vertices. No three edges share a single vertex (i.e., the curve is simple). The number of polygons is no more than 100. For each polygon, the number of vertices (m) is no more than 100. All coordinates x and y satisfy -2000 β€ x β€ 2000 and -2000 β€ y β€ 2000.
Output
The output should consist of as many lines as the number of polygons. The k-th output line should print an integer which is the area of the k-th polygon, approximated in the way described above. No other characters, including whitespaces, should be printed.
Example
Input
4
5 -3
1 0
1 7
-7 -1
3
5 5
18 5
5 10
3
-5 -5
-5 -10
-18 -10
5
0 0
20 2
11 1
21 2
2 0
0
Output
55
41
41
23
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.
Example
Input
6
2
3
1
1
4
2
Output
Yes
Yes
Yes
No
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.
Entrance Examination
The International Competitive Programming College (ICPC) is famous for its research on competitive programming. Applicants to the college are required to take its entrance examination.
The successful applicants of the examination are chosen as follows.
* The score of any successful applicant is higher than that of any unsuccessful applicant.
* The number of successful applicants n must be between nmin and nmax, inclusive. We choose n within the specified range that maximizes the gap. Here, the gap means the difference between the lowest score of successful applicants and the highest score of unsuccessful applicants.
* When two or more candidates for n make exactly the same gap, use the greatest n among them.
Let's see the first couple of examples given in Sample Input below. In the first example, nmin and nmax are two and four, respectively, and there are five applicants whose scores are 100, 90, 82, 70, and 65. For n of two, three and four, the gaps will be 8, 12, and 5, respectively. We must choose three as n, because it maximizes the gap.
In the second example, nmin and nmax are two and four, respectively, and there are five applicants whose scores are 100, 90, 80, 75, and 65. For n of two, three and four, the gap will be 10, 5, and 10, respectively. Both two and four maximize the gap, and we must choose the greatest number, four.
You are requested to write a program that computes the number of successful applicants that satisfies the conditions.
Input
The input consists of multiple datasets. Each dataset is formatted as follows.
> m nmin nmax
> P1
> P2
> ...
> Pm
>
The first line of a dataset contains three integers separated by single spaces. m represents the number of applicants, nmin represents the minimum number of successful applicants, and nmax represents the maximum number of successful applicants. Each of the following m lines contains an integer Pi, which represents the score of each applicant. The scores are listed in descending order. These numbers satisfy 0 < nmin < nmax < m β€ 200, 0 β€ Pi β€ 10000 (1 β€ i β€ m) and Pnmin > Pnmax+1. These ensure that there always exists an n satisfying the conditions.
The end of the input is represented by a line containing three zeros separated by single spaces.
Output
For each dataset, output the number of successful applicants in a line.
Sample Input
5 2 4
100
90
82
70
65
5 2 4
100
90
80
75
65
3 1 2
5000
4000
3000
4 2 3
10000
10000
8000
8000
4 2 3
10000
10000
10000
8000
5 2 3
100
80
68
60
45
0 0 0
Output for the Sample Input
3
4
2
2
3
2
Example
Input
5 2 4
100
90
82
70
65
5 2 4
100
90
80
75
65
3 1 2
5000
4000
3000
4 2 3
10000
10000
8000
8000
4 2 3
10000
10000
10000
8000
5 2 3
100
80
68
60
45
0 0 0
Output
3
4
2
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.
G --Derangement / Derangement
Story
Person D is doing research on permutations. At one point, D found a permutation class called "Derangement". "It's cool to have a perfect permutation !!! And it starts with D !!!", the person of D who had a crush on Chunibyo decided to rewrite all the permutations given to him.
Problem
Given a permutation of length n, p = (p_1 p_2 ... p_n). The operation of swapping the i-th element and the j-th element requires the cost of (p_i + p_j) \ times | i-j |. At this time, find the minimum cost required to make p into a perfect permutation using only the above swap operation.
However, the fact that the permutation q is a perfect permutation means that q_i \ neq i holds for 1 \ leq i \ leq n. For example, (5 3 1 2 4) is a perfect permutation, but (3 2 5 4 1) is not a perfect permutation because the fourth number is 4.
Input
The input consists of the following format.
n
p_1 p_2 ... p_n
The first row consists of one integer representing the length n of the permutation. The second line consists of n integers, and the i-th integer represents the i-th element of the permutation p. Each is separated by a single blank character.
Constraints:
* 2 \ leq n \ leq 100
* 1 \ leq p_i \ leq n, i \ neq j β p_i \ neq p_j
Output
Print the minimum cost to sort p into a complete permutation on one line. Be sure to start a new line at the end of the line.
Sample Input 1
Five
1 2 3 5 4
Sample Output 1
7
After swapping 1 and 2, swapping 1 and 3 yields (2 3 1 5 4), which is a complete permutation.
Sample Input 2
Five
5 3 1 2 4
Sample Output 2
0
It is a perfect permutation from the beginning.
Sample Input 3
Ten
1 3 4 5 6 2 7 8 9 10
Sample Output 3
38
Example
Input
5
1 2 3 5 4
Output
7
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 reads a sequence and prints it in the reverse order.
Note
θ§£θͺ¬
Constraints
* n β€ 100
* 0 β€ ai < 1000
Input
The input is given in the following format:
n
a1 a2 . . . an
n is the size of the sequence and ai is the ith element of the sequence.
Output
Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).
Examples
Input
5
1 2 3 4 5
Output
5 4 3 2 1
Input
8
3 3 4 4 5 8 7 9
Output
9 7 8 5 4 4 3 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 two strings s and t. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by 1. You can't choose a string if it is empty.
For example:
* by applying a move to the string "where", the result is the string "here",
* by applying a move to the string "a", the result is an empty string "".
You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.
Write a program that finds the minimum number of moves to make two given strings s and t equal.
Input
The first line of the input contains s. In the second line of the input contains t. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and 2β
10^5, inclusive.
Output
Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.
Examples
Input
test
west
Output
2
Input
codeforces
yes
Output
9
Input
test
yes
Output
7
Input
b
ab
Output
1
Note
In the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".
In the second example, the move should be applied to the string "codeforces" 8 times. As a result, the string becomes "codeforces" β "es". The move should be applied to the string "yes" once. The result is the same string "yes" β "es".
In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.
In the fourth example, the first character of the second string should be deleted.
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 string s consisting only of lowercase Latin letters.
You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.
Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β number of queries.
Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).
Output
Print t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.
Example
Input
3
aa
abacaba
xdd
Output
-1
abaacba
xdd
Note
In the first query we cannot rearrange letters to obtain a good string.
Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".
In the third query we can do nothing to obtain a good string.
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 day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i.
This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer x, then choose one machine and reduce the power of its machine by x times, and at the same time increase the power of one another machine by x times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices i and j, and one integer x such that x is a divisor of a_i, and change powers as following: a_i = (a_i)/(x), a_j = a_j β
x
Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!
Input
The first line contains one integer n (2 β€ n β€ 5 β
10^4) β the number of machines.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 100) β the powers of the machines.
Output
Print one integer β minimum total power.
Examples
Input
5
1 2 3 4 5
Output
14
Input
4
4 2 4 4
Output
14
Input
5
2 4 2 3 7
Output
18
Note
In the first example, the farmer can reduce the power of the 4-th machine by 2 times, and increase the power of the 1-st machine by 2 times, then the powers will be: [2, 2, 3, 2, 5].
In the second example, the farmer can reduce the power of the 3-rd machine by 2 times, and increase the power of the 2-nd machine by 2 times. At the same time, the farmer can leave is be as it is and the total power won't change.
In the third example, it is optimal to leave it be as it is.
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 superhero fights with a monster. The battle consists of rounds, each of which lasts exactly n minutes. After a round ends, the next round starts immediately. This is repeated over and over again.
Each round has the same scenario. It is described by a sequence of n numbers: d_1, d_2, ..., d_n (-10^6 β€ d_i β€ 10^6). The i-th element means that monster's hp (hit points) changes by the value d_i during the i-th minute of each round. Formally, if before the i-th minute of a round the monster's hp is h, then after the i-th minute it changes to h := h + d_i.
The monster's initial hp is H. It means that before the battle the monster has H hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 0. Print -1 if the battle continues infinitely.
Input
The first line contains two integers H and n (1 β€ H β€ 10^{12}, 1 β€ n β€ 2β
10^5). The second line contains the sequence of integers d_1, d_2, ..., d_n (-10^6 β€ d_i β€ 10^6), where d_i is the value to change monster's hp in the i-th minute of a round.
Output
Print -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer k such that k is the first minute after which the monster is dead.
Examples
Input
1000 6
-100 -200 -300 125 77 -4
Output
9
Input
1000000000000 5
-1 0 0 0 0
Output
4999999999996
Input
10 4
-3 -6 5 4
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 are organizing a boxing tournament, where n boxers will participate (n is a power of 2), and your friend is one of them. All boxers have different strength from 1 to n, and boxer i wins in the match against boxer j if and only if i is stronger than j.
The tournament will be organized as follows: n boxers will be divided into pairs; the loser in each pair leaves the tournament, and n/2 winners advance to the next stage, where they are divided into pairs again, and the winners in all pairs advance to the next stage, and so on, until only one boxer remains (who is declared the winner).
Your friend really wants to win the tournament, but he may be not the strongest boxer. To help your friend win the tournament, you may bribe his opponents: if your friend is fighting with a boxer you have bribed, your friend wins even if his strength is lower.
Furthermore, during each stage you distribute the boxers into pairs as you wish.
The boxer with strength i can be bribed if you pay him a_i dollars. What is the minimum number of dollars you have to spend to make your friend win the tournament, provided that you arrange the boxers into pairs during each stage as you wish?
Input
The first line contains one integer n (2 β€ n β€ 2^{18}) β the number of boxers. n is a power of 2.
The second line contains n integers a_1, a_2, ..., a_n, where a_i is the number of dollars you have to pay if you want to bribe the boxer with strength i. Exactly one of a_i is equal to -1 β it means that the boxer with strength i is your friend. All other values are in the range [1, 10^9].
Output
Print one integer β the minimum number of dollars you have to pay so your friend wins.
Examples
Input
4
3 9 1 -1
Output
0
Input
8
11 -1 13 19 24 7 17 5
Output
12
Note
In the first test case no matter how you will distribute boxers into pairs, your friend is the strongest boxer and anyway wins the tournament.
In the second test case you can distribute boxers as follows (your friend is number 2):
1 : 2, 8 : 5, 7 : 3, 6 : 4 (boxers 2, 8, 7 and 6 advance to the next stage);
2 : 6, 8 : 7 (boxers 2 and 8 advance to the next stage, you have to bribe the boxer with strength 6);
2 : 8 (you have to bribe the boxer with strength 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.
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal (β) and existential (β). You can read more about them here.
The universal quantifier is used to make a claim that a statement holds for all real numbers. For example:
* β x,x<100 is read as: for all real numbers x, x is less than 100. This statement is false.
* β x,x>x-1 is read as: for all real numbers x, x is greater than x-1. This statement is true.
The existential quantifier is used to make a claim that there exists some real number for which the statement holds. For example:
* β x,x<100 is read as: there exists a real number x such that x is less than 100. This statement is true.
* β x,x>x-1 is read as: there exists a real number x such that x is greater than x-1. This statement is true.
Moreover, these quantifiers can be nested. For example:
* β x,β y,x<y is read as: for all real numbers x, there exists a real number y such that x is less than y. This statement is true since for every x, there exists y=x+1.
* β y,β x,x<y is read as: there exists a real number y such that for all real numbers x, x is less than y. This statement is false because it claims that there is a maximum real number: a number y larger than every x.
Note that the order of variables and quantifiers is important for the meaning and veracity of a statement.
There are n variables x_1,x_2,β¦,x_n, and you are given some formula of the form $$$ f(x_1,...,x_n):=(x_{j_1}<x_{k_1})β§ (x_{j_2}<x_{k_2})β§ β
β
β
β§ (x_{j_m}<x_{k_m}), $$$
where β§ denotes logical AND. That is, f(x_1,β¦, x_n) is true if every inequality x_{j_i}<x_{k_i} holds. Otherwise, if at least one inequality does not hold, then f(x_1,β¦,x_n) is false.
Your task is to assign quantifiers Q_1,β¦,Q_n to either universal (β) or existential (β) so that the statement $$$ Q_1 x_1, Q_2 x_2, β¦, Q_n x_n, f(x_1,β¦, x_n) $$$
is true, and the number of universal quantifiers is maximized, or determine that the statement is false for every possible assignment of quantifiers.
Note that the order the variables appear in the statement is fixed. For example, if f(x_1,x_2):=(x_1<x_2) then you are not allowed to make x_2 appear first and use the statement β x_2,β x_1, x_1<x_2. If you assign Q_1=β and Q_2=β, it will only be interpreted as β x_1,β x_2,x_1<x_2.
Input
The first line contains two integers n and m (2β€ nβ€ 2β
10^5; 1β€ mβ€ 2β
10^5) β the number of variables and the number of inequalities in the formula, respectively.
The next m lines describe the formula. The i-th of these lines contains two integers j_i,k_i (1β€ j_i,k_iβ€ n, j_iβ k_i).
Output
If there is no assignment of quantifiers for which the statement is true, output a single integer -1.
Otherwise, on the first line output an integer, the maximum possible number of universal quantifiers.
On the next line, output a string of length n, where the i-th character is "A" if Q_i should be a universal quantifier (β), or "E" if Q_i should be an existential quantifier (β). All letters should be upper-case. If there are multiple solutions where the number of universal quantifiers is maximum, print any.
Examples
Input
2 1
1 2
Output
1
AE
Input
4 3
1 2
2 3
3 1
Output
-1
Input
3 2
1 3
2 3
Output
2
AAE
Note
For the first test, the statement β x_1, β x_2, x_1<x_2 is true. Answers of "EA" and "AA" give false statements. The answer "EE" gives a true statement, but the number of universal quantifiers in this string is less than in our answer.
For the second test, we can show that no assignment of quantifiers, for which the statement is true exists.
For the third test, the statement β x_1, β x_2, β x_3, (x_1<x_3)β§ (x_2<x_3) is true: We can set x_3=max\\{x_1,x_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.
Polycarp wrote on the board a string s containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.
After that, he erased some letters from the string s, and he rewrote the remaining letters in any order. As a result, he got some new string t. You have to find it with some additional information.
Suppose that the string t has length m and the characters are numbered from left to right from 1 to m. You are given a sequence of m integers: b_1, b_2, β¦, b_m, where b_i is the sum of the distances |i-j| from the index i to all such indices j that t_j > t_i (consider that 'a'<'b'<...<'z'). In other words, to calculate b_i, Polycarp finds all such indices j that the index j contains a letter that is later in the alphabet than t_i and sums all the values |i-j|.
For example, if t = "abzb", then:
* since t_1='a', all other indices contain letters which are later in the alphabet, that is: b_1=|1-2|+|1-3|+|1-4|=1+2+3=6;
* since t_2='b', only the index j=3 contains the letter, which is later in the alphabet, that is: b_2=|2-3|=1;
* since t_3='z', then there are no indexes j such that t_j>t_i, thus b_3=0;
* since t_4='b', only the index j=3 contains the letter, which is later in the alphabet, that is: b_4=|4-3|=1.
Thus, if t = "abzb", then b=[6,1,0,1].
Given the string s and the array b, find any possible string t for which the following two requirements are fulfilled simultaneously:
* t is obtained from s by erasing some letters (possibly zero) and then writing the rest in any order;
* the array, constructed from the string t according to the rules above, equals to the array b specified in the input data.
Input
The first line contains an integer q (1 β€ q β€ 100) β the number of test cases in the test. Then q test cases follow.
Each test case consists of three lines:
* the first line contains string s, which has a length from 1 to 50 and consists of lowercase English letters;
* the second line contains positive integer m (1 β€ m β€ |s|), where |s| is the length of the string s, and m is the length of the array b;
* the third line contains the integers b_1, b_2, ..., b_m (0 β€ b_i β€ 1225).
It is guaranteed that in each test case an answer exists.
Output
Output q lines: the k-th of them should contain the answer (string t) to the k-th test case. It is guaranteed that an answer to each test case exists. If there are several answers, output any.
Example
Input
4
abac
3
2 1 0
abc
1
0
abba
3
1 0 1
ecoosdcefr
10
38 13 24 14 11 5 3 24 17 0
Output
aac
b
aba
codeforces
Note
In the first test case, such strings t are suitable: "aac', "aab".
In the second test case, such trings t are suitable: "a", "b", "c".
In the third test case, only the string t equals to "aba" is suitable, but the character 'b' can be from the second or third position.
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 Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 β€ i β€ n);
2. Add a_i to ans;
3. If b_i β -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 β€ i β€ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 β€ n β€ 2 β
10^5) β the length of arrays a and b.
The second line contains n integers a_1, a_2, β¦, a_n (β10^6 β€ a_i β€ 10^6).
The third line contains n integers b_1, b_2, β¦, b_n (1 β€ b_i β€ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 β€ i β€ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, β¦ is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, β¦, p_n (1 β€ p_i β€ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 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 four integers a, b, x and y. Initially, a β₯ x and b β₯ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to find the minimum possible product of a and b (a β
b) you can achieve by applying the given operation no more than n times.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The only line of the test case contains five integers a, b, x, y and n (1 β€ a, b, x, y, n β€ 10^9). Additional constraint on the input: a β₯ x and b β₯ y always holds.
Output
For each test case, print one integer: the minimum possible product of a and b (a β
b) you can achieve by applying the given operation no more than n times.
Example
Input
7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10
Output
70
77
177177
999999999000000000
999999999
55
10
Note
In the first test case of the example, you need to decrease b three times and obtain 10 β
7 = 70.
In the second test case of the example, you need to decrease a one time, b one time and obtain 11 β
7 = 77.
In the sixth test case of the example, you need to decrease a five times and obtain 5 β
11 = 55.
In the seventh test case of the example, you need to decrease b ten times and obtain 10 β
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.
Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. That's why he wants to find the shortest route from the excavation point to his crypt. Greg has recollected how the Codeforces participants successfully solved the problem of transporting his coffin to a crypt. So, in some miraculous way Greg appeared in your bedroom and asks you to help him in a highly persuasive manner. As usual, you didn't feel like turning him down.
After some thought, you formalized the task as follows: as the Neverland mountain has a regular shape and ends with a rather sharp peak, it can be represented as a cone whose base radius equals r and whose height equals h. The graveyard where Greg is busy excavating and his crypt can be represented by two points on the cone's surface. All you've got to do is find the distance between points on the cone's surface.
The task is complicated by the fact that the mountain's base on the ground level and even everything below the mountain has been dug through by gnome (one may wonder whether they've been looking for the same stuff as Greg...). So, one can consider the shortest way to pass not only along the side surface, but also along the cone's base (and in a specific case both points can lie on the cone's base β see the first sample test)
Greg will be satisfied with the problem solution represented as the length of the shortest path between two points β he can find his way pretty well on his own. He gave you two hours to solve the problem and the time is ticking!
Input
The first input line contains space-separated integers r and h (1 β€ r, h β€ 1000) β the base radius and the cone height correspondingly. The second and third lines contain coordinates of two points on the cone surface, groups of three space-separated real numbers. The coordinates of the points are given in the systems of coordinates where the origin of coordinates is located in the centre of the cone's base and its rotation axis matches the OZ axis. In this coordinate system the vertex of the cone is located at the point (0, 0, h), the base of the cone is a circle whose center is at the point (0, 0, 0), lying on the XOY plane, and all points on the cone surface have a non-negative coordinate z. It is guaranteed that the distances from the points to the cone surface do not exceed 10 - 12. All real numbers in the input have no more than 16 digits after decimal point.
Output
Print the length of the shortest path between the points given in the input, with absolute or relative error not exceeding 10 - 6.
Examples
Input
2 2
1.0 0.0 0.0
-1.0 0.0 0.0
Output
2.000000000
Input
2 2
1.0 0.0 0.0
1.0 0.0 1.0
Output
2.414213562
Input
2 2
1.0 0.0 1.0
-1.0 0.0 1.0
Output
2.534324263
Input
2 2
1.0 0.0 0.0
0.0 1.0 1.0
Output
3.254470198
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.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j β€ n must also be included in the subsegment.
Gildong wants to make all elements of a equal β he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 β€ n β€ 2 β
10^5) β the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 β
10^8 β€ a_i β€ 5 β
10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 β
10^5.
Output
For each test case, print one integer β the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-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 deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1β€ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1β€ nβ€ 2β
10^5) β the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1β€ a_i, b_iβ€ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck.
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 only difference between the easy and hard versions is that the given string s in the easy version is initially a palindrome, this condition is not always true for the hard version.
A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.
Alice and Bob are playing a game on a string s of length n consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.
In each turn, the player can perform one of the following operations:
1. Choose any i (1 β€ i β€ n), where s[i] = '0' and change s[i] to '1'. Pay 1 dollar.
2. Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa.
Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.
The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.
Input
The first line contains a single integer t (1 β€ t β€ 10^3). Then t test cases follow.
The first line of each test case contains a single integer n (1 β€ n β€ 10^3).
The second line of each test case contains the string s of length n, consisting of the characters '0' and '1'. It is guaranteed that the string s contains at least one '0'.
Note that there is no limit on the sum of n over test cases.
Output
For each test case print a single word in a new line:
* "ALICE", if Alice will win the game,
* "BOB", if Bob will win the game,
* "DRAW", if the game ends in a draw.
Example
Input
3
3
110
2
00
4
1010
Output
ALICE
BOB
ALICE
Note
In the first test case of example,
* in the 1-st move, Alice will use the 2-nd operation to reverse the string, since doing the 1-st operation will result in her loss anyway. This also forces Bob to use the 1-st operation.
* in the 2-nd move, Bob has to perform the 1-st operation, since the 2-nd operation cannot be performed twice in a row. All characters of the string are '1', game over.
Alice spends 0 dollars while Bob spends 1 dollar. Hence, Alice wins.
In the second test case of example,
* in the 1-st move Alice has to perform the 1-st operation, since the string is currently a palindrome.
* in the 2-nd move Bob reverses the string.
* in the 3-rd move Alice again has to perform the 1-st operation. All characters of the string are '1', game over.
Alice spends 2 dollars while Bob spends 0 dollars. Hence, Bob wins.
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 has a hobby β he develops an unusual social network. His work is almost completed, and there is only one more module to implement β the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user A sent user B a message at time t1, and user B sent user A a message at time t2. If 0 < t2 - t1 β€ d, then user B's message was an answer to user A's one. Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message.
You are given the log of messages in chronological order and a number d. Find all pairs of users who will be considered to be friends.
Input
The first line of the input contains two integers n and d (1 β€ n, d β€ 1000). The next n lines contain the messages log. The i-th line contains one line of the log formatted as "Ai Bi ti" (without the quotes), which means that user Ai sent a message to user Bi at time ti (1 β€ i β€ n). Ai and Bi are non-empty strings at most 20 characters long, consisting of lowercase letters ('a' ... 'z'), and ti is an integer (0 β€ ti β€ 10000). It is guaranteed that the lines are given in non-decreasing order of ti's and that no user sent a message to himself. The elements in the lines are separated by single spaces.
Output
In the first line print integer k β the number of pairs of friends. In the next k lines print pairs of friends as "Ai Bi" (without the quotes). You can print users in pairs and the pairs themselves in any order. Each pair must be printed exactly once.
Examples
Input
4 1
vasya petya 1
petya vasya 2
anya ivan 2
ivan anya 4
Output
1
petya vasya
Input
1 1000
a b 0
Output
0
Note
In the first sample test case Vasya and Petya are friends because their messages' sending times are one second apart. Anya and Ivan are not, because their messages' sending times differ by more than one second.
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 Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size n Γ n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure:
<image> Magic squares
You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n Γ n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.
It is guaranteed that a solution exists!
Input
The first input line contains a single integer n. The next line contains n2 integers ai ( - 108 β€ ai β€ 108), separated by single spaces.
The input limitations for getting 20 points are:
* 1 β€ n β€ 3
The input limitations for getting 50 points are:
* 1 β€ n β€ 4
* It is guaranteed that there are no more than 9 distinct numbers among ai.
The input limitations for getting 100 points are:
* 1 β€ n β€ 4
Output
The first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.
Examples
Input
3
1 2 3 4 5 6 7 8 9
Output
15
2 7 6
9 5 1
4 3 8
Input
3
1 0 -1 0 2 -1 -2 0 1
Output
0
1 0 -1
-2 0 2
1 0 -1
Input
2
5 5 5 5
Output
10
5 5
5 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.
Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values).
Valery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures.
A procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled:
* its name equals to the name of the called procedure;
* the number of its parameters equals to the number of parameters of the procedure call;
* the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same.
You are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call.
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of template procedures. The next n lines contain the description of the procedures specified in the following format:
"void procedureName (type_1, type_2, ..., type_t)" (1 β€ t β€ 5), where void is the keyword, procedureName is the procedure name, type_i is the type of the next parameter. Types of language parameters can be "int", "string", "double", and the keyword "T", which denotes the generic type.
The next line contains a single integer m (1 β€ m β€ 1000) β the number of used variables. Next m lines specify the description of the variables in the following format:
"type variableName", where type is the type of variable that can take values "int", "string", "double", variableName β the name of the variable.
The next line contains a single integer k (1 β€ k β€ 1000) β the number of procedure calls. Next k lines specify the procedure calls in the following format:
"procedureName (var_1, var_2, ..., var_t)" (1 β€ t β€ 5), where procedureName is the name of the procedure, var_i is the name of a variable.
The lines describing the variables, template procedures and their calls may contain spaces at the beginning of the line and at the end of the line, before and after the brackets and commas. Spaces may be before and after keyword void. The length of each input line does not exceed 100 characters. The names of variables and procedures are non-empty strings of lowercase English letters and numbers with lengths of not more than 10 characters. Note that this is the only condition at the names. Only the specified variables are used in procedure calls. The names of the variables are distinct. No two procedures are the same. Two procedures are the same, if they have identical names and identical ordered sets of types of their parameters.
Output
On each of k lines print a single number, where the i-th number stands for the number of suitable template procedures for the i-th call.
Examples
Input
4
void f(int,T)
void f(T, T)
void foo123 ( int, double, string,string )
void p(T,double)
3
int a
string s
double x123
5
f(a, a)
f(s,a )
foo (a,s,s)
f ( s ,x123)
proc(a)
Output
2
1
0
1
0
Input
6
void f(string,double,int)
void f(int)
void f ( T )
void procedure(int,double)
void f (T, double,int)
void f(string, T,T)
4
int a
int x
string t
double val
5
f(t, a, a)
f(t,val,a)
f(val,a, val)
solve300(val, val)
f (x)
Output
1
3
0
0
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.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 β€ n β€ 100) β amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 β€ ai, bi β€ n, ai β bi, 1 β€ ci β€ 100) β road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer β the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
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.
The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.
Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.
However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.
Input
The first line contains space-separated integers n and m <image> β the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1 β€ ai, bi β€ n; ai β bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n.
It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.
Output
Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on.
If there are multiple correct orders, you are allowed to print any of them.
Examples
Input
2 1
1 2
Output
2 1
Input
3 3
1 2
2 3
3 1
Output
2 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.
One day Vasya decided to have a look at the results of Berland 1910 Football Championshipβs finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of lines in the description. Then follow n lines β for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.
Output
Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.
Examples
Input
1
ABC
Output
ABC
Input
5
A
ABA
ABA
A
A
Output
A
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.
Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems.
Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square.
Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.
Input
The first line of the input contains number n β the number of mines on the map (2 β€ n β€ 1000). Each of the next n lines contains a pair of integers xi and yi β the coordinates of the corresponding mine ( - 109 β€ xi, yi β€ 109). All points are pairwise distinct.
Output
Print the minimum area of the city that can cover all the mines with valuable resources.
Examples
Input
2
0 0
2 2
Output
4
Input
2
0 0
0 3
Output
9
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.
Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.
Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.
To do this, Amr can do two different kind of operations.
* Choose some chemical i and double its current volume so the new volume will be 2ai
* Choose some chemical i and divide its volume by two (integer division) so the new volume will be <image>
Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?
Input
The first line contains one number n (1 β€ n β€ 105), the number of chemicals.
The second line contains n space separated integers ai (1 β€ ai β€ 105), representing the initial volume of the i-th chemical in liters.
Output
Output one integer the minimum number of operations required to make all the chemicals volumes equal.
Examples
Input
3
4 8 2
Output
2
Input
3
3 5 6
Output
5
Note
In the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.
In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 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.
Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple actions)?
Input
The first line of the input contains three integers a, b and c (0 β€ a, b, c β€ 1 000 000) β the number of blue, violet and orange spheres that are in the magician's disposal.
The second line of the input contains three integers, x, y and z (0 β€ x, y, z β€ 1 000 000) β the number of blue, violet and orange spheres that he needs to get.
Output
If the wizard is able to obtain the required numbers of spheres, print "Yes". Otherwise, print "No".
Examples
Input
4 4 0
2 1 2
Output
Yes
Input
5 6 1
2 7 2
Output
No
Input
3 3 3
2 2 2
Output
Yes
Note
In the first sample the wizard has 4 blue and 4 violet spheres. In his first action he can turn two blue spheres into one violet one. After that he will have 2 blue and 5 violet spheres. Then he turns 4 violet spheres into 2 orange spheres and he ends up with 2 blue, 1 violet and 2 orange spheres, which is exactly what he needs.
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 several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.
The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.
Input
The first line of the input data contains two integer numbers separated by a space n (1 β€ n β€ 105) and k (0 β€ k β€ 106) β the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 β€ hi β€ 106) is the height of the i-th book in millimeters.
Output
In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b β the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters.
In each of the following b lines print two integer numbers separated by a space β indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.
Examples
Input
3 3
14 12 10
Output
2 2
1 2
2 3
Input
2 0
10 10
Output
2 1
1 2
Input
4 5
8 19 10 13
Output
2 1
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.
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.
Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.
The verse patterns for the given text is a sequence of n integers p1, p2, ..., pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.
You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100) β the number of lines in the text.
The second line contains integers p1, ..., pn (0 β€ pi β€ 100) β the verse pattern.
Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.
Output
If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).
Examples
Input
3
2 2 3
intel
code
ch allenge
Output
YES
Input
4
1 2 3 1
a
bcdefghi
jklmnopqrstu
vwxyz
Output
NO
Input
4
13 11 15 15
to be or not to be that is the question
whether tis nobler in the mind to suffer
the slings and arrows of outrageous fortune
or to take arms against a sea of troubles
Output
YES
Note
In the first sample, one can split words into syllables in the following way:
in-tel
co-de
ch al-len-ge
Since the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one.
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 was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions:
* the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers <image> the condition |ci - cj| β€ 1 must hold.
* if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition.
Please help Vladik to find the length of the longest subsequence that satisfies both conditions.
Input
The first line contains single integer n (1 β€ n β€ 1000) β the number of cards in Vladik's sequence.
The second line contains the sequence of n positive integers not exceeding 8 β the description of Vladik's sequence.
Output
Print single integer β the length of the longest subsequence of Vladik's sequence that satisfies both conditions.
Examples
Input
3
1 1 1
Output
1
Input
8
8 7 6 5 4 3 2 1
Output
8
Input
24
1 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8
Output
17
Note
In the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition.
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! Vasya have come of age and that means he can finally get a passport! To do it, he needs to visit the passport office, but it's not that simple. There's only one receptionist at the passport office and people can queue up long before it actually opens. Vasya wants to visit the passport office tomorrow.
He knows that the receptionist starts working after ts minutes have passed after midnight and closes after tf minutes have passed after midnight (so that (tf - 1) is the last minute when the receptionist is still working). The receptionist spends exactly t minutes on each person in the queue. If the receptionist would stop working within t minutes, he stops serving visitors (other than the one he already serves).
Vasya also knows that exactly n visitors would come tomorrow. For each visitor Vasya knows the point of time when he would come to the passport office. Each visitor queues up and doesn't leave until he was served. If the receptionist is free when a visitor comes (in particular, if the previous visitor was just served and the queue is empty), the receptionist begins to serve the newcomer immediately.
<image> "Reception 1"
For each visitor, the point of time when he would come to the passport office is positive. Vasya can come to the office at the time zero (that is, at midnight) if he needs so, but he can come to the office only at integer points of time. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and stand in the queue after the last of them.
Vasya wants to come at such point of time that he will be served by the receptionist, and he would spend the minimum possible time in the queue. Help him!
Input
The first line contains three integers: the point of time when the receptionist begins to work ts, the point of time when the receptionist stops working tf and the time the receptionist spends on each visitor t. The second line contains one integer n β the amount of visitors (0 β€ n β€ 100 000). The third line contains positive integers in non-decreasing order β the points of time when the visitors arrive to the passport office.
All times are set in minutes and do not exceed 1012; it is guaranteed that ts < tf. It is also guaranteed that Vasya can arrive at the passport office at such a point of time that he would be served by the receptionist.
Output
Print single non-negative integer β the point of time when Vasya should arrive at the passport office. If Vasya arrives at the passport office at the same time with several other visitors, he yields to them and queues up the last. If there are many answers, you can print any of them.
Examples
Input
10 15 2
2
10 13
Output
12
Input
8 17 3
4
3 4 5 8
Output
2
Note
In the first example the first visitor comes exactly at the point of time when the receptionist begins to work, and he is served for two minutes. At 12 minutes after the midnight the receptionist stops serving the first visitor, and if Vasya arrives at this moment, he will be served immediately, because the next visitor would only come at 13 minutes after midnight.
In the second example, Vasya has to come before anyone else to be served.
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.
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.
After how many full years will Limak become strictly larger (strictly heavier) than Bob?
Input
The only line of the input contains two integers a and b (1 β€ a β€ b β€ 10) β the weight of Limak and the weight of Bob respectively.
Output
Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.
Examples
Input
4 7
Output
2
Input
4 9
Output
3
Input
1 1
Output
1
Note
In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4Β·3 = 12 and 7Β·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.
In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.
In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then.
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 often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they canβt belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
Input
First line contains single integer n (1 β€ n β€ 5000) β number of people.
Second line contains n space-separated integers a1, a2, ..., an (0 β€ ai β€ 5000), where ai denotes code of the city to which i-th person is going.
Output
The output should contain a single integer β maximal possible total comfort.
Examples
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
Note
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
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 is studying number theory. He has denoted a function f(a, b) such that:
* f(a, 0) = 0;
* f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b.
Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.
Input
The first line contains two integer numbers x and y (1 β€ x, y β€ 1012).
Output
Print f(x, y).
Examples
Input
3 5
Output
3
Input
6 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.
For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n.
For example, 4-rounding of 375 is 375Β·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375.
Write a program that will perform the k-rounding of n.
Input
The only line contains two integers n and k (1 β€ n β€ 109, 0 β€ k β€ 8).
Output
Print the k-rounding of n.
Examples
Input
375 4
Output
30000
Input
10000 1
Output
10000
Input
38101 0
Output
38101
Input
123456789 8
Output
12345678900000000
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 a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices.
Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans:
1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s;
2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s.
In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans.
Help Vasya find the plans.
Input
The first line contains three integers n, m and s (2 β€ n β€ 3Β·105, 1 β€ m β€ 3Β·105, 1 β€ s β€ n) β number of vertices and edges in the graph, and the vertex Vasya has picked.
The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 β€ ti β€ 2, 1 β€ ui, vi β€ n, ui β vi) β edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi.
It is guaranteed that there is at least one undirected edge in the graph.
Output
The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices.
A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input.
If there are multiple solutions, print any of them.
Examples
Input
2 2 1
1 1 2
2 2 1
Output
2
-
2
+
Input
6 6 3
2 2 6
1 4 5
2 3 4
1 4 1
1 3 1
2 2 3
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.
Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field.
<image>
Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (xl, yl) in some small field, the next move should be done in one of the cells of the small field with coordinates (xl, yl). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.
You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.
A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.
Input
First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell.
The line after the table contains two integers x and y (1 β€ x, y β€ 9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right.
It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable.
Output
Output the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified.
Examples
Input
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... x.. ...
... ... ...
... ... ...
... ... ...
6 4
Output
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... x.. ...
!!! ... ...
!!! ... ...
!!! ... ...
Input
xoo x.. x..
ooo ... ...
ooo ... ...
x.. x.. x..
... ... ...
... ... ...
x.. x.. x..
... ... ...
... ... ...
7 4
Output
xoo x!! x!!
ooo !!! !!!
ooo !!! !!!
x!! x!! x!!
!!! !!! !!!
!!! !!! !!!
x!! x!! x!!
!!! !!! !!!
!!! !!! !!!
Input
o.. ... ...
... ... ...
... ... ...
... xxx ...
... xox ...
... ooo ...
... ... ...
... ... ...
... ... ...
5 5
Output
o!! !!! !!!
!!! !!! !!!
!!! !!! !!!
!!! xxx !!!
!!! xox !!!
!!! ooo !!!
!!! !!! !!!
!!! !!! !!!
!!! !!! !!!
Note
In the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.
In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.
In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable.
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 has a strict daily schedule. He has n alarms set for each day, and the i-th alarm rings each day at the same time during exactly one minute.
Determine the longest time segment when Polycarp can sleep, i. e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in another.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of alarms.
Each of the next n lines contains a description of one alarm. Each description has a format "hh:mm", where hh is the hour when the alarm rings, and mm is the minute of that hour when the alarm rings. The number of hours is between 0 and 23, and the number of minutes is between 0 and 59. All alarm times are distinct. The order of the alarms is arbitrary.
Each alarm starts ringing in the beginning of the corresponding minute and rings for exactly one minute (i. e. stops ringing in the beginning of the next minute). Polycarp can start sleeping instantly when no alarm is ringing, and he wakes up at the moment when some alarm starts ringing.
Output
Print a line in format "hh:mm", denoting the maximum time Polycarp can sleep continuously. hh denotes the number of hours, and mm denotes the number of minutes. The number of minutes should be between 0 and 59. Look through examples to understand the format better.
Examples
Input
1
05:43
Output
23:59
Input
4
22:00
03:21
16:03
09:59
Output
06:37
Note
In the first example there is only one alarm which rings during one minute of a day, and then rings again on the next day, 23 hours and 59 minutes later. Polycarp can sleep all this time.
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.