question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Consider a tunnel on a one-way road. During a particular day, $n$ cars numbered from $1$ to $n$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.
A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.
Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.
Traffic regulations prohibit overtaking inside the tunnel. If car $i$ overtakes any other car $j$ inside the tunnel, car $i$ must be fined. However, each car can be fined at most once.
Formally, let's say that car $i$ definitely overtook car $j$ if car $i$ entered the tunnel later than car $j$ and exited the tunnel earlier than car $j$. Then, car $i$ must be fined if and only if it definitely overtook at least one other car.
Find the number of cars that must be fined.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 10^5$), denoting the number of cars.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$), denoting the ids of cars in order of entering the tunnel. All $a_i$ are pairwise distinct.
The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$), denoting the ids of cars in order of exiting the tunnel. All $b_i$ are pairwise distinct.
-----Output-----
Output the number of cars to be fined.
-----Examples-----
Input
5
3 5 2 1 4
4 3 2 5 1
Output
2
Input
7
5 2 3 6 7 1 4
2 3 6 7 1 4 5
Output
6
Input
2
1 2
1 2
Output
0
-----Note-----
The first example is depicted below:
[Image]
Car $2$ definitely overtook car $5$, while car $4$ definitely overtook cars $1$, $2$, $3$ and $5$. Cars $2$ and $4$ must be fined.
In the second example car $5$ was definitely overtaken by all other cars.
In the third example no car must be fined.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks.
The second line contains n integers a_{i} ( - 10^9 ≤ a_{i} ≤ 10^9), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all a_{i} is equal to 0.
-----Output-----
Print the minimum number of operations required to change balance in each bank to zero.
-----Examples-----
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
-----Note-----
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.
It is known that during the day q tasks will come, the i-th of them is characterized with three integers: t_{i} — the moment in seconds in which the task will come, k_{i} — the number of servers needed to perform it, and d_{i} — the time needed to perform this task in seconds. All t_{i} are distinct.
To perform the i-th task you need k_{i} servers which are unoccupied in the second t_{i}. After the servers begin to perform the task, each of them will be busy over the next d_{i} seconds. Thus, they will be busy in seconds t_{i}, t_{i} + 1, ..., t_{i} + d_{i} - 1. For performing the task, k_{i} servers with the smallest ids will be chosen from all the unoccupied servers. If in the second t_{i} there are not enough unoccupied servers, the task is ignored.
Write the program that determines which tasks will be performed and which will be ignored.
-----Input-----
The first line contains two positive integers n and q (1 ≤ n ≤ 100, 1 ≤ q ≤ 10^5) — the number of servers and the number of tasks.
Next q lines contains three integers each, the i-th line contains integers t_{i}, k_{i} and d_{i} (1 ≤ t_{i} ≤ 10^6, 1 ≤ k_{i} ≤ n, 1 ≤ d_{i} ≤ 1000) — the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds.
-----Output-----
Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.
-----Examples-----
Input
4 3
1 3 2
2 2 1
3 4 3
Output
6
-1
10
Input
3 2
3 2 3
5 1 2
Output
3
3
Input
8 6
1 3 20
4 2 1
6 5 5
10 1 1
15 3 6
21 8 8
Output
6
9
30
-1
15
36
-----Note-----
In the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10).
In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows: $f(0) = a$; $f(1) = b$; $f(n) = f(n-1) \oplus f(n-2)$ when $n > 1$, where $\oplus$ denotes the bitwise XOR operation.
You are given three integers $a$, $b$, and $n$, calculate $f(n)$.
You have to answer for $T$ independent test cases.
-----Input-----
The input contains one or more independent test cases.
The first line of input contains a single integer $T$ ($1 \le T \le 10^3$), the number of test cases.
Each of the $T$ following lines contains three space-separated integers $a$, $b$, and $n$ ($0 \le a, b, n \le 10^9$) respectively.
-----Output-----
For each test case, output $f(n)$.
-----Example-----
Input
3
3 4 2
4 5 0
325 265 1231232
Output
7
4
76
-----Note-----
In the first example, $f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 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.
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x_1, x_2, ..., x_{k} (k > 1) is such maximum element x_{j}, that the following inequality holds: $x_{j} \neq \operatorname{max}_{i = 1}^{k} x_{i}$.
The lucky number of the sequence of distinct positive integers x_1, x_2, ..., x_{k} (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.
You've got a sequence of distinct positive integers s_1, s_2, ..., s_{n} (n > 1). Let's denote sequence s_{l}, s_{l} + 1, ..., s_{r} as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].
Note that as all numbers in sequence s are distinct, all the given definitions make sence.
-----Input-----
The first line contains integer n (1 < n ≤ 10^5). The second line contains n distinct integers s_1, s_2, ..., s_{n} (1 ≤ s_{i} ≤ 10^9).
-----Output-----
Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r].
-----Examples-----
Input
5
5 2 1 4 3
Output
7
Input
5
9 8 3 5 7
Output
15
-----Note-----
For the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].
For the second sample you must choose s[2..5] = {8, 3, 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.
Holidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an $n \times m$ matrix consisting of "*" and ".".
To find every spruce first let's define what a spruce in the matrix is. A set of matrix cells is called a spruce of height $k$ with origin at point $(x, y)$ if:
All cells in the set contain an "*".
For each $1 \le i \le k$ all cells with the row number $x+i-1$ and columns in range $[y - i + 1, y + i - 1]$ must be a part of the set. All other cells cannot belong to the set.
Examples of correct and incorrect spruce trees:
Now Rick wants to know how many spruces his $n \times m$ matrix contains. Help Rick solve this problem.
-----Input-----
Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10$).
The first line of each test case contains two integers $n$ and $m$ ($1 \le n, m \le 500$) — matrix size.
Next $n$ lines of each test case contain $m$ characters $c_{i, j}$ — matrix contents. It is guaranteed that $c_{i, j}$ is either a "." or an "*".
It is guaranteed that the sum of $n \cdot m$ over all test cases does not exceed $500^2$ ($\sum n \cdot m \le 500^2$).
-----Output-----
For each test case, print single integer — the total number of spruces in the matrix.
-----Examples-----
Input
4
2 3
.*.
***
2 3
.*.
**.
4 5
.***.
*****
*****
*.*.*
5 7
..*.*..
.*****.
*******
.*****.
..*.*..
Output
5
3
23
34
-----Note-----
In the first test case the first spruce of height $2$ has its origin at point $(1, 2)$, the second spruce of height $1$ has its origin at point $(1, 2)$, the third spruce of height $1$ has its origin at point $(2, 1)$, the fourth spruce of height $1$ has its origin at point $(2, 2)$, the fifth spruce of height $1$ has its origin at point $(2, 3)$.
In the second test case the first spruce of height $1$ has its origin at point $(1, 2)$, the second spruce of height $1$ has its origin at point $(2, 1)$, the third spruce of height $1$ has its origin at point $(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.
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.
It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?
You are given a string of n lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
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 out what the MEX of the string is!
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000). Description of the test cases follows.
The first line of each test case contains an integer n (1 ≤ n ≤ 1000) — the length of the word. The second line for each test case contains a single string of n lowercase Latin letters.
The sum of n over all test cases will not exceed 1000.
Output
For each test case, output the MEX of the string on a new line.
Example
Input
3
28
qaabzwsxedcrfvtgbyhnujmiklop
13
cleanairactbd
10
aannttoonn
Output
ac
f
b
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of n playing cards. Let's describe the house they want to make:
1. The house consists of some non-zero number of floors.
2. Each floor consists of a non-zero number of rooms and the ceiling. A room is two cards that are leaned towards each other. The rooms are made in a row, each two adjoining rooms share a ceiling made by another card.
3. Each floor besides for the lowest one should contain less rooms than the floor below.
Please note that the house may end by the floor with more than one room, and in this case they also must be covered by the ceiling. Also, the number of rooms on the adjoining floors doesn't have to differ by one, the difference may be more.
While bears are practicing to put cards, Horace tries to figure out how many floors their house should consist of. The height of the house is the number of floors in it. It is possible that you can make a lot of different houses of different heights out of n cards. It seems that the elephant cannot solve this problem and he asks you to count the number of the distinct heights of the houses that they can make using exactly n cards.
Input
The single line contains integer n (1 ≤ n ≤ 1012) — the number of cards.
Output
Print the number of distinct heights that the houses made of exactly n cards can have.
Examples
Input
13
Output
1
Input
6
Output
0
Note
In the first sample you can build only these two houses (remember, you must use all the cards):
<image>
Thus, 13 cards are enough only for two floor houses, so the answer is 1.
The six cards in the second sample are not enough to build any house.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an initially empty cauldron, and you want to brew a potion in it. The potion consists of two ingredients: magic essence and water. The potion you want to brew should contain exactly $k\ \%$ magic essence and $(100 - k)\ \%$ water.
In one step, you can pour either one liter of magic essence or one liter of water into the cauldron. What is the minimum number of steps to brew a potion? You don't care about the total volume of the potion, only about the ratio between magic essence and water in it.
A small reminder: if you pour $e$ liters of essence and $w$ liters of water ($e + w > 0$) into the cauldron, then it contains $\frac{e}{e + w} \cdot 100\ \%$ (without rounding) magic essence and $\frac{w}{e + w} \cdot 100\ \%$ water.
-----Input-----
The first line contains the single $t$ ($1 \le t \le 100$) — the number of test cases.
The first and only line of each test case contains a single integer $k$ ($1 \le k \le 100$) — the percentage of essence in a good potion.
-----Output-----
For each test case, print the minimum number of steps to brew a good potion. It can be proved that it's always possible to achieve it in a finite number of steps.
-----Examples-----
Input
3
3
100
25
Output
100
1
4
-----Note-----
In the first test case, you should pour $3$ liters of magic essence and $97$ liters of water into the cauldron to get a potion with $3\ \%$ of magic essence.
In the second test case, you can pour only $1$ liter of essence to get a potion with $100\ \%$ of magic essence.
In the third test case, you can pour $1$ liter of magic essence and $3$ liters of water.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 arrange a deck of cards. There are totally 36 cards of 4 suits(S, H, C, D) and 9 values (1, 2, ... 9). For example, 'eight of heart' is represented by H8 and 'one of diamonds' is represented by D1.
Your task is to write a program which sorts a given set of cards in ascending order by their values using the Bubble Sort algorithms and the Selection Sort algorithm respectively. These algorithms should be based on the following pseudocode:
BubbleSort(C)
1 for i = 0 to C.length-1
2 for j = C.length-1 downto i+1
3 if C[j].value < C[j-1].value
4 swap C[j] and C[j-1]
SelectionSort(C)
1 for i = 0 to C.length-1
2 mini = i
3 for j = i to C.length-1
4 if C[j].value < C[mini].value
5 mini = j
6 swap C[i] and C[mini]
Note that, indices for array elements are based on 0-origin.
For each algorithm, report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).
Constraints
1 ≤ N ≤ 36
Input
The first line contains an integer N, the number of cards.
N cards are given in the following line. Each card is represented by two characters. Two consecutive cards are separated by a space character.
Output
In the first line, print the arranged cards provided by the Bubble Sort algorithm. Two consecutive cards should be separated by a space character.
In the second line, print the stability ("Stable" or "Not stable") of this output.
In the third line, print the arranged cards provided by the Selection Sort algorithm. Two consecutive cards should be separated by a space character.
In the fourth line, print the stability ("Stable" or "Not stable") of this output.
Examples
Input
5
H4 C9 S4 D2 C3
Output
D2 C3 H4 S4 C9
Stable
D2 C3 S4 H4 C9
Not stable
Input
2
S1 H1
Output
S1 H1
Stable
S1 H1
Stable
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Aiz, which is located in cyberspace, trades information with Wakamatsu. The two countries are developing their economies by exchanging useful data with each other. The two countries, whose national policy is philanthropy and equality, and above all, the old word of the Aizu region, "what must be done", conducts regular surveys of trade conditions.
In the survey, a table is given in which the value obtained by subtracting the outflow amount from the data inflow amount seen from Aiz country in byte units is calculated every 1 nanosecond. From that table, find the longest interval where the sum of the values is zero. It is judged that the longer this section is, the more equality is maintained.
Given a table with trade status, write a program to find the length of the longest interval where the sum of the values is zero.
Input
The input is given in the following format.
N
d1
d2
::
dN
The first row gives the number N (1 ≤ N ≤ 200000) of the values written in the table. The next N rows are given the integer di (-109 ≤ di ≤ 109), which indicates the value written in row i of the table.
Output
The length of the longest section obtained from the table where the sum is 0 is output in one line. If such an interval does not exist, "0" is output on one line.
Examples
Input
5
18
102
-155
53
32
Output
3
Input
4
1
1
-1
-1
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.
Niwango created a playlist of N songs. The title and the duration of the i-th song are s_i and t_i seconds, respectively. It is guaranteed that s_1,\ldots,s_N are all distinct.
Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.) However, he fell asleep during his work, and he woke up after all the songs were played. According to his record, it turned out that he fell asleep at the very end of the song titled X.
Find the duration of time when some song was played while Niwango was asleep.
Constraints
* 1 \leq N \leq 50
* s_i and X are strings of length between 1 and 100 (inclusive) consisting of lowercase English letters.
* s_1,\ldots,s_N are distinct.
* There exists an integer i such that s_i = X.
* 1 \leq t_i \leq 1000
* t_i is an integer.
Input
Input is given from Standard Input in the following format:
N
s_1 t_1
\vdots
s_{N} t_N
X
Output
Print the answer.
Examples
Input
3
dwango 2
sixth 5
prelims 25
dwango
Output
30
Input
1
abcde 1000
abcde
Output
0
Input
15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu
Output
6348
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.
Let's consider a rectangular image that is represented with a table of size n × m. The table elements are integers that specify the brightness of each pixel in the image.
A feature also is a rectangular table of size n × m. Each cell of a feature is painted black or white.
To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of W - B, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.
Some examples of the most popular Haar features are given below. [Image]
Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.
A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.
You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values at any prefix rectangle, multiply it by any integer and add to variable value.
You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.
-----Input-----
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — the number of rows and columns in the feature.
Next n lines contain the description of the feature. Each line consists of m characters, the j-th character of the i-th line equals to "W", if this element of the feature is white and "B" if it is black.
-----Output-----
Print a single number — the minimum number of operations that you need to make to calculate the value of the feature.
-----Examples-----
Input
6 8
BBBBBBBB
BBBBBBBB
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW
Output
2
Input
3 3
WBW
BWW
WWW
Output
4
Input
3 6
WWBBWW
WWBBWW
WWBBWW
Output
3
Input
4 4
BBBB
BBBB
BBBB
BBBW
Output
4
-----Note-----
The first sample corresponds to feature B, the one shown in the picture. The value of this feature in an image of size 6 × 8 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations:
add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable value (the rectangle is indicated by a red frame); $\left. \begin{array}{|r|r|r|r|r|r|r|r|} \hline 1 & {1} & {1} & {1} & {1} & {1} & {1} & {1} \\ \hline 1 & {1} & {1} & {1} & {1} & {1} & {1} & {1} \\ \hline 1 & {1} & {1} & {1} & {1} & {1} & {1} & {1} \\ \hline 1 & {1} & {1} & {1} & {1} & {1} & {1} & {1} \\ \hline 1 & {1} & {1} & {1} & {1} & {1} & {1} & {1} \\ \hline 1 & {1} & {1} & {1} & {1} & {1} & {1} & {1} \\ \hline \end{array} \right.$
add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient - 2 and variable value. [Image]
Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1 - 2 = - 1, as required.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).
The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays).
Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:
* Each boy plays for exactly one team (x + y = n).
* The sizes of teams differ in no more than one (|x - y| ≤ 1).
* The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: <image>
Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
Input
The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.
Output
On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills.
If there are multiple ways to solve the problem, print any of them.
The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
Examples
Input
3
1 2 1
Output
2
1 2
1
3
Input
5
2 3 3 1 1
Output
3
4 1 3
2
5 2
Note
Let's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer N. Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:
* The graph is simple and connected.
* There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.
It can be proved that at least one such graph exists under the constraints of this problem.
Constraints
* All values in input are integers.
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.
The output will be judged correct if the graph satisfies the conditions.
Example
Input
3
Output
2
1 3
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.
There are $n$ students numerated from $1$ to $n$. The level of the $i$-th student is $a_i$. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than $x$.
For example, if $x = 4$, then the group with levels $[1, 10, 8, 4, 4]$ is stable (because $4 - 1 \le x$, $4 - 4 \le x$, $8 - 4 \le x$, $10 - 8 \le x$), while the group with levels $[2, 10, 10, 7]$ is not stable ($7 - 2 = 5 > x$).
Apart from the $n$ given students, teachers can invite at most $k$ additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).
For example, if there are two students with levels $1$ and $5$; $x = 2$; and $k \ge 1$, then you can invite a new student with level $3$ and put all the students in one stable group.
-----Input-----
The first line contains three integers $n$, $k$, $x$ ($1 \le n \le 200000$, $0 \le k \le 10^{18}$, $1 \le x \le 10^{18}$) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{18}$) — the students levels.
-----Output-----
In the only line print a single integer: the minimum number of stable groups you can split the students into.
-----Examples-----
Input
8 2 3
1 1 5 8 12 13 20 22
Output
2
Input
13 0 37
20 20 80 70 70 70 420 5 1 5 1 60 90
Output
3
-----Note-----
In the first example you can invite two students with levels $2$ and $11$. Then you can split the students into two stable groups:
$[1, 1, 2, 5, 8, 11, 12, 13]$,
$[20, 22]$.
In the second example you are not allowed to invite new students, so you need $3$ groups:
$[1, 1, 5, 5, 20, 20]$
$[60, 70, 70, 70, 80, 90]$
$[420]$
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 tree of $n$ vertices. You are going to convert this tree into $n$ rubber bands on infinitely large plane. Conversion rule follows:
For every pair of vertices $a$ and $b$, rubber bands $a$ and $b$ should intersect if and only if there is an edge exists between $a$ and $b$ in the tree.
Shape of rubber bands must be a simple loop. In other words, rubber band is a loop which doesn't self-intersect.
Now let's define following things:
Rubber band $a$ includes rubber band $b$, if and only if rubber band $b$ is in rubber band $a$'s area, and they don't intersect each other.
Sequence of rubber bands $a_{1}, a_{2}, \ldots, a_{k}$ ($k \ge 2$) are nested, if and only if for all $i$ ($2 \le i \le k$), $a_{i-1}$ includes $a_{i}$.
This is an example of conversion. Note that rubber bands $5$ and $6$ are nested.
It can be proved that is it possible to make a conversion and sequence of nested rubber bands under given constraints.
What is the maximum length of sequence of nested rubber bands can be obtained from given tree? Find and print it.
-----Input-----
The first line contains integer $n$ ($3 \le n \le 10^{5}$) — the number of vertices in tree.
The $i$-th of the next $n-1$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$) — it means there is an edge between $a_{i}$ and $b_{i}$. It is guaranteed that given graph forms tree of $n$ vertices.
-----Output-----
Print the answer.
-----Examples-----
Input
6
1 3
2 3
3 4
4 5
4 6
Output
4
Input
4
1 2
2 3
3 4
Output
2
-----Note-----
In the first sample, you can obtain a nested sequence of $4$ rubber bands($1$, $2$, $5$, and $6$) by the conversion shown below. Of course, there are other conversions exist to make a nested sequence of $4$ rubber bands. However, you cannot make sequence of $5$ or more nested rubber bands with given tree.
You can see one of the possible conversions for the second sample below.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try?
-----Input-----
The input contains two integers a and b (0 ≤ a, b ≤ 10^3), separated by a single space.
-----Output-----
Output the sum of the given integers.
-----Examples-----
Input
5 14
Output
19
Input
381 492
Output
873
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._
> You are given the memories as a string containing people's surname and name (comma separated). The scientist marked one occurrence of each of the people he hates by putting a '!' right before their name.
**Your task is to destroy all the occurrences of the marked people.
One more thing ! Hate is contagious, so you also need to erase any memory of the person that comes after any marked name!**
---
Examples
---
---
Input:
```
"Albert Einstein, !Sarah Connor, Marilyn Monroe, Abraham Lincoln, Sarah Connor, Sean Connery, Marilyn Monroe, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
Output:
```
"Albert Einstein, Abraham Lincoln, Sean Connery, Bjarne Stroustrup, Manson Marilyn, Monroe Mary"
```
=> We must remove every memories of Sarah Connor because she's marked, but as a side-effect we must also remove all the memories about Marilyn Monroe that comes right after her! Note that we can't destroy the memories of Manson Marilyn or Monroe Mary, so be careful!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.
The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.
Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r, c).
You are staying in the cell (r_1, c_1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r_2, c_2) since the exit to the next level is there. Can you do this?
-----Input-----
The first line contains two integers, n and m (1 ≤ n, m ≤ 500) — the number of rows and columns in the cave description.
Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice).
The next line contains two integers, r_1 and c_1 (1 ≤ r_1 ≤ n, 1 ≤ c_1 ≤ m) — your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r_1, c_1), that is, the ice on the starting cell is initially cracked.
The next line contains two integers r_2 and c_2 (1 ≤ r_2 ≤ n, 1 ≤ c_2 ≤ m) — the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.
-----Output-----
If you can reach the destination, print 'YES', otherwise print 'NO'.
-----Examples-----
Input
4 6
X...XX
...XX.
.X..X.
......
1 6
2 2
Output
YES
Input
5 4
.X..
...X
X.X.
....
.XX.
5 3
1 1
Output
NO
Input
4 7
..X.XX.
.XX..X.
X...X..
X......
2 2
1 6
Output
YES
-----Note-----
In the first sample test one possible path is:
[Image]
After the first visit of cell (2, 2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Lucy loves to travel. Luckily she is a renowned computer scientist and gets to travel to international conferences using her department's budget.
Each year, Society for Exciting Computer Science Research (SECSR) organizes several conferences around the world. Lucy always picks one conference from that list that is hosted in a city she hasn't been to before, and if that leaves her with more than one option, she picks the conference that she thinks would be most relevant for her field of research.
Write a function `conferencePicker` that takes in two arguments:
- `citiesVisited`, a list of cities that Lucy has visited before, given as an array of strings.
- `citiesOffered`, a list of cities that will host SECSR conferences this year, given as an array of strings. `citiesOffered` will already be ordered in terms of the relevance of the conferences for Lucy's research (from the most to the least relevant).
The function should return the city that Lucy should visit, as a string.
Also note:
- You should allow for the possibility that Lucy hasn't visited any city before.
- SECSR organizes at least two conferences each year.
- If all of the offered conferences are hosted in cities that Lucy has visited before, the function should return `'No worthwhile conferences this year!'` (`Nothing` in Haskell)
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.
Read problems statements in Mandarin Chinese and Russian.
N one dimensional kingdoms are represented as intervals of the form [a_{i} , b_{i}] on the real line.
A kingdom of the form [L, R] can be destroyed completely by placing a bomb at a point x on the real line if L
≤ x ≤ R.
Your task is to determine minimum number of bombs required to destroy all the one dimensional kingdoms.
------ Input ------
First line of the input contains T denoting number of test cases.
For each test case, first line contains N denoting the number of one dimensional kingdoms.
For each next N lines, each line contains two space separated integers a_{i} and b_{i}.
------ Output ------
For each test case , output an integer denoting the minimum number of bombs required.
------ Constraints ------
Subtask 1 (20 points) : 1 ≤ T ≤ 100 , 1 ≤ N ≤ 100 , 0 ≤ a_{i} ≤ b_{i} ≤500
Subtask 2 (30 points) : 1 ≤ T ≤ 100 , 1 ≤ N ≤ 1000 , 0 ≤ a_{i} ≤ b_{i} ≤ 1000
Subtask 3 (50 points) : 1 ≤ T ≤ 20 , 1 ≤ N ≤ 10^{5}, 0 ≤ a_{i} ≤ b_{i} ≤ 2000
----- Sample Input 1 ------
1
3
1 3
2 5
6 9
----- Sample Output 1 ------
2
----- explanation 1 ------
There are three kingdoms [1,3] ,[2,5] and [6,9]. You will need at least 2 bombs
to destroy the kingdoms. In one of the possible solutions, you can place two bombs at x = 2 and x = 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.
You are given a string S consisting of letters `b`, `d`, `p` and `q`. Determine whether S is a mirror string.
Here, a mirror string is a string S such that the following sequence of operations on S results in the same string S:
1. Reverse the order of the characters in S.
2. Replace each occurrence of `b` by `d`, `d` by `b`, `p` by `q`, and `q` by `p`, simultaneously.
Constraints
* 1 \leq |S| \leq 10^5
* S consists of letters `b`, `d`, `p`, and `q`.
Input
The input is given from Standard Input in the following format:
S
Output
If S is a mirror string, print `Yes`. Otherwise, print `No`.
Examples
Input
pdbq
Output
Yes
Input
ppqb
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.
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $n$ haybale piles on the farm. The $i$-th pile contains $a_i$ haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $i$ and $j$ ($1 \le i, j \le n$) such that $|i-j|=1$ and $a_i>0$ and apply $a_i = a_i - 1$, $a_j = a_j + 1$. She may also decide to not do anything on some days because she is lazy.
Bessie wants to maximize the number of haybales in pile $1$ (i.e. to maximize $a_1$), and she only has $d$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $1$ if she acts optimally!
-----Input-----
The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases. Next $2t$ lines contain a description of test cases — two lines per test case.
The first line of each test case contains integers $n$ and $d$ ($1 \le n,d \le 100$) — the number of haybale piles and the number of days, respectively.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 100$) — the number of haybales in each pile.
-----Output-----
For each test case, output one integer: the maximum number of haybales that may be in pile $1$ after $d$ days if Bessie acts optimally.
-----Example-----
Input
3
4 5
1 0 3 2
2 2
100 1
1 8
0
Output
3
101
0
-----Note-----
In the first test case of the sample, this is one possible way Bessie can end up with $3$ haybales in pile $1$: On day one, move a haybale from pile $3$ to pile $2$ On day two, move a haybale from pile $3$ to pile $2$ On day three, move a haybale from pile $2$ to pile $1$ On day four, move a haybale from pile $2$ to pile $1$ On day five, do nothing
In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $2$ to pile $1$ on the second 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.
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the nodes of the tree such that The root is number 1 Each internal node i (i ≤ 2^{h} - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1
The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out!
In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.
Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.
-----Input-----
The first line contains two integers h, q (1 ≤ h ≤ 50, 0 ≤ q ≤ 10^5), the height of the tree and the number of questions respectively.
The next q lines will contain four integers each i, L, R, ans (1 ≤ i ≤ h, 2^{i} - 1 ≤ L ≤ R ≤ 2^{i} - 1, $\text{ans} \in \{0,1 \}$), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").
-----Output-----
If the information provided by the game is contradictory output "Game cheated!" without the quotes.
Else if you can uniquely identify the exit to the maze output its index.
Otherwise output "Data not sufficient!" without the quotes.
-----Examples-----
Input
3 1
3 4 6 0
Output
7
Input
4 3
4 10 14 1
3 6 6 0
2 3 3 1
Output
14
Input
4 2
3 4 6 1
4 12 15 1
Output
Data not sufficient!
Input
4 2
3 4 5 1
2 3 3 1
Output
Game cheated!
-----Note-----
Node u is an ancestor of node v if and only if u is the same node as v, u is the parent of node v, or u is an ancestor of the parent of node v.
In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.
In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
[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.
There are N positive integers A_1, A_2, ..., A_N. Takahashi can perform the following operation on these integers any number of times:
* Choose 1 \leq i \leq N and multiply the value of A_i by -2.
Notice that he multiplies it by minus two.
He would like to make A_1 \leq A_2 \leq ... \leq A_N holds. Find the minimum number of operations required. If it is impossible, print `-1`.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the answer.
Examples
Input
4
3 1 4 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
8
657312726 129662684 181537270 324043958 468214806 916875077 825989291 319670097
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.
Snuke has an integer sequence A of length N.
He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E. The positions of the cuts can be freely chosen.
Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively. Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller. Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.
Constraints
* 4 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.
Examples
Input
5
3 2 4 1 2
Output
2
Input
10
10 71 84 33 6 47 23 25 52 64
Output
36
Input
7
1 2 3 1000000000 4 5 6
Output
999999994
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya has an array a_1, a_2, ..., a_n.
You don't know this array, but he told you m facts about this array. The i-th fact is a triple of numbers t_i, l_i and r_i (0 ≤ t_i ≤ 1, 1 ≤ l_i < r_i ≤ n) and it means:
* if t_i=1 then subbarray a_{l_i}, a_{l_i + 1}, ..., a_{r_i} is sorted in non-decreasing order;
* if t_i=0 then subbarray a_{l_i}, a_{l_i + 1}, ..., a_{r_i} is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter.
For example if a = [2, 1, 1, 3, 2] then he could give you three facts: t_1=1, l_1=2, r_1=4 (the subarray [a_2, a_3, a_4] = [1, 1, 3] is sorted), t_2=0, l_2=4, r_2=5 (the subarray [a_4, a_5] = [3, 2] is not sorted), and t_3=0, l_3=3, r_3=5 (the subarray [a_3, a_5] = [1, 3, 2] is not sorted).
You don't know the array a. Find any array which satisfies all the given facts.
Input
The first line contains two integers n and m (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000).
Each of the next m lines contains three integers t_i, l_i and r_i (0 ≤ t_i ≤ 1, 1 ≤ l_i < r_i ≤ n).
If t_i = 1 then subbarray a_{l_i}, a_{l_i + 1}, ... , a_{r_i} is sorted. Otherwise (if t_i = 0) subbarray a_{l_i}, a_{l_i + 1}, ... , a_{r_i} is not sorted.
Output
If there is no array that satisfies these facts in only line print NO (in any letter case).
If there is a solution, print YES (in any letter case). In second line print n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9) — the array a, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them.
Examples
Input
7 4
1 1 3
1 2 5
0 5 6
1 6 7
Output
YES
1 2 2 3 5 4 4
Input
4 2
1 1 4
0 2 3
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.
In April 2008, Aizuwakamatsu City succeeded in making yakitori with a length of 20 m 85 cm. The chicken used at this time is Aizu local chicken, which is a specialty of Aizu. Aizu local chicken is very delicious, but it is difficult to breed, so the production volume is small and the price is high.
<image>
Relatives come to visit Ichiro's house from afar today. Mom decided to cook chicken and entertain her relatives. A nearby butcher shop sells two types of chicken, Aizu chicken and regular chicken. The mother gave Ichiro the following instructions and asked the butcher to go and buy chicken.
* If you run out of chicken, you will be in trouble, so buy more chicken than you have decided.
* Buy as many Aizu local chickens as your budget allows (must buy Aizu local chickens).
* Buy as much regular chicken as possible with the rest of the Aizu chicken (don't buy if you don't have enough budget).
When Ichiro went to the butcher shop, the amount of Aizu chicken that could be bought by one person was limited due to lack of stock. When Ichiro follows all the instructions given by his mother when shopping, how many grams of Aizu chicken and regular chicken will Ichiro buy?
Enter the lower limit of the amount of chicken to buy q1, the budget b, the price of 100 grams of Aizu chicken at this butcher c1, the price of 100 grams of regular chicken c2, and the upper limit of the amount of Aizu chicken that one person can buy q2. Create a program that outputs the amount of Aizu chicken and ordinary chicken that Ichiro buys in units of 100 grams. However, if you cannot buy at this butcher's shop as instructed by your mother, please output "NA".
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
q1 b c1 c2 q2
The data q1 and q2, which represent the amount of chicken, are specified in units of 100 grams. Also, b, c1, c2, q1, and q2 are integers between 1 and 1,000,000.
The number of datasets does not exceed 50.
Output
For each data set, the amount of Aizu chicken purchased by Ichiro and the amount of normal chicken (separated by half-width spaces) or "NA" is output on one line.
Example
Input
48 9297 240 126 32
20 3010 157 141 7
30 117002 5680 962 15
8 1673 1712 190 22
64 8478 87 54 307
23 5477 117 92 12
50 7558 1396 187 17
279 88677 4522 514 14
0
Output
28 20
7 13
15 33
NA
97 0
12 44
NA
NA
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 same as the previous one, but has larger constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the $n$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $i$-th day has a ribbon with color $u_i$. Shiro wants to know the largest number $x$, such that if we consider the streak of the first $x$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $x - 1$ will have the same number of occurrences.
For example, consider the following sequence of $u_i$: $[2, 2, 1, 1, 5, 4, 4, 5]$. Then $x = 7$ makes a streak, since if we remove the leftmost $u_i = 5$, each ribbon color will appear exactly twice in the prefix of $x - 1$ days. Note that $x = 8$ doesn't form a streak, since you must remove exactly one day.
Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the total number of days.
The second line contains $n$ integers $u_1, u_2, \ldots, u_n$ ($1 \leq u_i \leq 10^5$) — the colors of the ribbons the cats wear.
-----Output-----
Print a single integer $x$ — the largest possible streak of days.
-----Examples-----
Input
13
1 1 1 2 2 2 3 3 3 4 4 4 5
Output
13
Input
5
10 100 20 200 1
Output
5
Input
1
100000
Output
1
Input
7
3 2 1 1 4 5 1
Output
6
Input
6
1 1 1 2 2 2
Output
5
-----Note-----
In the first example, we can choose the longest streak of $13$ days, since upon removing the last day out of the streak, all of the remaining colors $1$, $2$, $3$, and $4$ will have the same number of occurrences of $3$. Note that the streak can also be $10$ days (by removing the $10$-th day from this streak) but we are interested in the longest streak.
In the fourth example, if we take the streak of the first $6$ days, we can remove the third day from this streak then all of the remaining colors $1$, $2$, $3$, $4$ and $5$ will occur exactly once.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 create function```isDivideBy``` (or ```is_divide_by```) to check if an integer number is divisible by each out of two arguments.
A few cases:
```
(-12, 2, -6) -> true
(-12, 2, -5) -> false
(45, 1, 6) -> false
(45, 5, 15) -> true
(4, 1, 4) -> true
(15, -5, 3) -> true
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vova is playing a computer game. There are in total $n$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $k$.
During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than $a$, Vova can just play, and then the charge of his laptop battery will decrease by $a$; if the current charge of his laptop battery is strictly greater than $b$ ($b<a$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $b$; if the current charge of his laptop battery is less than or equal to $a$ and $b$ at the same time then Vova cannot do anything and loses the game.
Regardless of Vova's turns the charge of the laptop battery is always decreases.
Vova wants to complete the game (Vova can complete the game if after each of $n$ turns the charge of the laptop battery is strictly greater than $0$). Vova has to play exactly $n$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.
Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.
You have to answer $q$ independent queries.
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries. Each query is presented by a single line.
The only line of the query contains four integers $k, n, a$ and $b$ ($1 \le k, n \le 10^9, 1 \le b < a \le 10^9$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $a$ and $b$, correspondingly.
-----Output-----
For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.
-----Example-----
Input
6
15 5 3 2
15 5 4 3
15 5 2 1
15 5 5 1
16 7 5 2
20 5 7 3
Output
4
-1
5
2
0
1
-----Note-----
In the first example query Vova can just play $4$ turns and spend $12$ units of charge and then one turn play and charge and spend $2$ more units. So the remaining charge of the battery will be $1$.
In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $0$ after the last turn.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.
Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.
-----Constraints-----
- 1≦N≦1000
- 1≦T_i,A_i≦1000 (1≦i≦N)
- T_i and A_i (1≦i≦N) are coprime.
- It is guaranteed that the correct answer is at most 10^{18}.
-----Input-----
The input is given from Standard Input in the following format:
N
T_1 A_1
T_2 A_2
:
T_N A_N
-----Output-----
Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.
-----Sample Input-----
3
2 3
1 1
3 2
-----Sample Output-----
10
When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!
In the morning, there are $n$ opportunities to buy shares. The $i$-th of them allows to buy as many shares as you want, each at the price of $s_i$ bourles.
In the evening, there are $m$ opportunities to sell shares. The $i$-th of them allows to sell as many shares as you want, each at the price of $b_i$ bourles. You can't sell more shares than you have.
It's morning now and you possess $r$ bourles and no shares.
What is the maximum number of bourles you can hold after the evening?
-----Input-----
The first line of the input contains three integers $n, m, r$ ($1 \leq n \leq 30$, $1 \leq m \leq 30$, $1 \leq r \leq 1000$) — the number of ways to buy the shares on the market, the number of ways to sell the shares on the market, and the number of bourles you hold now.
The next line contains $n$ integers $s_1, s_2, \dots, s_n$ ($1 \leq s_i \leq 1000$); $s_i$ indicates the opportunity to buy shares at the price of $s_i$ bourles.
The following line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \leq b_i \leq 1000$); $b_i$ indicates the opportunity to sell shares at the price of $b_i$ bourles.
-----Output-----
Output a single integer — the maximum number of bourles you can hold after the evening.
-----Examples-----
Input
3 4 11
4 2 5
4 4 5 4
Output
26
Input
2 2 50
5 7
4 2
Output
50
-----Note-----
In the first example test, you have $11$ bourles in the morning. It's optimal to buy $5$ shares of a stock at the price of $2$ bourles in the morning, and then to sell all of them at the price of $5$ bourles in the evening. It's easy to verify that you'll have $26$ bourles after the evening.
In the second example test, it's optimal not to take any action.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.
For each opponent Arya knows his schedule — whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.
Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.
-----Input-----
The first line of the input contains two integers n and d (1 ≤ n, d ≤ 100) — the number of opponents and the number of days, respectively.
The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.
-----Output-----
Print the only integer — the maximum number of consecutive days that Arya will beat all present opponents.
-----Examples-----
Input
2 2
10
00
Output
2
Input
4 1
0100
Output
1
Input
4 5
1101
1111
0110
1011
1111
Output
2
-----Note-----
In the first and the second samples, Arya will beat all present opponents each of the d days.
In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 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.
You are given a sequence of positive integers a_1, a_2, ..., a_{n}.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step.
You stop performing the operation when there is no pair of equal consecutive elements.
For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second — [5, 3, 2, 2], after the third — [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.
Determine the final sequence after you stop performing the operation.
-----Input-----
The first line contains a single integer n (2 ≤ n ≤ 2·10^5) — the number of elements in the sequence.
The second line contains the sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
In the first line print a single integer k — the number of elements in the sequence after you stop performing the operation.
In the second line print k integers — the sequence after you stop performing the operation.
-----Examples-----
Input
6
5 2 1 1 2 2
Output
2
5 4
Input
4
1000000000 1000000000 1000000000 1000000000
Output
1
1000000002
Input
7
4 10 22 11 12 5 6
Output
7
4 10 22 11 12 5 6
-----Note-----
The first example is described in the statements.
In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].
In the third example there are no two equal consecutive elements initially, so the sequence does not change.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let us define the FizzBuzz sequence a_1,a_2,... as follows:
- If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.
- If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.
- If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.
- If none of the above holds, a_i=i.
Find the sum of all numbers among the first N terms of the FizzBuzz sequence.
-----Constraints-----
- 1 \leq N \leq 10^6
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the sum of all numbers among the first N terms of the FizzBuzz sequence.
-----Sample Input-----
15
-----Sample Output-----
60
The first 15 terms of the FizzBuzz sequence are:
1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}
Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 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 Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all.
After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
Input
The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.
Output
Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.
Examples
Input
5
1 2 3 4 5
Output
1 1 2 3 4
Input
5
2 3 4 5 6
Output
1 2 3 4 5
Input
3
2 2 2
Output
1 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.
One of the first algorithm used for approximating the integer square root of a positive integer `n` is known as "Hero's method",
named after the first-century Greek mathematician Hero of Alexandria who gave the first description
of the method. Hero's method can be obtained from Newton's method which came 16 centuries after.
We approximate the square root of a number `n` by taking an initial guess `x`, an error `e` and repeatedly calculating a new approximate *integer* value `x` using: `(x + n / x) / 2`; we are finished when the previous `x` and the `new x` have an absolute difference less than `e`.
We supply to a function (int_rac) a number `n` (positive integer) and a parameter `guess` (positive integer) which will be our initial `x`. For this kata the parameter 'e' is set to `1`.
Hero's algorithm is not always going to come to an exactly correct result! For instance: if n = 25 we get 5 but for n = 26 we also get 5. Nevertheless `5` is the *integer* square root of `26`.
The kata is to return the count of the progression of integer approximations that the algorithm makes.
Reference:
Some examples:
```
int_rac(25,1): follows a progression of [1,13,7,5] so our function should return 4.
int_rac(125348,300): has a progression of [300,358,354] so our function should return 3.
int_rac(125348981764,356243): has a progression of [356243,354053,354046] so our function should return 3.
```
#
You can use Math.floor (or similar) for each integer approximation.
#
Note for JavaScript, Coffescript, Typescript:
Don't use the double bitwise NOT ~~ at each iteration if you want to have the same results as in the tests and the other languages.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:
- In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.
For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.
You are given a positive integer K. Find the K-th smallest lunlun number.
-----Constraints-----
- 1 \leq K \leq 10^5
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
K
-----Output-----
Print the answer.
-----Sample Input-----
15
-----Sample Output-----
23
We will list the 15 smallest lunlun numbers in ascending order:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.
Thus, the answer is 23.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:
\\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\]
where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.
Note
解説
Constraints
* $1 \leq n, m, l \leq 100$
* $0 \leq a_{ij}, b_{ij} \leq 10000$
Input
In the first line, three integers $n$, $m$ and $l$ are given separated by space characters
In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.
Output
Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.
Example
Input
3 2 3
1 2
0 3
4 5
1 2 1
0 3 2
Output
1 8 5
0 9 6
4 23 14
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 set of cards with positive integers written on them. Stack the cards to make several piles and arrange them side by side. Select two adjacent piles of cards from them, and stack the left pile on top of the right pile. Repeat this operation until there is only one pile of cards.
When stacking two piles of cards, multiply all the numbers written on the top and bottom cards of them. We will call the number obtained in this way the cost of stacking cards. The cost of unifying a pile of cards shall be the sum of the costs of all stacking.
The cost will change depending on the order in which the piles of cards are stacked. For example, suppose you have a pile of three cards. Suppose the numbers on the top and bottom cards are 3, 5, 2, 8, 5, and 4, respectively, from the left pile. At this time, the cost of stacking the left and middle mountains first is 3 x 5 x 2 x 8 = 240. This stack creates a pile with 3 on the top and 8 on the bottom.
If you stack this mountain on top of the mountain on the right, the cost is 3 x 8 x 5 x 4 = 480. Therefore, the cost of combining piles of cards in this order is 240 + 480 = 720. (Figure 1)
On the other hand, if you first stack the middle and right peaks and then the left peak at the end, the cost will be 2 x 8 x 5 x 4 + 3 x 5 x 2 x 4 = 440. Therefore, the cost will be lower if they are stacked as in the later case. (Figure 2)
<image> | <image>
--- | ---
Enter the number of piles of cards and the number written on the top and bottom cards of each pile, and create a program that outputs the minimum cost required to combine the piles of cards into one. However, the number of ridges should be 100 or less, and the data entered should not exceed 231-1 in any order of cost calculation.
Input
The input is given in the following format:
n
a1 b1
a2 b2
::
an bn
The number of piles of cards n (n ≤ 100) on the first line, the number ai (1 ≤ ai ≤ 200) written on the top card of the i-th pile from the left on the following n lines, and the bottom The number bi (1 ≤ bi ≤ 200) written on the card is given.
Output
Print the minimum cost required to combine a pile of cards into one line.
Example
Input
3
3 5
2 8
5 4
Output
440
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 islands lining up from west to east, connected by N-1 bridges.
The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.
One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:
Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.
You decided to remove some bridges to meet all these M requests.
Find the minimum number of bridges that must be removed.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10^5
- 1 \leq M \leq 10^5
- 1 \leq a_i < b_i \leq N
- All pairs (a_i, b_i) are distinct.
-----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-----
Print the minimum number of bridges that must be removed.
-----Sample Input-----
5 2
1 4
2 5
-----Sample Output-----
1
The requests can be met by removing the bridge connecting the second and third islands 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.
-----Input-----
The input contains a single integer a (1 ≤ a ≤ 64).
-----Output-----
Output a single integer.
-----Examples-----
Input
2
Output
1
Input
4
Output
2
Input
27
Output
5
Input
42
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.
Well, those numbers were right and we're going to feed their ego.
Write a function, isNarcissistic, that takes in any amount of numbers and returns true if all the numbers are narcissistic. Return false for invalid arguments (numbers passed in as strings are ok).
For more information about narcissistic numbers (and believe me, they love it when you read about them) follow this link: https://en.wikipedia.org/wiki/Narcissistic_number
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $s$ of length $n$.
Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $s$.
She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $s$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.
A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. The next $2 \cdot t$ lines contain the description of test cases. The description of each test case consists of two lines.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the length of the string.
The second line of each test case contains the string $s$ consisting of $n$ lowercase English letters.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $-1$, if it is impossible.
-----Examples-----
Input
5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky
Output
2
-1
0
3
2
-----Note-----
In the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.
In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.
In the third test case, you don't have to erase any symbols because the string is already a palindrome.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 109) — the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≤ i ≤ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position 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.
Late last night in the Tanner household, ALF was repairing his spaceship so he might get back to Melmac. Unfortunately for him, he forgot to put on the parking brake, and the spaceship took off during repair. Now it's hovering in space.
ALF has the technology to bring the spaceship home if he can lock on to its location.
Given a map:
````
..........
..........
..........
.......X..
..........
..........
````
The map will be given in the form of a string with \n separating new lines. The bottom left of the map is [0, 0]. X is ALF's spaceship.
In this example:
If you cannot find the spaceship, the result should be
```
"Spaceship lost forever."
```
Can you help ALF?
Check out my other 80's Kids Katas:
80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5: You Can't Do That on Television
80's Kids #6: Rock 'Em, Sock 'Em Robots
80's Kids #7: She's a Small Wonder
80's Kids #8: The Secret World of Alex Mack
80's Kids #9: Down in Fraggle Rock
80's Kids #10: Captain Planet
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Christmas is coming. In the [previous kata](https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e), we build a custom Christmas tree with the specified characters and the specified height.
Now, we are interested in the center of the Christmas tree.
Please imagine that we build a Christmas tree with `chars = "abc" and n = Infinity`, we got:
```
a
b c
a b c
a b c a
b c a b c
a b c a b c
a b c a b c a
b c a b c a b c
a b c a b c a b a
b c a b c a b a b c
a b c a b a b c a b c
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
|
|
.
.
```
If we keep only the center part of leaves, we will got:
```
a
b
a
a
b
a
.
.
.
```
As you can see, it's a infinite string, but it has a repeat substring "aba"(spaces will be removed). If we join them together, it looks like:`"abaabaabaabaaba......"`.
So, your task is to find the repeat substring of the center part of leaves.
# Inputs:
- `chars`: the specified characters. In this kata, they always be lowercase letters.
# Output:
- The repeat substring that satisfy the above conditions.
Still not understand the task? Look at the following example ;-)
# Examples
For `chars = "abc"`,the output should be `"aba"`
```
center leaves sequence: "abaabaabaabaabaaba....."
```
For `chars = "abab"`,the output should be `a`
```
center leaves sequence: "aaaaaaaaaa....."
```
For `chars = "abcde"`,the output should be `aecea`
```
center leaves sequence: "aeceaaeceaaecea....."
```
For `chars = "aaaaaaaaaaaaaa"`,the output should be `a`
```
center leaves sequence: "aaaaaaaaaaaaaa....."
```
For `chars = "abaabaaab"`,the output should be `aba`
```
center leaves sequence: "abaabaabaaba....."
```
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.
Input
The first line of the input contains integer n (1 ≤ n ≤ 2·108) and integer m (1 ≤ m ≤ 20). The i + 1-th line contains a pair of numbers ai and bi (1 ≤ ai ≤ 108, 1 ≤ bi ≤ 10). All the input numbers are integer.
Output
Output the only number — answer to the problem.
Examples
Input
7 3
5 10
2 5
3 6
Output
62
Input
3 3
1 3
2 2
3 1
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.
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): $\rho(s, t) = \sum_{i = 0}^{n - 1} \sum_{j = 0}^{n - 1} h(\operatorname{shift}(s, i), \operatorname{shift}(t, j))$ where $\operatorname{shift}(s, i)$ is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") = h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") + h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") + h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") = 1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6
Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: $\rho(s, t) = \operatorname{max}_{u :|u|=|s|} \rho(s, u)$.
Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 10^9 + 7.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 10^5).
The second line of the input contains a single string of length n, consisting of characters "ACGT".
-----Output-----
Print a single number — the answer modulo 10^9 + 7.
-----Examples-----
Input
1
C
Output
1
Input
2
AG
Output
4
Input
3
TTT
Output
1
-----Note-----
Please note that if for two distinct strings t_1 and t_2 values ρ(s, t_1) и ρ(s, t_2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.
In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.
In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.
In the third sample, ρ("TTT", "TTT") = 27
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?
-----Constraints-----
- 1≦N≦100
-----Input-----
The input is given from Standard Input in the following format:
N
-----Output-----
Print the necessary number of candies in total.
-----Sample Input-----
3
-----Sample Output-----
6
The answer is 1+2+3=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.
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.
The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.
Input
The first line contains integer n (2 ≤ n ≤ 100) which indicates the number of kids in the circle.
Output
In the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.
Examples
Input
10
Output
2 4 7 1 6 2 9 7 6
Input
3
Output
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.
Let's call a string a phone number if it has length 11 and fits the pattern "8xxxxxxxxxx", where each "x" is replaced by a digit.
For example, "80123456789" and "80000000000" are phone numbers, while "8012345678" and "79000000000" are not.
You have $n$ cards with digits, and you want to use them to make as many phone numbers as possible. Each card must be used in at most one phone number, and you don't have to use all cards. The phone numbers do not necessarily have to be distinct.
-----Input-----
The first line contains an integer $n$ — the number of cards with digits that you have ($1 \leq n \leq 100$).
The second line contains a string of $n$ digits (characters "0", "1", ..., "9") $s_1, s_2, \ldots, s_n$. The string will not contain any other characters, such as leading or trailing spaces.
-----Output-----
If at least one phone number can be made from these cards, output the maximum number of phone numbers that can be made. Otherwise, output 0.
-----Examples-----
Input
11
00000000008
Output
1
Input
22
0011223344556677889988
Output
2
Input
11
31415926535
Output
0
-----Note-----
In the first example, one phone number, "8000000000", can be made from these cards.
In the second example, you can make two phone numbers from the cards, for example, "80123456789" and "80123456789".
In the third example you can't make any phone number from the given cards.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 heroes fighting in the arena. Initially, the i-th hero has a_i health points.
The fight in the arena takes place in several rounds. At the beginning of each round, each alive hero deals 1 damage to all other heroes. Hits of all heroes occur simultaneously. Heroes whose health is less than 1 at the end of the round are considered killed.
If exactly 1 hero remains alive after a certain round, then he is declared the winner. Otherwise, there is no winner.
Your task is to calculate the number of ways to choose the initial health points for each hero a_i, where 1 ≤ a_i ≤ x, so that there is no winner of the fight. The number of ways can be very large, so print it modulo 998244353. Two ways are considered different if at least one hero has a different amount of health. For example, [1, 2, 1] and [2, 1, 1] are different.
Input
The only line contains two integers n and x (2 ≤ n ≤ 500; 1 ≤ x ≤ 500).
Output
Print one integer — the number of ways to choose the initial health points for each hero a_i, where 1 ≤ a_i ≤ x, so that there is no winner of the fight, taken modulo 998244353.
Examples
Input
2 5
Output
5
Input
3 3
Output
15
Input
5 4
Output
1024
Input
13 37
Output
976890680
Read the inputs from stdin solve the problem and write the answer to stdout (do 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, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 10^18.
-----Input-----
The first line contains two space-separated integers, m and k (0 ≤ m ≤ 10^18; 1 ≤ k ≤ 64).
-----Output-----
Print the required number n (1 ≤ n ≤ 10^18). If there are multiple answers, print any of them.
-----Examples-----
Input
1 1
Output
1
Input
3 2
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.
You have full control over a robot that walks around in a rectangular field paved with square tiles like a chessboard. There are m columns of tiles from west to east, and n rows of tiles from south to north (1 <= m, n <= 100). Each tile is given a pair of coordinates, such as (i, j), where 1 <= i <= m and 1 <= j <= n.
Your robot is initially on the center of the tile at (1, 1), that is, one at the southwest corner of the field, facing straight north. It can move either forward or backward, or can change its facing direction by ninety degrees at a time, according to a command you give to it, which is one of the following.
* `FORWARD` k
Go forward by k tiles to its facing direction (1 <= k < 100).
* `BACKWARD` k
Go backward by k tiles, without changing its facing direction (1 <= k < 100).
* `RIGHT`
Turn to the right by ninety degrees.
* `LEFT`
Turn to the left by ninety degrees.
* `STOP`
Stop.
While executing either a "`FORWARD`" or a "`BACKWARD`" command, the robot may bump against the wall surrounding the field. If that happens, the robot gives up the command execution there and stands at the center of the tile right in front of the wall, without changing its direction.
After finishing or giving up execution of a given command, your robot will stand by for your next command.
Input
The input consists of one or more command sequences. Each input line has at most fifty characters.
The first line of a command sequence contains two integer numbers telling the size of the field, the first number being the number of columns and the second being the number of rows. There might be white spaces (blanks and/or tabs) before, in between, or after the two numbers. Two zeros as field size indicates the end of input.
Each of the following lines of a command sequence contains a command to the robot. When a command has an argument, one or more white spaces are put between them. White spaces may also appear before and after the command and/or its argument.
A command sequence is terminated by a line containing a "`STOP`" command. The next command sequence, if any, starts from the next line.
Output
The output should be one line for each command sequence in the input. It should contain two numbers i and j of the coordinate pair (i, j), in this order, of the tile on which your robot stops. Two numbers should be separated by one white spaces.
Example
Input
6 5
FORWARD 3
RIGHT
FORWARD 5
LEFT
BACKWARD 2
STOP
3 1
FORWARD 2
STOP
0 0
Output
6 2
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.
In this Kata we are passing a number (n) into a function.
Your code will determine if the number passed is even (or not).
The function needs to return either a true or false.
Numbers may be positive or negative, integers or floats.
Floats are considered UNeven for this kata.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a 3×3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.
Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.
-----Constraints-----
- Input consists of lowercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}
-----Output-----
Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.
-----Sample Input-----
ant
obe
rec
-----Sample Output-----
abc
The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.
A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.
Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
-----Input-----
The first line of the input contains an integer N (1 ≤ N ≤ 10^5) – the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
-----Output-----
On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.
-----Examples-----
Input
3
1 2
2 3
Output
1 3 3
Input
4
1 2
3 2
4 2
Output
1 3 4 4
-----Note-----
Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,..., 10" will be corrected to "1, 2, 3, ..., 10".
In this task you are given a string s, which is composed by a concatination of terms, each of which may be:
* a positive integer of an arbitrary length (leading zeroes are not allowed),
* a "comma" symbol (","),
* a "space" symbol (" "),
* "three dots" ("...", that is, exactly three points written one after another, also known as suspension points).
Polycarp wants to add and remove spaces in the string s to ensure the following:
* each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it),
* each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term),
* if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left,
* there should not be other spaces.
Automate Polycarp's work and write a program that will process the given string s.
Input
The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.
Output
Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.
Examples
Input
1,2 ,3,..., 10
Output
1, 2, 3, ..., 10
Input
1,,,4...5......6
Output
1, , , 4 ...5 ... ...6
Input
...,1,2,3,...
Output
..., 1, 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.
You survived several months of exam wars and were able to enter ICPC University on a sunny day. On the day of admission, there was an enthusiastic recruitment of circles on the campus of the university, and you received a large number of pamphlets and returned. When you return to your room, you find one of the pamphlets you received that interests you. The pamphlet was given by the university's public relations department.
The following problems were described in the pamphlet.
> How many combinations of two or more consecutive positive integers have a sum of N? For example, 9 has two combinations, 2 + 3 + 4 and 4 + 5.
If you were curious about the answer to this question, you decided to write a program to find out the answer. Therefore, your job is to write a program that outputs the answer to the problem for the positive integer N given as the input.
Input
The input is a sequence of datasets. Each dataset is a line of one integer N. Where 1 ≤ N ≤ 1000.
The end of the input is indicated by a single line of zeros.
Output
The output is the order of the input datasets, which is the answer to the question for the positive integers represented by each dataset of the inputs. No other characters should be in the output.
Example
Input
9
500
0
Output
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.
You are given an integer array $a_1, a_2, \ldots, a_n$.
The array $b$ is called to be a subsequence of $a$ if it is possible to remove some elements from $a$ to get $b$.
Array $b_1, b_2, \ldots, b_k$ is called to be good if it is not empty and for every $i$ ($1 \le i \le k$) $b_i$ is divisible by $i$.
Find the number of good subsequences in $a$ modulo $10^9 + 7$.
Two subsequences are considered different if index sets of numbers included in them are different. That is, the values of the elements do not matter in the comparison of subsequences. In particular, the array $a$ has exactly $2^n - 1$ different subsequences (excluding an empty subsequence).
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 100\,000$) — the length of the array $a$.
The next line contains integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$).
-----Output-----
Print exactly one integer — the number of good subsequences taken modulo $10^9 + 7$.
-----Examples-----
Input
2
1 2
Output
3
Input
5
2 2 1 22 14
Output
13
-----Note-----
In the first example, all three non-empty possible subsequences are good: $\{1\}$, $\{1, 2\}$, $\{2\}$
In the second example, the possible good subsequences are: $\{2\}$, $\{2, 2\}$, $\{2, 22\}$, $\{2, 14\}$, $\{2\}$, $\{2, 22\}$, $\{2, 14\}$, $\{1\}$, $\{1, 22\}$, $\{1, 14\}$, $\{22\}$, $\{22, 14\}$, $\{14\}$.
Note, that some subsequences are listed more than once, since they occur in the original array multiple times.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
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.
Polycarp is very fond of playing the game Minesweeper. Recently he found a similar game and there are such rules.
There are mines on the field, for each the coordinates of its location are known ($x_i, y_i$). Each mine has a lifetime in seconds, after which it will explode. After the explosion, the mine also detonates all mines vertically and horizontally at a distance of $k$ (two perpendicular lines). As a result, we get an explosion on the field in the form of a "plus" symbol ('+'). Thus, one explosion can cause new explosions, and so on.
Also, Polycarp can detonate anyone mine every second, starting from zero seconds. After that, a chain reaction of explosions also takes place. Mines explode instantly and also instantly detonate other mines according to the rules described above.
Polycarp wants to set a new record and asks you to help him calculate in what minimum number of seconds all mines can be detonated.
-----Input-----
The first line of the input contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the test.
An empty line is written in front of each test suite.
Next comes a line that contains integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $0 \le k \le 10^9$) — the number of mines and the distance that hit by mines during the explosion, respectively.
Then $n$ lines follow, the $i$-th of which describes the $x$ and $y$ coordinates of the $i$-th mine and the time until its explosion ($-10^9 \le x, y \le 10^9$, $0 \le timer \le 10^9$). It is guaranteed that all mines have different coordinates.
It is guaranteed that the sum of the values $n$ over all test cases in the test does not exceed $2 \cdot 10^5$.
-----Output-----
Print $t$ lines, each of the lines must contain the answer to the corresponding set of input data — the minimum number of seconds it takes to explode all the mines.
-----Examples-----
Input
3
5 0
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
5 2
0 0 1
0 1 4
1 0 2
1 1 3
2 2 9
6 1
1 -1 3
0 -1 9
0 1 7
-1 0 1
-1 1 9
-1 -1 7
Output
2
1
0
-----Note-----
Picture from examples
First example:
$0$ second: we explode a mine at the cell $(2, 2)$, it does not detonate any other mine since $k=0$.
$1$ second: we explode the mine at the cell $(0, 1)$, and the mine at the cell $(0, 0)$ explodes itself.
$2$ second: we explode the mine at the cell $(1, 1)$, and the mine at the cell $(1, 0)$ explodes itself.
Second example:
$0$ second: we explode a mine at the cell $(2, 2)$ we get:
$1$ second: the mine at coordinate $(0, 0)$ explodes and since $k=2$ the explosion detonates mines at the cells $(0, 1)$ and $(1, 0)$, and their explosions detonate the mine at the cell $(1, 1)$ and there are no mines left on the field.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's call a list of positive integers $a_0, a_1, ..., a_{n-1}$ a power sequence if there is a positive integer $c$, so that for every $0 \le i \le n-1$ then $a_i = c^i$.
Given a list of $n$ positive integers $a_0, a_1, ..., a_{n-1}$, you are allowed to: Reorder the list (i.e. pick a permutation $p$ of $\{0,1,...,n - 1\}$ and change $a_i$ to $a_{p_i}$), then Do the following operation any number of times: pick an index $i$ and change $a_i$ to $a_i - 1$ or $a_i + 1$ (i.e. increment or decrement $a_i$ by $1$) with a cost of $1$.
Find the minimum cost to transform $a_0, a_1, ..., a_{n-1}$ into a power sequence.
-----Input-----
The first line contains an integer $n$ ($3 \le n \le 10^5$).
The second line contains $n$ integers $a_0, a_1, ..., a_{n-1}$ ($1 \le a_i \le 10^9$).
-----Output-----
Print the minimum cost to transform $a_0, a_1, ..., a_{n-1}$ into a power sequence.
-----Examples-----
Input
3
1 3 2
Output
1
Input
3
1000000000 1000000000 1000000000
Output
1999982505
-----Note-----
In the first example, we first reorder $\{1, 3, 2\}$ into $\{1, 2, 3\}$, then increment $a_2$ to $4$ with cost $1$ to get a power sequence $\{1, 2, 4\}$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Everybody knows that the m-coder Tournament will happen soon. m schools participate in the tournament, and only one student from each school participates.
There are a total of n students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate.
Arkady is a hacker who wants to have k Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.
You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that k Chosen Ones would be selected by the Technogoblet.
Input
The first line contains three integers n, m and k (1 ≤ n ≤ 100, 1 ≤ m, k ≤ n) — the total number of students, the number of schools and the number of the Chosen Ones.
The second line contains n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n), where p_i denotes the power of i-th student. The bigger the power, the stronger the student.
The third line contains n integers s_1, s_2, …, s_n (1 ≤ s_i ≤ m), where s_i denotes the school the i-th student goes to. At least one student studies in each of the schools.
The fourth line contains k different integers c_1, c_2, …, c_k (1 ≤ c_i ≤ n) — the id's of the Chosen Ones.
Output
Output a single integer — the minimal number of schools to be made up by Arkady so that k Chosen Ones would be selected by the Technogoblet.
Examples
Input
7 3 1
1 5 3 4 6 7 2
1 3 1 2 1 2 3
3
Output
1
Input
8 4 4
1 2 3 4 5 6 7 8
4 3 2 1 4 3 2 1
3 4 5 6
Output
2
Note
In the first example there's just a single Chosen One with id 3. His power is equal to 3, but in the same school 1, there's a student with id 5 and power 6, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be 4) for the Chosen One, Technogoblet would select students with ids 2 (strongest in 3), 5 (strongest in 1), 6 (strongest in 2) and 3 (strongest in 4).
In the second example, you can change the school of student 3 to the made-up 5 and the school of student 4 to the made-up 6. It will cause the Technogoblet to choose students 8, 7, 6, 5, 3 and 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
-----Input-----
The first and only line contains two integers x and y (3 ≤ y < x ≤ 100 000) — the starting and ending equilateral triangle side lengths respectively.
-----Output-----
Print a single integer — the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
-----Examples-----
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
-----Note-----
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do $(6,6,6) \rightarrow(6,6,3) \rightarrow(6,4,3) \rightarrow(3,4,3) \rightarrow(3,3,3)$.
In the second sample test, Memory can do $(8,8,8) \rightarrow(8,8,5) \rightarrow(8,5,5) \rightarrow(5,5,5)$.
In the third sample test, Memory can do: $(22,22,22) \rightarrow(7,22,22) \rightarrow(7,22,16) \rightarrow(7,10,16) \rightarrow(7,10,4) \rightarrow$
$(7,4,4) \rightarrow(4,4,4)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:
- For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.
- There is an edge between Vertex X and Vertex Y.
For each k=1,2,...,N-1, solve the problem below:
- Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.
-----Constraints-----
- 3 \leq N \leq 2 \times 10^3
- 1 \leq X,Y \leq N
- X+1 < Y
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N X Y
-----Output-----
For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.
-----Sample Input-----
5 2 4
-----Sample Output-----
5
4
1
0
The graph in this input is as follows:
There are five pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 1: (1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5).
There are four pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 2: (1,3)\,,(1,4)\,,(2,5)\,,(3,5).
There is one pair (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 3: (1,5).
There are no pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a program that converts the date expressed in the Christian era to the Japanese calendar using the era name and outputs the date. The input is three integers, as shown in the example, in the order year, month, and day. Convert this as shown in the sample output. If the date before the Meiji era is entered, please display "pre-meiji".
The first year of each year will be output as "1 year" instead of "first year".
Era | Period
--- | ---
meiji | 1868. 9. 8 ~ 1912. 7.29
taisho | 1912. 7.30 ~ 1926.12.24
showa | 1926.12.25 ~ 1989. 1. 7
heisei | 1989. 1. 8 ~
input
Multiple data are given. As each data, three integers representing year, month and day are given on one line separated by blanks.
Please process until the end of the input. The number of data does not exceed 50.
output
Output the blank-separated era, year, month, day, or "pre-meiji" on one line.
Example
Input
2005 9 3
1868 12 2
1868 9 7
Output
heisei 17 9 3
meiji 1 12 2
pre-meiji
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.
<image>
Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.
Input
The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Output
Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).
Examples
Input
1
Output
3
Input
2
Output
10
Note
The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a_1, a_2, \dots, a_n$, consisting of $n$ positive integers.
Initially you are standing at index $1$ and have a score equal to $a_1$. You can perform two kinds of moves: move right — go from your current index $x$ to $x+1$ and add $a_{x+1}$ to your score. This move can only be performed if $x<n$. move left — go from your current index $x$ to $x-1$ and add $a_{x-1}$ to your score. This move can only be performed if $x>1$. Also, you can't perform two or more moves to the left in a row.
You want to perform exactly $k$ moves. Also, there should be no more than $z$ moves to the left among them.
What is the maximum score you can achieve?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases.
The first line of each testcase contains three integers $n, k$ and $z$ ($2 \le n \le 10^5$, $1 \le k \le n - 1$, $0 \le z \le min(5, k)$) — the number of elements in the array, the total number of moves you should perform and the maximum number of moves to the left you can perform.
The second line of each testcase contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^4$) — the given array.
The sum of $n$ over all testcases does not exceed $3 \cdot 10^5$.
-----Output-----
Print $t$ integers — for each testcase output the maximum score you can achieve if you make exactly $k$ moves in total, no more than $z$ of them are to the left and there are no two or more moves to the left in a row.
-----Example-----
Input
4
5 4 0
1 5 4 3 2
5 4 1
1 5 4 3 2
5 4 4
10 20 30 40 50
10 7 3
4 6 8 2 9 9 7 4 10 9
Output
15
19
150
56
-----Note-----
In the first testcase you are not allowed to move left at all. So you make four moves to the right and obtain the score $a_1 + a_2 + a_3 + a_4 + a_5$.
In the second example you can move one time to the left. So we can follow these moves: right, right, left, right. The score will be $a_1 + a_2 + a_3 + a_2 + a_3$.
In the third example you can move four times to the left but it's not optimal anyway, you can just move four times to the right and obtain the score $a_1 + a_2 + a_3 + a_4 + a_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.
Make a program that takes a value (x) and returns "Bang" if the number is divisible by 3, "Boom" if it is divisible by 5, "BangBoom" if it divisible by 3 and 5, and "Miss" if it isn't divisible by any of them.
Note: Your program should only return one value
Ex: Input: 105 --> Output: "BangBoom"
Ex: Input: 9 --> Output: "Bang"
Ex:Input: 25 --> Output: "Boom"
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tashizan Hikizan (Calculation Training)
square1001 You gave E869120 two numbers, $ A $ and $ B $, as birthday presents.
E869120 You decided to use these two numbers for calculation training.
Specifically, E869120 does the following for these numbers exactly $ N $ times:
* Replace $ A $ with $ A-B $ on odd-numbered operations
* Replace $ B $ with $ A + B $ on even-numbered operations
E869120 Find out what the values of $ A $ and $ B $ are after you have operated $ N $ times.
input
Input is given from standard input in the following format.
$ N $
$ A $ $ B $
output
E869120 Please output the values of $ A $ and $ B $ after you have operated $ N $ times in this order, separated by blanks.
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000000000000000000 \ (= 10 ^ {18}) $
* $ 1 \ leq A \ leq 1000000000 \ (= 10 ^ 9) $
* $ 1 \ leq B \ leq 1000000000 \ (= 10 ^ 9) $
* All inputs are integers.
Input example 1
3
3 4
Output example 1
-4 3
The value of $ (A, B) $ changes as $ (3,4) → (-1,4) → (-1,3) → (-4,3) $.
Input example 2
8
6 9
Output example 2
3 -6
Example
Input
3
3 4
Output
-4 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Find the least common multiple (LCM) of given n integers.
Constraints
* 2 ≤ n ≤ 10
* 1 ≤ ai ≤ 1000
* Product of given integers ai(i = 1, 2, ... n) does not exceed 231-1
Input
n
a1 a2 ... an
n is given in the first line. Then, n integers are given in the second line.
Output
Print the least common multiple of the given integers in a line.
Examples
Input
3
3 4 6
Output
12
Input
4
1 2 3 5
Output
30
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.
A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, `atcoder`, `zscoder` and `agc` are diverse words while `gotou` and `connect` aren't diverse words.
Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.
Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.
Constraints
* 1 \leq |S| \leq 26
* S is a diverse word.
Input
Input is given from Standard Input in the following format:
S
Output
Print the next word that appears after S in the dictionary, or `-1` if it doesn't exist.
Examples
Input
atcoder
Output
atcoderb
Input
abc
Output
abcd
Input
zyxwvutsrqponmlkjihgfedcba
Output
-1
Input
abcdefghijklmnopqrstuvwzyx
Output
abcdefghijklmnopqrstuvx
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A pair of numbers has a unique LCM but a single number can be the LCM of more than one possible
pairs. For example `12` is the LCM of `(1, 12), (2, 12), (3,4)` etc. For a given positive integer N, the number of different integer pairs with LCM is equal to N can be called the LCM cardinality of that number N. In this kata your job is to find out the LCM cardinality of a number.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auction winner is the participant who offered the highest price. However, he pay not the price he offers, but the highest price among the offers of other participants (hence the name: the second-price auction).
Write a program that reads prices offered by bidders and finds the winner and the price he will pay. Consider that all of the offered prices are different.
-----Input-----
The first line of the input contains n (2 ≤ n ≤ 1000) — number of bidders. The second line contains n distinct integer numbers p_1, p_2, ... p_{n}, separated by single spaces (1 ≤ p_{i} ≤ 10000), where p_{i} stands for the price offered by the i-th bidder.
-----Output-----
The single output line should contain two integers: index of the winner and the price he will pay. Indices are 1-based.
-----Examples-----
Input
2
5 7
Output
2 5
Input
3
10 2 8
Output
1 8
Input
6
3 8 2 9 4 14
Output
6 9
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.
You are given a three-digit integer n written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in n.
-----Constraints-----
- 111 \leq n \leq 999
- n is an integer consisting of digits 1 and 9.
-----Input-----
Input is given from Standard Input in the following format:
n
-----Output-----
Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in n.
-----Sample Input-----
119
-----Sample Output-----
991
Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level $n$ as a rooted tree constructed as described below.
A rooted dead bush of level $1$ is a single vertex. To construct an RDB of level $i$ we, at first, construct an RDB of level $i-1$, then for each vertex $u$: if $u$ has no children then we will add a single child to it; if $u$ has one child then we will add two children to it; if $u$ has more than one child, then we will skip it.
[Image] Rooted Dead Bushes of level $1$, $2$ and $3$.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
[Image] The center of the claw is the vertex with label $1$.
Lee has a Rooted Dead Bush of level $n$. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $10^9+7$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases.
Next $t$ lines contain test cases — one per line.
The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^6$) — the level of Lee's RDB.
-----Output-----
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo $10^9 + 7$.
-----Example-----
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
-----Note-----
It's easy to see that the answer for RDB of level $1$ or $2$ is $0$.
The answer for RDB of level $3$ is $4$ since there is only one claw we can choose: $\{1, 2, 3, 4\}$.
The answer for RDB of level $4$ is $4$ since we can choose either single claw $\{1, 3, 2, 4\}$ or single claw $\{2, 7, 5, 6\}$. There are no other claws in the RDB of level $4$ (for example, we can't choose $\{2, 1, 7, 6\}$, since $1$ is not a child of center vertex $2$).
$\therefore$ Rooted Dead Bush of level 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The robot is located on a checkered rectangular board of size $n \times m$ ($n$ rows, $m$ columns). The rows in the board are numbered from $1$ to $n$ from top to bottom, and the columns — from $1$ to $m$ from left to right.
The robot is able to move from the current cell to one of the four cells adjacent by side.
The sequence of commands $s$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.
The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $s$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.
The robot's task is to execute as many commands as possible without falling off the board. For example, on board $3 \times 3$, if the robot starts a sequence of actions $s=$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $(2, 1)$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $(1, 2)$ (first row, second column).
The robot starts from cell $(2, 1)$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $(1, 2)$ (first row, second column).
Determine the cell from which the robot should start its movement in order to execute as many commands as possible.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases.
The next $2t$ lines contain descriptions of the test cases.
In the description of each test case, the first line contains two integers $n$ and $m$ ($1 \leq n, m \leq 10^6$) — the height and width of the field that the robot is located on. The second line of the description is a string $s$ consisting solely of characters 'L', 'R', 'D' and 'U' — the sequence of commands the robot executes. The string has a length from $1$ to $10^6$ commands.
It is guaranteed that the total length of $s$ over all test cases does not exceed $10^6$.
-----Output-----
Print $t$ lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers $r$ ($1 \leq r \leq n$) and $c$ ($1 \leq c \leq m$), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible.
If there are several such cells, you may output any of them.
-----Examples-----
Input
4
1 1
L
1 2
L
3 3
RRDLUU
4 3
LUURRDDLLLUU
Output
1 1
1 2
2 1
3 2
-----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.
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:
All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting.
Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad?
-----Input-----
The first line of input contains two integer numbers $n$ and $k$ ($1 \le n \le 10^{9}$, $0 \le k \le 2\cdot10^5$), where $n$ denotes total number of pirates and $k$ is the number of pirates that have any coins.
The next $k$ lines of input contain integers $a_i$ and $b_i$ ($1 \le a_i \le n$, $1 \le b_i \le 10^{9}$), where $a_i$ denotes the index of the pirate sitting at the round table ($n$ and $1$ are neighbours) and $b_i$ the total number of coins that pirate $a_i$ has at the start of the game.
-----Output-----
Print $1$ if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations.
Print $-1$ if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations.
-----Examples-----
Input
4 2
1 2
2 2
Output
1
Input
6 2
2 3
4 1
Output
1
Input
3 2
1 1
2 2
Output
-1
-----Note-----
In the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting one.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (1, 1) → (0, 1) → ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.
Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.
To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) → (0, 1) → (0, 0) cannot occur in a valid grid path.
One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.
Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.
Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 1 000 000) — the length of the paths.
The second line of the input contains a string consisting of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the first grid path. The characters can be thought of as the sequence of moves needed to traverse the grid path. For example, the example path in the problem statement can be expressed by the string "NNESWW".
The third line of the input contains a string of n - 1 characters (each of which is either 'N', 'E', 'S', or 'W') — the second grid path.
Output
Print "YES" (without quotes) if it is possible for both marbles to be at the end position at the same time. Print "NO" (without quotes) otherwise. In both cases, the answer is case-insensitive.
Examples
Input
7
NNESWW
SWSWSW
Output
YES
Input
3
NN
SS
Output
NO
Note
In the first sample, the first grid path is the one described in the statement. Moreover, the following sequence of moves will get both marbles to the end: NNESWWSWSW.
In the second sample, no sequence of moves can get both marbles to the end.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.
The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.
Input
A text is given in a line. You can assume the following conditions:
* The number of letters in the text is less than or equal to 1000.
* The number of letters in a word is less than or equal to 32.
* There is only one word which is arise most frequently in given text.
* There is only one word which has the maximum number of letters in given text.
Output
The two words separated by a space.
Example
Input
Thank you for your mail and your lectures
Output
your lectures
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Complete the function that accepts a string parameter, and reverses each word in the string. **All** spaces in the string should be retained.
## Examples
```
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.
To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.
Determine how many groups of students will be kicked out of the club.
Input
The first line contains two integers n and m — the initial number of students and laces (<image>). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.
Output
Print the single number — the number of groups of students that will be kicked out from the club.
Examples
Input
3 3
1 2
2 3
3 1
Output
0
Input
6 3
1 2
2 3
3 4
Output
2
Input
6 5
1 4
2 4
3 4
5 4
6 4
Output
1
Note
In the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.
In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.
In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.
The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).
Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.
At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.
It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.
Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 50) — the length of the hidden word.
The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed.
The third line contains an integer m (1 ≤ m ≤ 1000) — the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves — n-letter strings of lowercase Latin letters. All words are distinct.
It is guaranteed that the hidden word appears as one of the given m words. Before the current move Polycarp has told exactly the letters which are currently revealed.
-----Output-----
Output the single integer — the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero.
-----Examples-----
Input
4
a**d
2
abcd
acbd
Output
2
Input
5
lo*er
2
lover
loser
Output
0
Input
3
a*a
2
aaa
aba
Output
1
-----Note-----
In the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed.
The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word.
In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a program to simulate rolling a dice, which can be constructed by the following net.
<image>
<image>
As shown in the figures, each face is identified by a different label from 1 to 6.
Write a program which reads integers assigned to each face identified by the label and a sequence of commands to roll the dice, and prints the integer on the top face. At the initial state, the dice is located as shown in the above figures.
Constraints
* $0 \leq $ the integer assigned to a face $ \leq 100$
* $0 \leq $ the length of the command $\leq 100$
Input
In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.
In the second line, a string which represents a sequence of commands, is given. The command is one of 'E', 'N', 'S' and 'W' representing four directions shown in the above figures.
Output
Print the integer which appears on the top face after the simulation.
Examples
Input
1 2 4 8 16 32
SE
Output
8
Input
1 2 4 8 16 32
EESWN
Output
32
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.
In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.
The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles.
The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).
Output
Print a single number — the sought number of days.
Examples
Input
4
10 3 5 10
Output
5
Input
5
10 2 8 3 5
Output
5
Note
In the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.
In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals n (n is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first n / 2 digits) equals the sum of digits in the second half (the sum of the last n / 2 digits). Check if the given ticket is lucky.
Input
The first line contains an even integer n (2 ≤ n ≤ 50) — the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly n — the ticket number. The number may contain leading zeros.
Output
On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes).
Examples
Input
2
47
Output
NO
Input
4
4738
Output
NO
Input
4
4774
Output
YES
Note
In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 ≠ 7).
In the second sample the ticket number is not the lucky number.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that A follows Z. For example, shifting A by 2 results in C (A \to B \to C), and shifting Y by 3 results in B (Y \to Z \to A \to B).
-----Constraints-----
- 0 \leq N \leq 26
- 1 \leq |S| \leq 10^4
- S consists of uppercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
N
S
-----Output-----
Print the string resulting from shifting each character of S by N in alphabetical order.
-----Sample Input-----
2
ABCXYZ
-----Sample Output-----
CDEZAB
Note that A follows Z.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are N problems, numbered 1 through N.
Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).
Also, there are M kinds of drinks offered to the contestants, numbered 1 through M.
If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds.
It does not affect the time to solve the other problems.
A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink.
Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems.
Your task is to write a program to calculate it instead of her.
-----Constraints-----
- All input values are integers.
- 1≦N≦100
- 1≦T_i≦10^5
- 1≦M≦100
- 1≦P_i≦N
- 1≦X_i≦10^5
-----Input-----
The input is given from Standard Input in the following format:
N
T_1 T_2 ... T_N
M
P_1 X_1
P_2 X_2
:
P_M X_M
-----Output-----
For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line.
-----Sample Input-----
3
2 1 4
2
1 1
2 3
-----Sample Output-----
6
9
If Joisino takes drink 1, the time it takes her to solve each problem will be 1, 1 and 4 seconds, respectively, totaling 6 seconds.
If Joisino takes drink 2, the time it takes her to solve each problem will be 2, 3 and 4 seconds, respectively, totaling 9 seconds.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000.
If the quantity and price per item are input, write a program to calculate the total expenses.
------ Input Format ------
The first line contains an integer T, total number of test cases. Then follow T lines, each line contains integers quantity and price.
------ Output Format ------
For each test case, output the total expenses while purchasing items, in a new line.
------ Constraints ------
1 ≤ T ≤ 1000
1 ≤ quantity,price ≤ 100000
----- Sample Input 1 ------
3
100 120
10 20
1200 20
----- Sample Output 1 ------
12000.000000
200.000000
21600.000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.
But his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. This means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. Now Megabyte wants to know, how many numbers were loaded successfully.
Input
Input data contains the only number n (1 ≤ n ≤ 109).
Output
Output the only number — answer to the problem.
Examples
Input
10
Output
2
Note
For n = 10 the answer includes numbers 1 and 10.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given $n$ lengths of segments that need to be placed on an infinite axis with coordinates.
The first segment is placed on the axis so that one of its endpoints lies at the point with coordinate $0$. Let's call this endpoint the "start" of the first segment and let's call its "end" as that endpoint that is not the start.
The "start" of each following segment must coincide with the "end" of the previous one. Thus, if the length of the next segment is $d$ and the "end" of the previous one has the coordinate $x$, the segment can be placed either on the coordinates $[x-d, x]$, and then the coordinate of its "end" is $x - d$, or on the coordinates $[x, x+d]$, in which case its "end" coordinate is $x + d$.
The total coverage of the axis by these segments is defined as their overall union which is basically the set of points covered by at least one of the segments. It's easy to show that the coverage will also be a segment on the axis. Determine the minimal possible length of the coverage that can be obtained by placing all the segments on the axis without changing their order.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 1000$) — the number of test cases.
The next $2t$ lines contain descriptions of the test cases.
The first line of each test case description contains an integer $n$ ($1 \le n \le 10^4$) — the number of segments. The second line of the description contains $n$ space-separated integers $a_i$ ($1 \le a_i \le 1000$) — lengths of the segments in the same order they should be placed on the axis.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^4$.
-----Output-----
Print $t$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible length of the axis coverage.
-----Examples-----
Input
6
2
1 3
3
1 2 3
4
6 2 3 9
4
6 8 4 5
7
1 2 4 6 7 7 3
8
8 6 5 1 2 2 3 6
Output
3
3
9
9
7
8
-----Note-----
In the third sample test case the segments should be arranged as follows: $[0, 6] \rightarrow [4, 6] \rightarrow [4, 7] \rightarrow [-2, 7]$. As you can see, the last segment $[-2, 7]$ covers all the previous ones, and the total length of coverage is $9$.
In the fourth sample test case the segments should be arranged as $[0, 6] \rightarrow [-2, 6] \rightarrow [-2, 2] \rightarrow [2, 7]$. The union of these segments also occupies the area $[-2, 7]$ and has the length of $9$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Here is a very simple variation of the game backgammon, named “Minimal Backgammon”. The game is played by only one player, using only one of the dice and only one checker (the token used by the player).
The game board is a line of (N + 1) squares labeled as 0 (the start) to N (the goal). At the beginning, the checker is placed on the start (square 0). The aim of the game is to bring the checker to the goal (square N). The checker proceeds as many squares as the roll of the dice. The dice generates six integers from 1 to 6 with equal probability.
The checker should not go beyond the goal. If the roll of the dice would bring the checker beyond the goal, the checker retreats from the goal as many squares as the excess. For example, if the checker is placed at the square (N - 3), the roll "5" brings the checker to the square (N - 2), because the excess beyond the goal is 2. At the next turn, the checker proceeds toward the goal as usual.
Each square, except the start and the goal, may be given one of the following two special instructions.
* Lose one turn (labeled "L" in Figure 2) If the checker stops here, you cannot move the checker in the next turn.
* Go back to the start (labeled "B" in Figure 2)
If the checker stops here, the checker is brought back to the start.
<image>
Figure 2: An example game
Given a game board configuration (the size N, and the placement of the special instructions), you are requested to compute the probability with which the game succeeds within a given number of turns.
Input
The input consists of multiple datasets, each containing integers in the following format.
N T L B
Lose1
...
LoseL
Back1
...
BackB
N is the index of the goal, which satisfies 5 ≤ N ≤ 100. T is the number of turns. You are requested to compute the probability of success within T turns. T satisfies 1 ≤ T ≤ 100. L is the number of squares marked “Lose one turn”, which satisfies 0 ≤ L ≤ N - 1. B is the number of squares marked “Go back to the start”, which satisfies 0 ≤ B ≤ N - 1. They are separated by a space.
Losei's are the indexes of the squares marked “Lose one turn”, which satisfy 1 ≤ Losei ≤ N - 1. All Losei's are distinct, and sorted in ascending order. Backi's are the indexes of the squares marked “Go back to the start”, which satisfy 1 ≤ Backi ≤ N - 1. All Backi's are distinct, and sorted in ascending order. No numbers occur both in Losei's and Backi's.
The end of the input is indicated by a line containing four zeros separated by a space.
Output
For each dataset, you should answer the probability with which the game succeeds within the given number of turns. The output should not contain an error greater than 0.00001.
Example
Input
6 1 0 0
7 1 0 0
7 2 0 0
6 6 1 1
2
5
7 10 0 6
1
2
3
4
5
6
0 0 0 0
Output
0.166667
0.000000
0.166667
0.619642
0.000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0. During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right. That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i. The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible. Find the earliest possible time to reach coordinate X.
Constraints
* X is an integer.
* 1≤X≤10^9
Input
The input is given from Standard Input in the following format:
X
Output
Print the earliest possible time for the kangaroo to reach coordinate X.
Examples
Input
6
Output
3
Input
2
Output
2
Input
11
Output
5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string $s$ consisting of $n$ lowercase Latin letters.
In one move you can take any subsequence $t$ of the given string and add it to the set $S$. The set $S$ can't contain duplicates. This move costs $n - |t|$, where $|t|$ is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set $S$ of size $k$ or report that it is impossible to do so.
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 100$) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string $s$ consisting of $n$ lowercase Latin letters.
-----Output-----
Print one integer — if it is impossible to obtain the set $S$ of size $k$, print -1. Otherwise, print the minimum possible total cost to do it.
-----Examples-----
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
-----Note-----
In the first example we can generate $S$ = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in $S$ is $0$ and the cost of the others is $1$. So the total cost of $S$ 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.
Input
The input is given from standard input in the following format.
> $H \ W$ $a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}$ $a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}$ $\vdots \ \ \ \ \ \ \ \ \ \ \vdots \ \ \ \ \ \ \ \ \ \ \vdots$ $a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}$
Output
* Print the maximum number of souvenirs they can get.
Constraints
* $1 \le H, W \le 200$
* $0 \le a_{i, j} \le 10^5$
Subtasks
Subtask 1 [ 50 points ]
* The testcase in the subtask satisfies $1 \le H \le 2$.
Subtask 2 [ 80 points ]
* The testcase in the subtask satisfies $1 \le H \le 3$.
Subtask 3 [ 120 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 7$.
Subtask 4 [ 150 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 30$.
Subtask 5 [ 200 points ]
* There are no additional constraints.
Output
* Print the maximum number of souvenirs they can get.
Constraints
* $1 \le H, W \le 200$
* $0 \le a_{i, j} \le 10^5$
Subtasks
Subtask 1 [ 50 points ]
* The testcase in the subtask satisfies $1 \le H \le 2$.
Subtask 2 [ 80 points ]
* The testcase in the subtask satisfies $1 \le H \le 3$.
Subtask 3 [ 120 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 7$.
Subtask 4 [ 150 points ]
* The testcase in the subtask satisfies $1 \le H, W \le 30$.
Subtask 5 [ 200 points ]
* There are no additional constraints.
Input
The input is given from standard input in the following format.
> $H \ W$ $a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}$ $a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}$ $\vdots \ \ \ \ \ \ \ \ \ \ \vdots \ \ \ \ \ \ \ \ \ \ \vdots$ $a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}$
Examples
Input
3 3
1 0 5
2 2 3
4 2 4
Output
21
Input
6 6
1 2 3 4 5 6
8 6 9 1 2 0
3 1 4 1 5 9
2 6 5 3 5 8
1 4 1 4 2 1
2 7 1 8 2 8
Output
97
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image>
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.