question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Rng has a connected undirected graph with N vertices. Currently, there are M edges in the graph, and the i-th edge connects Vertices A_i and B_i.
Rng will add new edges to the graph by repeating the following operation:
* Operation: Choose u and v (u \neq v) such that Vertex v can be reached by traversing exactly three edges from Vertex u, and add an edge connecting Vertices u and v. It is not allowed to add an edge if there is already an edge connecting Vertices u and v.
Find the maximum possible number of edges that can be added.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i,B_i \leq N
* The graph has no self-loops or multiple edges.
* The graph is connected.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1
A_2 B_2
:
A_M B_M
Output
Find the maximum possible number of edges that can be added.
Examples
Input
6 5
1 2
2 3
3 4
4 5
5 6
Output
4
Input
5 5
1 2
2 3
3 1
5 4
5 1
Output
5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden.
Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is Ti, each pile will reduce its volume by Ti. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other.
Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day.
You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day.
Input
The first line contains a single integer N (1 ≤ N ≤ 105) — the number of days.
The second line contains N integers V1, V2, ..., VN (0 ≤ Vi ≤ 109), where Vi is the initial size of a snow pile made on the day i.
The third line contains N integers T1, T2, ..., TN (0 ≤ Ti ≤ 109), where Ti is the temperature on the day i.
Output
Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i.
Examples
Input
3
10 10 5
5 7 2
Output
5 12 4
Input
5
30 25 20 15 10
9 10 12 4 13
Output
9 20 35 11 25
Note
In the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Squid loves painting vertices in graphs.
There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1.
Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i.
Find the color of each vertex after the Q operations.
Constraints
* 1 ≤ N,M,Q ≤ 10^5
* 1 ≤ a_i,b_i,v_i ≤ N
* a_i ≠ b_i
* 0 ≤ d_i ≤ 10
* 1 ≤ c_i ≤10^5
* d_i and c_i are all integers.
* There are no self-loops or multiple edges in the given graph.
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
:
a_{M} b_{M}
Q
v_1 d_1 c_1
:
v_{Q} d_{Q} c_{Q}
Output
Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations.
Examples
Input
7 7
1 2
1 3
1 4
4 5
5 6
5 7
2 3
2
6 1 1
1 2 2
Output
2
2
2
2
2
1
0
Input
14 10
1 4
5 7
7 11
4 10
14 7
14 3
6 14
8 11
5 13
8 3
8
8 6 2
9 7 85
6 9 3
6 7 5
10 3 1
12 9 4
9 6 6
8 2 3
Output
1
0
3
1
5
5
3
3
6
1
3
4
5
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Your task is to write a program of a simple dictionary which implements the following instructions:
* insert str: insert a string str in to the dictionary
* find str: if the distionary contains str, then print 'yes', otherwise print 'no'
Notes
Template in C
Constraints
* A string consists of 'A', 'C', 'G', or 'T'
* 1 ≤ length of a string ≤ 12
* n ≤ 1000000
Input
In the first line n, the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format.
Output
Print yes or no for each find instruction in a line.
Examples
Input
5
insert A
insert T
insert C
find G
find A
Output
no
yes
Input
13
insert AAA
insert AAC
insert AGA
insert AGG
insert TTT
find AAA
find CCC
find CCC
insert CCC
find CCC
insert T
find TTT
find T
Output
yes
no
no
yes
yes
yes
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!
As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.
Photo can be represented as a matrix sized n × m, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors: 'C' (cyan) 'M' (magenta) 'Y' (yellow) 'W' (white) 'G' (grey) 'B' (black)
The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of photo pixel matrix rows and columns respectively.
Then n lines describing matrix rows follow. Each of them contains m space-separated characters describing colors of pixels in a row. Each character in the line is one of the 'C', 'M', 'Y', 'W', 'G' or 'B'.
-----Output-----
Print the "#Black&White" (without quotes), if the photo is black-and-white and "#Color" (without quotes), if it is colored, in the only line.
-----Examples-----
Input
2 2
C M
Y Y
Output
#Color
Input
3 2
W W
W W
B B
Output
#Black&White
Input
1 1
W
Output
#Black&White
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.
If $x$ is the number of passengers in a bus just before the current bus stop and $y$ is the number of passengers in the bus just after current bus stop, the system records the number $y-x$. So the system records show how number of passengers changed.
The test run was made for single bus and $n$ bus stops. Thus, the system recorded the sequence of integers $a_1, a_2, \dots, a_n$ (exactly one number for each bus stop), where $a_i$ is the record for the bus stop $i$. The bus stops are numbered from $1$ to $n$ in chronological order.
Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $w$ (that is, at any time in the bus there should be from $0$ to $w$ passengers inclusive).
-----Input-----
The first line contains two integers $n$ and $w$ $(1 \le n \le 1\,000, 1 \le w \le 10^{9})$ — the number of bus stops and the capacity of the bus.
The second line contains a sequence $a_1, a_2, \dots, a_n$ $(-10^{6} \le a_i \le 10^{6})$, where $a_i$ equals to the number, which has been recorded by the video system after the $i$-th bus stop.
-----Output-----
Print the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to $w$. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.
-----Examples-----
Input
3 5
2 1 -3
Output
3
Input
2 4
-1 1
Output
4
Input
4 10
2 4 1 2
Output
2
-----Note-----
In the first example initially in the bus could be $0$, $1$ or $2$ passengers.
In the second example initially in the bus could be $1$, $2$, $3$ or $4$ passengers.
In the third example initially in the bus could be $0$ or $1$ passenger.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Give you N cards. Only one natural number is written on each card. However, the same number is never written.
From now on, as a question, I will say an appropriate natural number. Please answer the largest remainder you get when you divide the number on the card you have by the number I said.
For example, suppose you have three cards with 9, 3, and 8, respectively. If I say "4", find the remainder of 9 and 3 and 8 divided by 4, respectively. The remainders are 1, 3, and 0, respectively, but the largest remainder is 3, so 3 is the correct answer.
Let's get started. e? Is it hard to have a lot of cards? It can not be helped. Now let's use the computer to find the largest remainder. Create a program that finds the largest of the remainders of the number on the card divided by the number asked. Ask the question many times, not just once, but never ask the same number more than once.
input
The input consists of one dataset. Input data is given in the following format.
N Q
c1 c2 ... cN
q1
q2
::
qQ
The number of cards N (2 ≤ N ≤ 300000) and the number of questions Q (2 ≤ Q ≤ 100000) are given in the first line, separated by one space, and the number ci (1 ≤ 100000) written on the card in the second line. ci ≤ 300000) is given with one space delimiter. The following Q line is given the number qi (1 ≤ qi ≤ 300000) given as a question.
output
Output the maximum remainder on one line for each question.
Example
Input
3 3
9 3 8
4
6
5
Output
3
3
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem
Jennifer and Marian presented Carla with the string S.
However, Carla is not happy to receive the string S.
I wanted the string T.
The three decided to work together to change the string S to the string T.
Jennifer first sorts the letters in any order.
Marian then exchanges the lowercase letters of the two alphabets any number of times.
This operation exchanges all the same characters in the string, for example:
* aab-> Swap a and b-> bba
* aab-> Swap a and c-> ccb
Finally, Carla replaces one character with another and repeats until T.
Jennifer and Marian decided to try to reduce the number of Carla replacements.
Find the minimum number of replacements that Carla makes.
Constraints
* 1 ≤ n ≤ 105
* S and T contain only'a'~'z'
* | S | = | T | = n
Input
n
S
T
The length n of the string is given on the first line.
The character string S is given on the second line, and the character string T is given on the third line.
Output
Print the minimum number of Carla replacements on one line.
Examples
Input
3
abc
xyz
Output
0
Input
5
aaabb
xyxyz
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
Chef has a box full of infinite number of identical coins. One day while playing, he made N piles each containing equal number of coins. Chef suddenly remembered an important task and left the room for sometime. While he was away, his newly hired assistant came across the piles and mixed them up while playing.
When Chef returned home, he was angry to see that all of his piles didn't contain equal number of coins as he very strongly believes in the policy of equality for all, may it be people or piles of coins.
In order to calm down the Chef, the assistant proposes to make all the piles equal. Chef agrees to give this task to him, but as a punishment gives him only two type of operations that he can perform.
Pick some coins from any pile and put them back in Chef's coin box.
Pick some coins from the Chef's coin box and put them on any one pile.
The assistant wants to do this task as fast as possible. So he wants to know the minimum number of operations needed to make all the piles equal.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains a single integer N denoting the number of piles.
The second line contains N space-separated integers A_{1}, A_{2}, ..., A_{N} denoting the number of coins in each pile.
------ Output ------
For each test case, output a single line containing an integer corresponding to the minimum number of operations assistant needs to do.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ N ≤ 10^{5}$
$1 ≤ A_{i} ≤ 10^{5}$
------ Sub tasks ------
$Subtask #1: 1 ≤ N ≤ 1000 (30 points)$
$Subtask #2: original constraints (70 points)$
----- Sample Input 1 ------
1
4
1 2 3 4
----- Sample Output 1 ------
3
----- explanation 1 ------
In test case 1, if you decide to convert all the piles to contain either of 1, 2, 3, or 4 coins you will have to change the other 3 piles. For any other choice you will have to alter more than 3 (i.e. 4) piles.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
You have to play a darts game with the following rules.
You can throw up to four arrows towards the target. You don't have to throw all four, you don't have to throw one. The target is divided into N parts. The score P1, ..., PN is written in each part. The total score S of the place where the arrow is stuck is the basis of your score. S is a predetermined score M or less. In the case of, S will be your score as it is. However, if S exceeds M, your score will be 0 points.
Create a program that finds the maximum number of points you can get given the written points and the value of M.
input
The input consists of multiple datasets. Each dataset is given in the following format.
On the first line, the integers N (1 ≤ N ≤ 1000) and M (1 ≤ M ≤ 200000000 = 2 × 108) are written in this order, separated by blanks. In (1 ≤ i ≤ N), Pi (1 ≤ Pi ≤ 100000000 = 108) is written.
Of the scoring data, 20% of the points satisfy N ≤ 100 and 50% of the points satisfy N ≤ 300.
When both N and M are 0, the input is completed. The number of data sets does not exceed 10.
output
Outputs the maximum number of points you can get for each dataset on one line.
Examples
Input
4 50
3
14
15
9
3 21
16
11
2
0 0
Output
48
20
Input
None
Output
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N mountains ranging from east to west, and an ocean to the west.
At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.
The height of the i-th mountain from the west is H_i.
You can certainly see the ocean from the inn at the top of the westmost mountain.
For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.
From how many of these N inns can you see the ocean?
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 20
- 1 \leq H_i \leq 100
-----Input-----
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
-----Output-----
Print the number of inns from which you can see the ocean.
-----Sample Input-----
4
6 5 6 8
-----Sample Output-----
3
You can see the ocean from the first, third and fourth inns from the west.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard.
He intended to write `CODEFESTIVAL2016` on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length.
So Mr. Takahashi decided to perform an operation that replaces a certain character with another in the minimum number of iterations, changing the string to `CODEFESTIVAL2016`.
Find the minimum number of iterations for the rewrite operation.
Constraints
* S is 16 characters long.
* S consists of uppercase and lowercase alphabet letters and numerals.
Input
Inputs are provided from Standard Input in the following form.
S
Output
Output an integer representing the minimum number of iterations needed for the rewrite operation.
Examples
Input
C0DEFESTIVAL2O16
Output
2
Input
FESTIVAL2016CODE
Output
16
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
n people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.
What is the maximum amount of people that could stay at the party in the end?
Input
The first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).
Output
For each test output in a separate line one number — the maximum amount of people that could stay in the end.
Examples
Input
1
3
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Assume `"#"` is like a backspace in string. This means that string `"a#bc#d"` actually is `"bd"`
Your task is to process a string with `"#"` symbols.
## Examples
```
"abc#d##c" ==> "ac"
"abc##d######" ==> ""
"#######" ==> ""
"" ==> ""
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.
After how many full years will Limak become strictly larger (strictly heavier) than Bob?
-----Input-----
The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10) — the weight of Limak and the weight of Bob respectively.
-----Output-----
Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.
-----Examples-----
Input
4 7
Output
2
Input
4 9
Output
3
Input
1 1
Output
1
-----Note-----
In the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.
In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.
In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..."
The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride.
The bus fare equals one berland ruble in High Bertown. However, not everything is that easy — no more than one child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his k (k > 0) children, pays overall k rubles: a ticket for himself and (k - 1) tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble.
We know that in High Bertown children can't ride in a bus unaccompanied by grown-ups.
Help Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total.
Input
The input file consists of a single line containing two space-separated numbers n and m (0 ≤ n, m ≤ 105) — the number of the grown-ups and the number of the children in the bus, correspondingly.
Output
If n grown-ups and m children could have ridden in the bus, then print on a single line two space-separated integers — the minimum and the maximum possible total bus fare, correspondingly.
Otherwise, print "Impossible" (without the quotes).
Examples
Input
1 2
Output
2 2
Input
0 5
Output
Impossible
Input
2 2
Output
2 3
Note
In the first sample a grown-up rides with two children and pays two rubles.
In the second sample there are only children in the bus, so the situation is impossible.
In the third sample there are two cases:
* Each of the two grown-ups rides with one children and pays one ruble for the tickets. In this case the passengers pay two rubles in total.
* One of the grown-ups ride with two children's and pays two rubles, the another one rides alone and pays one ruble for himself. So, they pay three rubles in total.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
In a far away dystopian world, the measure of the quality of a person’s life is the numbers of likes he gets for an article about their life. For a person to stay alive, he has to acquire at least L number of likes before D days pass.
People in this world employ various techniques to increase the number of likes. One of the famous ones is to dis-like and re-like their own article once per day. On doing so you can assume that the number of likes for the post increase by a constant factor C.
So if one starts with S likes on Day-1, he would have D2 = S + C * S likes on Day-2, D3 = D2 + D2 * C on Day-3 etc. You are to answer if the person would survive at the end of Day-D or not.
Input
First line contains a single positive integer T denoting the number of test cases. The following T lines represent a test case each. Each test case contains 4 space-separated integers L, D, S and C.
Output
For each test case, print a single line containing “ALIVE AND KICKING” if the person would live, otherwise print, “DEAD AND ROTTING”.
Constraints
1 ≤ T ≤ 1000
1 ≤ L ≤ 1000000000
1 ≤ D ≤ 1000000000
1 ≤ S ≤ 1000000000
1 ≤ C ≤ 1000000000
----- Sample Input 1 ------
2
5 1 5 1
10 2 2 2
----- Sample Output 1 ------
ALIVE AND KICKING
DEAD AND ROTTING
----- explanation 1 ------
In the first case by the end of Day-1 we would be having S that is 5 number of likes, as it is ? L, the answer is ALIVE AND KICKING.
In the second case, D2 =S + C*S, therefore D2 = 2 + 2 * 2 = 6, as 6 is less than 10, the answer is DEAD AND ROTTING.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Gildong's town has a train system that has $100$ trains that travel from the bottom end to the top end and $100$ trains that travel from the left end to the right end. The trains starting from each side are numbered from $1$ to $100$, respectively, and all trains have the same speed. Let's take a look at the picture below.
The train system can be represented as coordinates on a 2D plane. The $i$-th train starting at the bottom end is initially at $(i,0)$ and will be at $(i,T)$ after $T$ minutes, and the $i$-th train starting at the left end is initially at $(0,i)$ and will be at $(T,i)$ after $T$ minutes. All trains arrive at their destinations after $101$ minutes.
However, Gildong found that some trains scheduled to depart at a specific time, simultaneously, are very dangerous. At this time, $n$ trains are scheduled to depart from the bottom end and $m$ trains are scheduled to depart from the left end. If two trains are both at $(x,y)$ at the same time for some $x$ and $y$, they will crash into each other. Therefore, he is asking you to find the minimum number of trains that should be cancelled to prevent all such crashes.
-----Input-----
Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$).
Each test case contains three lines. The first line of each test case consists of two integers $n$ and $m$ ($1 \le n, m \le 100$) — the number of trains scheduled to depart from the bottom end, and the number of trains scheduled to depart from the left end, respectively.
The second line of each test case contains $n$ integers. Each integer is a train number that is scheduled to start from the bottom end. The numbers are given in strictly increasing order, and are between $1$ and $100$, inclusive.
The third line of each test case contains $m$ integers. Each integer is a train number that is scheduled to start from the left end. The numbers are given in strictly increasing order, and are between $1$ and $100$, inclusive.
-----Output-----
For each test case, print a single integer: the minimum number of trains that should be canceled in order to prevent all crashes.
-----Examples-----
Input
3
1 2
1
3 4
3 2
1 3 4
2 4
9 14
2 7 16 28 33 57 59 86 99
3 9 14 19 25 26 28 35 41 59 85 87 99 100
Output
0
1
3
-----Note-----
In the first case, we can show that there will be no crashes if the current schedule is followed. Therefore, the answer is zero.
In the second case, at $T=4$, there will be a crash, as can be seen in the picture below. We can prove that after canceling one of these trains, the remaining trains will not crash. Therefore, the answer is one.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
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 \le n \le 200\,000, 1 \le k \le 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" $\rightarrow$ "WWBWBWW" $\rightarrow$ "WWWBWWW" $\rightarrow$ "WWWWWWW". So all chips become white.
The third example: "BWBWBW" $\rightarrow$ "WBWBWB" $\rightarrow$ "BWBWBW" $\rightarrow$ "WBWBWB" $\rightarrow$ "BWBWBW".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Mobiles are widely known as moving works of art. The IOI Japan Committee has decided to create mobiles to publicize JOI. JOI public relations mobiles are sticks, strings, and weights. It is constructed as follows using the three types of elements of.
* One end of the bar is painted blue and the other end is painted red.
* The rod is hung with a string with one point other than both ends as a fulcrum.
* Both the length from the fulcrum to the red end and the length from the fulcrum to the blue end are positive integers.
* At both ends of the rod, hang a weight or another rod with a string.
* The weight is hung on one end of one of the rods using a string.
* Nothing hangs on the weight.
* The weight of the weight is a positive integer.
* Only one of the strings is tied at one end to the fulcrum of that bar to hang one bar, the other end is not tied to any other component. Meet one or the other.
* Connect the end of a bar to the fulcrum of a bar.
* Connect the end of a rod to a weight.
However, all rods need to be balanced. The weights of the rods and strings are negligibly light, so consider that the weights of the rods and strings are all 0. About the stick,
(Total weight of weights suspended below the red end of the rod) × (Length from the fulcrum of the rod to the red end) = (Hung below the blue end of the rod) Total weight of the weight) × (length from the fulcrum of the rod to the end of the blue)
If, then the bar is balanced.
<image>
The length and how to tie the rods to make up the mobile has already been decided, but the weight of the weight has not been decided yet. The lighter the mobile, the easier it is to hang, so I want to make the mobile as light as possible. As mentioned above, while balancing all the rods, find a way to attach a weight that minimizes the total weight of the mobile, and create a program that outputs the total weight of the mobile at that time. Information about the configuration is given.
* Number of bars n
* Information for each bar (bar numbers 1 to n)
* Ratio of the length from the fulcrum to the red end to the length from the fulcrum to the blue end
* Number of rods to hang on the red end (0 for hanging weights)
* Number of rods to hang on the blue edge (0 for hanging weights)
<image>
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing one zero.
The first line contains the number of bars n used in the mobile. The following n lines (1 ≤ n ≤ 100) contain the data for each bar. I + 1st line In (1 ≤ i ≤ n), four integers p, q, r, b are written with a blank as a delimiter, and on the bar i, the length from the fulcrum to the red end and the length from the fulcrum to the blue end. The ratio is p: q, the number of the bar hanging at the red end is r, and the number of the bar hanging at the blue end is b, where bar number 0 is the weight. In any input, if the minimum value of the weight of the mobile is w and the maximum value of the positive integer used to express the ratio in the input is L, then wL <231 Meet.
The number of datasets does not exceed 15.
output
The weight of the mobile is output to one line for each data set.
Examples
Input
1
6 9 0 0
4
3 2 0 4
1 3 0 0
4 4 2 1
2 2 0 0
0
Output
5
40
Input
None
Output
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."
And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not.
Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $k$, so they got $k+1$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.
In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $3$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.
More formally, Sasha wants for the given palindrome $s$ find such minimum $k$, that you can cut this string into $k + 1$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $s$. It there is no answer, then print "Impossible" (without quotes).
-----Input-----
The first line contains one string $s$ ($1 \le |s| \le 5\,000$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $s$ is a palindrome.
-----Output-----
Print one integer $k$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).
-----Examples-----
Input
nolon
Output
2
Input
otto
Output
1
Input
qqqq
Output
Impossible
Input
kinnikkinnik
Output
1
-----Note-----
In the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.
In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.
In the third example, you can't make a string, that won't be equal to the initial one.
In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.
There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.
There are n cars in the rental service, i-th of them is characterized with two integers c_{i} and v_{i} — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity v_{i}. All cars are completely fueled at the car rental service.
Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.
Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.
-----Input-----
The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·10^5, 1 ≤ k ≤ 2·10^5, 2 ≤ s ≤ 10^9, 1 ≤ t ≤ 2·10^9) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.
Each of the next n lines contains two positive integers c_{i} and v_{i} (1 ≤ c_{i}, v_{i} ≤ 10^9) — the price of the i-th car and its fuel tank capacity.
The next line contains k distinct integers g_1, g_2, ..., g_{k} (1 ≤ g_{i} ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.
-----Output-----
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.
-----Examples-----
Input
3 1 8 10
10 8
5 7
11 9
3
Output
10
Input
2 2 10 18
10 4
20 6
5 3
Output
20
-----Note-----
In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.
We will consider an extremely simplified subset of Python with only two types of statements.
Simple statements are written in a single line, one per line. An example of a simple statement is assignment.
For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.
You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.
-----Input-----
The first line contains a single integer N (1 ≤ N ≤ 5000) — the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.
-----Output-----
Output one line containing an integer - the number of ways the given sequence of statements can be indented modulo 10^9 + 7.
-----Examples-----
Input
4
s
f
f
s
Output
1
Input
4
f
s
f
s
Output
2
-----Note-----
In the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.
simple statement
for statement
for statement
simple statement
In the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.
for statement
simple statement
for statement
simple statement
or
for statement
simple statement
for statement
simple statement
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Example
Input
3
3 0 1
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out — one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100, 2 ≤ n · m) — the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).
Output
On the first line output integer k — the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m) — the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2).
Then print nm + 1 lines containing 2 numbers each — the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.
Examples
Input
2 2
Output
0
1 1
1 2
2 2
2 1
1 1
Input
3 3
Output
1
3 3 1 1
1 1
1 2
1 3
2 3
2 2
2 1
3 1
3 2
3 3
1 1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A: four tea
problem
Tea is indispensable for programming contests. Tea has the effect of relieving constant tension [citation needed]
There are N players participating in the contest, so I would like to prepare tea for this number of people. There are four types of tea packages, A, B, C, and D, all of which are the same variety but have different contents. For a package X, the price of one package is p_X yen, and it is known that if you buy one, you can make t_X cups of tea.
Find the minimum amount needed to make tea for N people. You may have a package that you don't buy at all, and you don't have to buy a package for just N people (if you can make more than N people).
Input format
The input is given in the following format.
N
p_A p_B p_C p_D
t_A t_B t_C t_D
* The first line gives the number of players participating in the contest.
* In the second line, the prices of tea in packages A, B, C and D are given separated by blanks.
* The third line gives the number of cups of tea that can be made from packages A, B, C, and D, separated by blanks.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq p_X \ leq 100
* 1 \ leq t_X \ leq 100
* All inputs are given as integers.
Output format
Output the minimum amount required to make tea for N people in one line.
Input example 1
Ten
1 2 3 4
1 2 4 8
Output example 1
6
* It's best to buy one package B and one D.
Input example 2
Five
2 9 9 8
1 4 5 100
Output example 2
8
* You will have 20 times more tea than you need, but buying one Package D is the cheapest way to get more than 5 cups of tea.
Input example 3
twenty four
2 3 4 7
7 9 11 20
Output example 3
8
* It's best to buy two packages A and one C. It may not be possible to make just enough tea for the number of people as in this case.
Example
Input
10
1 2 3 4
1 2 4 8
Output
6
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
**_Given_** a **_list of digits_**, *return the **_smallest number_** that could be formed from these digits, using the digits only once (ignore duplicates).*
___
# Notes:
* Only **_positive integers_** *will be passed to the function (> 0 ), no negatives or zeros.*
___
# Input >> Output Examples
```
minValue ({1, 3, 1}) ==> return (13)
```
## Explanation:
**_(13)_** *is the minimum number could be formed from* **_{1, 3, 1}_** , *Without duplications*
___
```
minValue({5, 7, 5, 9, 7}) ==> return (579)
```
## Explanation:
**_(579)_** *is the minimum number could be formed from* **_{5, 7, 5, 9, 7}_** , *Without duplications*
___
```
minValue({1, 9, 3, 1, 7, 4, 6, 6, 7}) return ==> (134679)
```
## Explanation:
**_(134679)_** *is the minimum number could be formed from* **_{1, 9, 3, 1, 7, 4, 6, 6, 7}_** , *Without duplications*
___
___
## [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [Bizarre Sorting-katas](https://www.codewars.com/collections/bizarre-sorting-katas)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Initially, each vertex is uncolored.
Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi:
* Select a vertex that is not painted yet.
* If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki.
Then, after all the vertices are colored, the following procedure takes place:
* Repaint every white vertex that is adjacent to a black vertex, in black.
Note that all such white vertices are repainted simultaneously, not one at a time.
If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally.
Constraints
* 2 ≤ N ≤ 10^5
* 1 ≤ a_i,b_i ≤ N
* a_i ≠ b_i
* The input graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print `First` if Takahashi wins; print `Second` if Aoki wins.
Examples
Input
3
1 2
2 3
Output
First
Input
4
1 2
2 3
2 4
Output
First
Input
6
1 2
2 3
3 4
2 5
5 6
Output
Second
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Beans are popular at Otsu University. N beans are lined up in a straight line. Each is numbered from 0 to N-1, and the hardness of the i-th bean is ai.
Cyan considers the ideal bean hardness to be D. However, Cyan doesn't want to go get the beans that are too far away because he is troublesome. Therefore, Cyan wants to know the beans whose hardness is closest to D among the l-th to r-th beans.
Cyan asks Q questions, so create a program to find the minimum value of | bean hardness − D | in the closed interval [l, r] for each question. (However, | a | represents the absolute value of a.)
Constraints
The input satisfies the following constraints.
* 1 ≤ N ≤ 105
* 0 ≤ | ai | ≤ 106 (0 ≤ i ≤ N−1)
* 1 ≤ Q ≤ 105
* 0 ≤ Di ≤ 106
* 0 ≤ li ≤ ri ≤ N-1
Input
The input is given in the following format.
N
a0 a1 ... aN−1
Q
l0 r0 D0
l1 r1 D1
..
..
..
lQ−1 rQ−1 DQ−1
The first line is given one integer N. On the second line, N integers are given, separated by blanks. On the third line, the number of queries is given as one integer Q. The query values l, r, and D are given in the following 4 to 3 + Q lines.
Output
For each query, output the absolute value of the difference between D and the hardness of the bean closest to hardness D among the [l, r] th beans on one line.
Examples
Input
3
1 2 3
3
0 2 2
0 2 4
0 0 2
Output
0
1
1
Input
10
4 5 0 21 9 100 12 9 0 8
5
0 3 20
2 5 100
8 9 9
5 5 10
0 9 20
Output
1
0
1
90
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number — the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N cards placed on a grid with H rows and W columns of squares.
The i-th card has an integer A_i written on it, and it is placed on the square at the R_i-th row from the top and the C_i-th column from the left.
Multiple cards may be placed on the same square.
You will first pick up at most one card from each row.
Then, you will pick up at most one card from each column.
Find the maximum possible sum of the integers written on the picked cards.
Constraints
* All values are integers.
* 1 \leq N \leq 10^5
* 1 \leq H, W \leq 10^5
* 1 \leq A_i \leq 10^5
* 1 \leq R_i \leq H
* 1 \leq C_i \leq W
Input
Input is given from Standard Input in the following format:
N H W
R_1 C_1 A_1
R_2 C_2 A_2
\vdots
R_N C_N A_N
Output
Print the maximum possible sum of the integers written on the picked cards.
Examples
Input
6 2 2
2 2 2
1 1 8
1 1 5
1 2 9
1 2 7
2 1 4
Output
28
Input
13 5 6
1 3 35902
4 6 19698
4 6 73389
3 6 3031
3 1 4771
1 4 4784
2 1 36357
2 1 24830
5 6 50219
4 6 22645
1 2 30739
1 4 68417
1 5 78537
Output
430590
Input
1 100000 100000
1 1 1
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two integer arrays a_0, a_1, ..., a_{N - 1} and b_0, b_1, ..., b_{M - 1}. Calculate the array c_0, c_1, ..., c_{(N - 1) + (M - 1)}, defined by c_i = \sum_{j = 0}^i a_j b_{i - j} \bmod 998244353.
Constraints
* 1 \leq N, M \leq 524288
* 0 \leq a_i, b_i < 998244353
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N M
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{M-1}
Output
Print the answer in the following format:
c_0 c_1 ... c_{(N - 1) + (M - 1)}
Output
Print the answer in the following format:
c_0 c_1 ... c_{(N - 1) + (M - 1)}
Examples
Input
4 5
1 2 3 4
5 6 7 8 9
Output
5 16 34 60 70 70 59 36
Input
1 1
10000000
10000000
Output
871938225
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has N hats. The i-th hat has an integer a_i written on it.
There are N camels standing in a circle. Snuke will put one of his hats on each of these camels.
If there exists a way to distribute the hats to the camels such that the following condition is satisfied for every camel, print `Yes`; otherwise, print `No`.
* The bitwise XOR of the numbers written on the hats on both adjacent camels is equal to the number on the hat on itself.
What is XOR? The bitwise XOR x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows: - When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even. For example, 3 \oplus 5 = 6.
Constraints
* All values in input are integers.
* 3 \leq N \leq 10^{5}
* 0 \leq a_i \leq 10^{9}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_{N}
Output
Print the answer.
Examples
Input
3
1 2 3
Output
Yes
Input
4
1 2 4 8
Output
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet.
You have $b$ buns, $p$ beef patties and $f$ chicken cutlets in your restaurant. You can sell one hamburger for $h$ dollars and one chicken burger for $c$ dollars. Calculate the maximum profit you can achieve.
You have to answer $t$ independent queries.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) – the number of queries.
The first line of each query contains three integers $b$, $p$ and $f$ ($1 \le b, ~p, ~f \le 100$) — the number of buns, beef patties and chicken cutlets in your restaurant.
The second line of each query contains two integers $h$ and $c$ ($1 \le h, ~c \le 100$) — the hamburger and chicken burger prices in your restaurant.
-----Output-----
For each query print one integer — the maximum profit you can achieve.
-----Example-----
Input
3
15 2 3
5 10
7 5 2
10 12
1 100 100
100 100
Output
40
34
0
-----Note-----
In first query you have to sell two hamburgers and three chicken burgers. Your income is $2 \cdot 5 + 3 \cdot 10 = 40$.
In second query you have to ell one hamburgers and two chicken burgers. Your income is $1 \cdot 10 + 2 \cdot 12 = 34$.
In third query you can not create any type of burgers because because you have only one bun. So your income is zero.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of: uppercase and lowercase English letters, underscore symbols (they are used as separators), parentheses (both opening and closing).
It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.
For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".
Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds: the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses), the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 255) — the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols.
-----Output-----
Print two space-separated integers: the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses), the number of words inside the parentheses (print 0, if there is no word inside the parentheses).
-----Examples-----
Input
37
_Hello_Vasya(and_Petya)__bye_(and_OK)
Output
5 4
Input
37
_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__
Output
2 6
Input
27
(LoooonG)__shOrt__(LoooonG)
Output
5 2
Input
5
(___)
Output
0 0
-----Note-----
In the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider a currency system in which there are notes of six denominations, namely, Rs. 1, Rs. 2, Rs. 5, Rs. 10, Rs. 50, Rs. 100.
If the sum of Rs. N is input, write a program to computer smallest number of notes that will combine to give Rs. N.
-----Input-----
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.
-----Output-----
For each test case, display the smallest number of notes that will combine to give N, in a new line.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000000
-----Example-----
Input
3
1200
500
242
Output
12
5
7
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.
There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs $(i + j) \operatorname{mod}(n + 1)$ and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of schools.
-----Output-----
Print single integer: the minimum cost of tickets needed to visit all schools.
-----Examples-----
Input
2
Output
0
Input
10
Output
4
-----Note-----
In the first example we can buy a ticket between the schools that costs $(1 + 2) \operatorname{mod}(2 + 1) = 0$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
With one die of 6 sides we will have six different possible results:``` 1, 2, 3, 4, 5, 6``` .
With 2 dice of six sides, we will have 36 different possible results:
```
(1,1),(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(1,5),
(5,1), (1,6),(6,1),(2,2),(2,3),(3,2),(2,4),(4,2),
(2,5),(5,2)(2,6),(6,2),(3,3),(3,4),(4,3),(3,5),(5,3),
(3,6),(6,3),(4,4),(4,5),(5,4),(4,6),(6,4),(5,5),
(5,6),(6,5),(6,6)
```
So, with 2 dice of 6 sides we get 36 different events.
```
([6,6] ---> 36)
```
But with 2 different dice we can get for this case, the same number of events.
One die of ```4 sides``` and another of ```9 sides``` will produce the exact amount of events.
```
([4,9] ---> 36)
```
We say that the dice set ```[4,9]``` is equivalent to ```[6,6]``` because both produce the same number of events.
Also we may have an amount of three dice producing the same amount of events. It will be for:
```
[4,3,3] ---> 36
```
(One die of 4 sides and two dice of 3 sides each)
Perhaps you may think that the following set is equivalent: ```[6,3,2]``` but unfortunately dice have a **minimum of three sides** (well, really a
tetrahedron with one empty side)
The task for this kata is to get the amount of equivalent dice sets, having **2 dice at least**,for a given set.
For example, for the previous case: [6,6] we will have 3 equivalent sets that are: ``` [4, 3, 3], [12, 3], [9, 4]``` .
You may assume that dice are available from 3 and above for any value up to an icosahedral die (20 sides).
```
[5,6,4] ---> 5 (they are [10, 4, 3], [8, 5, 3], [20, 6], [15, 8], [12, 10])
```
For the cases we cannot get any equivalent set the result will be `0`.
For example for the set `[3,3]` we will not have equivalent dice.
Range of inputs for Random Tests:
```
3 <= sides <= 15
2 <= dices <= 7
```
See examples in the corresponding box.
Enjoy it!!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $n$ positive integers $a_1, a_2, \ldots, a_n$. Your task is to calculate the number of arrays of $n$ positive integers $b_1, b_2, \ldots, b_n$ such that:
$1 \le b_i \le a_i$ for every $i$ ($1 \le i \le n$), and
$b_i \neq b_{i+1}$ for every $i$ ($1 \le i \le n - 1$).
The number of such arrays can be very large, so print it modulo $998\,244\,353$.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$).
-----Output-----
Print the answer modulo $998\,244\,353$ in a single line.
-----Examples-----
Input
3
2 2 2
Output
2
Input
2
2 3
Output
4
Input
3
1 1 1
Output
0
-----Note-----
In the first test case possible arrays are $[1, 2, 1]$ and $[2, 1, 2]$.
In the second test case possible arrays are $[1, 2]$, $[1, 3]$, $[2, 1]$ and $[2, 3]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query lj, rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj, alj + 1, ..., arj.
Help the Little Elephant to count the answers to all queries.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1 ≤ lj ≤ rj ≤ n).
Output
In m lines print m integers — the answers to the queries. The j-th line should contain the answer to the j-th query.
Examples
Input
7 2
3 1 2 2 3 3 7
1 7
3 4
Output
3
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a playlist consisting of $n$ songs. The $i$-th song is characterized by two numbers $t_i$ and $b_i$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $3$ songs having lengths $[5, 7, 4]$ and beauty values $[11, 14, 6]$ is equal to $(5 + 7 + 4) \cdot 6 = 96$.
You need to choose at most $k$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 3 \cdot 10^5$) – the number of songs in the playlist and the maximum number of songs you can choose, respectively.
Each of the next $n$ lines contains two integers $t_i$ and $b_i$ ($1 \le t_i, b_i \le 10^6$) — the length and beauty of $i$-th song.
-----Output-----
Print one integer — the maximum pleasure you can get.
-----Examples-----
Input
4 3
4 7
15 1
3 6
6 8
Output
78
Input
5 3
12 31
112 4
100 100
13 55
55 50
Output
10000
-----Note-----
In the first test case we can choose songs ${1, 3, 4}$, so the total pleasure is $(4 + 3 + 6) \cdot 6 = 78$.
In the second test case we can choose song $3$. The total pleasure will be equal to $100 \cdot 100 = 10000$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have $n$ lectures. Hyunuk has two candidate venues $a$ and $b$. For each of the $n$ lectures, the speaker specified two time intervals $[sa_i, ea_i]$ ($sa_i \le ea_i$) and $[sb_i, eb_i]$ ($sb_i \le eb_i$). If the conference is situated in venue $a$, the lecture will be held from $sa_i$ to $ea_i$, and if the conference is situated in venue $b$, the lecture will be held from $sb_i$ to $eb_i$. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval $[x, y]$ overlaps with a lecture held in interval $[u, v]$ if and only if $\max(x, u) \le \min(y, v)$.
We say that a participant can attend a subset $s$ of the lectures if the lectures in $s$ do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue $a$ or venue $b$ to hold the conference.
A subset of lectures $s$ is said to be venue-sensitive if, for one of the venues, the participant can attend $s$, but for the other venue, the participant cannot attend $s$.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in $s$ because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 100000$), the number of lectures held in the conference.
Each of the next $n$ lines contains four integers $sa_i$, $ea_i$, $sb_i$, $eb_i$ ($1 \le sa_i, ea_i, sb_i, eb_i \le 10^9$, $sa_i \le ea_i, sb_i \le eb_i$).
-----Output-----
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
-----Examples-----
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
-----Note-----
In second example, lecture set $\{1, 3\}$ is venue-sensitive. Because participant can't attend this lectures in venue $a$, but can attend in venue $b$.
In first and third example, venue-sensitive set does not exist.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length $k$ ($k \ge 3$). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights $a_1, a_2, \dots, a_n$ in order from left to right ($k \le n$). It is guaranteed that neighboring heights are not equal to each other (that is, $a_i \ne a_{i+1}$ for all $i$ from $1$ to $n-1$).
Peaks of mountains on the segment $[l,r]$ (from $l$ to $r$) are called indexes $i$ such that $l < i < r$, $a_{i - 1} < a_i$ and $a_i > a_{i + 1}$. It is worth noting that the boundary indexes $l$ and $r$ for the segment are not peaks. For example, if $n=8$ and $a=[3,1,4,1,5,9,2,6]$, then the segment $[1,8]$ has only two peaks (with indexes $3$ and $6$), and there are no peaks on the segment $[3, 6]$.
To break the door, Nastya throws it to a segment $[l,l+k-1]$ of consecutive mountains of length $k$ ($1 \le l \le n-k+1$). When the door touches the peaks of the mountains, it breaks into two parts, after that these parts will continue to fall in different halves and also break into pieces when touching the peaks of the mountains, and so on. Formally, the number of parts that the door will break into will be equal to $p+1$, where $p$ is the number of peaks on the segment $[l,l+k-1]$.
Nastya wants to break it into as many pieces as possible. Help her choose such a segment of mountains $[l, l+k-1]$ that the number of peaks on it is maximum. If there are several optimal segments, Nastya wants to find one for which the value $l$ is minimal.
Formally, you need to choose a segment of mountains $[l, l+k-1]$ that has the maximum number of peaks. Among all such segments, you need to find the segment that has the minimum possible value $l$.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases. Then the descriptions of the test cases follow.
The first line of each test case contains two integers $n$ and $k$ ($3 \leq k \leq n \leq 2 \cdot 10^5$) — the number of mountains and the length of the door.
The second line of the input data set contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \leq a_i \leq 10 ^ 9$, $a_i \neq a_{i + 1}$) — the heights of mountains.
It is guaranteed that the sum of $n$ over all the test cases will not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output two integers $t$ and $l$ — the maximum number of parts that the door can split into, and the left border of the segment of length $k$ that the door should be reset to.
-----Example-----
Input
5
8 6
1 2 4 1 2 4 1 2
5 3
3 2 3 2 1
10 4
4 3 4 3 2 3 2 1 0 1
15 7
3 7 4 8 2 3 4 5 21 2 3 4 2 1 3
7 5
1 2 3 4 5 6 1
Output
3 2
2 2
2 1
3 1
2 3
-----Note-----
In the first example, you need to select a segment of mountains from $2$ to $7$. In this segment, the indexes $3$ and $6$ are peaks, so the answer is $3$ (only $2$ peaks, so the door will break into $3$ parts). It is not difficult to notice that the mountain segments $[1, 6]$ and $[3, 8]$ are not suitable since they only have a $1$ peak (for the first segment, the $6$ index is not a peak, and for the second segment, the $3$ index is not a peak).
In the second example, you need to select a segment of mountains from $2$ to $4$. In this segment, the index $3$ is a peak, so the answer is $2$ (only $1$ peak, so the door will break into $2$ parts).
In the third example, you need to select a segment of mountains from $1$ to $4$. In this segment, the index $3$ is a peak, so the answer is $2$ (only $1$ peak, so the door will break into $2$ parts). You can see that on the segments $[2, 5]$, $[4, 7]$ and $[5, 8]$ the number of peaks is also $1$, but these segments have a left border greater than the segment $[1, 4]$, so they are not the correct answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kode Festival is an anual contest where the hardest stone in the world is determined. (Kode is a Japanese word for "hardness".)
This year, 2^N stones participated. The hardness of the i-th stone is A_i.
In the contest, stones are thrown at each other in a knockout tournament.
When two stones with hardness X and Y are thrown at each other, the following will happen:
* When X > Y: The stone with hardness Y will be destroyed and eliminated. The hardness of the stone with hardness X will become X-Y.
* When X = Y: One of the stones will be destroyed and eliminated. The hardness of the other stone will remain the same.
* When X < Y: The stone with hardness X will be destroyed and eliminated. The hardness of the stone with hardness Y will become Y-X.
The 2^N stones will fight in a knockout tournament as follows:
1. The following pairs will fight: (the 1-st stone versus the 2-nd stone), (the 3-rd stone versus the 4-th stone), ...
2. The following pairs will fight: (the winner of (1-st versus 2-nd) versus the winner of (3-rd versus 4-th)), (the winner of (5-th versus 6-th) versus the winner of (7-th versus 8-th)), ...
3. And so forth, until there is only one stone remaining.
Determine the eventual hardness of the last stone remaining.
Constraints
* 1 \leq N \leq 18
* 1 \leq A_i \leq 10^9
* A_i is an integer.
Input
The input is given from Standard Input in the following format:
N
A_1
A_2
:
A_{2^N}
Output
Print the eventual hardness of the last stone remaining.
Examples
Input
2
1
3
10
19
Output
7
Input
3
1
3
2
4
6
8
100
104
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Jzzhu have n non-negative integers a1, a2, ..., an. We will call a sequence of indexes i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n) a group of size k.
Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aik = 0 (1 ≤ k ≤ n)? Help him and print this number modulo 1000000007 (109 + 7). Operation x & y denotes bitwise AND operation of two numbers.
Input
The first line contains a single integer n (1 ≤ n ≤ 106). The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 106).
Output
Output a single integer representing the number of required groups modulo 1000000007 (109 + 7).
Examples
Input
3
2 3 3
Output
0
Input
4
0 1 2 3
Output
10
Input
6
5 2 0 5 2 1
Output
53
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.
There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.
The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.
Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.
Constraints
* 1 ≦ W,H ≦ 10^5
* 1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)
* 1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)
* p_i (0 ≦ i ≦ W−1) is an integer.
* q_j (0 ≦ j ≦ H−1) is an integer.
Input
Inputs are provided from Standard Input in the following form.
W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}
Output
Output an integer representing the minimum total cost.
Examples
Input
2 2
3
5
2
7
Output
29
Input
4 3
2
4
8
1
2
9
3
Output
60
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: if the last digit of the number is non-zero, she decreases the number by one; if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit).
You are given an integer number $n$. Tanya will subtract one from it $k$ times. Your task is to print the result after all $k$ subtractions.
It is guaranteed that the result will be positive integer number.
-----Input-----
The first line of the input contains two integer numbers $n$ and $k$ ($2 \le n \le 10^9$, $1 \le k \le 50$) — the number from which Tanya will subtract and the number of subtractions correspondingly.
-----Output-----
Print one integer number — the result of the decreasing $n$ by one $k$ times.
It is guaranteed that the result will be positive integer number.
-----Examples-----
Input
512 4
Output
50
Input
1000000000 9
Output
1
-----Note-----
The first example corresponds to the following sequence: $512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Illumination
Illuminations are displayed in the corridors every year at the JOI High School Cultural Festival. The illuminations consist of N light bulbs, which are lined up in a row from the west side to the east side of the corridor. Each light bulb is either on or off.
A machine that operates a light bulb is sleeping in the warehouse of JOI High School. When a continuous light bulb is specified in the illumination, this machine turns all the specified light bulbs with the light on and all the light bulbs without the light on. However, the machine is aging and can only be used once.
JOI high school students like alternating rows of light bulbs with and without lights (such rows of light bulbs are called alternating rows). Therefore, I decided to use this machine only once if necessary to make illuminations containing alternating rows as long as possible.
Example
For example, the arrangement of illuminations is from west to east
<image>
(○ indicates a light bulb with a light, ● indicates a light bulb without a light). At this time, if you operate the machine for the four light bulbs from the 4th to the 7th,
<image>
The second to eighth bulbs form an alternating row of length 7.
<image>
Also, if you operate the machine only for the 8th light bulb,
<image>
The 4th to 10th light bulbs form an alternating row of length 7.
<image>
It is not possible to create alternating rows longer than 8 by using the machine up to once.
Task
Given the illumination information, write a program to find the maximum possible length of the alternating rows in the array of light bulbs that can be obtained by using the machine up to once.
Limits
* 2 ≤ N ≤ 100 000 Number of light bulbs that make up the illumination
input
Read the following data from standard input.
* The integer N is written on the first line.
* On the second line, N 0s or 1s are written with a space as a delimiter. Each integer represents the information of the light bulb before operating the machine. The i (1 ≤ i ≤ N) th integer from the left represents the information of the i-th light bulb from the west, and if the integer is 1, the light bulb is on, and if it is 0, the light bulb is off.
output
Output an integer representing the maximum length of the alternating columns contained in the columns of light bulbs that can be created to the standard output on one line.
Input / output example
Input example 1
Ten
1 1 0 0 1 0 1 1 1 0
Output example 1
7
This is an example explained in the problem statement.
Input example 2
Ten
1 0 0 0 0 1 0 1 0 1
Output example 2
8
Manipulating only the fourth bulb from the west yields an alternating sequence that satisfies the maximum value of 8.
Input example 3
Five
1 1 0 1 1
Output example 3
Five
By manipulating the second to fourth light bulbs counting from the west, you can create an alternating row of all light bulbs.
Input example 4
3
0 1 0
Output example 4
3
Note that you may not need to use a machine.
The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics.
Example
Input
10
1 1 0 0 1 0 1 1 1 0
Output
7
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a1, a2, ..., ak and b1, b2, ..., bk satisfying the following requirements:
* k ≥ 1
* <image>
* <image>
* <image>
* <image> t is a substring of string saisai + 1... sbi (string s is considered as 1-indexed).
As the number of ways can be rather large print it modulo 109 + 7.
Input
Input consists of two lines containing strings s and t (1 ≤ |s|, |t| ≤ 105). Each string consists of lowercase Latin letters.
Output
Print the answer in a single line.
Examples
Input
ababa
aba
Output
5
Input
welcometoroundtwohundredandeightytwo
d
Output
274201
Input
ddd
d
Output
12
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Parsa has a humongous tree on $n$ vertices.
On each vertex $v$ he has written two integers $l_v$ and $r_v$.
To make Parsa's tree look even more majestic, Nima wants to assign a number $a_v$ ($l_v \le a_v \le r_v$) to each vertex $v$ such that the beauty of Parsa's tree is maximized.
Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of $|a_u - a_v|$ over all edges $(u, v)$ of the tree.
Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.
-----Input-----
The first line contains an integer $t$ $(1\le t\le 250)$ — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer $n$ $(2\le n\le 10^5)$ — the number of vertices in Parsa's tree.
The $i$-th of the following $n$ lines contains two integers $l_i$ and $r_i$ $(1 \le l_i \le r_i \le 10^9)$.
Each of the next $n-1$ lines contains two integers $u$ and $v$ $(1 \le u , v \le n, u\neq v)$ meaning that there is an edge between the vertices $u$ and $v$ in Parsa's tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case print the maximum possible beauty for Parsa's tree.
-----Examples-----
Input
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
Output
7
8
62
-----Note-----
The trees in the example:
In the first test case, one possible assignment is $a = \{1, 8\}$ which results in $|1 - 8| = 7$.
In the second test case, one of the possible assignments is $a = \{1, 5, 9\}$ which results in a beauty of $|1 - 5| + |5 - 9| = 8$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This problem is a complicated version of D1, but it has significant differences, so read the whole statement.
Polycarp has an array of $n$ ($n$ is even) integers $a_1, a_2, \dots, a_n$. Polycarp conceived of a positive integer $k$. After that, Polycarp began performing the following operations on the array: take an index $i$ ($1 \le i \le n$) and reduce the number $a_i$ by $k$.
After Polycarp performed some (possibly zero) number of such operations, it turned out that at least half of the numbers in the array became the same. Find the maximum $k$ at which such a situation is possible, or print $-1$ if such a number can be arbitrarily large.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10$) — the number of test cases. Then $t$ test cases follow.
Each test case consists of two lines. The first line contains an even integer $n$ ($4 \le n \le 40$) ($n$ is even). The second line contains $n$ integers $a_1, a_2, \dots a_n$ ($-10^6 \le a_i \le 10^6$).
It is guaranteed that the sum of all $n$ specified in the given test cases does not exceed $100$.
-----Output-----
For each test case output on a separate line an integer $k$ ($k \ge 1$) — the maximum possible number that Polycarp used in operations on the array, or $-1$, if such a number can be arbitrarily large.
-----Examples-----
Input
4
6
48 13 22 -15 16 35
8
-1 0 1 -1 0 1 -1 0
4
100 -1000 -1000 -1000
4
1 1 1 1
Output
13
2
-1
-1
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ho ho! So you think you know integers, do you? Well then, young wizard, tell us what the Nth digit of the [Champernowne constant](https://en.wikipedia.org/wiki/Champernowne_constant) is!
The constant proceeds like this: `0.12345678910111213141516...`
I hope you see the pattern!
Conjure a function that will accept an integer, `n`, and return the (one-indexed) `n`th digit of Champernowne's constant. Can you get it to run in _constant_ time?
For example:
`n = 1` should return `0` (the very first digit)
`n = 2` should return `1` (we ignore the period character since it's not a digit!)
`n = 20` should return `4` (that's the `4` in the number `14`, 20th in sequence)
For any invalid values, such as `0` and below, or non-integers, return... `NaN`!
I hope (for your sake) that you've been practicing your mathemagical spells, because a naïve solution will _not_ be fast enough to compete in this championship!
Invoke with _precision_, and be wary of rounding errors in the realms of enormity!
May the best integer win!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 phantom thief "Lupin IV" is told by the beautiful "Fujiko Mine", a descendant of the Aizu clan, that the military funds left by the Aizu clan are sleeping in Aizuwakamatsu city. According to a report by Lupine's longtime companion, "Ishikawa Koshiemon," military funds are stored in several warehouses in a Senryobako box. There is no lookout in the warehouse, but it is tightly locked. However, Koshiemon says that if he uses the secret "steel slashing" technique taught by his father, he can instantly break the warehouse.
<image>
The remaining problem is the transportation of Senryobako. Lupine and Yuemon, who have no physical strength, cannot carry a Senryobako. So, I asked the reliable man "Infinity" to carry it. In order to carry out all the Senryobako, Lupine made the following plan.
First, drive Lupine to the first warehouse and drop off Koshiemon and Daisuke.
* Koshiemon breaks the warehouse
* Daisuke carries out all Senryobako
* While holding the Senryobako, head to the next warehouse decided by Lupine
Repeat this and carry out the Senryobako to the last warehouse. Meanwhile, Lupine prepares a helicopter and carries a thousand boxes with them in the last warehouse and escapes. Daisuke can carry anything heavy, but the speed of movement slows down depending on the weight of the luggage. Lupine must take this into consideration when deciding the order in which to break the warehouse.
Instead of Lupine, create a program that outputs the order of breaking the warehouse so that the travel time from breaking the first warehouse to reaching the last warehouse is minimized. However,
* All the warehouses face the street that runs straight north from Tsuruga Castle. The number of warehouses is at most 15, and the distance from the castle is at most 10,000 meters or less.
* Each Senryobako weighs 20 kilograms. The number of Senryobako in each warehouse is less than 10,000.
* To move from warehouse to warehouse, use the underground passage that is installed underground along the street.
* Daisuke travels at 2,000 / (70 + w) meters per minute to carry w kilograms of luggage.
The input data is given the number of the warehouse (integer of 100 or less), the distance from the castle (meters), and the number of Senryobako stored in the warehouse for each warehouse.
Input
The input is given in the following format:
n
s1 d1 v1
s2 d2 v2
::
sn dn vn
The number of warehouses n (n ≤ 15) is given in the first line, and the information of the i-th warehouse is given in the following n lines. As information on the warehouse, the number si (1 ≤ si ≤ 100), the distance from the castle di (1 ≤ di ≤ 10000), and the number of Senryobako vi (1 ≤ vi ≤ 10000) are given in one line.
Output
Please output the order of breaking the warehouse on one line. Please separate the warehouse numbers with a blank.
Examples
Input
2
1 100 1
2 200 2
Output
1 2
Input
3
11 100 1
13 200 20
12 300 3
Output
11 12 13
Input
5
13 199 1
51 1000 1
37 350 10
27 300 2
99 200 1000
Output
51 37 27 13 99
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>]
where: <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), <domain> is a non-empty string, consisting of lowercase English letters, the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters.
If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context).
When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".".
Help Vasya to restore the possible address of the recorded Internet resource.
-----Input-----
The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only.
It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above.
-----Output-----
Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them.
-----Examples-----
Input
httpsunrux
Output
http://sun.ru/x
Input
ftphttprururu
Output
ftp://http.ru/ruru
-----Note-----
In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).
Find the number on the n-th position of the sequence.
-----Input-----
The only line contains integer n (1 ≤ n ≤ 10^14) — the position of the number to find.
Note that the given number is too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
-----Output-----
Print the element in the n-th position of the sequence (the elements are numerated from one).
-----Examples-----
Input
3
Output
2
Input
5
Output
2
Input
10
Output
4
Input
55
Output
10
Input
56
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $a$ and screen height not greater than $b$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $w$, and the height of the screen is $h$, then the following condition should be met: $\frac{w}{h} = \frac{x}{y}$.
There are many different TV sets in the shop. Monocarp is sure that for any pair of positive integers $w$ and $h$ there is a TV set with screen width $w$ and height $h$ in the shop.
Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of positive integers $w$ and $h$, beforehand, such that $(w \le a)$, $(h \le b)$ and $(\frac{w}{h} = \frac{x}{y})$.
In other words, Monocarp wants to determine the number of TV sets having aspect ratio $\frac{x}{y}$, screen width not exceeding $a$, and screen height not exceeding $b$. Two TV sets are considered different if they have different screen width or different screen height.
-----Input-----
The first line contains four integers $a$, $b$, $x$, $y$ ($1 \le a, b, x, y \le 10^{18}$) — the constraints on the screen width and height, and on the aspect ratio.
-----Output-----
Print one integer — the number of different variants to choose TV screen width and screen height so that they meet the aforementioned constraints.
-----Examples-----
Input
17 15 5 3
Output
3
Input
14 16 7 22
Output
0
Input
4 2 6 4
Output
1
Input
1000000000000000000 1000000000000000000 999999866000004473 999999822000007597
Output
1000000063
-----Note-----
In the first example, there are $3$ possible variants: $(5, 3)$, $(10, 6)$, $(15, 9)$.
In the second example, there is no TV set meeting the constraints.
In the third example, there is only one variant: $(3, 2)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Guy-Manuel and Thomas are going to build a polygon spaceship.
You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of the translation:
<image>
Define T as a set of points which is the union of all P(x,y) such that the origin (0,0) lies in P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y) lies in T only if there are two points A,B in P such that \overrightarrow {AB} = \overrightarrow {(x,y)}. One can prove T is a polygon too. For example, if P is a regular triangle then T is a regular hexagon. At the picture below P is drawn in black and some P(x,y) which contain the origin are drawn in colored:
<image>
The spaceship has the best aerodynamic performance if P and T are similar. Your task is to check whether the polygons P and T are [similar](https://tinyurl.com/vp5m7vl).
Input
The first line of input will contain a single integer n (3 ≤ n ≤ 10^5) — the number of points.
The i-th of the next n lines contains two integers x_i, y_i (|x_i|, |y_i| ≤ 10^9), denoting the coordinates of the i-th vertex.
It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.
Output
Output "YES" in a separate line, if P and T are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).
Examples
Input
4
1 0
4 1
3 4
0 3
Output
YES
Input
3
100 86
50 0
150 0
Output
nO
Input
8
0 0
1 0
2 1
3 3
4 6
3 6
2 5
1 3
Output
YES
Note
The following image shows the first sample: both P and T are squares. The second sample was shown in the statements.
<image>
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Find the union of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$.
Constraints
* $1 \leq n, m \leq 200,000$
* $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$
* $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a_{n-1}$
$m$
$b_0 \; b_1 \; ... \; b_{m-1}$
Elements of $A$ and $B$ are given in ascending order respectively. There are no duplicate elements in each set.
Output
Print elements in the union in ascending order. Print an element in a line.
Example
Input
3
1 5 8
2
5 9
Output
1
5
8
9
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix $M$ of size $n \times n$ contains only 'X' and '.' (without quotes). The element in the $i$-th row and the $j$-th column $(i, j)$ is defined as $M(i, j)$, where $1 \leq i, j \leq n$. We define a cross appearing in the $i$-th row and the $j$-th column ($1 < i, j < n$) if and only if $M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $ 'X'.
The following figure illustrates a cross appearing at position $(2, 2)$ in a $3 \times 3$ matrix.
X.X
.X.
X.X
Your task is to find out the number of crosses in the given matrix $M$. Two crosses are different if and only if they appear in different rows or columns.
-----Input-----
The first line contains only one positive integer $n$ ($1 \leq n \leq 500$), denoting the size of the matrix $M$.
The following $n$ lines illustrate the matrix $M$. Each line contains exactly $n$ characters, each of them is 'X' or '.'. The $j$-th element in the $i$-th line represents $M(i, j)$, where $1 \leq i, j \leq n$.
-----Output-----
Output a single line containing only one integer number $k$ — the number of crosses in the given matrix $M$.
-----Examples-----
Input
5
.....
.XXX.
.XXX.
.XXX.
.....
Output
1
Input
2
XX
XX
Output
0
Input
6
......
X.X.X.
.X.X.X
X.X.X.
.X.X.X
......
Output
4
-----Note-----
In the first sample, a cross appears at $(3, 3)$, so the answer is $1$.
In the second sample, no crosses appear since $n < 3$, so the answer is $0$.
In the third sample, crosses appear at $(3, 2)$, $(3, 4)$, $(4, 3)$, $(4, 5)$, so the answer is $4$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya has an array of integers a_1, a_2, …, a_n. He only likes sorted arrays. Unfortunately, the given array could be arbitrary, so Petya wants to sort it.
Petya likes to challenge himself, so he wants to sort array using only 3-cycles. More formally, in one operation he can pick 3 pairwise distinct indices i, j, and k (1 ≤ i, j, k ≤ n) and apply i → j → k → i cycle to the array a. It simultaneously places a_i on position j, a_j on position k, and a_k on position i, without changing any other element.
For example, if a is [10, 50, 20, 30, 40, 60] and he chooses i = 2, j = 1, k = 5, then the array becomes [\underline{50}, \underline{40}, 20, 30, \underline{10}, 60].
Petya can apply arbitrary number of 3-cycles (possibly, zero). You are to determine if Petya can sort his array a, i. e. make it non-decreasing.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 5 ⋅ 10^5). Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the length of the array a.
The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n).
It is guaranteed that the sum of n over all test cases does not exceed 5 ⋅ 10^5.
Output
For each test case, print "YES" (without quotes) if Petya can sort the array a using 3-cycles, and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).
Example
Input
7
1
1
2
2 2
2
2 1
3
1 2 3
3
2 1 3
3
3 1 2
4
2 1 4 3
Output
YES
YES
NO
YES
NO
YES
YES
Note
In the 6-th test case Petya can use the 3-cycle 1 → 3 → 2 → 1 to sort the array.
In the 7-th test case Petya can apply 1 → 3 → 2 → 1 and make a = [1, 4, 2, 3]. Then he can apply 2 → 4 → 3 → 2 and finally sort the array.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 picture consisting of $n$ rows and $m$ columns. Rows are numbered from $1$ to $n$ from the top to the bottom, columns are numbered from $1$ to $m$ from the left to the right. Each cell is painted either black or white.
You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $x$ and $y$, where $1 \le x \le n$ and $1 \le y \le m$, such that all cells in row $x$ and all cells in column $y$ are painted black.
For examples, each of these pictures contain crosses:
[Image]
The fourth picture contains 4 crosses: at $(1, 3)$, $(1, 5)$, $(3, 3)$ and $(3, 5)$.
Following images don't contain crosses:
[Image]
You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.
What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?
You are also asked to answer multiple independent queries.
-----Input-----
The first line contains an integer $q$ ($1 \le q \le 5 \cdot 10^4$) — the number of queries.
The first line of each query contains two integers $n$ and $m$ ($1 \le n, m \le 5 \cdot 10^4$, $n \cdot m \le 4 \cdot 10^5$) — the number of rows and the number of columns in the picture.
Each of the next $n$ lines contains $m$ characters — '.' if the cell is painted white and '*' if the cell is painted black.
It is guaranteed that $\sum n \le 5 \cdot 10^4$ and $\sum n \cdot m \le 4 \cdot 10^5$.
-----Output-----
Print $q$ lines, the $i$-th line should contain a single integer — the answer to the $i$-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.
-----Example-----
Input
9
5 5
..*..
..*..
*****
..*..
..*..
3 4
****
.*..
.*..
4 3
***
*..
*..
*..
5 5
*****
*.*.*
*****
..*.*
..***
1 4
****
5 5
.....
..*..
.***.
..*..
.....
5 3
...
.*.
.*.
***
.*.
3 3
.*.
*.*
.*.
4 4
*.**
....
*.**
*.**
Output
0
0
0
0
0
4
1
1
2
-----Note-----
The example contains all the pictures from above in the same order.
The first 5 pictures already contain a cross, thus you don't have to paint anything.
You can paint $(1, 3)$, $(3, 1)$, $(5, 3)$ and $(3, 5)$ on the $6$-th picture to get a cross in $(3, 3)$. That'll take you $4$ minutes.
You can paint $(1, 2)$ on the $7$-th picture to get a cross in $(4, 2)$.
You can paint $(2, 2)$ on the $8$-th picture to get a cross in $(2, 2)$. You can, for example, paint $(1, 3)$, $(3, 1)$ and $(3, 3)$ to get a cross in $(3, 3)$ but that will take you $3$ minutes instead of $1$.
There are 9 possible crosses you can get in minimum time on the $9$-th picture. One of them is in $(1, 1)$: paint $(1, 2)$ and $(2, 1)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For two permutations p and q of the integers from 1 through N, let f(p,q) be the permutation that satisfies the following:
* The p_i-th element (1 \leq i \leq N) in f(p,q) is q_i. Here, p_i and q_i respectively denote the i-th element in p and q.
You are given two permutations p and q of the integers from 1 through N. We will now define a sequence {a_n} of permutations of the integers from 1 through N, as follows:
* a_1=p, a_2=q
* a_{n+2}=f(a_n,a_{n+1}) ( n \geq 1 )
Given a positive integer K, find a_K.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq K \leq 10^9
* p and q are permutations of the integers from 1 through N.
Input
Input is given from Standard Input in the following format:
N K
p_1 ... p_N
q_1 ... q_N
Output
Print N integers, with spaces in between. The i-th integer (1 \leq i \leq N) should be the i-th element in a_K.
Examples
Input
3 3
1 2 3
3 2 1
Output
3 2 1
Input
5 5
4 5 1 2 3
3 2 1 5 4
Output
4 3 2 1 5
Input
10 1000000000
7 10 6 5 4 2 9 1 3 8
4 1 9 2 3 7 8 10 6 5
Output
7 9 4 8 2 5 1 6 10 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem
There are coins with front and back sides and dice with rolls from $ 1 $ to $ N $. Gacho decided to play the following games using these.
The game starts with a score of $ 0 $ and proceeds as follows.
1. Roll the dice $ 1 $ and add the number of rolls to the score.
2. If the current score is $ K $ or more, the game is cleared and the game ends.
3. If the current score is less than $ K $, toss a coin and return to 1. if the front appears, and if the back appears, the game is over and the game ends.
When a coin is thrown, it has a probability of $ A \% $ and a probability of $ (100-A) \% $. Also, when the dice are rolled, each eye appears with equal probability.
At this time, find the probability that Gacho can clear the game in one game.
When the probability to be calculated is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $ $ 0 $ or more and $ 998244352 $ or less. Output the integer $ R $ of. Under the constraints of this problem, such $ R $ always exists uniquely.
Constraints
The input satisfies the following conditions.
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq K \ leq 10 ^ 5 $
* $ 1 \ leq A \ leq 99 $
* All inputs are integers
Input
The input is given in the following format.
$ N $ $ K $ $ A $
$ N, K, A $ are given on one line separated by blanks.
Output
When the probability of clearing the game is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $. Output an integer $ R $ that is greater than or equal to $ 0 $ and less than or equal to $ 998244352 $.
Examples
Input
1 1 50
Output
1
Input
2 2 10
Output
648858830
Input
6 10 99
Output
650893870
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
The game starts with `n` people standing in a circle. The presenter counts `m` people starting with the first one, and gives `1` coin to each of them. The rest of the players receive `2` coins each. After that, the last person who received `1` coin leaves the circle, giving everything he had to the next participant (who will also be considered "the first in the circle" in the next round). This process continues until only 1 person remains.
Determine the `number` of this person and how many `coins` he has at the end of the game.
The result should be a pair of values in the format: `[person, coins]`.
## Example:
```
n = 8, m = 3
People
1 2 3 1 2 ∙ 1 2 ∙ ∙ 2 ∙ ∙ 2 ∙ ∙ ∙ ∙ ∙ ∙ ∙
8 4 => 8 4 => 8 4 => 8 4 => 8 4 => 8 4 => ∙ 4 => 7
7 6 5 7 6 5 7 ∙ 5 7 ∙ 5 7 ∙ ∙ 7 ∙ ∙ 7 ∙ ∙
Coins
0 0 0 1 1 ∙ 3 3 ∙ ∙ 9 ∙ ∙ 10 ∙ ∙ ∙ ∙ ∙ ∙ ∙
0 0 => 2 3 => 4 4 => 5 6 => 7 7 => 8 20 => ∙ 30 => 51
0 0 0 2 2 2 7 ∙ 3 8 ∙ 5 16 ∙ ∙ 17 ∙ ∙ 18 ∙ ∙
```
## Notes:
* The presenter can do several full circles during one counting.
* In this case, the same person will receive `1` coin multiple times, i.e. no matter how many people are left in the circle, at least `m` coins will always be distributed among the participants during the round.
* If a person had already received `1` coin (possibly multiple times), he won't receive any additional `2` coins **at once(!)** during that round.
* People are counted starting with `1`.
* `m` can be **bigger** than `n` at start
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.
Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. [Image]
Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.
-----Output-----
On the single line of the output print the number of groups of magnets.
-----Examples-----
Input
6
10
10
10
01
10
10
Output
3
Input
4
01
01
10
10
Output
2
-----Note-----
The first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.
The second testcase has two groups, each consisting of two magnets.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's introduce some definitions that will be needed later.
Let $prime(x)$ be the set of prime divisors of $x$. For example, $prime(140) = \{ 2, 5, 7 \}$, $prime(169) = \{ 13 \}$.
Let $g(x, p)$ be the maximum possible integer $p^k$ where $k$ is an integer such that $x$ is divisible by $p^k$. For example: $g(45, 3) = 9$ ($45$ is divisible by $3^2=9$ but not divisible by $3^3=27$), $g(63, 7) = 7$ ($63$ is divisible by $7^1=7$ but not divisible by $7^2=49$).
Let $f(x, y)$ be the product of $g(y, p)$ for all $p$ in $prime(x)$. For example: $f(30, 70) = g(70, 2) \cdot g(70, 3) \cdot g(70, 5) = 2^1 \cdot 3^0 \cdot 5^1 = 10$, $f(525, 63) = g(63, 3) \cdot g(63, 5) \cdot g(63, 7) = 3^2 \cdot 5^0 \cdot 7^1 = 63$.
You have integers $x$ and $n$. Calculate $f(x, 1) \cdot f(x, 2) \cdot \ldots \cdot f(x, n) \bmod{(10^{9} + 7)}$.
-----Input-----
The only line contains integers $x$ and $n$ ($2 \le x \le 10^{9}$, $1 \le n \le 10^{18}$) — the numbers used in formula.
-----Output-----
Print the answer.
-----Examples-----
Input
10 2
Output
2
Input
20190929 1605
Output
363165664
Input
947 987654321987654321
Output
593574252
-----Note-----
In the first example, $f(10, 1) = g(1, 2) \cdot g(1, 5) = 1$, $f(10, 2) = g(2, 2) \cdot g(2, 5) = 2$.
In the second example, actual value of formula is approximately $1.597 \cdot 10^{171}$. Make sure you print the answer modulo $(10^{9} + 7)$.
In the third example, be careful about overflow issue.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left.
For example, the regular way to evaluate the sum $2039 + 2976$ would be as shown:
However, Alice evaluates it as shown:
In particular, this is what she does:
add $9$ and $6$ to make $15$, and carry the $1$ to the column two columns to the left, i. e. to the column "$0$ $9$";
add $3$ and $7$ to make $10$ and carry the $1$ to the column two columns to the left, i. e. to the column "$2$ $2$";
add $1$, $0$, and $9$ to make $10$ and carry the $1$ to the column two columns to the left, i. e. to the column above the plus sign;
add $1$, $2$ and $2$ to make $5$;
add $1$ to make $1$.
Thus, she ends up with the incorrect result of $15005$.
Alice comes up to Bob and says that she has added two numbers to get a result of $n$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $n$. Note that pairs $(a, b)$ and $(b, a)$ are considered different if $a \ne b$.
-----Input-----
The input consists of multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 1000$) — the number of test cases. The description of the test cases follows.
The only line of each test case contains an integer $n$ ($2 \leq n \leq 10^9$) — the number Alice shows Bob.
-----Output-----
For each test case, output one integer — the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $n$.
-----Examples-----
Input
5
100
12
8
2021
10000
Output
9
4
7
44
99
-----Note-----
In the first test case, when Alice evaluates any of the sums $1 + 9$, $2 + 8$, $3 + 7$, $4 + 6$, $5 + 5$, $6 + 4$, $7 + 3$, $8 + 2$, or $9 + 1$, she will get a result of $100$. The picture below shows how Alice evaluates $6 + 4$:
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A: Union Ball
Problem Statement
There are N balls in a box. The i-th ball is labeled with a positive integer A_i.
You can interact with balls in the box by taking actions under the following rules:
* If integers on balls in the box are all odd or all even, you cannot take actions anymore.
* Otherwise, you select arbitrary two balls in the box and remove them from the box. Then, you generate a new ball labeled with the sum of the integers on the two balls and put it into the box.
For given balls, what is the maximum number of actions you can take under the above rules?
Input
N
A_1 A_2 ... A_N
* The first line gives an integer N representing the initial number of balls in a box.
* The second line contains N integers, the i-th of which is the integer on the i-th ball.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq 10^9
* Inputs consist only of integers.
Output
Output the maximum number of actions you can take in one line.
Sample Input 1
3
4 5 6
Output for Sample Input 1
2
First, you select and remove balls labeled with 4 and 5, respectively, and add a ball labeled with 9. Next, you select and remove balls labeled with 6 and 9, respectively, and add a ball labeled with 15. Now, the balls in the box only have odd numbers. So you cannot take any actions anymore. The number of actions you took is two, and there is no way to achieve three actions or more. Thus the maximum is two and the series of the above actions is one of the optimal ways.
Sample Input 2
4
4 2 4 2
Output for Sample Input 2
0
You cannot take any actions in this case.
Example
Input
3
4 5 6
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are standing at the point $0$ on a coordinate line. Your goal is to reach the point $n$. In one minute, you can move by $2$ or by $3$ to the left or to the right (i. e., if your current coordinate is $x$, it can become $x-3$, $x-2$, $x+2$ or $x+3$). Note that the new coordinate can become negative.
Your task is to find the minimum number of minutes required to get from the point $0$ to the point $n$.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ lines describing the test cases follow.
The $i$-th of these lines contains one integer $n$ ($1 \le n \le 10^9$) — the goal of the $i$-th test case.
-----Output-----
For each test case, print one integer — the minimum number of minutes required to get from the point $0$ to the point $n$ for the corresponding test case.
-----Examples-----
Input
4
1
3
4
12
Output
2
1
2
4
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
Input
The first line contains the only integer q (1 ≤ q ≤ 1013).
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.
Examples
Input
6
Output
2
Input
30
Output
1
6
Input
1
Output
1
0
Note
Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.
Ostap knows that grasshopper is able to jump to any empty cell that is exactly k cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if k = 1 the grasshopper can jump to a neighboring cell only, and if k = 2 the grasshopper can jump over a single cell.
Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.
-----Input-----
The first line of the input contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1) — the number of cells in the line and the length of one grasshopper's jump.
The second line contains a string of length n consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once.
-----Output-----
If there exists a sequence of jumps (each jump of length k), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes).
-----Examples-----
Input
5 2
#G#T#
Output
YES
Input
6 1
T....G
Output
YES
Input
7 3
T..#..G
Output
NO
Input
6 2
..GT..
Output
NO
-----Note-----
In the first sample, the grasshopper can make one jump to the right in order to get from cell 2 to cell 4.
In the second sample, the grasshopper is only able to jump to neighboring cells but the way to the insect is free — he can get there by jumping left 5 times.
In the third sample, the grasshopper can't make a single jump.
In the fourth sample, the grasshopper can only jump to the cells with odd indices, thus he won't be able to reach the insect.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly t_{i} milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.
Unfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer a_{i} to every problem i meaning that the problem i can bring you a point to the final score only in case you have solved no more than a_{i} problems overall (including problem i).
Formally, suppose you solve problems p_1, p_2, ..., p_{k} during the exam. Then, your final score s will be equal to the number of values of j between 1 and k such that k ≤ a_{p}_{j}.
You have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.
-----Input-----
The first line contains two integers n and T (1 ≤ n ≤ 2·10^5; 1 ≤ T ≤ 10^9) — the number of problems in the exam and the length of the exam in milliseconds, respectively.
Each of the next n lines contains two integers a_{i} and t_{i} (1 ≤ a_{i} ≤ n; 1 ≤ t_{i} ≤ 10^4). The problems are numbered from 1 to n.
-----Output-----
In the first line, output a single integer s — your maximum possible final score.
In the second line, output a single integer k (0 ≤ k ≤ n) — the number of problems you should solve.
In the third line, output k distinct integers p_1, p_2, ..., p_{k} (1 ≤ p_{i} ≤ n) — the indexes of problems you should solve, in any order.
If there are several optimal sets of problems, you may output any of them.
-----Examples-----
Input
5 300
3 100
4 150
4 80
2 90
2 300
Output
2
3
3 1 4
Input
2 100
1 787
2 788
Output
0
0
Input
2 100
2 42
2 58
Output
2
2
1 2
-----Note-----
In the first example, you should solve problems 3, 1, and 4. In this case you'll spend 80 + 100 + 90 = 270 milliseconds, falling within the length of the exam, 300 milliseconds (and even leaving yourself 30 milliseconds to have a rest). Problems 3 and 1 will bring you a point each, while problem 4 won't. You'll score two points.
In the second example, the length of the exam is catastrophically not enough to solve even a single problem.
In the third example, you have just enough time to solve both problems in 42 + 58 = 100 milliseconds and hand your solutions to the teacher with a smile.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given time in 24-hour format, convert it to words.
```
For example:
13:00 = one o'clock
13:09 = nine minutes past one
13:15 = quarter past one
13:29 = twenty nine minutes past one
13:30 = half past one
13:31 = twenty nine minutes to two
13:45 = quarter to two
00:48 = twelve minutes to one
00:08 = eight minutes past midnight
12:00 = twelve o'clock
00:00 = midnight
Note: If minutes == 0, use 'o'clock'. If minutes <= 30, use 'past', and for minutes > 30, use 'to'.
```
More examples in test cases. Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.
Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?
-----Input-----
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 10^9; 0 ≤ p ≤ q ≤ 10^9; y > 0; q > 0).
It is guaranteed that p / q is an irreducible fraction.
Hacks. For hacks, an additional constraint of t ≤ 5 must be met.
-----Output-----
For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.
-----Example-----
Input
4
3 10 1 2
7 14 3 8
20 70 2 7
5 6 1 1
Output
4
10
0
-1
-----Note-----
In the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.
In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.
In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.
In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Student A and student B are giving each other test answers during a test.
They don't want to be caught so they are sending each other coded messages.
Student A is sending student B the message: `Answer to Number 5 Part b`.
He starts of with a square grid (in this example the grid = 5x5).
He writes the message down (with spaces):
```
Answe
r to
Numbe
r 5 P
art b
```
He then starts writing the message down one column at a time (from the top to the bottom).
The new message is now: `ArNran u rstm5twob e ePb`
You are the teacher of this class.
Your job is to decipher this message and bust the students.
# Task
Write a function `decipher_message`.
This function will take one parameter (`message`).
This function will return the original message.
*** Note: The length of the string is always going to be a prefect square ***
Hint: You should probably decipher the example message first before you start coding
Have fun !!!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 forest with N vertices and M edges. The vertices are numbered 0 through N-1. The edges are given in the format (x_i,y_i), which means that Vertex x_i and y_i are connected by an edge.
Each vertex i has a value a_i. You want to add edges in the given forest so that the forest becomes connected. To add an edge, you choose two different vertices i and j, then span an edge between i and j. This operation costs a_i + a_j dollars, and afterward neither Vertex i nor j can be selected again.
Find the minimum total cost required to make the forest connected, or print `Impossible` if it is impossible.
Constraints
* 1 ≤ N ≤ 100,000
* 0 ≤ M ≤ N-1
* 1 ≤ a_i ≤ 10^9
* 0 ≤ x_i,y_i ≤ N-1
* The given graph is a forest.
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M
a_0 a_1 .. a_{N-1}
x_1 y_1
x_2 y_2
:
x_M y_M
Output
Print the minimum total cost required to make the forest connected, or print `Impossible` if it is impossible.
Examples
Input
7 5
1 2 3 4 5 6 7
3 0
4 0
1 2
1 3
5 6
Output
7
Input
5 0
3 1 4 1 5
Output
Impossible
Input
1 0
5
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.
The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 10^9 + 7. Help him!
-----Input-----
The first line contains two integers, n and k (0 ≤ k < n ≤ 10^5).
The second line contains a string consisting of n digits.
-----Output-----
Print the answer to the problem modulo 10^9 + 7.
-----Examples-----
Input
3 1
108
Output
27
Input
3 2
108
Output
9
-----Note-----
In the first sample the result equals (1 + 08) + (10 + 8) = 27.
In the second sample the result equals 1 + 0 + 8 = 9.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An eviternity number is a number which:
* contains only digits 8, 5 and 3, and
* the count of the digit `8` >= count of digit `5` >= count of digit `3`.
The first few eviternity numbers are as follows.
```Haskell
[8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
```
You will be given two integers, `a` and `b`, and your task is to return the number of eviternity numbers in the range `>= a and < b`.
```Haskell
For example:
solve(0,1000) = 14, because they are [8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
```
The upper bound will not exceed `500,000`.
More examples in test cases. Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Connect the countless points with lines, till we reach the faraway yonder.
There are n points on a coordinate plane, the i-th of which being (i, y_{i}).
Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes through at least one point in the set.
-----Input-----
The first line of input contains a positive integer n (3 ≤ n ≤ 1 000) — the number of points.
The second line contains n space-separated integers y_1, y_2, ..., y_{n} ( - 10^9 ≤ y_{i} ≤ 10^9) — the vertical coordinates of each point.
-----Output-----
Output "Yes" (without quotes) if it's possible to fulfill the requirements, and "No" otherwise.
You can print each letter in any case (upper or lower).
-----Examples-----
Input
5
7 5 8 6 9
Output
Yes
Input
5
-1 -2 0 0 -5
Output
No
Input
5
5 4 3 2 1
Output
No
Input
5
1000000000 0 0 0 0
Output
Yes
-----Note-----
In the first example, there are five points: (1, 7), (2, 5), (3, 8), (4, 6) and (5, 9). It's possible to draw a line that passes through points 1, 3, 5, and another one that passes through points 2, 4 and is parallel to the first one.
In the second example, while it's possible to draw two lines that cover all points, they cannot be made parallel.
In the third example, it's impossible to satisfy both requirements at the same time.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a permutation $a$ consisting of $n$ numbers $1$, $2$, ..., $n$ (a permutation is an array in which each element from $1$ to $n$ occurs exactly once).
You can perform the following operation: choose some subarray (contiguous subsegment) of $a$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.
For example, if $a = [2, 1, 4, 5, 3]$ and we want to apply the operation to the subarray $a[2, 4]$ (the subarray containing all elements from the $2$-nd to the $4$-th), then after the operation, the array can become $a = [2, 5, 1, 4, 3]$ or, for example, $a = [2, 1, 5, 4, 3]$.
Your task is to calculate the minimum number of operations described above to sort the permutation $a$ in ascending order.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 2000$) — the number of test cases.
The first line of the test case contains a single integer $n$ ($3 \le n \le 50$) — the number of elements in the permutation.
The second line of the test case contains $n$ distinct integers from $1$ to $n$ — the given permutation $a$.
-----Output-----
For each test case, output a single integer — the minimum number of operations described above to sort the array $a$ in ascending order.
-----Examples-----
Input
3
4
1 3 2 4
3
1 2 3
5
2 1 4 5 3
Output
1
0
2
-----Note-----
In the explanations, $a[i, j]$ defines the subarray of $a$ that starts from the $i$-th element and ends with the $j$-th element.
In the first test case of the example, you can select the subarray $a[2, 3]$ and swap the elements in it.
In the second test case of the example, the permutation is already sorted, so you don't need to apply any operations.
In the third test case of the example, you can select the subarray $a[3, 5]$ and reorder the elements in it so $a$ becomes $[2, 1, 3, 4, 5]$, and then select the subarray $a[1, 2]$ and swap the elements in it, so $a$ becomes $[1, 2, 3, 4, 5]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the current Daleks' plan – which is to use a minimum spanning tree of Corridors. Heidi knows that all energy requirements for different Corridors are now different, and that the Daleks have a single unique plan which they are intending to use.
Your task is to calculate the number E_{max}(c), which is defined in the same way as in the easy version – i.e., the largest e ≤ 10^9 such that if we changed the energy of corridor c to e, the Daleks might use it – but now for every corridor that Heidi considers.
Input
The first line: number n of destinations, number m of Time Corridors (2 ≤ n ≤ 10^5, n - 1 ≤ m ≤ 10^6). The next m lines: destinations a, b and energy e (1 ≤ a, b ≤ n, a ≠ b, 0 ≤ e ≤ 10^9).
No pair \\{a, b\} will repeat. The graph is guaranteed to be connected. All energy requirements e are distinct.
Output
Output m-(n-1) lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input that is not part of the current Daleks' plan (minimum spanning tree).
Example
Input
3 3
1 2 8
2 3 3
3 1 4
Output
4
Note
If m = n-1, then you need not output anything.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 является другом b, то b также является другом a.
В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя x. Пусть некоторый другой человек y, не являющийся другом x на текущий момент, является другом не менее, чем для k% друзей x. Тогда он является предполагаемым другом для x.
У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 10^9. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей.
-----Входные данные-----
В первой строке следуют два целых числа m и k (1 ≤ m ≤ 100, 0 ≤ k ≤ 100) — количество пар друзей и необходимый процент общих друзей для того, чтобы считаться предполагаемым другом.
В последующих m строках записано по два числа a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ 10^9, a_{i} ≠ b_{i}), обозначающих идентификаторы пользователей, являющихся друзьями.
Гарантируется, что каждая пара людей фигурирует в списке не более одного раза.
-----Выходные данные-----
Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "id: k id_1 id_2 ... id_{k}", где id — это id самого человека, k — количество его предполагаемых друзей, а id_1, id_2, ..., id_{k} — идентификаторы его предполагаемых друзей в возрастающем порядке.
-----Примеры-----
Входные данные
5 51
10 23
23 42
39 42
10 39
39 58
Выходные данные
10: 1 42
23: 1 39
39: 1 23
42: 1 10
58: 2 10 42
Входные данные
5 100
1 2
1 3
1 4
2 3
2 4
Выходные данные
1: 0
2: 0
3: 1 4
4: 1 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp has come up with a new game to play with you. He calls it "A missing bigram".
A bigram of a word is a sequence of two adjacent letters in it.
For example, word "abbaaba" contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".
The game goes as follows. First, Polycarp comes up with a word, consisting only of lowercase letters 'a' and 'b'. Then, he writes down all its bigrams on a whiteboard in the same order as they appear in the word. After that, he wipes one of them off the whiteboard.
Finally, Polycarp invites you to guess what the word that he has come up with was.
Your goal is to find any word such that it's possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.
The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 2000$) — the number of testcases.
The first line of each testcase contains a single integer $n$ ($3 \le n \le 100$) — the length of the word Polycarp has come up with.
The second line of each testcase contains $n-2$ bigrams of that word, separated by a single space. Each bigram consists of two letters, each of them is either 'a' or 'b'.
Additional constraint on the input: there exists at least one string such that it is possible to write down all its bigrams, except one, so that the resulting sequence is the same as the sequence in the input. In other words, the answer exists.
-----Output-----
For each testcase print a word, consisting of $n$ letters, each of them should be either 'a' or 'b'. It should be possible to write down all its bigrams and remove one of them, so that the resulting sequence of bigrams is the same as the one Polycarp ended up with.
The tests are generated in such a way that the answer exists. If there are multiple answers, you can print any of them.
-----Examples-----
Input
4
7
ab bb ba aa ba
7
ab ba aa ab ba
3
aa
5
bb ab bb
Output
abbaaba
abaabaa
baa
bbabb
-----Note-----
The first two testcases from the example are produced from the word "abbaaba". As listed in the statement, it contains bigrams "ab", "bb", "ba", "aa", "ab" and "ba".
In the first testcase, the $5$-th bigram is removed.
In the second testcase, the $2$-nd bigram is removed. However, that sequence could also have been produced from the word "abaabaa". It contains bigrams "ab", "ba", "aa", "ab", "ba" and "aa". The missing bigram is the $6$-th one.
In the third testcase, all of "baa", "aab" and "aaa" are valid answers.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Challenge:
Given two null-terminated strings in the arguments "string" and "prefix", determine if "string" starts with the "prefix" string. Return 1 (or any other "truthy" value) if true, 0 if false.
Example:
```
startsWith("hello world!", "hello"); // should return 1.
startsWith("hello world!", "HELLO"); // should return 0.
startsWith("nowai", "nowaisir"); // should return 0.
```
Addendum:
For this problem, an empty "prefix" string should always return 1 (true) for any value of "string".
If the length of the "prefix" string is greater than the length of the "string", return 0.
The check should be case-sensitive, i.e. startsWith("hello", "HE") should return 0, whereas startsWith("hello", "he") should return 1.
The length of the "string" as well as the "prefix" can be defined by the formula: 0 <= length < +Infinity
No characters should be ignored and/or omitted during the test, e.g. whitespace characters should not be ignored.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Absent-minded Masha got set of n cubes for her birthday.
At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x.
To make a number Masha can rotate her cubes and put them in a row. After that, she looks at upper faces of cubes from left to right and reads the number.
The number can't contain leading zeros. It's not required to use all cubes to build a number.
Pay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations.
-----Input-----
In first line integer n is given (1 ≤ n ≤ 3) — the number of cubes, Masha got for her birthday.
Each of next n lines contains 6 integers a_{i}_{j} (0 ≤ a_{i}_{j} ≤ 9) — number on j-th face of i-th cube.
-----Output-----
Print single integer — maximum number x such Masha can make any integers from 1 to x using her cubes or 0 if Masha can't make even 1.
-----Examples-----
Input
3
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7
Output
87
Input
3
0 1 3 5 6 8
1 2 4 5 7 8
2 3 4 6 7 9
Output
98
-----Note-----
In the first test case, Masha can build all numbers from 1 to 87, but she can't make 88 because there are no two cubes with digit 8.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Meikyokan University is very famous for its research and education in the area of computer science. This university has a computer center that has advanced and secure computing facilities including supercomputers and many personal computers connected to the Internet.
One of the policies of the computer center is to let the students select their own login names. Unfortunately, students are apt to select similar login names, and troubles caused by mistakes in entering or specifying login names are relatively common. These troubles are a burden on the staff of the computer center.
To avoid such troubles, Dr. Choei Takano, the chief manager of the computer center, decided to stamp out similar and confusing login names. To this end, Takano has to develop a program that detects confusing login names.
Based on the following four operations on strings, the distance between two login names is determined as the minimum number of operations that transforms one login name to the other.
1. Deleting a character at an arbitrary position.
2. Inserting a character into an arbitrary position.
3. Replacing a character at an arbitrary position with another character.
4. Swapping two adjacent characters at an arbitrary position.
For example, the distance between “omura” and “murai” is two, because the following sequence of operations transforms “omura” to “murai”.
delete ‘o’ insert ‘i’
omura --> mura --> murai
Another example is that the distance between “akasan” and “kaason” is also two.
swap ‘a’ and ‘k’ replace ‘a’ with ‘o’
akasan --> kaasan --> kaason
Takano decided that two login names with a small distance are confusing and thus must be avoided.
Your job is to write a program that enumerates all the confusing pairs of login names.
Beware that the rules may combine in subtle ways. For instance, the distance between “ant” and “neat” is two.
swap ‘a’ and ‘n’ insert ‘e’
ant --> nat --> neat
Input
The input consists of multiple datasets. Each dataset is given in the following format.
n
d
name1
name2
...
namen
The first integer n is the number of login names. Then comes a positive integer d. Two login names whose distance is less than or equal to d are deemed to be confusing. You may assume that 0 < n ≤ 200 and 0 < d ≤ 2. The i-th student’s login name is given by namei, which is composed of only lowercase letters. Its length is less than 16. You can assume that there are no duplicates in namei (1 ≤ i ≤ n).
The end of the input is indicated by a line that solely contains a zero.
Output
For each dataset, your program should output all pairs of confusing login names, one pair per line, followed by the total number of confusing pairs in the dataset.
In each pair, the two login names are to be separated only by a comma character (,), and the login name that is alphabetically preceding the other should appear first. The entire output of confusing pairs for each dataset must be sorted as follows. For two pairs “w1,w2” and “w3,w4”, if w1 alphabetically precedes w3, or they are the same and w2 precedes w4, then “w1,w2” must appear before “w3,w4”.
Example
Input
8
2
omura
toshio
raku
tanaka
imura
yoshoi
hayashi
miura
3
1
tasaka
nakata
tanaka
1
1
foo
5
2
psqt
abcdef
abzdefa
pqrst
abdxcef
0
Output
imura,miura
imura,omura
miura,omura
toshio,yoshoi
4
tanaka,tasaka
1
0
abcdef,abdxcef
abcdef,abzdefa
pqrst,psqt
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way.
-----Input-----
The first line of input consists of three integers $n$, $m$ and $s$ ($1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$) — the number of cities, the number of roads and the index of the capital. Cities are indexed from $1$ to $n$.
The following $m$ lines contain roads: road $i$ is given as a pair of cities $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). For each pair of cities $(u, v)$, there can be at most one road from $u$ to $v$. Roads in opposite directions between a pair of cities are allowed (i.e. from $u$ to $v$ and from $v$ to $u$).
-----Output-----
Print one integer — the minimum number of extra roads needed to make all the cities reachable from city $s$. If all the cities are already reachable from $s$, print 0.
-----Examples-----
Input
9 9 1
1 2
1 3
2 3
1 5
5 6
6 1
1 8
9 8
7 1
Output
3
Input
5 4 5
1 2
2 3
3 4
4 1
Output
1
-----Note-----
The first example is illustrated by the following: [Image]
For example, you can add roads ($6, 4$), ($7, 9$), ($1, 7$) to make all the cities reachable from $s = 1$.
The second example is illustrated by the following: [Image]
In this example, you can add any one of the roads ($5, 1$), ($5, 2$), ($5, 3$), ($5, 4$) to make all the cities reachable from $s = 5$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In 1862, the lord of Aizu was ordered to serve as a guardian of Kyoto. The Kyoto Shugoshoku is an important role to protect Kyoto at the end of the Edo period when security has deteriorated. You have to patrol the city by sharing it with the shogunate and other clan. However, when it came time to decide the sharing route, the following order was received from a stubborn old man who is famous among his vassals.
<image>
It was a big deal. Even the lord cannot ignore the statement of this vassal. Depending on the selection of the sharing route, it will be "the samurai's face is not noticeable".
So, please make a program to judge whether the above three conditions are met by inputting the information of the start point, the goal point, and the intersection, and give it to the lord.
The start point is represented by 1, the goal point is represented by 2, and other intersections are represented by integers of 3 or more. A road is represented by a set of intersection numbers that the roads connect to. The number of intersections shall be 100 or less, and there shall be one or more routes from all intersections to the start point and goal point.
input
Given multiple datasets. Each dataset is given in the following format:
a1 b1
a2 b2
:
:
0 0
The two integers in each row indicate that there is a road connecting intersection ai and intersection bi. When both ai and bi are 0, it indicates the end of inputting intersection information.
The number of datasets does not exceed 50.
output
For each data set, if the samurai's face stands out (if the three conditions are met), OK, otherwise (if the three conditions are not met), output NG on one line.
Example
Input
1 3
3 4
3 5
3 6
4 6
4 7
4 7
5 6
6 7
5 8
5 8
6 8
6 9
7 9
8 9
9 2
0 0
1 3
3 4
3 4
4 2
0 0
Output
OK
NG
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$, each of length $n$ and consisting of lowercase Latin alphabets. You want to make $s$ equal to $t$.
You can perform the following operation on $s$ any number of times to achieve it — Choose any substring of $s$ and rotate it clockwise once, that is, if the selected substring is $s[l,l+1...r]$, then it becomes $s[r,l,l + 1 ... r - 1]$. All the remaining characters of $s$ stay in their position.
For example, on rotating the substring $[2,4]$ , string "abcde" becomes "adbce".
A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Find the minimum number of operations required to convert $s$ to $t$, or determine that it's impossible.
-----Input-----
The first line of the input contains a single integer $t$ $(1\leq t \leq 2000)$ — 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\leq n \leq 2000)$ — the length of the strings.
The second and the third lines contain strings $s$ and $t$ respectively.
The sum of $n$ over all the test cases does not exceed $2000$.
-----Output-----
For each test case, output the minimum number of operations to convert $s$ to $t$. If it is not possible to convert $s$ to $t$, output $-1$ instead.
-----Example-----
Input
6
1
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
Output
0
1
1
2
1
-1
-----Note-----
For the $1$-st test case, since $s$ and $t$ are equal, you don't need to apply any operation.
For the $2$-nd test case, you only need to apply one operation on the entire string ab to convert it to ba.
For the $3$-rd test case, you only need to apply one operation on the entire string abc to convert it to cab.
For the $4$-th test case, you need to apply the operation twice: first on the entire string abc to convert it to cab and then on the substring of length $2$ beginning at the second character to convert it to cba.
For the $5$-th test case, you only need to apply one operation on the entire string abab to convert it to baba.
For the $6$-th test case, it is not possible to convert string $s$ to $t$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata, you should calculate type of triangle with three given sides ``a``, ``b`` and ``c`` (given in any order).
If all angles are less than ``90°``, this triangle is ``acute`` and function should return ``1``.
If one angle is strictly ``90°``, this triangle is ``right`` and function should return ``2``.
If one angle more than ``90°``, this triangle is ``obtuse`` and function should return ``3``.
If three sides cannot form triangle, or one angle is ``180°`` (which turns triangle into segment) - function should return ``0``.
Input parameters are ``sides`` of given triangle. All input values are non-negative floating point or integer numbers (or both).
Acute
Right
Obtuse
### Examples:
```python
triangle_type(2, 4, 6) # return 0 (Not triangle)
triangle_type(8, 5, 7) # return 1 (Acute, angles are approx. 82°, 38° and 60°)
triangle_type(3, 4, 5) # return 2 (Right, angles are approx. 37°, 53° and exactly 90°)
triangle_type(7, 12, 8) # return 3 (Obtuse, angles are approx. 34°, 106° and 40°)
```
If you stuck, this can help you: http://en.wikipedia.org/wiki/Law_of_cosines. But you can solve this kata even without angle calculation.
There is very small chance of random test to fail due to round-off error, in such case resubmit your solution.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Math, an improper fraction is a fraction where the numerator (the top number) is greater than or equal to the denominator (the bottom number) For example: ```5/3``` (five third).
A mixed numeral is a whole number and a fraction combined into one "mixed" number. For example: ```1 1/2``` (one and a half) is a mixed numeral.
## Task
Write a function `convertToMixedNumeral` to convert the improper fraction into a mixed numeral.
The input will be given as a ```string``` (e.g. ```'4/3'```).
The output should be a ```string```, with a space in between the whole number and the fraction (e.g. ```'1 1/3'```). You do not need to reduce the result to its simplest form.
For the purpose of this exercise, there will be no ```0```, ```empty string``` or ```null``` input value. However, the input can be:
- a negative fraction
- a fraction that does not require conversion
- a fraction that can be converted into a whole number
## Example
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Petya loves playing with squares. Mum bought him a square 2n × 2n in size. Petya marked a cell inside the square and now he is solving the following task.
The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any common points with the marked cell and the resulting two parts should be equal up to rotation.
Petya wants to determine whether it is possible to cut the square in the required manner given the sizes of the square side and the coordinates of the marked cell. Help him.
Input
The first line contains three space-separated integers 2n, x and y (2 ≤ 2n ≤ 100, 1 ≤ x, y ≤ 2n), representing the length of a square's side and the coordinates of the marked cell. It is guaranteed that 2n is even.
The coordinates of the marked cell are represented by a pair of numbers x y, where x represents the number of the row and y represents the number of the column. The rows and columns are numbered by consecutive integers from 1 to 2n. The rows are numbered from top to bottom and the columns are numbered from the left to the right.
Output
If the square is possible to cut, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
4 1 1
Output
YES
Input
2 2 2
Output
NO
Note
A sample test from the statement and one of the possible ways of cutting the square are shown in the picture:
<image>
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold T — the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least T of user's friends.
-----Input-----
The first line of the input will contain three space-separated integers: the number of friends F (1 ≤ F ≤ 10), the number of items I (1 ≤ I ≤ 10) and the threshold T (1 ≤ T ≤ F).
The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.
-----Output-----
Output an integer — the number of items liked by at least T of user's friends.
-----Examples-----
Input
3 3 2
YYY
NNN
YNY
Output
2
Input
4 4 1
NNNY
NNYN
NYNN
YNNN
Output
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.
In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".
The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.
-----Constraints-----
- 0 \leq A,B \leq 23
- A and B are integers.
-----Input-----
The input is given from Standard Input in the following format:
A B
-----Output-----
Print the hour of the starting time of the contest in 24-hour time.
-----Sample Input-----
9 12
-----Sample Output-----
21
In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Input
The input contains two integers N, M (1 ≤ N ≤ 1024, 2 ≤ M ≤ 16), separated by a single space.
Output
Output "YES" or "NO".
Examples
Input
2 3
Output
YES
Input
3 2
Output
NO
Input
33 16
Output
YES
Input
26 5
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Did you ever hear about 'crossing the bridge noodle' ? Let me tell you that it's not some kind of bridge made of noodles. It's a dish, a kind of rice noodle soup. Mr.Ping makes the best noodle soup and his son Po is eagerly waiting for the user reviews in his father's blog. Users can vote with a (+) or a (-) and accordingly +1 or -1 is added to the total score respectively. Note that if a user votes multiple times, only his/her latest vote is counted towards the total score.
Po opens the blog to see initial score of 0. To see the updated score without refreshing the page, he has to keep voting himself. After each of Po's clicks on (+) or (-), he can see the current total score, of course that considers Po's vote too. He is wondering how many users other than him could have possibly voted. Given the sequence of clicks made by Po and the total score displayed just after each of his clicks, can you tell him the minimum number of users that could have possibly voted at least once, other than Po.
------ Input ------
There are multiple test cases ( at most 21 ). Each case starts with an integer N ( 1 ≤ N ≤ 1000 ), the number of Po's clicks. Sequence of N clicks follows, one on each line of the form "vote score" (without quotes, separated by a space), where vote is either a 'P' or a 'M', representing Plus(+) and Minus(-) respectively, the one clicked by Po and score is the score displayed after Po's click ( -1,000,000,000 ≤ score ≤ 1,000,000,000 ). The last case has N = 0 and should not be processed. Each case is followed by an empty line.
------ Output ------
For each test case, output the minimum number of users that could have possibly voted at least once.
----- Sample Input 1 ------
2
P 1
P 2
2
P 2
M -2
0
----- Sample Output 1 ------
1
1
----- explanation 1 ------
Case 1 :
P 1 , Po voted (+) and score = 1 is possibly Po's vote itself.
P 2 , Po again voted (+), but as only latest vote of a user is counted, Po contributed only +1 to the score, so possibly one more user voted with a (+). Remember that we have to find the number of users other than Po, so answer is 1
Case 2 :
P 2 , Po voted (+) and score = 2, possibly another user A also voted (+)
M -2 , Po voted (-) and score = -2. Possibly the same user A also voted (-)
So there can possibly be just one other user A
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 computing, there are two primary byte order formats: big-endian and little-endian. Big-endian is used primarily for networking (e.g., IP addresses are transmitted in big-endian) whereas little-endian is used mainly by computers with microprocessors.
Here is an example (using 32-bit integers in hex format):
Little-Endian: 00 6D F4 C9 = 7,206,089
Big-Endian: C9 F4 6D 00 = 3,388,239,104
Your job is to write a function that switches the byte order of a given integer. The function should take an integer n for the first argument, and the bit-size of the integer for the second argument. The bit size must be a power of 2 greater than or equal to 8. Your function should return a None value if the integer is negative, if the specified bit size is not a power of 2 that is 8 or larger, or if the integer is larger than the specified bit size can handle. In this kata, assume that all integers are unsigned (non-negative) and that all input arguments are integers (no floats, strings, None/nil values, etc.). Remember that you will need to account for padding of null (00) bytes.
Hint: bitwise operators are very helpful! :)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi has two integers X and Y.
He computed X + Y and X - Y, and the results were A and B, respectively.
Now he cannot remember what X and Y were. Find X and Y for him.
-----Constraints-----
- -100 \leq A, B \leq 100
- For the given integers A and B, there uniquely exist integers X and Y such that X + Y = A and X - Y = B.
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
Print X and Y.
-----Sample Input-----
2 -2
-----Sample Output-----
0 2
If X = 0 and Y = 2, they match the situation: 0 + 2 = 2 and 0 - 2 = -2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# The die is cast!
Your task in this kata is to write a "dice roller" that interprets a subset of [dice notation](http://en.wikipedia.org/wiki/Dice_notation).
# Description
In most role-playing games, die rolls required by the system are given in the form `AdX`. `A` and `X` are variables, separated by the letter **d**, which stands for *die* or *dice*.
- `A` is the number of dice to be rolled (usually omitted if 1).
- `X` is the number of faces of each die.
Here are some examples of input:
# Modifiers
As an addition to the above rules the input may also contain modifiers in the form `+N` or `-N` where `N` is an integer.
Here are some examples of input containing modifiers:
*Modifiers must be applied **after** all dice has been summed up.*
# Output
Your function must support two types of output depending on the second argument; *verbose* and *summed*.
## Summed output
If the verbose flag isn't set your function should sum up all the dice and modifiers and return the result as an integer.
## Verbose output
With the verbose flag your function should return an object/hash containing an array (`dice`) with all the dice rolls, and a integer (`modifier`) containing the sum of the modifiers which defaults to zero.
Example of verbose output:
# Invalid input
Here are some examples of invalid inputs:
# Additional information
- Your solution should ignore all whitespace.
- `roll` should return `false` for invalid input.
Read the inputs from 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.