question large_stringlengths 265 13.2k |
|---|
Solve the programming task below in a Python markdown code block.
First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to).
Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language.
Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match.
Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: <image>, where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.
Input
The only line contains a string s (5 β€ |s| β€ 104) consisting of lowercase English letters.
Output
On the first line print integer k β a number of distinct possible suffixes. On the next k lines print suffixes.
Print suffixes in lexicographical (alphabetical) order.
Examples
Input
abacabaca
Output
3
aca
ba
ca
Input
abaca
Output
0
Note
The first test was analysed in the problem statement.
In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
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.
Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
Input
The first and only line contains two integers x and y (3 β€ y < x β€ 100 000) β the starting and ending equilateral triangle side lengths respectively.
Output
Print a single integer β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
Examples
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
Note
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do <image>.
In the second sample test, Memory can do <image>.
In the third sample test, Memory can do: <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.
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.
There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.
The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.
No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri.
Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.
Input
The first line contains single integer n (1 β€ n β€ 105) β the number of columns.
The next n lines contain the pairs of integers li and ri (1 β€ li, ri β€ 500) β the number of soldiers in the i-th column which start to march from the left or the right leg respectively.
Output
Print single integer k β the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached.
Consider that columns are numbered from 1 to n in the order they are given in the input data.
If there are several answers, print any of them.
Examples
Input
3
5 6
8 9
10 3
Output
3
Input
2
6 5
5 6
Output
1
Input
6
5 9
1 3
4 8
4 5
23 54
12 32
Output
0
Note
In the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg β 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.
If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg β 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.
It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 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.
It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has gi Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving.
Formally, an evolution plan is a permutation f of {1, 2, ..., m}, such that f(x) = y means that a Pokemon of type x evolves into a Pokemon of type y.
The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol.
Two evolution plans f1 and f2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f1(i) β f2(i).
Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109 + 7.
Input
The first line contains two integers n and m (1 β€ n β€ 105, 1 β€ m β€ 106) β the number of gyms and the number of Pokemon types.
The next n lines contain the description of Pokemons in the gyms. The i-th of these lines begins with the integer gi (1 β€ gi β€ 105) β the number of Pokemon in the i-th gym. After that gi integers follow, denoting types of the Pokemons in the i-th gym. Each of these integers is between 1 and m.
The total number of Pokemons (the sum of all gi) does not exceed 5Β·105.
Output
Output the number of valid evolution plans modulo 109 + 7.
Examples
Input
2 3
2 1 2
2 2 3
Output
1
Input
1 3
3 1 2 3
Output
6
Input
2 4
2 1 2
3 2 3 4
Output
2
Input
2 2
3 2 2 1
2 1 2
Output
1
Input
3 7
2 1 2
2 3 4
3 5 6 7
Output
24
Note
In the first case, the only possible evolution plan is:
<image>
In the second case, any permutation of (1, 2, 3) is valid.
In the third case, there are two possible plans:
<image> <image>
In the fourth case, the only possible evolution plan is:
<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.
Thanks to your help, Heidi is confident that no one can fool her. She has now decided to post some fake news on the HC2 Facebook page. However, she wants to be able to communicate to the HC2 committee that the post is fake, using some secret phrase hidden in the post as a subsequence. To make this method foolproof, she wants the phrase to appear n times in the post. She is asking you to design a post (string) s and a hidden phrase p such that p appears in s as a subsequence exactly n times.
Input
The first and only line of input contains a single integer n (1 β€ n β€ 1 000 000).
Output
The output should contain two nonempty strings s and p separated by a single space. Each string should be composed of letters (a-z and A-Z: both lowercase and uppercase are allowed) and have length at most 200. The number of occurrences of p in s as a subsequence should be exactly n. If there are many possible solutions, output any of them. It is guaranteed that at least one solution exists.
Examples
Input
2
Output
hHheidi Hei
Input
4
Output
bbbba ba
Input
6
Output
aaabb ab
Note
An occurrence of p as a subsequence in s should be thought of as a set of positions in s such that the letters at these positions, in order, form p. The number of occurences is thus the number of such sets. For example, ab appears 6 times as a subsequence in aaabb, for the following sets of positions: {1, 4}, {1, 5}, {2, 4}, {2, 5}, {3, 4}, {3, 5} (that is, we should choose one of the a's and one of the b's).
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
You are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters.
Suitability of string s is calculated by following metric:
Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings s, you choose the one with the largest number of non-intersecting occurrences of string t. Suitability is this number of occurrences.
You should replace all '?' characters with small Latin letters in such a way that the suitability of string s is maximal.
Input
The first line contains string s (1 β€ |s| β€ 106).
The second line contains string t (1 β€ |t| β€ 106).
Output
Print string s with '?' replaced with small Latin letters in such a way that suitability of that string is maximal.
If there are multiple strings with maximal suitability then print any of them.
Examples
Input
?aa?
ab
Output
baab
Input
??b?
za
Output
azbz
Input
abcd
abacaba
Output
abcd
Note
In the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2.
In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them.
In the third example there are no '?' characters and the suitability of the string is 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.
Wherever the destination is, whoever we meet, let's render this song together.
On a Cartesian coordinate plane lies a rectangular stage of size w Γ h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.
On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups:
* Vertical: stands at (xi, 0), moves in positive y direction (upwards);
* Horizontal: stands at (0, yi), moves in positive x direction (rightwards).
<image>
According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on.
<image>
Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.
Input
The first line of input contains three space-separated positive integers n, w and h (1 β€ n β€ 100 000, 2 β€ w, h β€ 100 000) β the number of dancers and the width and height of the stage, respectively.
The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 β€ gi β€ 2, 1 β€ pi β€ 99 999, 0 β€ ti β€ 100 000), describing a dancer's group gi (gi = 1 β vertical, gi = 2 β horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 β€ xi β€ w - 1 and 1 β€ yi β€ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.
Output
Output n lines, the i-th of which contains two space-separated integers (xi, yi) β the stopping position of the i-th dancer in the input.
Examples
Input
8 10 8
1 1 10
1 4 13
1 7 1
1 8 2
2 2 0
2 5 14
2 6 0
2 6 1
Output
4 8
10 5
8 8
10 6
10 2
1 8
7 8
10 6
Input
3 2 3
1 1 2
2 1 1
1 1 5
Output
1 3
2 1
1 3
Note
The first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure.
<image>
In the second example, no dancers collide.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor.
The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), β¦, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.
You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?"
Input
The first line contains five integers n, m, c_l, c_e, v (2 β€ n, m β€ 10^8, 0 β€ c_l, c_e β€ 10^5, 1 β€ c_l + c_e β€ m - 1, 1 β€ v β€ n - 1) β the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.
The second line contains c_l integers l_1, β¦, l_{c_l} in increasing order (1 β€ l_i β€ m), denoting the positions of the stairs. If c_l = 0, the second line is empty.
The third line contains c_e integers e_1, β¦, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct.
The fourth line contains a single integer q (1 β€ q β€ 10^5) β the number of queries.
The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 β€ x_1, x_2 β€ n, 1 β€ y_1, y_2 β€ m) β the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i.
Output
Print q integers, one per line β the answers for the queries.
Example
Input
5 6 1 1 3
2
5
3
1 1 5 6
1 3 5 4
3 3 5 3
Output
7
5
4
Note
In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.
In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
You have a set of n distinct positive numbers. You also have m colors. Your colors are labeled from 1 to m. You're also given a list c with m distinct integers.
You paint the numbers according to the following rules:
For each i in order from 1 to m, paint numbers divisible by c[i] with color i.
If multiple rules apply to a number, only the last rule applies.
You sorted your set of numbers and painted them. It turns out that no number was left unpainted. Unfortunately, you lost the set of numbers you had originally. Return the smallest possible value of the maximum number in your set. The input will be constructed such that it's guaranteed there is at least one set of numbers that is consistent with the given information.
Input format
The first line will contain two space separated integers n,m.
The second line will contain m space separated integers. The i-th integer in this line denotes c[i].
The third line will contain n space separated integers. This j-th integer in this line denotes the color of the j-th smallest number in your set.
Output format
Print a single integer on its own line, the minimum possible value of the largest number in your set.
Constraints
For all subtasks:
1 β€ n
1 β€ m
Elements in c will be in strictly increasing order.
1 β€ c[i] β€ 100
Subtask 1 (65 pts):
n β€ 100
m = 2
c[2] is divisible by c[1]
Subtask 2 (25 pts):
n β€ 100,000
m β€ 5
Subtask 3 (10 pts):
n β€ 100,000
m β€ 50
SAMPLE INPUT
6 4
3 6 7 9
1 2 1 1 4 3
SAMPLE OUTPUT
42
Explanation
For the first sample, we have four colors and six numbers in our set. All numbers with color 1 are divisible by 3, but not 6, 7, or 9. All numbers with color 2 are divisible by 6, but not 7 or 9. All numbers with color 3 are divisible by 7 but not 9. All numbers with color 4 are divisible by 9. One example of the original set could have been {3,6,15,33,36,42}.
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.
Hansa is throwing a birthday party. Seeing the extravagant parties thrown by her friends in the past, Hansa too decided to do something unique. Being a Computer Engineer herself, she knew just how to do it. She sent password-protected e-invites to T of her friends. Along with each of those e-invites there would be a number and a string. The number represents the base of the string. Their task was to convert the given string to decimal and add the Sum of Digits of that string which would be the password for that invite.
Help her friends find the password so that they can enjoy the party!
Input:
First line of input is an integer t, the number of test cases. The following t lines would contain an integer and a string separated by a space.
Output:
For each test case, print the sum of digits of the string after changing it to decimal.
Constraints:
1 β€ t β€ 500
2 β€ base β€ 36
1 β€ |string length| β€ 10000
Problem Setter: Rohit Mishra
SAMPLE INPUT
5
27 1
4 3201011
6 5
29 ffarpr
3 1
SAMPLE OUTPUT
1
14
5
49
1
Explanation
Test case #1 - 1 in base-27 means (1 x 27^0) = 1, So, sum of digits is 1
Test case #2 - 3201011 in base-4 means (1 x 4^0) + (1 x 4^1) + (0 x 4^2) + (1 x 4^3) + (0 x 4^4) + (2 x 4^5) + (3 x 4^6) = 144051, So, sum of digits is 14
Test case #3 - 5 in base-6 means (5 x 6^0) = 5, So, sum of digits is 5
Test case #4 - ffarpr in base-29 means (27 x 29^0) + (25 x 29^1) + (27 x 29^2) + (10 x 29^3) + (15 x 29^4) + (15 x 29^5) = 318543799, So, sum of digits is 49
Test case #5 - 1 in base-3 means (1 x 3^0) = 1, So, sum of digits 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.
Gazi is a very talented mathematician, recently he discovered the majestic power of the number '9' so he wants to play a game with you. He tells you to pick any real integer [from 10 to 10^200], then subtract sum of digits of this number from the number itself.
You will get another number, now omit any digit from this number then tell Gazi the final number obtained and he will tell you the number you omitted.
For example: you picked number: 2181
step1) 2181-(2+1+8+1)=2181-12=2169
step2) omit any number from 2169, say 1 i.e,2_69(=final number=F)
tell this number to Gazi and he will give you the number which you omitted in this case '1'. In case the omitted number is '0' or '9' he says "0 or 9".
Gazi don't want to do the calculations again and again so he request you to craft a code to do the same task.
Input
The first line contains number of testcases 't' (1 β€ t β€ 100), second line contains the final number 'F' (10 β€ F<10^200) with a symbol of underscore where you omitted the number.
Output
For each test case, print the omitted number and in case the number comes out to be '0' or '9' print "0 or 9". With a new line at the end of each output.
SAMPLE INPUT
4
4_1
52_2
63_124
25141452_5575
SAMPLE OUTPUT
4
0 or 9
2
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.
Little Shino is interested in the fighting tournaments. Once she went to watch one of the tournaments. There were N fighters and i^{th} fighter will be represented by i. Each fighter has some distinct strength. Rules of the tournament are:
Each fight will have 2 fighters.
In a fight, fighter with more strength will win.
In one round, 1st fighter will fight against 2nd fighter, 3rd fighter will fight against 4th fighter and so on. If there is odd number of fighters, last one will qualify to the next round without fighting.
Input:
First line contains 2 integers, N and Q, number of fighters and number of queries.
Second line contains N space separated integers. k^{th} integer represents the strength of k^{th} fighter.
Next Q line contain one integer i each, denoting Q queries.
Output:
For each query, print the number of fights i^{th} fighter will take part in.
Constraints:
1 β€ N β€ 10^5
1 β€ Q β€ 10^6
1 β€ i β€ N
1 β€ strength\;of\;fighters β€ 10^9
SAMPLE INPUT
5 5
1 2 3 4 5
1
2
3
4
5
SAMPLE OUTPUT
1
2
1
3
1
Explanation
The fights in first round will be between (1, 2) and (3, 4).
From fight between (1, 2), 2 will win and from fight between (3, 4), 4 will win.
Second round will have 3 fighters left. {2, 4, 5}.
In second round there will be one fight between (2, 4) and 4 will win the fight.
Third round will have 2 fighters left. {4, 5}
There will one fight in the third round between (4, 5) and 5 will win in the fight.
Number of fight 1 took part in: 1
Number of fight 2 took part in: 2
Number of fight 3 took part in: 1
Number of fight 4 took part in: 3
Number of fight 5 took part in: 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.
Gandalf the Grey is in trouble as Saurons eye Rearrived in the middle
world. Now he has to prepare for the war, But in order to defeat Sauron
he has to know the power of saurons eye on the day in which he wants to
attack.
According to the Elves(Good Friends of Gandalf),Gandalf came to know that
saurons eye power on current day is equal to 3 time to its power on
previous day minus the power on a day before previous day.
Now Gandalf ask Frodo to give him the power of the Saurons Eye on nth day, but poor Frodo is not
good in mathematics so he ask for help from you.
Given the nth day you have to give Frodo power of Saurons eye on
that day mod 10^9 + 7.
Note You can assume the power of sauron eye is 1 on 1st day
and 3 on 2nd day.
Input
The first line of the input contains an integer T, the number of test cases. Each of the following T lines contains a single integer N
denoting the day for which you have to calculate power of Saurons Eye.
Output
For each test case output a single integer in a separate line, the answer for the corresponding test case.
Constraints
1 β€ T β€ 10000
1 β€ N β€ 10^12SAMPLE INPUT
2
1
3
SAMPLE OUTPUT
1
8
Explanation
First test Case: As indicated in the question power on first day is 1
Second test Case: Answer will be 3*3-1=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.
You are on a game show "Who Wants to Be a Millionaire".The host presents you "N" number of closed doors.There is huge prize behind one door while there are sumo wrestlers behind rest of the doors.Initially you are asked to choose a door.After that the host opens (N-2) doors,revealing sumo wrestlers.The host is omniscient and always reveals sumo wrestlers when he opens the doors. The host then says to you.""Do you want to pick the door you have initially chosen or you want to chose the other closed door?".So it's your decision either stick with your original unopened door or switch to the other unopened door.You are good at maths so you will first calculate the probability of winning the prize by switching from the original selection.
INPUT:
the first line contain number of testcases "T". "T" testcases follows then.Each testcase contains the number of doors "N".
OUTPUT:
for each testcase output the probability of winning the prize by switching from the original selection.output upto 6 places of decimal.
Constraint:
1 β€ T β€ 1000
3 β€ N β€ 1000
SAMPLE INPUT
1
3
SAMPLE OUTPUT
0.666667
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.
1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:
* the dogs numbered 1,2,\cdots,26 were respectively given the names `a`, `b`, ..., `z`;
* the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names `aa`, `ab`, `ac`, ..., `zy`, `zz`;
* the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names `aaa`, `aab`, `aac`, ..., `zzy`, `zzz`;
* the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names `aaaa`, `aaab`, `aaac`, ..., `zzzy`, `zzzz`;
* the dogs numbered 475255,475256,\cdots were respectively given the names `aaaaa`, `aaaab`, ...;
* and so on.
To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:
`a`, `b`, ..., `z`, `aa`, `ab`, ..., `az`, `ba`, `bb`, ..., `bz`, ..., `za`, `zb`, ..., `zz`, `aaa`, `aab`, ..., `aaz`, `aba`, `abb`, ..., `abz`, ..., `zzz`, `aaaa`, ...
Now, Roger asks you:
"What is the name for the dog numbered N?"
Constraints
* N is an integer.
* 1 \leq N \leq 1000000000000001
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer to Roger's question as a string consisting of lowercase English letters.
Examples
Input
2
Output
b
Input
27
Output
aa
Input
123456789
Output
jjddja
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.
Constraints
* All values in input are integers.
* 1 \leq A_{i, j} \leq 100
* A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))
* 1 \leq N \leq 10
* 1 \leq b_i \leq 100
* b_i \neq b_j (i \neq j)
Input
Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N
Output
If we will have a bingo, print `Yes`; otherwise, print `No`.
Examples
Input
84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30
Output
Yes
Input
41 7 46
26 89 2
78 92 8
5
6
45
16
57
17
Output
No
Input
60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34
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.
You have decided to write a book introducing good restaurants. There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i. No two restaurants have the same score.
You want to introduce the restaurants in the following order:
* The restaurants are arranged in lexicographical order of the names of their cities.
* If there are multiple restaurants in the same city, they are arranged in descending order of score.
Print the identification numbers of the restaurants in the order they are introduced in the book.
Constraints
* 1 β€ N β€ 100
* S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.
* 0 β€ P_i β€ 100
* P_i is an integer.
* P_i β P_j (1 β€ i < j β€ N)
Input
Input is given from Standard Input in the following format:
N
S_1 P_1
:
S_N P_N
Output
Print N lines. The i-th line (1 β€ i β€ N) should contain the identification number of the restaurant that is introduced i-th in the book.
Examples
Input
6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40
Output
3
4
6
1
5
2
Input
10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100
Output
10
9
8
7
6
5
4
3
2
1
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December?
Constraints
* 1β€Mβ€23
* M is an integer.
Input
Input is given from Standard Input in the following format:
M
Output
If we have x hours until New Year at M o'clock on 30th, December, print x.
Examples
Input
21
Output
27
Input
12
Output
36
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 word `internationalization` is sometimes abbreviated to `i18n`. This comes from the fact that there are 18 letters between the first `i` and the last `n`.
You are given a string s of length at least 3 consisting of lowercase English letters. Abbreviate s in the same way.
Constraints
* 3 β€ |s| β€ 100 (|s| denotes the length of s.)
* s consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
Output
Print the abbreviation of s.
Examples
Input
internationalization
Output
i18n
Input
smiles
Output
s4s
Input
xyz
Output
x1z
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.
AtCoDeer the deer recently bought three paint cans. The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c. Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.
Since he is forgetful, he might have bought more than one paint can in the same color. Count the number of different kinds of colors of these paint cans and tell him.
Constraints
* 1β¦a,b,cβ¦100
Input
The input is given from Standard Input in the following format:
a b c
Output
Print the number of different kinds of colors of the paint cans.
Examples
Input
3 1 4
Output
3
Input
3 3 33
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.
Let p (i) be the i-th prime number from the smallest. For example, 7 is the fourth prime number from the smallest, 2, 3, 5, 7, so p (4) = 7.
Given n, the sum of p (i) from i = 1 to n s
s = p (1) + p (2) + .... + p (n)
Create a program that outputs. For example, when n = 9, s = 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 = 100.
Input
Given multiple datasets. Each dataset is given the integer n (n β€ 10000). When n is 0, it is the last input. The number of datasets does not exceed 50.
Output
For n in each dataset, print s on one line.
Example
Input
2
9
0
Output
5
100
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Consider a tic-tac-toe on a 3x3 board. Tic-tac-toe is a two-player battle game. Decide the first attack and the second attack, one hits Kuroishi and one hits Shiraishi. The winner is the person who puts stones one by one on the board alternately and arranges three of his own stones first in either the vertical, horizontal, or diagonal direction.
Create a program that inputs the information on the board, judges the victory or defeat, outputs "b" if black wins, "w" if white wins, and "NA" if neither is available. please. The board information consists of 3 rows and 3 columns of character strings. "B" is Kuroishi, "w" is Shiraishi, and "+" (half-width plus) is nothing. However, three blacks and three whites cannot be lined up at the same time.
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:
board1
board2
board3
The i-line is given the string boardi that represents the information on the i-th line of the board.
The number of datasets does not exceed 50.
Output
Outputs "b", "w", or "NA" on one line for each data set.
Example
Input
bbw
wbw
+b+
bwb
wbw
wbw
0
Output
b
NA
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Ordinary Jigsaw puzzles are solved with visual hints; players solve a puzzle with the picture which the puzzle shows on finish, and the diverse patterns of pieces. Such Jigsaw puzzles may be suitable for human players, because they require abilities of pattern recognition and imagination.
On the other hand, "Jigsaw puzzles" described below may be just the things for simple-minded computers.
As shown in Figure 1, a puzzle is composed of nine square pieces, and each of the four edges of a piece is labeled with one of the following eight symbols:
"R", "G", "B", "W", "r", "g", "b", and "w".
<image>
---
Figure 1: The nine pieces of a puzzle
In a completed puzzle, the nine pieces are arranged in a 3 x 3 grid, and each of the 12 pairs of edges facing each other must be labeled with one of the following four combinations of symbols:
"R" with "r", "G" with "g", "B" with "b", and "W" with "w".
For example, an edge labeled "R" can only face an edge with "r". Figure 2 is an example of a completed state of a puzzle. In the figure, edges under this restriction are indicated by shadowing their labels. The player can freely move and rotate the pieces, but cannot turn them over. There are no symbols on the reverse side of a piece !
<image>
---
Figure 2: A completed puzzle example
Each piece is represented by a sequence of the four symbols on the piece, starting with the symbol of the top edge, followed by the symbols of the right edge, the bottom edge, and the left edge. For example, gwgW represents the leftmost piece in Figure 1. Note that the same piece can be represented as wgWg, gWgw or Wgwg since you can rotate it in 90, 180 or 270 degrees.
The mission for you is to create a program which counts the number of solutions. It is needless to say that these numbers must be multiples of four, because, as shown in Figure 3, a configuration created by rotating a solution in 90, 180 or 270 degrees is also a solution.
<image>
---
Figure 3: Four obvious variations for a completed puzzle
A term "rotationally equal" is defined; if two different pieces are identical when one piece is rotated (in 90, 180 or 270 degrees), they are rotationally equal. For example, WgWr and WrWg are rotationally equal.
Another term "rotationally symmetric" is defined; if a piece is rotationally equal to itself, it is rotationally symmetric. For example, a piece gWgW is rotationally symmetric.
Given puzzles satisfy the following three conditions:
1. There is no identical pair of pieces in a puzzle.
2. There is no rotationally equal pair of pieces in a puzzle.
3. There is no rotationally symmetric piece in a puzzle.
Input
The input consists of multiple puzzles.
N
Puzzle1
Puzzle2
. . .
PuzzleN
N is the number of puzzles. Each Puzzlei gives a puzzle with a single line of 44 characters, consisting of four-character representations of the nine pieces of the puzzle, separated by a space character. For example, the following line represents the puzzle in Figure 1.
gwgW RBbW GWrb GRRb BWGr Rbgw rGbR gBrg GRwb
Output
For each Puzzlei , the number of its solutions should be the output, each in a separate line.
Example
Input
6
WwRR wwrg RRGb rGBG RGrb RrRg RGrg rgBB Wrgr
RrGb WWGR rGgb Wbrg wgBb GgBg WbBG Wwwg WWGG
RBbr Wrbr wGGG wggR WgGR WBWb WRgB wBgG WBgG
wBrg rGgb WRrB WWbw wRRB RbbB WRrb wrbb WgrG
WrwB WWww wRRB WGGb Wbbg WBgG WrbG Wrww RBgg
WWgg RBrr Rggr RGBg Wbgr WGbg WBbr WGWB GGGg
Output
40
8
32
4
12
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.
Emergency Evacuation
The Japanese government plans to increase the number of inbound tourists to forty million in the year 2020, and sixty million in 2030. Not only increasing touristic appeal but also developing tourism infrastructure further is indispensable to accomplish such numbers.
One possible enhancement on transport is providing cars extremely long and/or wide, carrying many passengers at a time. Too large a car, however, may require too long to evacuate all passengers in an emergency. You are requested to help estimating the time required.
The car is assumed to have the following seat arrangement.
* A center aisle goes straight through the car, directly connecting to the emergency exit door at the rear center of the car.
* The rows of the same number of passenger seats are on both sides of the aisle.
A rough estimation requested is based on a simple step-wise model. All passengers are initially on a distinct seat, and they can make one of the following moves in each step.
* Passengers on a seat can move to an adjacent seat toward the aisle. Passengers on a seat adjacent to the aisle can move sideways directly to the aisle.
* Passengers on the aisle can move backward by one row of seats. If the passenger is in front of the emergency exit, that is, by the rear-most seat rows, he/she can get off the car.
The seat or the aisle position to move to must be empty; either no other passenger is there before the step, or the passenger there empties the seat by moving to another position in the same step. When two or more passengers satisfy the condition for the same position, only one of them can move, keeping the others wait in their original positions.
The leftmost figure of Figure C.1 depicts the seat arrangement of a small car given in Sample Input 1. The car have five rows of seats, two seats each on both sides of the aisle, totaling twenty. The initial positions of seven passengers on board are also shown.
The two other figures of Figure C.1 show possible positions of passengers after the first and the second steps. Passenger movements are indicated by fat arrows. Note that, two of the passengers in the front seat had to wait for a vacancy in the first step, and one in the second row had to wait in the next step.
Your task is to write a program that gives the smallest possible number of steps for all the passengers to get off the car, given the seat arrangement and passengers' initial positions.
<image>
Figure C.1
Input
The input consists of a single test case of the following format.
$r$ $s$ $p$
$i_1$ $j_1$
...
$i_p$ $j_p$
Here, $r$ is the number of passenger seat rows, $s$ is the number of seats on each side of the aisle, and $p$ is the number of passengers. They are integers satisfying $1 \leq r \leq 500$, $1 \leq s \leq 500$, and $1 \leq p \leq 2rs$.
The following $p$ lines give initial seat positions of the passengers. The $k$-th line with $i_k$ and $j_k$ means that the $k$-th passenger's seat is in the $i_k$-th seat row and it is the $j_k$-th seat on that row. Here, rows and seats are counted from front to rear and left to right, both starting from one. They satisfy $1 \leq i_k \leq r$ and $1 \leq j_k \leq 2s$. Passengers are on distinct seats, that is, $i_k \ne= i_l$ or $j_k \ne j_l$ holds if $k \ne l$.
Output
The output should be one line containing a single integer, the minimum number of steps required for all the passengers to get off the car.
Sample Input 1
5 2 7
1 1
1 2
1 3
2 3
2 4
4 4
5 2
Sample Output 1
9
Sample Input 2
500 500 16
1 1
1 2
1 999
1 1000
2 1
2 2
2 999
2 1000
3 1
3 2
3 999
3 1000
499 500
499 501
499 999
499 1000
Sample Output 2
1008
Example
Input
5 2 7
1 1
1 2
1 3
2 3
2 4
4 4
5 2
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.
Almost Identical Programs
The programming contest named Concours de Programmation Comtemporaine Interuniversitaire (CPCI) has a judging system similar to that of ICPC; contestants have to submit correct outputs for two different inputs to be accepted as a correct solution. Each of the submissions should include the program that generated the output. A pair of submissions is judged to be a correct solution when, in addition to the correctness of the outputs, they include an identical program.
Many contestants, however, do not stop including a different version of their programs in their second submissions, after modifying a single string literal in their programs representing the input file name, attempting to process different input. The organizers of CPCI are exploring the possibility of showing a special error message for such close submissions, indicating contestants what's wrong with such submissions. Your task is to detect such close submissions.
Input
The input consists of at most 100 datasets, each in the following format.
s1
s2
Each of s1 and s2 is a string written in a line, with the length between 1 and 200, inclusive. They are the first and the second submitted programs respectively. A program consists of lowercase letters (`a`, `b`, ..., `z`), uppercase letters (`A`, `B`, ..., `Z`), digits (`0`, `1`, ..., `9`), double quotes (`"`), and semicolons (`;`). When double quotes occur in a program, there are always even number of them.
The end of the input is indicated by a line containing one '`.`' (period).
Output
For each dataset, print the judge result in a line.
If the given two programs are identical, print `IDENTICAL`. If two programs differ with only one corresponding string literal, print `CLOSE`. Otherwise, print `DIFFERENT`. A string literal is a possibly empty sequence of characters between an odd-numbered occurrence of a double quote and the next occurrence of a double quote.
Sample Input
print"hello";print123
print"hello";print123
read"B1input";solve;output;
read"B2";solve;output;
read"C1";solve;output"C1ans";
read"C2";solve;output"C2ans";
""""""""
"""42"""""
slow"program"
fast"code"
"super"fast"program"
"super"faster"program"
X""
X
I"S""CREAM"
I"CE""CREAM"
11"22"11
1"33"111
.
Output for the Sample Input
IDENTICAL
CLOSE
DIFFERENT
CLOSE
DIFFERENT
DIFFERENT
DIFFERENT
CLOSE
DIFFERENT
Example
Input
print"hello";print123
print"hello";print123
read"B1input";solve;output;
read"B2";solve;output;
read"C1";solve;output"C1ans";
read"C2";solve;output"C2ans";
""""""""
"""42"""""
slow"program"
fast"code"
"super"fast"program"
"super"faster"program"
X""
X
I"S""CREAM"
I"CE""CREAM"
11"22"11
1"33"111
.
Output
IDENTICAL
CLOSE
DIFFERENT
CLOSE
DIFFERENT
DIFFERENT
DIFFERENT
CLOSE
DIFFERENT
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 D: Legendary Sword
* This problem contains a lot of two ingredients in the kitchen. Please be careful about heartburn.
The Demon King, who has finally revived, is about to invade the human world to wrap the world in darkness again.
The Demon King decided to destroy the legendary sword first before launching a full-scale invasion. In the last war, the Demon King was defeated by a brave man with a legendary sword. Since the Demon King's body is protected by a dark robe, a half-hearted attack cannot hurt the Demon King. However, the legendary sword can easily penetrate even the dark robe of the Demon King with the blessing of the gods. Therefore, in order to win this war, it is necessary to obtain and destroy the legendary sword.
After investigation, it was found that the legendary sword was enshrined in the innermost part of a certain ruin, waiting for the next hero to appear. The legendary sword is sealed by a myriad of jewels scattered around it to prevent it from being robbed by the evil ones and bandits. The Demon King has powerful magical power, so you can destroy the jewels just by touching them. However, the jewel seal has a multi-layered structure, and it is necessary to destroy it in order from the surface layer. For example, even if you touch the jewels of the second and subsequent seals before destroying the jewels of the first seal, you cannot destroy them. Also, multiple jewels may form the same seal, but the Demon King can destroy the seal at the same time by touching one of them.
The ruins are full of sacred power, and ordinary monsters cannot even enter. Therefore, the Demon King himself went to collect the legendary sword. No matter how much the Demon King is, if you continue to receive that power for a long time, it will not be free. Your job as the Demon King's right arm is to seek the time it takes for the Demon King to break all the seals and reach under the legendary sword, just in case.
Input
The input consists of multiple datasets, and the end of the input is a line of two zeros separated by spaces. The total number of datasets is 50 or less. Each dataset has the following format:
w h
s (1,1) ... s (1, w)
s (2,1) ... s (2, w)
...
s (h, 1) ... s (h, w)
w and h are integers indicating the width and height of the matrix data representing the floor of the ruins, respectively, and it can be assumed that 1 β€ w and h β€ 100, respectively, and 2 β€ w + h β€ 100. Each of the following h lines is composed of w characters separated by a space, and the character s (y, x) indicates the state of the point at the coordinate (y, x).
The meaning is as follows.
* S: The point where the Demon King is first. There is always only one on the floor.
* G: The point of the legendary sword. There is always only one.
* .:Nothing.
* Number: The point where the jewel is located. The numbers indicate the seal numbers that make up the seal. The numbers are integers of 1 or more, and there may be no omissions in the numbers in between.
In addition, the Demon King can move to adjacent coordinates on the floor of the ruins, up, down, left, and right, and the time required for that movement is 1. It doesn't take long to destroy a jewel because it can be destroyed just by touching it.
Output
For each dataset, output the shortest time it takes for the Demon King to break all the seals and reach the legendary sword.
Sample Input
10 10
S .. .. .. .. ..
.. .. .. .. .. ..
.. .. 1 .. .. ..
.. .. .. .. .. ..
.. .. .. .. .. ..
.. .. .. .. 3 ..
.. .. .. .. .. ..
. . . . . Four . . . .
.. .. .. .. .. ..
2 .. .. .. .. G
10 10
S .. .. .3 .. ..
.. 3 .. .. .. ..
.. .. 1 .. .. ..
. . . . . . Four . . .
.. 3 .. .1 .. ..
.. .. .. .. 3 ..
.. .. .. .. .. ..
. . . . . Four . . . .
. . . . . Five . . . .
2 .. .. .. .. G
10 10
S .. .. .. .. 1
. . . . . Five . . . .
. Four . . . . . . . .
.. .. 8 .9 .. ..
. . . . Ten . . . . .
.. 7 .G .. .. ..
.. .11 .. .. .. ..
3 .. .. .. .. 6
.. .. .. .. 2 ..
.. .. .. .. .. ..
0 0
Output for Sample Input
38
36
71
Example
Input
10 10
S . . . . . . . . .
. . . . . . . . . .
. . . . 1 . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . 3 . .
. . . . . . . . . .
. . . . . 4 . . . .
. . . . . . . . . .
2 . . . . . . . . G
10 10
S . . . . . 3 . . .
. . 3 . . . . . . .
. . . . 1 . . . . .
. . . . . . 4 . . .
. . 3 . . . 1 . . .
. . . . . . . 3 . .
. . . . . . . . . .
. . . . . 4 . . . .
. . . . . 5 . . . .
2 . . . . . . . . G
10 10
S . . . . . . . . 1
. . . . . 5 . . . .
. 4 . . . . . . . .
. . . . 8 . 9 . . .
. . . . 10 . . . . .
. . 7 . G . . . . .
. . . 11 . . . . . .
3 . . . . . . . . 6
. . . . . . . 2 . .
. . . . . . . . . .
0 0
Output
38
36
71
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.
FizzBuzz is a game in which integers of 1 or more are spoken in order according to the following rules.
* "Fizz" when divisible by 3
* "Buzz" when divisible by 5
* "FizzBuzz" when divisible by both 3 and 5
* At other times, that number
An example of the progress of the game is shown below.
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,β¦
The character string obtained by combining the obtained remarks into one character string is called FizzBuzz String. Since the index s is given, output 20 characters from the s character of the FizzBuzz String. However, the index may start from 1, and the length of the obtained character string may be sufficiently large (s + 20 or more).
Constraints
* s is an integer
* 1 β€ s β€ 1018
Input
Input is given in the following format
> s
>
Output
Output 20 characters from the s character of FizzBuzz String on one line
Examples
Input
1
Output
12Fizz4BuzzFizz78Fiz
Input
20
Output
zzBuzz11Fizz1314Fizz
Input
10000000000
Output
93FizzBuzz1418650796
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Problem Statement
You want to compete in ICPC (Internet Contest of Point Collection). In this contest, we move around in $N$ websites, numbered $1$ through $N$, within a time limit and collect points as many as possible. We can start and end on any website.
There are $M$ links between the websites, and we can move between websites using these links. You can assume that it doesn't take time to move between websites. These links are directed and websites may have links to themselves.
In each website $i$, there is an advertisement and we can get $p_i$ point(s) by watching this advertisement in $t_i$ seconds. When we start on or move into a website, we can decide whether to watch the advertisement or not. But we cannot watch the same advertisement more than once before using any link in the website, while we can watch it again if we have moved among websites and returned to the website using one or more links, including ones connecting a website to itself. Also we cannot watch the advertisement in website $i$ more than $k_i$ times.
You want to win this contest by collecting as many points as you can. So you decided to compute the maximum points that you can collect within $T$ seconds.
Input
The input consists of multiple datasets. The number of dataset is no more than $60$.
Each dataset is formatted as follows.
> $N$ $M$ $T$
> $p_1$ $t_1$ $k_1$
> :
> :
> $p_N$ $t_N$ $k_N$
> $a_1$ $b_1$
> :
> :
> $a_M$ $b_M$
The first line of each dataset contains three integers $N$ ($1 \le N \le 100$), $M$ ($0 \le M \le 1{,}000$) and $T$ ($1 \le T \le 10{,}000$), which denote the number of websites, the number of links, and the time limit, respectively. All the time given in the input is expressed in seconds.
The following $N$ lines describe the information of advertisements. The $i$-th of them contains three integers $p_i$ ($1 \le p_i \le 10{,}000$), $t_i$ ($1 \le t_i \le 10{,}000$) and $k_i$ ($1 \le k_i \le 10{,}000$), which denote the points of the advertisement, the time required to watch the advertisement, and the maximum number of times you can watch the advertisement in website $i$, respectively.
The following $M$ lines describe the information of links. Each line contains two integers $a_i$ and $b_i$ ($1 \le a_i,b_i \le N$), which mean that we can move from website $a_i$ to website $b_i$ using a link.
The end of input is indicated by a line containing three zeros.
Output
For each dataset, output the maximum points that you can collect within $T$ seconds.
Sample Input
5 4 10
4 3 1
6 4 3
3 2 4
2 2 1
8 5 3
1 2
2 3
3 4
4 5
3 3 1000
1000 1 100
1 7 100
10 9 100
1 2
2 3
3 2
1 0 5
25 25 2
1 0 25
25 25 2
5 5 100
1 1 20
1 1 20
10 1 1
10 1 1
10 1 1
1 2
2 1
3 4
4 5
5 3
3 3 100
70 20 10
50 15 20
90 10 10
1 2
2 2
2 3
0 0 0
Output for the Sample Input
15
2014
0
25
40
390
Example
Input
5 4 10
4 3 1
6 4 3
3 2 4
2 2 1
8 5 3
1 2
2 3
3 4
4 5
3 3 1000
1000 1 100
1 7 100
10 9 100
1 2
2 3
3 2
1 0 5
25 25 2
1 0 25
25 25 2
5 5 100
1 1 20
1 1 20
10 1 1
10 1 1
10 1 1
1 2
2 1
3 4
4 5
5 3
3 3 100
70 20 10
50 15 20
90 10 10
1 2
2 2
2 3
0 0 0
Output
15
2014
0
25
40
390
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.
B: Pivots
problem
Given a permutation of length N, a_1, a_2, ..., a_N, which is a permutation of integers from 1 to N. Also, Q queries are given in order for this permutation. In the i-th query, you have to do the following:
* The value q_i (1 \ leq q_i \ leq N) is given. In the permutation \\ {a_1, a_2, ..., a_N \\}, where L is the permutation on the left side of q_i and R is the permutation on the right side of q_i, the original permutation L \\ q_i \\ R is R \\ Change to q_i \\ L. That is, when q_ {i} = a_j, the permutations \\ {a_1, ..., a_ {j-1}, a_j, a_ {j + 1}, ..., a_N \\} are \\ { Change to a_ {j + 1}, ..., a_N, a_j, a_1, ..., a_ {j-1} \\}.
The permutations L and R may be empty. For example, if L is empty, change q_i \\ R to R \\ q_i. The same is true when R is empty.
Output the permutation after processing these Q queries in order for the given permutation on one line.
Input format
N Q
a_1 a_2 ... a_N
q_1 q_2 ... q_Q
All inputs are integers.
The first row gives the number of elements in the permutation N and the number of queries Q, separated by blanks. In the second line, permutations a_1, a_2, ..., a_N, in which integers from 1 to N are rearranged, are given separated by blanks. The third line gives Q queries, separated by blanks. q_i represents the i-th query.
Constraint
* 1 \ leq N \ leq 10 ^ 5
* 1 \ leq Q \ leq 10 ^ 5
* 1 \ leq a_i \ leq N
* a_i is different
* 1 \ leq q_i \ leq N
Output format
Output the permutation after processing all the queries in order on one line.
Input example 1
5 2
1 5 3 2 4
5 2
Output example 1
4 5 1 2 3
* The first query changes the permutation to \\ {3, 2, 4, 5, 1 \\}.
* The second query changes the permutation to \\ {4, 5, 1, 2, 3 \\}.
Input example 2
5 1
1 2 3 4 5
Five
Output example 2
5 1 2 3 4
Example
Input
5 2
1 5 3 2 4
5 2
Output
4 5 1 2 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.
Recently, chef Ciel often hears about lucky numbers.
Everybody knows that lucky numbers are positive integers
whose decimal representation contains only the lucky digits 4 and 7.
For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Ciel decides to make Ciel numbers.
As you know, Ciel likes the digit 8 very much.
And then, Ciel likes the digits 5 and 3.
So Ciel defines Ciel numbers as the positive integers k such that d(k, 8) β₯ d(k, 5) β₯ d(k, 3) and d(k, i) = 0 for all i = 0, 1, 2, 4, 6, 7, 9,
where d(k, i) denotes the number of the digit i in the decimal representation of the integer k.
For example, the first few Ciel numbers are 8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888, ....
Ciel's restaurant has N menus.
And Ciel want to know how many menus have Ciel numbers as their price.
Your task is to find it.
Input
The first line contains an integer N.
Then N lines follow.
Each line has the name Si of the menu and its price Pi separated by a single space.
Output
Print the number of menus whose prices are one of Ciel numbers.
Constraints
1 β€ N β€ 1000
1 β€ |Si| β€ 100, where |Si| denotes the length of Si
Each letter of Si is either an alphabetical letter or a digit or a single quotation mark or a space.
1 β€ Pi < 1000000 (10^6)
Pi contains no leading zeros.
Sample Input
6
milk 58
Ciel's Drink 80
The curry 2nd edition 888888
rice omelet 85855
unagi 1
The first and last letters can be a space 358
Sample Output
3
Output details
58 and 888888 and 358 are Ciel numbers.
80 and 85855 and 1 are not Ciel numbers.
Notes
Different operating systems have different ways of representing a newline; do not assume one particular way will be used.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can permute it so that it becomes [20, 40, 10, 30]. Then on the first and the second positions the integers became larger (20>10, 40>20) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals 2. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the elements of the array.
Output
Print a single integer β the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
Examples
Input
7
10 1 1 1 5 5 3
Output
4
Input
5
1 1 1 1 1
Output
0
Note
In the first sample, one of the best permutations is [1, 5, 5, 3, 10, 1, 1]. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into wΓ h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one β 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings should consist of all bordering cells on the inner rectangle of size (w - 4(i - 1))Γ(h - 4(i - 1)).
<image> The picture corresponds to the third example.
Your task is to compute the number of cells to be gilded.
Input
The only line contains three integers w, h and k (3 β€ w, h β€ 100, 1 β€ k β€ \leftβ (min(n, m) + 1)/(4)\rightβ, where β x β denotes the number x rounded down) β the number of rows, columns and the number of rings, respectively.
Output
Print a single positive integer β the number of cells to be gilded.
Examples
Input
3 3 1
Output
8
Input
7 9 1
Output
28
Input
7 9 2
Output
40
Note
The first example is shown on the picture below.
<image>
The second example is shown on the picture below.
<image>
The third example is shown in the problem description.
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.
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha).
The house has a staircase and an elevator. If Masha uses the stairs, it takes t_1 seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in t_2 seconds. The elevator moves with doors closed. The elevator spends t_3 seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor.
Coming out of the apartment on her floor, Masha noticed that the elevator is now on the floor z and has closed doors. Now she has to choose whether to use the stairs or use the elevator.
If the time that Masha needs to get to the Egor's floor by the stairs is strictly less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator.
Help Mary to understand whether to use the elevator or the stairs.
Input
The only line contains six integers x, y, z, t_1, t_2, t_3 (1 β€ x, y, z, t_1, t_2, t_3 β€ 1000) β the floor Masha is at, the floor Masha wants to get to, the floor the elevator is located on, the time it takes Masha to pass between two floors by stairs, the time it takes the elevator to pass between two floors and the time it takes for the elevator to close or open the doors.
It is guaranteed that x β y.
Output
If the time it will take to use the elevator is not greater than the time it will take to use the stairs, print Β«YESΒ» (without quotes), otherwise print Β«NO> (without quotes).
You can print each letter in any case (upper or lower).
Examples
Input
5 1 4 4 2 1
Output
YES
Input
1 6 6 2 1 1
Output
NO
Input
4 1 7 4 1 2
Output
YES
Note
In the first example:
If Masha goes by the stairs, the time she spends is 4 β
4 = 16, because she has to go 4 times between adjacent floors and each time she spends 4 seconds.
If she chooses the elevator, she will have to wait 2 seconds while the elevator leaves the 4-th floor and goes to the 5-th. After that the doors will be opening for another 1 second. Then Masha will enter the elevator, and she will have to wait for 1 second for the doors closing. Next, the elevator will spend 4 β
2 = 8 seconds going from the 5-th floor to the 1-st, because the elevator has to pass 4 times between adjacent floors and spends 2 seconds each time. And finally, it will take another 1 second before the doors are open and Masha can come out.
Thus, all the way by elevator will take 2 + 1 + 1 + 8 + 1 = 13 seconds, which is less than 16 seconds, so Masha has to choose the elevator.
In the second example, it is more profitable for Masha to use the stairs, because it will take 13 seconds to use the elevator, that is more than the 10 seconds it will takes to go by foot.
In the third example, the time it takes to use the elevator is equal to the time it takes to walk up by the stairs, and is equal to 12 seconds. That means Masha will take the elevator.
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 of n lowercase Latin letters.
You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.
String s = s_1 s_2 ... s_n is lexicographically smaller than string t = t_1 t_2 ... t_m if n < m and s_1 = t_1, s_2 = t_2, ..., s_n = t_n or there exists a number p such that p β€ min(n, m) and s_1 = t_1, s_2 = t_2, ..., s_{p-1} = t_{p-1} and s_p < t_p.
For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z".
Input
The first line of the input contains one integer n (2 β€ n β€ 2 β
10^5) β the length of s.
The second line of the input contains exactly n lowercase Latin letters β the string s.
Output
Print one string β the smallest possible lexicographically string that can be obtained by removing at most one character from the string s.
Examples
Input
3
aaa
Output
aa
Input
5
abcda
Output
abca
Note
In the first example you can remove any character of s to obtain the string "aa".
In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda".
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.
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β D, Clubs β C, Spades β S, or Hearts β H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).
At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.
In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.
Input
The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.
Each string is two characters long. The first character denotes the rank and belongs to the set \{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}. The second character denotes the suit and belongs to the set \{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}.
All the cards in the input are different.
Output
If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Examples
Input
AS
2H 4C TH JH AD
Output
YES
Input
2H
3D 4C AC KD AS
Output
NO
Input
4D
AS AC AD AH 5H
Output
YES
Note
In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.
In the second example, you cannot play any card.
In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
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.
Tanya has n candies numbered from 1 to n. The i-th candy has the weight a_i.
She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.
Your task is to find the number of such candies i (let's call these candies good) that if dad gets the i-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.
For example, n=4 and weights are [1, 4, 3, 3]. Consider all possible cases to give a candy to dad:
* Tanya gives the 1-st candy to dad (a_1=1), the remaining candies are [4, 3, 3]. She will eat a_2=4 in the first day, a_3=3 in the second day, a_4=3 in the third day. So in odd days she will eat 4+3=7 and in even days she will eat 3. Since 7 β 3 this case shouldn't be counted to the answer (this candy isn't good).
* Tanya gives the 2-nd candy to dad (a_2=4), the remaining candies are [1, 3, 3]. She will eat a_1=1 in the first day, a_3=3 in the second day, a_4=3 in the third day. So in odd days she will eat 1+3=4 and in even days she will eat 3. Since 4 β 3 this case shouldn't be counted to the answer (this candy isn't good).
* Tanya gives the 3-rd candy to dad (a_3=3), the remaining candies are [1, 4, 3]. She will eat a_1=1 in the first day, a_2=4 in the second day, a_4=3 in the third day. So in odd days she will eat 1+3=4 and in even days she will eat 4. Since 4 = 4 this case should be counted to the answer (this candy is good).
* Tanya gives the 4-th candy to dad (a_4=3), the remaining candies are [1, 4, 3]. She will eat a_1=1 in the first day, a_2=4 in the second day, a_3=3 in the third day. So in odd days she will eat 1+3=4 and in even days she will eat 4. Since 4 = 4 this case should be counted to the answer (this candy is good).
In total there 2 cases which should counted (these candies are good), so the answer is 2.
Input
The first line of the input contains one integer n (1 β€ n β€ 2 β
10^5) β the number of candies.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^4), where a_i is the weight of the i-th candy.
Output
Print one integer β the number of such candies i (good candies) that if dad gets the i-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.
Examples
Input
7
5 5 4 5 5 5 6
Output
2
Input
8
4 8 8 7 8 4 4 5
Output
2
Input
9
2 3 4 2 2 3 2 2 4
Output
3
Note
In the first example indices of good candies are [1, 2].
In the second example indices of good candies are [2, 3].
In the third example indices of good candies are [4, 5, 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.
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.
Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1 β€ t β€ 25) β the number of queries. Then t queries follow.
The first line of the query contains one integer n (1 β€ n β€ 300) β the number of divisors in the list.
The second line of the query contains n integers d_1, d_2, ..., d_n (2 β€ d_i β€ 10^6), where d_i is the i-th divisor of the guessed number. It is guaranteed that all values d_i are distinct.
Output
For each query print the answer to it.
If the input data in the query is contradictory and it is impossible to find such number x that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible x.
Example
Input
2
8
8 2 12 6 4 24 16 3
1
2
Output
48
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 uppercase Latin letters 'A' and b letters 'B'.
The period of the string is the smallest such positive integer k that s_i = s_{i~mod~k} (0-indexed) for each i. Note that this implies that k won't always divide a+b = |s|.
For example, the period of string "ABAABAA" is 3, the period of "AAAA" is 1, and the period of "AABBB" is 5.
Find the number of different periods over all possible strings with a letters 'A' and b letters 'B'.
Input
The first line contains two integers a and b (1 β€ a, b β€ 10^9) β the number of letters 'A' and 'B', respectively.
Output
Print the number of different periods over all possible strings with a letters 'A' and b letters 'B'.
Examples
Input
2 4
Output
4
Input
5 3
Output
5
Note
All the possible periods for the first example:
* 3 "BBABBA"
* 4 "BBAABB"
* 5 "BBBAAB"
* 6 "AABBBB"
All the possible periods for the second example:
* 3 "BAABAABA"
* 5 "BAABABAA"
* 6 "BABAAABA"
* 7 "BAABAAAB"
* 8 "AAAAABBB"
Note that these are not the only possible strings for the given periods.
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 loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 β€ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all.
You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations.
Input
The first line contains two integers n and k (1 β€ n β€ 105, 0 β€ k β€ 109) β the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero.
Output
In the single line print the result without spaces β the number after the k operations are fulfilled.
Examples
Input
7 4
4727447
Output
4427477
Input
4 2
4478
Output
4478
Note
In the first sample the number changes in the following sequence: 4727447 β 4427447 β 4427477 β 4427447 β 4427477.
In the second sample: 4478 β 4778 β 4478.
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 chips arranged in a circle, numbered from 1 to n.
Initially each chip has black or white color. Then k iterations occur. During each iteration the chips change their colors according to the following rules. For each chip i, three chips are considered: chip i itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip i becomes white. Otherwise, the chip i becomes black.
Note that for each i from 2 to (n - 1) two neighbouring chips have numbers (i - 1) and (i + 1). The neighbours for the chip i = 1 are n and 2. The neighbours of i = n are (n - 1) and 1.
The following picture describes one iteration with n = 6. The chips 1, 3 and 4 are initially black, and the chips 2, 5 and 6 are white. After the iteration 2, 3 and 4 become black, and 1, 5 and 6 become white.
<image>
Your task is to determine the color of each chip after k iterations.
Input
The first line contains two integers n and k (3 β€ n β€ 200 000, 1 β€ k β€ 10^{9}) β the number of chips and the number of iterations, respectively.
The second line contains a string consisting of n characters "W" and "B". If the i-th character is "W", then the i-th chip is white initially. If the i-th character is "B", then the i-th chip is black initially.
Output
Print a string consisting of n characters "W" and "B". If after k iterations the i-th chip is white, then the i-th character should be "W". Otherwise the i-th character should be "B".
Examples
Input
6 1
BWBBWW
Output
WBBBWW
Input
7 3
WBWBWBW
Output
WWWWWWW
Input
6 4
BWBWBW
Output
BWBWBW
Note
The first example is described in the statement.
The second example: "WBWBWBW" β "WWBWBWW" β "WWWBWWW" β "WWWWWWW". So all chips become white.
The third example: "BWBWBW" β "WBWBWB" β "BWBWBW" β "WBWBWB" β "BWBWBW".
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.
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the i-th daughter receives a necklace with brightness x_i and a bracelet with brightness y_i, then the sums x_i + y_i should be pairwise distinct. Help Kuroni to distribute the gifts.
For example, if the brightnesses are a = [1, 7, 5] and b = [6, 1, 2], then we may distribute the gifts as follows:
* Give the third necklace and the first bracelet to the first daughter, for a total brightness of a_3 + b_1 = 11.
* Give the first necklace and the third bracelet to the second daughter, for a total brightness of a_1 + b_3 = 3.
* Give the second necklace and the second bracelet to the third daughter, for a total brightness of a_2 + b_2 = 8.
Here is an example of an invalid distribution:
* Give the first necklace and the first bracelet to the first daughter, for a total brightness of a_1 + b_1 = 7.
* Give the second necklace and the second bracelet to the second daughter, for a total brightness of a_2 + b_2 = 8.
* Give the third necklace and the third bracelet to the third daughter, for a total brightness of a_3 + b_3 = 7.
This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!
Input
The input consists of multiple test cases. The first line contains an integer t (1 β€ t β€ 100) β the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (1 β€ n β€ 100) β the number of daughters, necklaces and bracelets.
The second line of each test case contains n distinct integers a_1, a_2, ..., a_n (1 β€ a_i β€ 1000) β the brightnesses of the necklaces.
The third line of each test case contains n distinct integers b_1, b_2, ..., b_n (1 β€ b_i β€ 1000) β the brightnesses of the bracelets.
Output
For each test case, print a line containing n integers x_1, x_2, ..., x_n, representing that the i-th daughter receives a necklace with brightness x_i. In the next line print n integers y_1, y_2, ..., y_n, representing that the i-th daughter receives a bracelet with brightness y_i.
The sums x_1 + y_1, x_2 + y_2, ..., x_n + y_n should all be distinct. The numbers x_1, ..., x_n should be equal to the numbers a_1, ..., a_n in some order, and the numbers y_1, ..., y_n should be equal to the numbers b_1, ..., b_n in some order.
It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.
Example
Input
2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
Output
1 8 5
8 4 5
5 1 7
6 2 1
Note
In the first test case, it is enough to give the i-th necklace and the i-th bracelet to the i-th daughter. The corresponding sums are 1 + 8 = 9, 8 + 4 = 12, and 5 + 5 = 10.
The second test case is described in the statement.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Drazil likes heap very much. So he created a problem with heap:
There is a max heap with a height h implemented on the array. The details of this heap are the following:
This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed from 1 to 2^h-1. For any 1 < i < 2^h, a[i] < a[\left β{i/2}\right β].
Now we want to reduce the height of this heap such that the height becomes g with exactly 2^g-1 numbers in heap. To reduce the height, we should perform the following action 2^h-2^g times:
Choose an index i, which contains an element and call the following function f in index i:
<image>
Note that we suppose that if a[i]=0, then index i don't contain an element.
After all operations, the remaining 2^g-1 element must be located in indices from 1 to 2^g-1. Now Drazil wonders what's the minimum possible sum of the remaining 2^g-1 elements. Please find this sum and find a sequence of the function calls to achieve this value.
Input
The first line of the input contains an integer t (1 β€ t β€ 70 000): the number of test cases.
Each test case contain two lines. The first line contains two integers h and g (1 β€ g < h β€ 20). The second line contains n = 2^h-1 distinct positive integers a[1], a[2], β¦, a[n] (1 β€ a[i] < 2^{20}). For all i from 2 to 2^h - 1, a[i] < a[\left β{i/2}\right β].
The total sum of n is less than 2^{20}.
Output
For each test case, print two lines.
The first line should contain one integer denoting the minimum sum after reducing the height of heap to g. The second line should contain 2^h - 2^g integers v_1, v_2, β¦, v_{2^h-2^g}. In i-th operation f(v_i) should be called.
Example
Input
2
3 2
7 6 3 5 4 2 1
3 2
7 6 5 4 3 2 1
Output
10
3 2 3 1
8
2 1 3 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.
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend i the number of a friend who has given him a gift.
Input
The first line contains one integer n (1 β€ n β€ 100) β the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi β the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.
Output
Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.
Examples
Input
4
2 3 4 1
Output
4 1 2 3
Input
3
1 3 2
Output
1 3 2
Input
2
1 2
Output
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.
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index i such that 1 β€ i < n and a_{i} β a_{i+1}, delete both a_i and a_{i+1} from the array and put a_{i}+a_{i+1} in their place.
For example, for array [7, 4, 3, 7] you can choose i = 2 and the array will become [7, 4+3, 7] = [7, 7, 7]. Note that in this array you can't apply this operation anymore.
Notice that one operation will decrease the size of the password by 1. What is the shortest possible length of the password after some number (possibly 0) of operations?
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 100). Description of the test cases follows.
The first line of each test case contains an integer n (1 β€ n β€ 2 β
10^5) β the length of the password.
The second line of each test case contains n integers a_{1},a_{2},...,a_{n} (1 β€ a_{i} β€ 10^9) β the initial contents of your password.
The sum of n over all test cases will not exceed 2 β
10^5.
Output
For each password, print one integer: the shortest possible length of the password after some number of operations.
Example
Input
2
4
2 1 3 1
2
420 420
Output
1
2
Note
In the first test case, you can do the following to achieve a length of 1:
Pick i=2 to get [2, 4, 1]
Pick i=1 to get [6, 1]
Pick i=1 to get [7]
In the second test case, you can't perform any operations because there is no valid i that satisfies the requirements mentioned above.
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 non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i β x (β denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 β€ i < j β€ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x β output the smallest one.
Input
First line contains a single integer n (1 β€ n β€ 3 β
10^5) β the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
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 bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r the condition a_i = 1 holds) and:
* Shift it to the right by 1: move the book at index i to i + 1 for all l β€ i β€ r. This move can be done only if r+1 β€ n and there is no book at the position r+1.
* Shift it to the left by 1: move the book at index i to i-1 for all l β€ i β€ r. This move can be done only if l-1 β₯ 1 and there is no book at the position l-1.
Your task is to find the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without any gaps).
For example, for a = [0, 0, 1, 0, 1] there is a gap between books (a_4 = 0 when a_3 = 1 and a_5 = 1), for a = [1, 1, 0] there are no gaps between books and for a = [0, 0,0] there are also no gaps between books.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 200) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 50) β the number of places on a bookshelf. The second line of the test case contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 1), where a_i is 1 if there is a book at this position and 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
Output
For each test case, print one integer: the minimum number of moves required to collect all the books on the shelf as a contiguous (consecutive) segment (i.e. the segment without gaps).
Example
Input
5
7
0 0 1 0 1 0 1
3
1 0 0
5
1 1 0 0 1
6
1 0 0 0 0 1
5
1 1 0 1 1
Output
2
0
2
4
1
Note
In the first test case of the example, you can shift the segment [3; 3] to the right and the segment [4; 5] to the right. After all moves, the books form the contiguous segment [5; 7]. So the answer is 2.
In the second test case of the example, you have nothing to do, all the books on the bookshelf form the contiguous segment already.
In the third test case of the example, you can shift the segment [5; 5] to the left and then the segment [4; 4] to the left again. After all moves, the books form the contiguous segment [1; 3]. So the answer is 2.
In the fourth test case of the example, you can shift the segment [1; 1] to the right, the segment [2; 2] to the right, the segment [6; 6] to the left and then the segment [5; 5] to the left. After all moves, the books form the contiguous segment [3; 4]. So the answer is 4.
In the fifth test case of the example, you can shift the segment [1; 2] to the right. After all moves, the books form the contiguous segment [2; 5]. So the 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.
You are given two positive integer sequences a_1, β¦, a_n and b_1, β¦, b_m. For each j = 1, β¦, m find the greatest common divisor of a_1 + b_j, β¦, a_n + b_j.
Input
The first line contains two integers n and m (1 β€ n, m β€ 2 β
10^5).
The second line contains n integers a_1, β¦, a_n (1 β€ a_i β€ 10^{18}).
The third line contains m integers b_1, β¦, b_m (1 β€ b_j β€ 10^{18}).
Output
Print m integers. The j-th of them should be equal to GCD(a_1 + b_j, β¦, a_n + b_j).
Example
Input
4 4
1 25 121 169
1 2 7 23
Output
2 3 8 24
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 were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.
<image>
Space can be represented as the XY plane. You are starting at point (0, 0), and Planetforces is located in point (p_x, p_y).
The piloting system of your spaceship follows its list of orders which can be represented as a string s. The system reads s from left to right. Suppose you are at point (x, y) and current order is s_i:
* if s_i = U, you move to (x, y + 1);
* if s_i = D, you move to (x, y - 1);
* if s_i = R, you move to (x + 1, y);
* if s_i = L, you move to (x - 1, y).
Since string s could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from s but you can't change their positions.
Can you delete several orders (possibly, zero) from s in such a way, that you'll reach Planetforces after the system processes all orders?
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases.
Each test case consists of two lines. The first line in each test case contains two integers p_x and p_y (-10^5 β€ p_x, p_y β€ 10^5; (p_x, p_y) β (0, 0)) β the coordinates of Planetforces (p_x, p_y).
The second line contains the string s (1 β€ |s| β€ 10^5: |s| is the length of string s) β the list of orders.
It is guaranteed that the sum of |s| over all test cases does not exceed 10^5.
Output
For each test case, print "YES" if you can delete several orders (possibly, zero) from s in such a way, that you'll reach Planetforces. Otherwise, print "NO". You can print each letter in any case (upper or lower).
Example
Input
6
10 5
RRRRRRRRRRUUUUU
1 1
UDDDRLLL
-3 -5
LDLDLDDDR
1 2
LLLLUU
3 -2
RDULRLLDR
-1 6
RUDURUUUUR
Output
YES
YES
YES
NO
YES
NO
Note
In the first case, you don't need to modify s, since the given s will bring you to Planetforces.
In the second case, you can delete orders s_2, s_3, s_4, s_6, s_7 and s_8, so s becomes equal to "UR".
In the third test case, you have to delete order s_9, otherwise, you won't finish in the position of Planetforces.
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.
Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations.
A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} β₯ a_i - 1 holds for all i between 1 and n - 1 inclusive.
Maki is considering the list of all almost sorted permutations of 1, 2, ..., n, given in lexicographical order, and he wants to find the k-th permutation in this list. Can you help him to find such permutation?
Permutation p is lexicographically smaller than a permutation q if and only if the following holds:
* in the first position where p and q differ, the permutation p has a smaller element than the corresponding element in q.
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases.
Each test case consists of a single line containing two integers n and k (1 β€ n β€ 10^5, 1 β€ k β€ 10^{18}).
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case, print a single line containing the k-th almost sorted permutation of length n in lexicographical order, or -1 if it doesn't exist.
Example
Input
5
1 1
1 2
3 3
6 5
3 4
Output
1
-1
2 1 3
1 2 4 3 5 6
3 2 1
Note
For the first and second test, the list of almost sorted permutations with n = 1 is \{[1]\}.
For the third and fifth test, the list of almost sorted permutations with n = 3 is \{[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 2, 1]\}.
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an n Γ m rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.
Input
The first line contains two space-separated integers n and m (2 β€ n, m β€ 100) β the number of rows and columns in the table, correspondingly.
Each of the next n lines contains m characters β the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".
It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements.
Output
Print two integers β the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.
Examples
Input
3 2
.*
..
**
Output
1 1
Input
3 3
*.*
*..
...
Output
2 3
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug.
The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length β the first one from string a, the second one from string b. The choice is equiprobable among all possible pairs. Let's denote the substring of a as x, and the substring of b β as y. The Little Elephant gives string x to Furik and string y β to Rubik.
Let's assume that f(x, y) is the number of such positions of i (1 β€ i β€ |x|), that xi = yi (where |x| is the length of lines x and y, and xi, yi are the i-th characters of strings x and y, correspondingly). Help Furik and Rubik find the expected value of f(x, y).
Input
The first line contains a single integer n (1 β€ n β€ 2Β·105) β the length of strings a and b. The second line contains string a, the third line contains string b. The strings consist of uppercase English letters only. The length of both strings equals n.
Output
On a single line print a real number β the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10 - 6.
Examples
Input
2
AB
BA
Output
0.400000000
Input
3
AAB
CAA
Output
0.642857143
Note
Let's assume that we are given string a = a1a2... a|a|, then let's denote the string's length as |a|, and its i-th character β as ai.
A substring a[l... r] (1 β€ l β€ r β€ |a|) of string a is string alal + 1... ar.
String a is a substring of string b, if there exists such pair of integers l and r (1 β€ l β€ r β€ |b|), that b[l... r] = a.
Let's consider the first test sample. The first sample has 5 possible substring pairs: ("A", "B"), ("A", "A"), ("B", "B"), ("B", "A"), ("AB", "BA"). For the second and third pair value f(x, y) equals 1, for the rest it equals 0. The probability of choosing each pair equals <image>, that's why the answer is <image> Β· 0 + <image> Β· 1 + <image> Β· 1 + <image> Β· 0 + <image> Β· 0 = <image> = 0.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.
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.
Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.
It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.
Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.
Input
The first line contains two space-separated integers: n (2 β€ n β€ 105), the number of planets in the galaxy, and m (0 β€ m β€ 105) β the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 β€ ai, bi β€ n, ai β bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 β€ ci β€ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection.
Then n lines follow: the i-th line contains an integer ki (0 β€ ki β€ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 β€ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.
Output
Print a single number β the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.
Examples
Input
4 6
1 2 2
1 3 3
1 4 8
2 3 4
2 4 5
3 4 3
0
1 3
2 3 4
0
Output
7
Input
3 1
1 2 3
0
1 3
0
Output
-1
Note
In the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then β to planet 4, then he spends a total of only 2 + 5 = 7 seconds.
In the second sample one can't get from planet 1 to planet 3 by moving through stargates.
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 circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:
* d1 is the distance between the 1-st and the 2-nd station;
* d2 is the distance between the 2-nd and the 3-rd station;
...
* dn - 1 is the distance between the n - 1-th and the n-th station;
* dn is the distance between the n-th and the 1-st station.
The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.
Input
The first line contains integer n (3 β€ n β€ 100) β the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 β€ di β€ 100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1 β€ s, t β€ n) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same.
The numbers in the lines are separated by single spaces.
Output
Print a single number β the length of the shortest path between stations number s and t.
Examples
Input
4
2 3 4 9
1 3
Output
5
Input
4
5 8 2 100
4 1
Output
15
Input
3
1 1 1
3 1
Output
1
Input
3
31 41 59
1 1
Output
0
Note
In the first sample the length of path 1 β 2 β 3 equals 5, the length of path 1 β 4 β 3 equals 13.
In the second sample the length of path 4 β 1 is 100, the length of path 4 β 3 β 2 β 1 is 15.
In the third sample the length of path 3 β 1 is 1, the length of path 3 β 2 β 1 is 2.
In the fourth sample the numbers of stations are the same, so the shortest distance equals 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 Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered.
Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.
Input
The input data consists of three lines, each of them describes the position of one stadium. The lines have the format x, y, r, where (x, y) are the coordinates of the stadium's center ( - 103 β€ x, y β€ 103), and r (1 β€ r β€ 103) is its radius. All the numbers in the input data are integer, stadiums do not have common points, and their centers are not on the same line.
Output
Print the coordinates of the required point with five digits after the decimal point. If there is no answer meeting the conditions, the program shouldn't print anything. The output data should be left blank.
Examples
Input
0 0 10
60 0 10
30 30 10
Output
30.00000 0.00000
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.
Berland is going through tough times β the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!
The President of Berland was forced to leave only k of the currently existing n subway stations.
The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.
Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!
Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is <image>) and divided by the speed of the train.
Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.
Input
The first line of the input contains integer n (3 β€ n β€ 3Β·105) β the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 β€ xi β€ 108). The third line contains integer k (2 β€ k β€ n - 1) β the number of stations after the innovation.
The station coordinates are distinct and not necessarily sorted.
Output
Print a sequence of k distinct integers t1, t2, ..., tk (1 β€ tj β€ n) β the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.
Examples
Input
3
1 100 101
2
Output
2 3
Note
In the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
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.
Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n Γ n matrix W, consisting of integers, and you should find two n Γ n matrices A and B, all the following conditions must hold:
* Aij = Aji, for all i, j (1 β€ i, j β€ n);
* Bij = - Bji, for all i, j (1 β€ i, j β€ n);
* Wij = Aij + Bij, for all i, j (1 β€ i, j β€ n).
Can you solve the problem?
Input
The first line contains an integer n (1 β€ n β€ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0 β€ |Wij| < 1717).
Output
The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them.
The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 4.
Examples
Input
2
1 4
3 2
Output
1.00000000 3.50000000
3.50000000 2.00000000
0.00000000 0.50000000
-0.50000000 0.00000000
Input
3
1 2 3
4 5 6
7 8 9
Output
1.00000000 3.00000000 5.00000000
3.00000000 5.00000000 7.00000000
5.00000000 7.00000000 9.00000000
0.00000000 -1.00000000 -2.00000000
1.00000000 0.00000000 -1.00000000
2.00000000 1.00000000 0.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.
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.
Input
The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.
Output
Print a single number β the number of distinct letters in Anton's set.
Examples
Input
{a, b, c}
Output
3
Input
{b, a, b, a}
Output
2
Input
{}
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.
In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of swaps β your task is to find any sequence that is no longer than n.
Input
The first line of the input contains integer n (1 β€ n β€ 3000) β the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 β€ ai β€ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.
Output
In the first line print k (0 β€ k β€ n) β the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 β€ i, j β€ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times.
If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.
Examples
Input
5
5 2 5 1 4
Output
2
0 3
4 2
Input
6
10 20 20 40 60 60
Output
0
Input
2
101 100
Output
1
0 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 large banner with word CODEFORCES was ordered for the 1000-th onsite round of CodeforcesΟ that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.
There is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.
Help the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.
Input
The single line of the input contains the word written on the banner. The word only consists of upper-case English letters. The word is non-empty and its length doesn't exceed 100 characters. It is guaranteed that the word isn't word CODEFORCES.
Output
Print 'YES', if there exists a way to cut out the substring, and 'NO' otherwise (without the quotes).
Examples
Input
CODEWAITFORITFORCES
Output
YES
Input
BOTTOMCODER
Output
NO
Input
DECODEFORCES
Output
YES
Input
DOGEFORCES
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.
Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning tree.
Input
First line contains two integers n and m (1 β€ n β€ 2Β·105, n - 1 β€ m β€ 2Β·105) β the number of vertices and edges in graph.
Each of the next m lines contains three integers ui, vi, wi (1 β€ ui, vi β€ n, ui β vi, 1 β€ wi β€ 109) β the endpoints of the i-th edge and its weight.
Output
Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.
The edges are numbered from 1 to m in order of their appearing in input.
Examples
Input
5 7
1 2 3
1 3 1
1 4 5
2 3 2
2 5 3
3 4 2
4 5 4
Output
9
8
11
8
8
8
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.
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.
Some of magic effects are able to affect several field cells at once, cells that are situated not farther than n cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.
It is easy to see that the number of cells affected by a magic effect grows rapidly when n increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given n, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than n cells away from a given cell.
<image>
Input
The only line of the input contains one integer n (0 β€ n β€ 109).
Output
Output one integer β the number of hexagons situated not farther than n cells away from a given cell.
Examples
Input
2
Output
19
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty β it's guaranteed that pi < pi + 1 and ti < ti + 1.
A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0, pi - cΒ·x) points.
Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by pi). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by pi). Your task is to predict the outcome β print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.
You may assume that the duration of the competition is greater or equal than the sum of all ti. That means both Limak and Radewoosh will accept all n problems.
Input
The first line contains two integers n and c (1 β€ n β€ 50, 1 β€ c β€ 1000) β the number of problems and the constant representing the speed of loosing points.
The second line contains n integers p1, p2, ..., pn (1 β€ pi β€ 1000, pi < pi + 1) β initial scores.
The third line contains n integers t1, t2, ..., tn (1 β€ ti β€ 1000, ti < ti + 1) where ti denotes the number of minutes one needs to solve the i-th problem.
Output
Print "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points.
Examples
Input
3 2
50 85 250
10 15 25
Output
Limak
Input
3 6
50 85 250
10 15 25
Output
Radewoosh
Input
8 1
10 20 30 40 50 60 70 80
8 10 58 63 71 72 75 76
Output
Tie
Note
In the first sample, there are 3 problems. Limak solves them as follows:
1. Limak spends 10 minutes on the 1-st problem and he gets 50 - cΒ·10 = 50 - 2Β·10 = 30 points.
2. Limak spends 15 minutes on the 2-nd problem so he submits it 10 + 15 = 25 minutes after the start of the contest. For the 2-nd problem he gets 85 - 2Β·25 = 35 points.
3. He spends 25 minutes on the 3-rd problem so he submits it 10 + 15 + 25 = 50 minutes after the start. For this problem he gets 250 - 2Β·50 = 150 points.
So, Limak got 30 + 35 + 150 = 215 points.
Radewoosh solves problem in the reversed order:
1. Radewoosh solves 3-rd problem after 25 minutes so he gets 250 - 2Β·25 = 200 points.
2. He spends 15 minutes on the 2-nd problem so he submits it 25 + 15 = 40 minutes after the start. He gets 85 - 2Β·40 = 5 points for this problem.
3. He spends 10 minutes on the 1-st problem so he submits it 25 + 15 + 10 = 50 minutes after the start. He gets max(0, 50 - 2Β·50) = max(0, - 50) = 0 points.
Radewoosh got 200 + 5 + 0 = 205 points in total. Limak has 215 points so Limak wins.
In the second sample, Limak will get 0 points for each problem and Radewoosh will first solve the hardest problem and he will get 250 - 6Β·25 = 100 points for that. Radewoosh will get 0 points for other two problems but he is the winner anyway.
In the third sample, Limak will get 2 points for the 1-st problem and 2 points for the 2-nd problem. Radewoosh will get 4 points for the 8-th problem. They won't get points for other problems and thus there is a tie because 2 + 2 = 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.
This is an interactive problem. In the output section below you will see the information about flushing the output.
Bear Limak thinks of some hidden number β an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.
Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.
You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".
For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.
When you are done asking queries, print "prime" or "composite" and terminate your program.
You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.
You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).
Input
After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.
Output
Up to 20 times you can ask a query β print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input.
In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program.
To flush you can use (just after printing an integer and end-of-line):
* fflush(stdout) in C++;
* System.out.flush() in Java;
* stdout.flush() in Python;
* flush(output) in Pascal;
* See the documentation for other languages.
Hacking. To hack someone, as the input you should print the hidden number β one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.
Examples
Input
yes
no
yes
Output
2
80
5
composite
Input
no
yes
no
no
no
Output
58
59
78
78
2
prime
Note
The hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.
<image>
The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.
<image>
59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).
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 Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX β beautiful, but little-known northern country.
Here are some interesting facts about XXX:
1. XXX consists of n cities, k of whose (just imagine!) are capital cities.
2. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci.
3. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 β 2 β ... β n β 1. Formally, for every 1 β€ i < n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city.
4. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 β€ i β€ n, i β x, there is a road between cities x and i.
5. There is at most one road between any two cities.
6. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ciΒ·cj.
Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a < b), such that there is a road between a and b you are to find sum of products caΒ·cb. Will you help her?
Input
The first line of the input contains two integers n and k (3 β€ n β€ 100 000, 1 β€ k β€ n) β the number of cities in XXX and the number of capital cities among them.
The second line of the input contains n integers c1, c2, ..., cn (1 β€ ci β€ 10 000) β beauty values of the cities.
The third line of the input contains k distinct integers id1, id2, ..., idk (1 β€ idi β€ n) β indices of capital cities. Indices are given in ascending order.
Output
Print the only integer β summary price of passing each of the roads in XXX.
Examples
Input
4 1
2 3 1 2
3
Output
17
Input
5 2
3 5 2 2 4
1 4
Output
71
Note
This image describes first sample case:
<image>
It is easy to see that summary price is equal to 17.
This image describes second sample case:
<image>
It is easy to see that summary price is equal to 71.
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 new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle.
<image>
It's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row 1 while the second attendant serves row 3. When both rows are done they move one row forward: the first attendant serves row 2 while the second attendant serves row 4. Then they move three rows forward and the first attendant serves row 5 while the second attendant serves row 7. Then they move one row forward again and so on.
Flight attendants work with the same speed: it takes exactly 1 second to serve one passenger and 1 second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one β in seat 'c'. Assume that all seats are occupied.
Vasya has seat s in row n and wants to know how many seconds will pass before he gets his lunch.
Input
The only line of input contains a description of Vasya's seat in the format ns, where n (1 β€ n β€ 1018) is the index of the row and s is the seat in this row, denoted as letter from 'a' to 'f'. The index of the row and the seat are not separated by a space.
Output
Print one integer β the number of seconds Vasya has to wait until he gets his lunch.
Examples
Input
1f
Output
1
Input
2d
Output
10
Input
4a
Output
11
Input
5e
Output
18
Note
In the first sample, the first flight attendant serves Vasya first, so Vasya gets his lunch after 1 second.
In the second sample, the flight attendants will spend 6 seconds to serve everyone in the rows 1 and 3, then they will move one row forward in 1 second. As they first serve seats located to the right of the aisle in order from window to aisle, Vasya has to wait 3 more seconds. The total is 6 + 1 + 3 = 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.
The process of mammoth's genome decoding in Berland comes to its end!
One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.
It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.
Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.
Input
The first line contains the integer n (4 β€ n β€ 255) β the length of the genome.
The second line contains the string s of length n β the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.
Output
If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).
Examples
Input
8
AG?C??CT
Output
AGACGTCT
Input
4
AGCT
Output
AGCT
Input
6
????G?
Output
===
Input
4
AA??
Output
===
Note
In the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.
In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.
In the third and the fourth examples it is impossible to decode the genom.
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 on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
Input
The first line of input contains one integer number N (1 β€ N β€ 100 000) β the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 β€ X, Y β€ 10 000) β the coordinates of points. Two or more points may coincide.
Output
The only line of output should contain the required sum of squares of distances between all pairs of points.
Examples
Input
4
1 1
-1 -1
1 -1
-1 1
Output
32
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.
On the way to school, Karen became fixated on the puzzle game on her phone!
<image>
The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.
One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.
To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.
Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!
Input
The first line of input contains two integers, n and m (1 β€ n, m β€ 100), the number of rows and the number of columns in the grid, respectively.
The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 β€ gi, j β€ 500).
Output
If there is an error and it is actually not possible to beat the level, output a single integer -1.
Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level.
The next k lines should each contain one of the following, describing the moves in the order they must be done:
* row x, (1 β€ x β€ n) describing a move of the form "choose the x-th row".
* col x, (1 β€ x β€ m) describing a move of the form "choose the x-th column".
If there are multiple optimal solutions, output any one of them.
Examples
Input
3 5
2 2 2 3 2
0 0 0 1 0
1 1 1 2 1
Output
4
row 1
row 1
col 4
row 3
Input
3 3
0 0 0
0 1 0
0 0 0
Output
-1
Input
3 3
1 1 1
1 1 1
1 1 1
Output
3
row 1
row 2
row 3
Note
In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:
<image>
In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.
In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:
<image>
Note that this is not the only solution; another solution, among others, is col 1, col 2, col 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.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 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.
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.
Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.
Input
In the only line given a non-empty binary string s with length up to 100.
Output
Print Β«yesΒ» (without quotes) if it's possible to remove digits required way and Β«noΒ» otherwise.
Examples
Input
100010001
Output
yes
Input
100
Output
no
Note
In the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.
You can read more about binary numeral system representation here: <https://en.wikipedia.org/wiki/Binary_system>
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 group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.
The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.
All students are divided into three groups: r of them like to ascend only in the red cablecars, g of them prefer only the green ones and b of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,
The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.
Input
The first line contains three integers r, g and b (0 β€ r, g, b β€ 100). It is guaranteed that r + g + b > 0, it means that the group consists of at least one student.
Output
Print a single number β the minimal time the students need for the whole group to ascend to the top of the mountain.
Examples
Input
1 3 2
Output
34
Input
3 2 1
Output
33
Note
Let's analyze the first sample.
At the moment of time 0 a red cablecar comes and one student from the r group get on it and ascends to the top at the moment of time 30.
At the moment of time 1 a green cablecar arrives and two students from the g group get on it; they get to the top at the moment of time 31.
At the moment of time 2 comes the blue cablecar and two students from the b group get on it. They ascend to the top at the moment of time 32.
At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.
At the moment of time 4 a green cablecar arrives and one student from the g group gets on it. He ascends to top at the moment of time 34.
Thus, all the students are on the top, overall the ascension took exactly 34 minutes.
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 Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.
Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.
Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.
Input
First line of input contains single integer number n (2 β€ n β€ 100 000) β number of inflorescences.
Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 β€ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.
Output
Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.
Examples
Input
3
1 1
Output
1
Input
5
1 2 2 2
Output
3
Input
18
1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4
Output
4
Note
In first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.
In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect 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.
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.
Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k1 knights with lightsabers of the first color, k2 knights with lightsabers of the second color, ..., km knights with lightsabers of the m-th color.
However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights.
Input
The first line of the input contains n (1 β€ n β€ 2Β·105) and m (1 β€ m β€ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k1, k2, ..., km (with <image>) β the desired counts of Jedi Knights with lightsabers of each color from 1 to m.
Output
Output one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output - 1.
Example
Input
8 3
3 3 1 2 2 1 1 3
3 1 1
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 going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right.
Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height hi of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it.
Finally you ended up with the following conditions to building the castle:
* h1 β€ H: no sand from the leftmost spot should go over the fence;
* For any <image> |hi - hi + 1| β€ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen;
* <image>: you want to spend all the sand you brought with you.
As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible.
Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.
Input
The only line contains two integer numbers n and H (1 β€ n, H β€ 1018) β the number of sand packs you have and the height of the fence, respectively.
Output
Print the minimum number of spots you can occupy so the all the castle building conditions hold.
Examples
Input
5 2
Output
3
Input
6 8
Output
3
Note
Here are the heights of some valid castles:
* n = 5, H = 2, [2, 2, 1, 0, ...], [2, 1, 1, 1, 0, ...], [1, 0, 1, 2, 1, 0, ...]
* n = 6, H = 8, [3, 2, 1, 0, ...], [2, 2, 1, 1, 0, ...], [0, 1, 0, 1, 2, 1, 1, 0...] (this one has 5 spots occupied)
The first list for both cases is the optimal answer, 3 spots are occupied in them.
And here are some invalid ones:
* n = 5, H = 2, [3, 2, 0, ...], [2, 3, 0, ...], [1, 0, 2, 2, ...]
* n = 6, H = 8, [2, 2, 2, 0, ...], [6, 0, ...], [1, 4, 1, 0...], [2, 2, 1, 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.
Abhinav and Manav both being one of the best coders of SVNIT went onto participate in ACM ICPC Regional Contest. Apparently Manavβs team the 3Horsemen stood ahead of Abhinavβs team akatsuki11 in the contest though both solved the same number of questions .Manav is Abhinavβs greatest rival and Abhinav being adamant about him being The Best gives Manav a challenge described below:
For each positive number N consider the number mirror(N) which is obtained from N by replacing every digit d in the decimal notation(base 10) of N with the digit (9-d). We can now say that mirror(N) is the mirror image of N. For example, reflection of 325 equals 674. Note that leading zeros (if any) should be omitted. So the mirror image of 9 equals 0, so mirror(91) equals 8.
Let us define weight as the product of the number and its mirror image i.e. N * mirror(N). Thus, the weight of the number 20 is equal to 20 Β·79 = 1580.
Manav is very weak in mathematics and also he doesnβt want to lose this challenge. So now itβs your job to save Manav from Abhinavβs arrogance. Your task is to find the maximum weight of the numbers in the given range [L,R] (including boundaries).
Input:
First line of input contains number of test cases T. Next T lines contain two positive numbers L and R.
Output:
Find the maximum weight of the numbers in the given range [L, R] for each test case.
Constraints:
1 β€ T β€ 24
1 β€ L β€ R β€ 10^9
SAMPLE INPUT
3
3 7
1 1
8 10
SAMPLE OUTPUT
20
8
890
Explanation
For test case 3
8 * mirror(8) = 8 * 1 = 1
9 * mirror(9) = 9 * 0 = 0
10 * mirror(10) = 10 * 89 = 890
So max(1,0,890) = 890
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 hero of this story is a toddler named BooBoo. Inspired by the legendary competitive coder Gena, BooBoo has also started preparing to race to the top of the ranks.
BooBoo is going to practice N different problems in the exact given order over the next M days. For each problem, he writes down the amount of time q_i he will take to think and code the i^{th} problem (He is quite good at estimating!). Before starting on the problems, he took advice from experienced competitive programmers on his practice routine and almost all of them advised him to keep his daily load at the minimum possible and avoid over training.
Since BooBoo already has N problems to solve, he asks you to find the minimum time T such that training everyday for a time t_i β€ T is sufficient to solve all the N problems in M days.
Note : Unlike in real world, you cannot think on a problem on one day and solve it on the other day. You need to do it on the very same day!
Input Format:
The first line contains two space separated integers N and M. The next line contains N space separated integers denoting the time q_i required to solve the i^{th} problem.
Output Format:
The output consists of one integer, the minimum time T as described in the problem statement.
Constraints:
1 β€ N β€ 10^5
1 β€ M β€ N
1 β€ q_i β€ 10^{12}
SAMPLE INPUT
5 3
1 2 2 1 3
SAMPLE OUTPUT
3
Explanation
By setting T = 3, we can solve 1st two questions on day 1, next two on day 2 and 5th one on day 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 three numbers. Is there a way to replace variables A, B and C with these numbers so the equality Aβ+βBβ=βC is correct?
Input:
There are three numbers X1, X2 and X3 (1ββ€βXiββ€β10^100), each on a separate line of input.
Output:
Output either "YES", if there is a way to substitute variables A, B and C with given numbers so the equality is correct, or "NO" otherwise.
Sample Input:
1
2
3
Output:
YES
Sample Input:
1
2
4
Output
YES
Sample Input:
1
3
5
Output
NO
SAMPLE INPUT
1
2
3
SAMPLE 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.
See Russian Translation
After a long term relationship, Anandi and Jagdish decided to marry. Anandi being a studious girl decided to complete her studies first. What next, she comes to ABC Public School. Her classes haven't even started yet and Jagdish becomes restless, comes to her college and asks her to complete her studies as soon as possible. Here comes the twist.
Anandi has to attend N classes in total. On the first day, she couldn't attend more than one class as she was too exhausted from the Semester Registration process. If Anandi takes x classes on some day, then she can take x, x-1 or x+1 classes on the next day. Jagdish on the other hand has asked Anandi to take no more than one class on the final day of her course so that she wouldn't be too tired for the marriage ceremony.
Help Anandi calculate the minimum number of days required to complete her course, keeping in mind the conditions mentioned above.
Input :
The first line contains an integer T denoting the number of test cases.
Each of the next T lines contain an integer N.
Output :
T lines : Minimum number of days required for each test case.
Constraints
1 β€ N β€ 10^9
1 β€ T β€ 1000
SAMPLE INPUT
3
4
1
9
SAMPLE OUTPUT
3
1
5
Explanation
Case 1 : 1 + 2 + 1
Case 2 : 1
Case 3 : 1 + 2 + 3 + 2 + 1
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Rhezo is the new manager of Specialist Cinema Hall. A new movie is being released this Friday and Rhezo wants people in the hall to be seated according to some rules. His rules are weird and he likes that no 2 people in a row sit together/adjacent. He also wants that there are at least 2 people in each row.
The hall should have at least K people in it, if there are less the show gets cancelled. The hall can be visualised as a N \times M matrix. Rhezo wants to find the number of different seating arrangements of people in it. Two seating arrangements are different if there is at least one seat which is filled in one arrangement and vacant in other.
You being Rhezo's best friend, want to help him in this task. As the number can be large, output your answer modulo 10^9+7.
Input:
First line of input contains 2 integers N and M. Second line contains a single integer K.
Output:
Find the number of different arrangements of people in the hall satisfying the constraints given in problem statement. Output your answer modulo 10^9+7.
Constraints:
1 β€ N, K β€ 500
1 β€ M β€ 10
SAMPLE INPUT
1 5 2
SAMPLE OUTPUT
7
Explanation
Following are the 7 different seating arrangements:
x.x.x
..x.x
.x..x
.x.x.
x...x
x..x.
x.x..
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 rectangular grid with n rows and m columns. The rows are numbered 1 to n, from bottom to top, and the columns are numbered 1 to m, from left to right.
You are also given k special fields in the form (row, column). For each i, where 0 β€ i β€ k, count the number of different paths from (1, 1) to (n, m) that contains exactly n special fields.
There is one rule you must follow. You are only allowed to make moves that are straight up or to the right. In other words, from each field (row, column), you can only move to field (row+1, column) or field (row, column+1).
Output an array of k + 1 elements. The i-th element (0-indexed) must be the number of different paths that contain exactly i special fields. Since, the answer can be too big, output it modulo 1000007.
Input:
First line contains three space separated integers, n, m and k.
Next k lines, each contain two space separated integers, the coordinates of a special field.
Output:
k + 1 space separated integers, the answer to the question.
Constraints:
1 β€ n, m, k β€ 100
For all coordinates (r, c) - 1 β€ r β€ n, 1 β€ c β€ m
All coordinates are valid and different.
SAMPLE INPUT
3 3 2
2 2
3 2
SAMPLE OUTPUT
1 3 2
Explanation
0 special cell -
(1, 1) -> (1, 2) -> (1, 3) -> (2, 3) -> (3, 3)
1 special cell -
(1, 1) -> (2, 1) -> (2, 2) -> (2, 3) -> (3, 3)
(1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3)
(1, 1) -> (1, 2) -> (2, 2) -> (2, 3) -> (3, 3)
2 special cells -
(1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3)
(1, 1) -> (1, 2) -> (2, 2) -> (3, 2) -> (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.
An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.
Determine whether N is a multiple of 9.
Constraints
* 0 \leq N < 10^{200000}
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If N is a multiple of 9, print `Yes`; otherwise, print `No`.
Examples
Input
123456789
Output
Yes
Input
0
Output
Yes
Input
31415926535897932384626433832795028841971693993751058209749445923078164062862089986280
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.
We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N.
We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7).
Constraints
* 1 \leq N \leq 2\times 10^5
* 1 \leq K \leq N+1
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
Output
Print the number of possible values of the sum, modulo (10^9+7).
Examples
Input
3 2
Output
10
Input
200000 200001
Output
1
Input
141421 35623
Output
220280457
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 people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.
Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.
How many honest persons can be among those N people at most?
Constraints
* All values in input are integers.
* 1 \leq N \leq 15
* 0 \leq A_i \leq N - 1
* 1 \leq x_{ij} \leq N
* x_{ij} \neq i
* x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)
* y_{ij} = 0, 1
Input
Input is given from Standard Input in the following format:
N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}
Output
Print the maximum possible number of honest persons among the N people.
Examples
Input
3
1
2 1
1
1 1
1
2 0
Output
2
Input
3
2
2 1
3 0
2
3 1
1 0
2
1 1
2 0
Output
0
Input
2
1
2 0
1
1 0
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.
Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|.
Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.
Constraints
* All values in input are integers.
* 1 \leq n \leq 50
* 0 \leq k \leq n^2
Input
Input is given from Standard Input in the following format:
n k
Output
Print the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.
Examples
Input
3 2
Output
2
Input
39 14
Output
74764168
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.
Takahashi received otoshidama (New Year's money gifts) from N of his relatives.
You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either `JPY` or `BTC`, and x_i and u_i represent the content of the otoshidama from the i-th relative.
For example, if x_1 = `10000` and u_1 = `JPY`, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = `0.10000000` and u_2 = `BTC`, the otoshidama from the second relative is 0.1 bitcoins.
If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?
Constraints
* 2 \leq N \leq 10
* u_i = `JPY` or `BTC`.
* If u_i = `JPY`, x_i is an integer such that 1 \leq x_i \leq 10^8.
* If u_i = `BTC`, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.
Input
Input is given from Standard Input in the following format:
N
x_1 u_1
x_2 u_2
:
x_N u_N
Output
If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).
Output will be judged correct when the absolute or relative error from the judge's output is at most 10^{-5}.
Examples
Input
2
10000 JPY
0.10000000 BTC
Output
48000.0
Input
3
100000000 JPY
100.00000000 BTC
0.00000001 BTC
Output
138000000.0038
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
You are given an integer N.
Construct any one N-by-N matrix a that satisfies the conditions below. It can be proved that a solution always exists under the constraints of this problem.
* 1 \leq a_{i,j} \leq 10^{15}
* a_{i,j} are pairwise distinct integers.
* There exists a positive integer m such that the following holds: Let x and y be two elements of the matrix that are vertically or horizontally adjacent. Then, {\rm max}(x,y) {\rm mod} {\rm min}(x,y) is always m.
Constraints
* 2 \leq N \leq 500
Input
Input is given from Standard Input in the following format:
N
Output
Print your solution in the following format:
a_{1,1} ... a_{1,N}
:
a_{N,1} ... a_{N,N}
Output
Print your solution in the following format:
a_{1,1} ... a_{1,N}
:
a_{N,1} ... a_{N,N}
Example
Input
2
Output
4 7
23 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.
You are given three integers, A, B and C.
Among them, two are the same, but the remaining one is different from the rest.
For example, when A=5,B=7,C=5, A and C are the same, but B is different.
Find the one that is different from the rest among the given three integers.
Constraints
* -100 \leq A,B,C \leq 100
* A, B and C are integers.
* The input satisfies the condition in the statement.
Input
Input is given from Standard Input in the following format:
A B C
Output
Among A, B and C, print the integer that is different from the rest.
Examples
Input
5 7 5
Output
7
Input
1 1 7
Output
7
Input
-100 100 100
Output
-100
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
Takahashi loves sorting.
He has a permutation (p_1,p_2,...,p_N) of the integers from 1 through N. Now, he will repeat the following operation until the permutation becomes (1,2,...,N):
* First, we will define high and low elements in the permutation, as follows. The i-th element in the permutation is high if the maximum element between the 1-st and i-th elements, inclusive, is the i-th element itself, and otherwise the i-th element is low.
* Then, let a_1,a_2,...,a_k be the values of the high elements, and b_1,b_2,...,b_{N-k} be the values of the low elements in the current permutation, in the order they appear in it.
* Lastly, rearrange the permutation into (b_1,b_2,...,b_{N-k},a_1,a_2,...,a_k).
How many operations are necessary until the permutation is sorted?
Constraints
* 1 β€ N β€ 2Γ10^5
* (p_1,p_2,...,p_N) is a permutation of the integers from 1 through N.
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the number of operations that are necessary until the permutation is sorted.
Examples
Input
5
3 5 1 2 4
Output
3
Input
5
5 4 3 2 1
Output
4
Input
10
2 10 5 7 3 6 4 9 8 1
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.
Takahashi is drawing a segment on grid paper.
From a certain square, a square that is x squares to the right and y squares above, is denoted as square (x, y).
When Takahashi draws a segment connecting the lower left corner of square (A, B) and the lower left corner of square (C, D), find the number of the squares crossed by the segment.
Here, the segment is said to cross a square if the segment has non-empty intersection with the region within the square, excluding the boundary.
Constraints
* 1 \leq A, B, C, D \leq 10^9
* At least one of A \neq C and B \neq D holds.
Input
The input is given from Standard Input in the following format:
A B C D
Output
Print the number of the squares crossed by the segment.
Examples
Input
1 1 3 4
Output
4
Input
2 3 10 7
Output
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.
Snuke is having another barbeque party.
This time, he will make one serving of Skewer Meal.
He has a stock of N Skewer Meal Packs. The i-th Skewer Meal Pack contains one skewer, A_i pieces of beef and B_i pieces of green pepper. All skewers in these packs are different and distinguishable, while all pieces of beef and all pieces of green pepper are, respectively, indistinguishable.
To make a Skewer Meal, he chooses two of his Skewer Meal Packs, and takes out all of the contents from the chosen packs, that is, two skewers and some pieces of beef or green pepper. (Remaining Skewer Meal Packs will not be used.) Then, all those pieces of food are threaded onto both skewers, one by one, in any order.
(See the image in the Sample section for better understanding.)
In how many different ways can he make a Skewer Meal? Two ways of making a Skewer Meal is different if and only if the sets of the used skewers are different, or the orders of the pieces of food are different. Since this number can be extremely large, find it modulo 10^9+7.
Constraints
* 2β¦Nβ¦200,000
* 1β¦A_iβ¦2000, 1β¦B_iβ¦2000
Input
The input is given from Standard Input in the following format:
N
A_1 B_1
A_2 B_2
:
A_N B_N
Output
Print the number of the different ways Snuke can make a serving of Skewer Meal, modulo 10^9+7.
Example
Input
3
1 1
1 1
2 1
Output
26
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 trains with 26 cars or less. Each vehicle has an identification code from lowercase a to z. No vehicle has the same symbol. However, the order in which the vehicles are connected is arbitrary. The conductor patrols the train. The conductor patrolls back and forth in the train, so he may pass through the same vehicle many times. However, all vehicles shall be patrolled at least once. In addition, the vehicle that starts the patrol and the vehicle that finishes the patrol is not necessarily the vehicle at the end of the train.
There is a patrol record of all the trains on which an Aru Shashou is on board. Create a program that outputs the formation of each train that can be seen from it from the lead car. The patrol record corresponds to one train per line. Each line consists of a string of lowercase letters separated by <-or->. <-Represents a move to a vehicle in front, and-> represents a move to a vehicle behind.
For example, a-> b <-a <-c means that vehicle a has moved to the vehicle behind b, b has moved to a ahead, and a has moved to c ahead. In this case, the train formation will be cab from the first car.
Input
The number of patrol records n (n β€ 50) is given to the first line, and the character string si (half-width character string up to 1024 characters) representing the patrol record i is given to the following n lines.
Output
For patrol record i, output the character string indicating the formation of the train from the first car on the i-line.
Examples
Input
4
a->e->c->b->d
b
Output
aecbd
edacb
bacde
bcdae
Input
4
a->e->c->b->d
b<-c<-a<-d<-e
b->a->c<-a->c->d<-c<-a<-b->a->c->d->e<-d
a->e<-a<-d->a->e<-a<-d<-c->d->a<-d<-c<-b->c->d<-c
Output
aecbd
edacb
bacde
bcdae
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 32-bit real type with 7 bits from the right as the decimal part, the following 24 bits as the integer part, and the leftmost 1 bit as the sign part as shown below (b1, ..., b32). Represents 0 or 1).
<image>
To translate this format into a decimal representation that is easy for humans to understand, interpret it as follows.
(-1) Sign part Γ (integer part + decimal part)
In the above expression, the value of the integer part is b8 + 21 x b9 + 22 x b10 + ... + 223 x b31. For example, the integer part is
<image>
If it looks like, the value of the integer part is calculated as follows.
1 + 21 + 23 = 1 + 2 + 8 = 11
On the other hand, the value of the decimal part is (0.5) 1 Γ b7 οΌ (0.5) 2 Γ b6 οΌ ... οΌ (0.5) 7 Γ b1. For example, the decimal part
<image>
If it looks like, the decimal part is calculated as follows.
0.51 + 0.53 = 0.5 + 0.125 = 0.625
Furthermore, in the case of the following bit string that combines the sign part, the integer part, and the decimal part,
<image>
The decimal number represented by the entire bit string is as follows (where -1 to the 0th power is 1).
(-1) 0 Γ (1 + 2 + 8 + 0.5 + 0.125) = 1 Γ (11.625) = 11.625
If you enter Q 32-bit bit strings, create a program that outputs the real decimal notation represented by those bit strings without any error.
input
The input consists of one dataset. Input data is given in the following format.
Q
s1
s2
..
..
..
sQ
The number of bit strings Q (1 β€ Q β€ 10000) is given in the first row. The input bit string si is given in the following Q row. Suppose the input bit string is given in hexadecimal notation (for example, 0111 1111 1000 1000 0000 0000 0000 0000 is given as 7f880000). In other words, each of the Q lines contains eight hexadecimal numbers, which are 4-bit binary numbers, without any blanks. The table below shows the correspondence between decimal numbers, binary numbers, and hexadecimal numbers.
<image>
Hexadecimal letters a through f are given in lowercase.
output
Outputs the real decimal notation represented by each bit string line by line. However, in the decimal part, if all the digits after a certain digit are 0, the digits after that digit are omitted. As an exception, if the decimal part is 0, one 0 is output to the decimal part.
Example
Input
8
00000000
80000000
00000080
00000040
000000c0
00000100
80000780
80000f70
Output
0.0
-0.0
1.0
0.5
1.5
2.0
-15.0
-30.875
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
Play by arranging white and black stones on the table. First, place the stones on the left edge of the table. Then place the stones in the second place from the left. Repeat this n times to arrange n stones in a horizontal row. However, when placing a new i-th go stone, replace the go stone on the table according to the following rules.
* If i is odd: Do not replace the stones that were on the table, but place the new stones i-th from the left.
* If i is even: If the color of the new go stone placed i-th from the left and the color of the rightmost go stone on the table are the same, the go stone on the table is not replaced and the new go stone is placed i-th from the left. If this is not the case, that is, if the color of the new i-th go stone from the left is different from the color of the right-most go stone on the table, first remove all the consecutive right-end go stones of the same color on the table, and then use the i-th go stone. Replace with a go stone of the same color, and place the i-th go stone on the right edge of the table.
For example, when the first 7 go stones are placed,
ββ ββ βββ
(β represents white go stones, β represents black go stones.)
* If the 8th go stone is white (β), it is the same color as the rightmost go stone, so leave it as it is. Therefore, the go stone on the table is
ββ ββ ββββ
Will be.
* If the 8th go stone is black (β), the color is different from the rightmost go stone (β), so first remove the 3 consecutive white go stones (β) on the right end of the table, and then remove the black go stone (β). And put the eighth go stone on the far right. Therefore, the go stone on the table
ββ ββββββ
Will be.
Given the order of the stones to be placed as input, create a program to find the number of white stones placed on the table after arranging n stones.
input
The input consists of multiple datasets. Each dataset is given in the following format.
A positive integer n (1 β€ n β€ 100000) is written on the first line. In the second and subsequent lines i + 1 (1 β€ i β€ n), the color of the go stone placed in the i-th position is written. The integer ci is written, and if ci is 0, it means that the color of the i-th go stone is white, and if it is 1, it means that the color of the i-th go stone is black.
Of the scoring data, 50% of the points are given by satisfying n β€ 10000.
When n is 0, it indicates the end of input. The number of datasets does not exceed 10.
output
For each dataset, output the number of white stones placed on the table after arranging n stones in one line.
Examples
Input
8
1
0
1
1
0
0
0
0
8
1
0
1
1
0
0
0
1
0
Output
6
2
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.
Mr. Dango's family has extremely huge number of members. Once it had about 100 members, and now it has as many as population of a city. It is jokingly guessed that the member might fill this planet in near future. They all have warm and gracious personality and are close each other.
They usually communicate by a phone. Of course, They are all taking a family plan. This family plan is such a thing: when a choose b, and b choose a as a partner, a family plan can be applied between them and then the calling fee per unit time between them discounted to f(a, b), which is cheaper than a default fee. Each person can apply a family plan at most 2 times, but no same pair of persons can apply twice. Now, choosing their partner appropriately, all members of Mr. Dango's family applied twice.
Since there are huge number of people, it is very difficult to send a message to all family members by a phone call. Mr. Dang have decided to make a phone calling network that is named 'clan' using the family plan. Let us present a definition of clan.
Let S be an any subset of all phone calls that family plan is applied. Clan is S such that:
1. For any two persons (let them be i and j), if i can send a message to j through phone calls that family plan is applied (directly or indirectly), then i can send a message to j through only phone calls in S (directly or indirectly).
2. Meets condition 1 and a sum of the calling fee per unit time in S is minimized.
Clan allows to send a message efficiently. For example, we suppose that one have sent a message through all calls related to him in the clan. Additionaly we suppose that every people follow a rule, "when he/she receives a message through a call in clan, he/she relays the message all other neibors in respect to clan." Then, we can prove that this message will surely be derivered to every people that is connected by all discounted calls, and that the message will never be derivered two or more times to same person.
By the way, you are given information about application of family plan of Mr. Dango's family. Please write a program that calculates that in how many ways a different clan can be constructed. You should output the answer modulo 10007 because it may be very big.
Constraints
* 3 β€ n β€ 100,000
Input
The input consists of several datasets.
The first line of each dataset contains an integer n, which indicates the number of members in the family.
Next n lines represents information of the i-th member with four integers. The first two integers respectively represent b[0] (the partner of i) and f(i, b[0]) (the calling fee per unit time between i and b[0]). The following two integers represent b[1] and f(i, b[1]) in the same manner.
Input terminates with a dataset where n = 0.
Output
For each dataset, output the number of clan modulo 10007.
Example
Input
3
1 1 2 3
0 1 2 2
1 2 0 3
7
1 2 2 1
0 2 3 2
0 1 3 1
2 1 1 2
5 3 6 2
4 3 6 1
4 2 5 1
0
Output
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.
We have an analog clock whose three hands (the second hand, the minute hand and the hour hand) rotate quite smoothly. You can measure two angles between the second hand and two other hands.
Write a program to find the time at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on or after a given time.
<image>
Figure D.1. Angles between the second hand and two other hands
Clocks are not limited to 12-hour clocks. The hour hand of an H-hour clock goes around once in H hours. The minute hand still goes around once every hour, and the second hand goes around once every minute. At 0:0:0 (midnight), all the hands are at the upright position.
Input
The input consists of multiple datasets. Each of the dataset has four integers H, h, m and s in one line, separated by a space. H means that the clock is an H-hour clock. h, m and s mean hour, minute and second of the specified time, respectively.
You may assume 2 β€ H β€ 100, 0 β€ h < H, 0 β€ m < 60, and 0 β€ s < 60.
The end of the input is indicated by a line containing four zeros.
<image>
Figure D.2. Examples of H-hour clock (6-hour clock and 15-hour clock)
Output
Output the time T at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on and after the specified time.
For T being ho:mo:so (so seconds past mo minutes past ho o'clock), output four non-negative integers ho, mo, n, and d in one line, separated by a space, where n/d is the irreducible fraction representing so. For integer so including 0, let d be 1.
The time should be expressed in the remainder of H hours. In other words, one second after (H β 1):59:59 is 0:0:0, not H:0:0.
Example
Input
12 0 0 0
12 11 59 59
12 1 56 0
12 1 56 3
12 1 56 34
12 3 9 43
12 3 10 14
12 7 17 58
12 7 18 28
12 7 23 0
12 7 23 31
2 0 38 29
2 0 39 0
2 0 39 30
2 1 6 20
2 1 20 1
2 1 20 31
3 2 15 0
3 2 59 30
4 0 28 48
5 1 5 40
5 1 6 10
5 1 7 41
11 0 55 0
0 0 0 0
Output
0 0 43200 1427
0 0 43200 1427
1 56 4080 1427
1 56 47280 1427
1 57 4860 1427
3 10 18600 1427
3 10 61800 1427
7 18 39240 1427
7 18 82440 1427
7 23 43140 1427
7 24 720 1427
0 38 4680 79
0 39 2340 79
0 40 0 1
1 6 3960 79
1 20 2400 79
1 21 60 79
2 15 0 1
0 0 2700 89
0 28 48 1
1 6 320 33
1 6 40 1
1 8 120 11
0 55 0 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.
Problem
Given the string S, which consists of lowercase letters and numbers. Follow the steps below to compress the length of string S.
1. Change the order of the characters in the character string to any order.
Example: "0ig3he12fz99"-> "efghiz012399"
2. Perform the following operations any number of times.
* Select a contiguous substring of "abcdefghijklmnopqrstuvwxyz" in the string and replace it with (first character)'-' (last character).
Example: "efghiz012399"-> "e-iz012399"
* Select a string with a tolerance of 1 (a continuous substring of "0123456789") in the string and replace it with (first digit)'-' (last digit).
Example: "e-iz012399"-> "e-iz0-399"
Find the minimum length of the string obtained by compressing the string S.
Constraints
* 1 β€ | S | β€ 100
* String S contains only lowercase letters and numbers
Input
The string S is given on one line.
Output
Output the minimum value of the length of the character string obtained by compressing the character string S on one line. If it cannot be compressed, output the length of the original string S.
Examples
Input
0ig3he12fz99
Output
9
Input
1122334455
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.
ACM countries have rivers that flow from east to west in the center. This river flows from the neighboring country in the west through the neighboring country in ACM to the neighboring country in the east, and the total length in ACM is K km. It is planned to install several locks on this river and use it as a canal.
A lock is a mechanism for a ship to move between two different water levels. Locks have locks on the upstream and downstream sides, respectively, and a small body of water called a lock chamber between them. After putting the ship in this lock room, water is injected or drained, and the water level in the lock room is raised or lowered to raise or lower the ship. The schematic diagram is shown below.
<image>
Figure F-1: Schematic diagram of the lock
Since the width of this river is not very wide, it has been decided that it will be a one-way canal from west to east. The person in charge of design wants to optimize the location of the lock according to the expected navigation schedule of the ship in order to operate the canal efficiently.
You are a programmer hired by a designer. Your job is to write a program that simulates the time it takes for all ships to cross the river, given the lock information and the navigation schedules for multiple ships.
Each lock is represented by the following information.
* Distance from the western end of ACM country X (km)
* Volume of water required to switch the water level L (L)
* Maximum water injection amount per unit time F (L / h)
* Maximum displacement per unit time D (L / h)
* Hierarchical relationship between the water level on the west side and the water level on the east side of the lock
For convenience, in the simulation, it is assumed that the river continues infinitely outside the ACM as well.
At the start of the simulation, the water levels in all the lock chambers are the lower of the eastern and western water levels. In addition, the ships included in the navigation schedule shall be lined up every 1 km from east to west in the order given by input, starting from the western end of the ACM country. For convenience, the initial position of the leading ship is set to the 0km point.
As soon as the simulation starts, the ship begins to sail east. At this time, no other ship should enter less than 1km before and after one ship. The maximum speed V (km / h) is set for each ship. The ship can reach any speed in an instant and even stand still in an instant. Basically, a ship sails at the maximum speed, but if the following ship has a faster maximum speed than the preceding ship and the following ship catches up 1 km before the preceding ship, the following ship will lead. It sails at the same speed as the ship. The size of the ship and locks shall be negligible.
A ship can enter the lock only when the water level on the west side of the lock is equal to the water level in the lock chamber. Similarly, you can exit the lock only when the water level on the east side of the lock is equal to the water level in the lock chamber. If there is no ship inside, the water level in each lock will rise or fall until it matches the water level on the west side of the lock. If there is a ship, it will be displaced until it matches the water level on the east side of the lock. Even if the ship is moored just 1km away from the lock, the ship can leave the lock. However, at this time, the ship must berth at the exit from the lock until the preceding ship starts.
After passing the eastern end of the ACM country, the ship sails to infinity as fast as possible. The simulation ends when all ships have passed the eastern end of the ACM country.
Input
The input consists of multiple datasets. Each dataset is given in the following format.
> NMK
> X1 L1 F1 D1 UD1
> X2 L2 F2 D2 UD2
> ...
> XN LN FN DN UDN
> V1
> V2
> ...
> VM
>
The first line consists of three integers N, M, K. N (1 β€ N β€ 100) is the number of locks, M (1 β€ M β€ 100) is the number of ships, and K (2 β€ K β€ 1000) is the total length of the river in ACM.
The following N lines represent lock information. Each line consists of 5 integers Xi, Li, Fi, Di, UDi. Xi (1 β€ Xi β€ K -1) is the position of lock i from the western end of the ACM country (km), Li (1 β€ Li β€ 1000) is the volume of water required to switch the water level of lock i (L), Fi (1 β€ Fi β€ 1000) is the maximum water injection amount per unit time of lock i (L / h), Di (1 β€ Di β€ 1000) is the maximum drainage amount per unit time of lock i (L / h), UDi ( UDi β {0, 1}) represents the hierarchical relationship between the water level on the west side and the water level on the east side of the lock i, respectively. When UDi is 0, the lock i means that the water level is higher on the east side than on the west side. On the other hand, when UDi is 1, lock i means that the water level is lower on the east side than on the west side.
The following M rows are given the integer Vi (1 β€ Vi β€ 1000), which represents the maximum speed (km / h) of the i-th vessel in each row.
Locks are given in ascending order of Xi values. In addition, multiple locks will not be installed at the same position.
The end of the input consists of three zeros separated by spaces.
Output
For each dataset, output the time from the start to the end of the simulation in one line. The output value may contain an error of 10-6 or less. The value may be displayed in any number of digits after the decimal point.
Example
Input
1 1 100
50 200 20 40 0
1
2 4 100
7 4 1 4 1
19 5 1 4 0
5
3
7
9
1 2 3
1 1 1 1 0
1
3
1 2 10
5 10 1 1 1
2
3
0 0 0
Output
110
46.6666666667
5
41.6666666667
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
Dimension exists from $ 1 $ dimension to $ N $ dimension. AOR Ika can move between dimensions. Specifically, when AOR Ika is in the $ i $ dimension, she can move freely to the $ j $ dimension ($ i> j $), but in the $ k $ dimension ($ i <k $). You need to use magic to move to.
AOR Ika can use $ M $ types of magic and is numbered $ 1, 2, \ dots, M $. The $ i $ th magic allows you to move from the $ a_i $ dimension to the $ b_i $ dimension. This can only be used when you are in the $ a_i $ dimension.
When you go to the $ i $ dimension, you will receive a dimension-specific "curse of dimensionality". AOR Ika takes $ d_i $ damage due to the "curse of dimensionality" of the $ i $ dimension. If you receive the "curse of dimensionality" of the $ i $ dimension, you will not receive the "curse of dimensionality" of the $ j $ dimension ($ i> j $) forever.
Find the minimum total damage inflicted when AOR Ika moves from the $ s $ dimension to the $ t $ dimension. However, AOR Ika-chan has already received the "curse of dimensionality" of the $ s $ dimension, and we will not consider the damage. Also, AOR Ika is guaranteed to be able to go to the $ t $ dimension.
output
Output the minimum value of the total damage received by AOR Ika-chan. Also, output a line break at the end.
Example
Input
3 1 2 3
1 2 3
1 3
Output
3
The input will be give
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters. |
Solve the programming task below in a Python markdown code block.
A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.
Constraints
* 1 β€ |V| β€ 10,000
* 0 β€ |E| β€ 30,000
* 1 β€ Q β€ 100,000
Input
A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.
|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1
|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.
si and ti represent source and target nodes of i-th edge (directed).
ui and vi represent a pair of nodes given as the i-th query.
Output
For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.
Example
Input
5 6
0 1
1 0
1 2
2 4
4 3
3 2
4
0 1
0 3
2 3
3 4
Output
1
0
1
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.
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.
Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 β€ x β€ x_2 and y_1 β€ y β€ y_2, where (x_1, y_1) and (x_2, y_2) are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.
After taking the photo, Pavel wrote down coordinates of n of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.
Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.
Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
Input
The first line of the input contains an only integer n (1 β€ n β€ 100 000), the number of points in Pavel's records.
The second line contains 2 β
n integers a_1, a_2, ..., a_{2 β
n} (1 β€ a_i β€ 10^9), coordinates, written by Pavel in some order.
Output
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
Examples
Input
4
4 1 3 2 3 2 1 3
Output
1
Input
3
5 8 5 5 7 5
Output
0
Note
In the first sample stars in Pavel's records can be (1, 3), (1, 3), (2, 3), (2, 4). In this case, the minimal area of the rectangle, which contains all these points is 1 (rectangle with corners at (1, 3) and (2, 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.