question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.
Input
The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly.
Output
Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO".
Examples
Input
0 0 0
0 1 0
Output
YES
Input
1 1 0
0 1 0
Output
YES
Input
0 0 0
1 1 1
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.
For the given integer $n$ ($n > 2$) let's write down all the strings of length $n$ which contain $n-2$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.
Recall that the string $s$ of length $n$ is lexicographically less than string $t$ of length $n$, if there exists such $i$ ($1 \le i \le n$), that $s_i < t_i$, and for any $j$ ($1 \le j < i$) $s_j = t_j$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.
For example, if $n=5$ the strings are (the order does matter): aaabb aabab aabba abaab ababa abbaa baaab baaba babaa bbaaa
It is easy to show that such a list of strings will contain exactly $\frac{n \cdot (n-1)}{2}$ strings.
You are given $n$ ($n > 2$) and $k$ ($1 \le k \le \frac{n \cdot (n-1)}{2}$). Print the $k$-th string from the list.
-----Input-----
The input contains one or more test cases.
The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the test. Then $t$ test cases follow.
Each test case is written on the the separate line containing two integers $n$ and $k$ ($3 \le n \le 10^5, 1 \le k \le \min(2\cdot10^9, \frac{n \cdot (n-1)}{2})$.
The sum of values $n$ over all test cases in the test doesn't exceed $10^5$.
-----Output-----
For each test case print the $k$-th string from the list of all described above strings of length $n$. Strings in the list are sorted lexicographically (alphabetically).
-----Example-----
Input
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
Output
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* replaces all uppercase consonants with corresponding lowercase ones.
Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.
Help Petya cope with this easy task.
Input
The first line represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive.
Output
Print the resulting string. It is guaranteed that this string is not empty.
Examples
Input
tour
Output
.t.r
Input
Codeforces
Output
.c.d.f.r.c.s
Input
aBAcAba
Output
.b.c.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.
Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.
At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma.
They also decided that there must be given at least min_1 and at most max_1 diplomas of the first degree, at least min_2 and at most max_2 diplomas of the second degree, and at least min_3 and at most max_3 diplomas of the third degree.
After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree.
Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations.
It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree.
-----Input-----
The first line of the input contains a single integer n (3 ≤ n ≤ 3·10^6) — the number of schoolchildren who will participate in the Olympiad.
The next line of the input contains two integers min_1 and max_1 (1 ≤ min_1 ≤ max_1 ≤ 10^6) — the minimum and maximum limits on the number of diplomas of the first degree that can be distributed.
The third line of the input contains two integers min_2 and max_2 (1 ≤ min_2 ≤ max_2 ≤ 10^6) — the minimum and maximum limits on the number of diplomas of the second degree that can be distributed.
The next line of the input contains two integers min_3 and max_3 (1 ≤ min_3 ≤ max_3 ≤ 10^6) — the minimum and maximum limits on the number of diplomas of the third degree that can be distributed.
It is guaranteed that min_1 + min_2 + min_3 ≤ n ≤ max_1 + max_2 + max_3.
-----Output-----
In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas.
The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree.
-----Examples-----
Input
6
1 5
2 6
3 7
Output
1 2 3
Input
10
1 2
1 3
1 5
Output
2 3 5
Input
6
1 3
2 2
2 2
Output
2 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.
"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme."
"Little Alena got an array as a birthday present..."
The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:
b_1 = b_2 = b_3 = b_4 = 0.
For all 5 ≤ i ≤ n: b_{i} = 0 if a_{i}, a_{i} - 1, a_{i} - 2, a_{i} - 3, a_{i} - 4 > r and b_{i} - 1 = b_{i} - 2 = b_{i} - 3 = b_{i} - 4 = 1 b_{i} = 1 if a_{i}, a_{i} - 1, a_{i} - 2, a_{i} - 3, a_{i} - 4 < l and b_{i} - 1 = b_{i} - 2 = b_{i} - 3 = b_{i} - 4 = 0 b_{i} = b_{i} - 1 otherwise
You are given arrays a and b' of the same length. Find two integers l and r (l ≤ r), such that applying the algorithm described above will yield an array b equal to b'.
It's guaranteed that the answer exists.
-----Input-----
The first line of input contains a single integer n (5 ≤ n ≤ 10^5) — the length of a and b'.
The second line of input contains n space separated integers a_1, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the elements of a.
The third line of input contains a string of n characters, consisting of 0 and 1 — the elements of b'. Note that they are not separated by spaces.
-----Output-----
Output two integers l and r ( - 10^9 ≤ l ≤ r ≤ 10^9), conforming to the requirements described above.
If there are multiple solutions, output any of them.
It's guaranteed that the answer exists.
-----Examples-----
Input
5
1 2 3 4 5
00001
Output
6 15
Input
10
-10 -9 -8 -7 -6 6 7 8 9 10
0000111110
Output
-5 5
-----Note-----
In the first test case any pair of l and r pair is valid, if 6 ≤ l ≤ r ≤ 10^9, in that case b_5 = 1, because a_1, ..., a_5 < l.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 tube which is reflective inside represented as two non-coinciding, but parallel to $Ox$ lines. Each line has some special integer points — positions of sensors on sides of the tube.
You are going to emit a laser ray in the tube. To do so, you have to choose two integer points $A$ and $B$ on the first and the second line respectively (coordinates can be negative): the point $A$ is responsible for the position of the laser, and the point $B$ — for the direction of the laser ray. The laser ray is a ray starting at $A$ and directed at $B$ which will reflect from the sides of the tube (it doesn't matter if there are any sensors at a reflection point or not). A sensor will only register the ray if the ray hits exactly at the position of the sensor. [Image] Examples of laser rays. Note that image contains two examples. The $3$ sensors (denoted by black bold points on the tube sides) will register the blue ray but only $2$ will register the red.
Calculate the maximum number of sensors which can register your ray if you choose points $A$ and $B$ on the first and the second lines respectively.
-----Input-----
The first line contains two integers $n$ and $y_1$ ($1 \le n \le 10^5$, $0 \le y_1 \le 10^9$) — number of sensors on the first line and its $y$ coordinate.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — $x$ coordinates of the sensors on the first line in the ascending order.
The third line contains two integers $m$ and $y_2$ ($1 \le m \le 10^5$, $y_1 < y_2 \le 10^9$) — number of sensors on the second line and its $y$ coordinate.
The fourth line contains $m$ integers $b_1, b_2, \ldots, b_m$ ($0 \le b_i \le 10^9$) — $x$ coordinates of the sensors on the second line in the ascending order.
-----Output-----
Print the only integer — the maximum number of sensors which can register the ray.
-----Example-----
Input
3 1
1 5 6
1 3
3
Output
3
-----Note-----
One of the solutions illustrated on the image by pair $A_2$ and $B_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.
An n × n table a is defined as follows:
The first row and the first column contain ones, that is: a_{i}, 1 = a_{1, }i = 1 for all i = 1, 2, ..., n. Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula a_{i}, j = a_{i} - 1, j + a_{i}, j - 1.
These conditions define all the values in the table.
You are given a number n. You need to determine the maximum value in the n × n table defined by the rules above.
-----Input-----
The only line of input contains a positive integer n (1 ≤ n ≤ 10) — the number of rows and columns of the table.
-----Output-----
Print a single line containing a positive integer m — the maximum value in the table.
-----Examples-----
Input
1
Output
1
Input
5
Output
70
-----Note-----
In the second test the rows of the table look as follows: {1, 1, 1, 1, 1}, {1, 2, 3, 4, 5}, {1, 3, 6, 10, 15}, {1, 4, 10, 20, 35}, {1, 5, 15, 35, 70}.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to v_{i}. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree.
Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
-----Input-----
The first line of the input contains n (1 ≤ n ≤ 10^5). Each of the next n - 1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ n; a_{i} ≠ b_{i}) indicating there's an edge between vertices a_{i} and b_{i}. It's guaranteed that the input graph is a tree.
The last line of the input contains a list of n space-separated integers v_1, v_2, ..., v_{n} (|v_{i}| ≤ 10^9).
-----Output-----
Print the minimum number of operations needed to solve the task.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
3
1 2
1 3
1 -1 1
Output
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.
Vasya has two arrays $A$ and $B$ of lengths $n$ and $m$, respectively.
He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $[1, 10, 100, 1000, 10000]$ Vasya can obtain array $[1, 1110, 10000]$, and from array $[1, 2, 3]$ Vasya can obtain array $[6]$.
Two arrays $A$ and $B$ are considered equal if and only if they have the same length and for each valid $i$ $A_i = B_i$.
Vasya wants to perform some of these operations on array $A$, some on array $B$, in such a way that arrays $A$ and $B$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.
Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $A$ and $B$ equal.
-----Input-----
The first line contains a single integer $n~(1 \le n \le 3 \cdot 10^5)$ — the length of the first array.
The second line contains $n$ integers $a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$ — elements of the array $A$.
The third line contains a single integer $m~(1 \le m \le 3 \cdot 10^5)$ — the length of the second array.
The fourth line contains $m$ integers $b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$ - elements of the array $B$.
-----Output-----
Print a single integer — the maximum length of the resulting arrays after some operations were performed on arrays $A$ and $B$ in such a way that they became equal.
If there is no way to make array equal, print "-1".
-----Examples-----
Input
5
11 2 3 5 7
4
11 7 3 7
Output
3
Input
2
1 2
1
100
Output
-1
Input
3
1 2 3
3
1 2 3
Output
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.
Young Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha.
Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point xi, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions.
Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice.
Input
First line of input contains two integer numbers: n and m (1 ≤ n, m ≤ 100 000) — amount of segments of Teodor's picture and maximal coordinate of point that Sasha can ask about.
ith of next n lines contains two integer numbers li and ri (1 ≤ li ≤ ri ≤ m) — left and right ends of ith segment in the picture. Note that that left and right ends of segment can be the same point.
It is guaranteed that there is no integer point, that belongs to all segments.
Output
Single line of output should contain one integer number k – size of largest set (xi, cnt(xi)) where all xi are different, 1 ≤ xi ≤ m, and cnt(xi) is amount of segments, containing point with coordinate xi, such that one can't be sure that there doesn't exist point, belonging to all of segments in initial picture, if he knows only this set(and doesn't know n).
Examples
Input
2 4
1 2
3 4
Output
4
Input
4 6
1 3
2 3
4 6
5 6
Output
5
Note
First example shows situation where Sasha can never be sure that Teodor isn't lying to him, because even if one knows cnt(xi) for each point in segment [1;4], he can't distinguish this case from situation Teodor has drawn whole [1;4] segment.
In second example Sasha can ask about 5 points e.g. 1, 2, 3, 5, 6, still not being sure if Teodor haven't lied to him. But once he knows information about all points in [1;6] segment, Sasha can be sure that Teodor haven't lied to him.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a program which reads a sequence and prints it in the reverse order.
Note
解説
Constraints
* n ≤ 100
* 0 ≤ ai < 1000
Input
The input is given in the following format:
n
a1 a2 . . . an
n is the size of the sequence and ai is the ith element of the sequence.
Output
Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).
Examples
Input
5
1 2 3 4 5
Output
5 4 3 2 1
Input
8
3 3 4 4 5 8 7 9
Output
9 7 8 5 4 4 3 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
«Next please», — the princess called and cast an estimating glance at the next groom.
The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous ones added together, she exclaims «Wow!» (no «Oh...» in this case). At the sight of the first groom the princess stays calm and says nothing.
The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw n grooms, said «Oh...» exactly a times and exclaimed «Wow!» exactly b times. Your task is to output a sequence of n integers t1, t2, ..., tn, where ti describes the fortune of i-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.
Input
The only line of input data contains three integer numbers n, a and b (1 ≤ n ≤ 100, 0 ≤ a, b ≤ 15, n > a + b), separated with single spaces.
Output
Output any sequence of integers t1, t2, ..., tn, where ti (1 ≤ ti ≤ 50000) is the fortune of i-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1.
Examples
Input
10 2 3
Output
5 1 3 6 16 35 46 4 200 99
Input
5 0 0
Output
10 10 6 6 5
Note
Let's have a closer look at the answer for the first sample test.
* The princess said «Oh...» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.
* The princess exclaimed «Wow!» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese , Russian and Vietnamese as well.
Triangle classification is an important problem in modern mathematics. Mathematicians have developed many criteria according to which a triangle can be classified. In this problem, you will be asked to classify some triangles according to their sides and angles.
According to their measure, angles may be:
Acute — an angle that is less than 90 degrees
Right — a 90-degrees angle
Obtuse — an angle that is greater than 90 degrees
According to their sides, triangles may be:
Scalene — all sides are different
Isosceles — exactly two sides are equal
According to their angles, triangles may be:
Acute — all angles are acute
Right — one angle is right
Obtuse — one angle is obtuse
Triangles with three equal sides (equilateral triangles) will not appear in the test data.
The triangles formed by three collinear points are not considered in this problem. In order to classify a triangle, you should use only the adjactives from the statement. There is no triangle which could be described in two different ways according to the classification characteristics considered above.
------ Input ------
The first line of input contains an integer SUBTASK_{ID} denoting the subtask id this input belongs to.
The second line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains six integers x_{1}, y_{1}, x_{2}, y_{2}, x_{3} and y_{3} denoting Cartesian coordinates of points, that form the triangle to be classified.
It is guaranteed that the points are non-collinear.
------ Output ------
For each test case, output a single line containing the classification of the given triangle.
If SUBTASK_{ID} equals 1, then the classification should follow the "Side classification starting with a capital letter> triangle" format.
If SUBTASK_{ID} equals 2, then the classification should follow the "Side classification starting with a capital letter> angle classification> triangle" format.
Please, check out the samples section to better understand the format of the output.
------ Constraints ------
$1 ≤ T ≤ 60$
$|x_{i}|, |y_{i}| ≤ 100$
$Subtask 1 (50 points): no additional constraints$
$Subtask 2 (50 points): no additional constraints$
------ Note ------
The first test of the first subtask and the first test of the second subtask are the example tests (each in the corresponding subtask). It's made for you to make sure that your solution produces the same verdict both on your machine and our server.
------ Tip ------
Consider using the following condition in order to check whether two floats or doubles A and B are equal instead of traditional A == B: |A - B| < 10^{-6}.
----- Sample Input 1 ------
1
2
0 0 1 1 1 2
3 0 0 4 4 7
----- Sample Output 1 ------
Scalene triangle
Isosceles triangle
----- explanation 1 ------
----- Sample Input 2 ------
2
6
0 0 4 1 1 3
0 0 1 0 1 2
0 0 1 1 1 2
0 0 2 1 1 2
3 0 0 4 4 7
0 0 2 1 4 0
----- Sample Output 2 ------
Scalene acute triangle
Scalene right triangle
Scalene obtuse triangle
Isosceles acute triangle
Isosceles right triangle
Isosceles obtuse triangle
----- explanation 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.
Sereja has an array a, consisting of n integers a_1, a_2, ..., a_{n}. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l_1, l_2, ..., l_{m} (1 ≤ l_{i} ≤ n). For each number l_{i} he wants to know how many distinct numbers are staying on the positions l_{i}, l_{i} + 1, ..., n. Formally, he want to find the number of distinct numbers among a_{l}_{i}, a_{l}_{i} + 1, ..., a_{n}.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each l_{i}.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the array elements.
Next m lines contain integers l_1, l_2, ..., l_{m}. The i-th line contains integer l_{i} (1 ≤ l_{i} ≤ n).
-----Output-----
Print m lines — on the i-th line print the answer to the number l_{i}.
-----Examples-----
Input
10 10
1 2 3 4 1 2 3 4 100000 99999
1
2
3
4
5
6
7
8
9
10
Output
6
6
6
6
6
5
4
3
2
1
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.
Lala Land has exactly n apple trees. Tree number i is located in a position x_{i} and has a_{i} apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.
What is the maximum number of apples he can collect?
-----Input-----
The first line contains one number n (1 ≤ n ≤ 100), the number of apple trees in Lala Land.
The following n lines contains two integers each x_{i}, a_{i} ( - 10^5 ≤ x_{i} ≤ 10^5, x_{i} ≠ 0, 1 ≤ a_{i} ≤ 10^5), representing the position of the i-th tree and number of apples on it.
It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.
-----Output-----
Output the maximum number of apples Amr can collect.
-----Examples-----
Input
2
-1 5
1 5
Output
10
Input
3
-2 2
1 4
-1 3
Output
9
Input
3
1 9
3 5
7 10
Output
9
-----Note-----
In the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.
In the second sample test the optimal solution is to go left to x = - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x = - 2.
In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the books.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^9) — the number of books in the library.
-----Output-----
Print the number of digits needed to number all the books.
-----Examples-----
Input
13
Output
17
Input
4
Output
4
-----Note-----
Note to the first test. The books get numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, which totals to 17 digits.
Note to the second sample. The books get numbers 1, 2, 3, 4, which totals to 4 digits.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g.
Note: if the average of two digits is not an integer, round the result **up** (e.g. the average of 8 and 9 will be 9)
## Examples
```
digitsAverage(246) ==> 4
original: 2 4 6
\ / \ /
1st iter: 3 5
\ /
2nd iter: 4
digitsAverage(89) ==> 9
original: 8 9
\ /
1st iter: 9
```
p.s. for a bigger challenge, check out the [one line version](https://www.codewars.com/kata/one-line-task-digits-average) of this kata by myjinxin2015!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dmitry has an array of $n$ non-negative integers $a_1, a_2, \dots, a_n$.
In one operation, Dmitry can choose any index $j$ ($1 \le j \le n$) and increase the value of the element $a_j$ by $1$. He can choose the same index $j$ multiple times.
For each $i$ from $0$ to $n$, determine whether Dmitry can make the $\mathrm{MEX}$ of the array equal to exactly $i$. If it is possible, then determine the minimum number of operations to do it.
The $\mathrm{MEX}$ of the array is equal to the minimum non-negative integer that is not in the array. For example, the $\mathrm{MEX}$ of the array $[3, 1, 0]$ is equal to $2$, and the array $[3, 3, 1, 4]$ is equal to $0$.
-----Input-----
The first line of input data contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input.
The descriptions of the test cases follow.
The first line of the description of each test case contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the array $a$.
The second line of the description of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le n$) — elements of the array $a$.
It is guaranteed that the sum of the values $n$ over all test cases in the test does not exceed $2\cdot10^5$.
-----Output-----
For each test case, output $n + 1$ integer — $i$-th number is equal to the minimum number of operations for which you can make the array $\mathrm{MEX}$ equal to $i$ ($0 \le i \le n$), or -1 if this cannot be done.
-----Examples-----
Input
5
3
0 1 3
7
0 1 2 3 4 3 2
4
3 0 0 0
7
4 6 2 3 5 0 5
5
4 0 1 0 4
Output
1 1 0 -1
1 1 2 2 1 0 2 6
3 0 1 4 3
1 0 -1 -1 -1 -1 -1 -1
2 1 0 2 -1 -1
-----Note-----
In the first set of example inputs, $n=3$:
to get $\mathrm{MEX}=0$, it is enough to perform one increment: $a_1$++;
to get $\mathrm{MEX}=1$, it is enough to perform one increment: $a_2$++;
$\mathrm{MEX}=2$ for a given array, so there is no need to perform increments;
it is impossible to get $\mathrm{MEX}=3$ by performing increments.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 tree with N vertices. Vertex 1 is the root of the tree, and the parent of Vertex i (2 \leq i \leq N) is Vertex P_i.
To each vertex in the tree, Snuke will allocate a color, either black or white, and a non-negative integer weight.
Snuke has a favorite integer sequence, X_1, X_2, ..., X_N, so he wants to allocate colors and weights so that the following condition is satisfied for all v.
- The total weight of the vertices with the same color as v among the vertices contained in the subtree whose root is v, is X_v.
Here, the subtree whose root is v is the tree consisting of Vertex v and all of its descendants.
Determine whether it is possible to allocate colors and weights in this way.
-----Constraints-----
- 1 \leq N \leq 1 000
- 1 \leq P_i \leq i - 1
- 0 \leq X_i \leq 5 000
-----Inputs-----
Input is given from Standard Input in the following format:
N
P_2 P_3 ... P_N
X_1 X_2 ... X_N
-----Outputs-----
If it is possible to allocate colors and weights to the vertices so that the condition is satisfied, print POSSIBLE; otherwise, print IMPOSSIBLE.
-----Sample Input-----
3
1 1
4 3 2
-----Sample Output-----
POSSIBLE
For example, the following allocation satisfies the condition:
- Set the color of Vertex 1 to white and its weight to 2.
- Set the color of Vertex 2 to black and its weight to 3.
- Set the color of Vertex 3 to white and its weight to 2.
There are also other possible allocations.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?
Input
The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow.
The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.
Output
Print the maximum total happiness that can be achieved.
Examples
Input
3 12
3 5 7
4 6 7
5 9 5
Output
84
Input
6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6
Output
314
Note
In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
You have an array of integers A_{1}, A_{2}, ..., A_{N}. The function F(P), where P is a subset of A, is defined as the XOR (represented by the symbol ⊕) of all the integers present in the subset. If P is empty, then F(P)=0.
Given an integer K, what is the maximum value of K ⊕ F(P), over all possible subsets P of A?
------ Input ------
The first line contains T, the number of test cases. Each test case consists of N and K in one line, followed by the array A in the next line.
------ Output ------
For each test case, print the required answer in one line.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ K, A_{i} ≤ 1000$
$Subtask 1 (30 points):1 ≤ N ≤ 20$
$Subtask 2 (70 points):1 ≤ N ≤ 1000$
----- Sample Input 1 ------
1
3 4
1 2 3
----- Sample Output 1 ------
7
----- explanation 1 ------
Considering all subsets:
F({}) = 0 ? 4 ? 0 = 4
F({1}) = 1 ? 4 ? 1 = 5
F({1,2}) = 3 ? 4 ? 3 = 7
F({1,3}) = 2 ? 4 ? 2 = 6
F({1,2,3}) = 0 ? 4 ? 0 = 4
F({2}) = 2 ? 4 ? 2 = 6
F({2,3}) = 1 ? 4 ? 1 = 5
F({3}) = 3 ? 4 ? 3 = 7
Therefore, the answer is 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.
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.
However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.
Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.
-----Input-----
The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000).
The following line contains a binary string of length n representing Kevin's results on the USAICO.
-----Output-----
Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.
-----Examples-----
Input
8
10000011
Output
5
Input
2
01
Output
2
-----Note-----
In the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.
In the second sample, Kevin can flip the entire string and still have the same score.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
Input
First line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)
Output
Output one integer number — the minimal result which can be obtained.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Examples
Input
1 1 1 1
+ + *
Output
3
Input
2 2 2 2
* * +
Output
8
Input
1 2 3 4
* + +
Output
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.
Takahashi loves numbers divisible by 2.
You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique.
Here, the number of times an integer can be divisible by 2, is how many times the integer can be divided by 2 without remainder.
For example,
- 6 can be divided by 2 once: 6 -> 3.
- 8 can be divided by 2 three times: 8 -> 4 -> 2 -> 1.
- 3 can be divided by 2 zero times.
-----Constraints-----
- 1 ≤ N ≤ 100
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the answer.
-----Sample Input-----
7
-----Sample Output-----
4
4 can be divided by 2 twice, which is the most number of times among 1, 2, ..., 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.
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.
The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.
How much work is there left to be done: that is, how many remote planets are there?
-----Input-----
The first line of the input contains an integer N (2 ≤ N ≤ 1000) – 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-----
A single integer denoting the number of remote planets.
-----Examples-----
Input
5
4 1
4 2
1 3
1 5
Output
3
Input
4
1 2
4 3
1 4
Output
2
-----Note-----
In the first example, only planets 2, 3 and 5 are connected by a single tunnel.
In the second example, the remote planets are 2 and 3.
Note that this problem has only two versions – easy and medium.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 computer literacy course in your university. In the computer system, the login/logout records of all PCs in a day are stored in a file. Although students may use two or more PCs at a time, no one can log in to a PC which has been logged in by someone who has not logged out of that PC yet.
You are asked to write a program that calculates the total time of a student that he/she used at least one PC in a given time period (probably in a laboratory class) based on the records in the file.
The following are example login/logout records.
* The student 1 logged in to the PC 1 at 12:55
* The student 2 logged in to the PC 4 at 13:00
* The student 1 logged in to the PC 2 at 13:10
* The student 1 logged out of the PC 2 at 13:20
* The student 1 logged in to the PC 3 at 13:30
* The student 1 logged out of the PC 1 at 13:40
* The student 1 logged out of the PC 3 at 13:45
* The student 1 logged in to the PC 1 at 14:20
* The student 2 logged out of the PC 4 at 14:30
* The student 1 logged out of the PC 1 at 14:40
For a query such as "Give usage of the student 1 between 13:00 and 14:30", your program should answer "55 minutes", that is, the sum of 45 minutes from 13:00 to 13:45 and 10 minutes from 14:20 to 14:30, as depicted in the following figure.
<image>
Input
The input is a sequence of a number of datasets. The end of the input is indicated by a line containing two zeros separated by a space. The number of datasets never exceeds 10.
Each dataset is formatted as follows.
> N M
> r
> record1
> ...
> recordr
> q
> query1
> ...
> queryq
>
The numbers N and M in the first line are the numbers of PCs and the students, respectively. r is the number of records. q is the number of queries. These four are integers satisfying the following.
> 1 ≤ N ≤ 1000, 1 ≤ M ≤ 10000, 2 ≤ r ≤ 1000, 1 ≤ q ≤ 50
Each record consists of four integers, delimited by a space, as follows.
> t n m s
s is 0 or 1. If s is 1, this line means that the student m logged in to the PC n at time t . If s is 0, it means that the student m logged out of the PC n at time t . The time is expressed as elapsed minutes from 0:00 of the day. t , n and m satisfy the following.
> 540 ≤ t ≤ 1260, 1 ≤ n ≤ N , 1 ≤ m ≤ M
You may assume the following about the records.
* Records are stored in ascending order of time t.
* No two records for the same PC has the same time t.
* No PCs are being logged in before the time of the first record nor after that of the last record in the file.
* Login and logout records for one PC appear alternatingly, and each of the login-logout record pairs is for the same student.
Each query consists of three integers delimited by a space, as follows.
> ts te m
It represents "Usage of the student m between ts and te ". ts , te and m satisfy the following.
> 540 ≤ ts < te ≤ 1260, 1 ≤ m ≤ M
Output
For each query, print a line having a decimal integer indicating the time of usage in minutes. Output lines should not have any character other than this number.
Example
Input
4 2
10
775 1 1 1
780 4 2 1
790 2 1 1
800 2 1 0
810 3 1 1
820 1 1 0
825 3 1 0
860 1 1 1
870 4 2 0
880 1 1 0
1
780 870 1
13 15
12
540 12 13 1
600 12 13 0
650 13 15 1
660 12 15 1
665 11 13 1
670 13 15 0
675 11 13 0
680 12 15 0
1000 11 14 1
1060 12 14 1
1060 11 14 0
1080 12 14 0
3
540 700 13
600 1000 15
1000 1200 11
1 1
2
600 1 1 1
700 1 1 0
5
540 600 1
550 650 1
610 620 1
650 750 1
700 800 1
0 0
Output
55
70
30
0
0
50
10
50
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently, the bear started studying data structures and faced the following problem.
You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li, ri is the sum: <image>, where S(li, ri) is a set of prime numbers from segment [li, ri] (both borders are included in the segment).
Help the bear cope with the problem.
Input
The first line contains integer n (1 ≤ n ≤ 106). The second line contains n integers x1, x2, ..., xn (2 ≤ xi ≤ 107). The numbers are not necessarily distinct.
The third line contains integer m (1 ≤ m ≤ 50000). Each of the following m lines contains a pair of space-separated integers, li and ri (2 ≤ li ≤ ri ≤ 2·109) — the numbers that characterize the current query.
Output
Print m integers — the answers to the queries on the order the queries appear in the input.
Examples
Input
6
5 5 7 10 14 15
3
2 11
3 12
4 4
Output
9
7
0
Input
7
2 3 5 7 11 4 8
2
8 10
2 123
Output
0
7
Note
Consider the first sample. Overall, the first sample has 3 queries.
1. The first query l = 2, r = 11 comes. You need to count f(2) + f(3) + f(5) + f(7) + f(11) = 2 + 1 + 4 + 2 + 0 = 9.
2. The second query comes l = 3, r = 12. You need to count f(3) + f(5) + f(7) + f(11) = 1 + 4 + 2 + 0 = 7.
3. The third query comes l = 4, r = 4. As this interval has no prime numbers, then the sum equals 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according <image> (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj.
Input
On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000.
Output
On a single line output the coordinates of Mj, space separated.
Examples
Input
3 4
0 0
1 1
2 3
-5 3
Output
14 0
Input
3 1
5 5
1000 1000
-1000 1000
3 100
Output
1995 1995
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.
Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a_1, a_2, ..., a_{n}, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.
Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of a_{i} may be unknown. Such values are represented by number -1.
For a given sequence a = (a_1, a_2, ..., a_{n}), which consists of positive integers and values -1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values -1 may correspond to an arbitrary positive integer and the values a_{i} > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.
Let us remind you that a finite sequence c is called an arithmetic progression if the difference c_{i} + 1 - c_{i} of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 2·10^5) — the number of elements in the sequence. The second line contains integer values a_1, a_2, ..., a_{n} separated by a space (1 ≤ a_{i} ≤ 10^9 or a_{i} = - 1).
-----Output-----
Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.
-----Examples-----
Input
9
8 6 4 2 1 4 7 10 2
Output
3
Input
9
-1 6 -1 2 -1 4 7 -1 2
Output
3
Input
5
-1 -1 -1 -1 -1
Output
1
Input
7
-1 -1 4 5 1 2 3
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Your task is to calculate the number of arrays such that: each array contains $n$ elements; each element is an integer from $1$ to $m$; for each array, there is exactly one pair of equal elements; for each array $a$, there exists an index $i$ such that the array is strictly ascending before the $i$-th element and strictly descending after it (formally, it means that $a_j < a_{j + 1}$, if $j < i$, and $a_j > a_{j + 1}$, if $j \ge i$).
-----Input-----
The first line contains two integers $n$ and $m$ ($2 \le n \le m \le 2 \cdot 10^5$).
-----Output-----
Print one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo $998244353$.
-----Examples-----
Input
3 4
Output
6
Input
3 5
Output
10
Input
42 1337
Output
806066790
Input
100000 200000
Output
707899035
-----Note-----
The arrays in the first example are: $[1, 2, 1]$; $[1, 3, 1]$; $[1, 4, 1]$; $[2, 3, 2]$; $[2, 4, 2]$; $[3, 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.
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if $\operatorname{mod}(x, b) \neq 0$ and $\frac{\operatorname{div}(x, b)}{\operatorname{mod}(x, b)} = k$, where k is some integer number in range [1, a].
By $\operatorname{div}(x, y)$ we denote the quotient of integer division of x and y. By $\operatorname{mod}(x, y)$ we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT.
The answer may be large, so please print its remainder modulo 1 000 000 007 (10^9 + 7). Can you compute it faster than Dreamoon?
-----Input-----
The single line of the input contains two integers a, b (1 ≤ a, b ≤ 10^7).
-----Output-----
Print a single integer representing the answer modulo 1 000 000 007 (10^9 + 7).
-----Examples-----
Input
1 1
Output
0
Input
2 2
Output
8
-----Note-----
For the first sample, there are no nice integers because $\operatorname{mod}(x, 1)$ is always zero.
For the second sample, the set of nice integers is {3, 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.
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y).
What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect?
Input
Single line of the input contains three integers x, y and m ( - 1018 ≤ x, y, m ≤ 1018).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier.
Output
Print the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one.
Examples
Input
1 2 5
Output
2
Input
-1 4 15
Output
4
Input
0 -1 5
Output
-1
Note
In the first sample the following sequence of operations is suitable: (1, 2) <image> (3, 2) <image> (5, 2).
In the second sample: (-1, 4) <image> (3, 4) <image> (7, 4) <image> (11, 4) <image> (15, 4).
Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i).
On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation:
* Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1.
A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally.
Constraints
* 2 \leq N \leq 100000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
Output
Print `Alice` if Alice wins; print `Bob` if Bob wins.
Examples
Input
5
1 2
2 3
2 4
4 5
Output
Alice
Input
5
1 2
2 3
1 4
4 5
Output
Bob
Input
6
1 2
2 4
5 1
6 3
3 2
Output
Alice
Input
7
1 2
3 7
4 6
2 3
2 4
1 5
Output
Bob
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
2332
110011
54322345
For a given number ```num```, return its closest numerical palindrome which can either be smaller or larger than ```num```. If there are 2 possible values, the larger value should be returned. If ```num``` is a numerical palindrome itself, return it.
For this kata, single digit numbers will NOT be considered numerical palindromes.
Also, you know the drill - be sure to return "Not valid" if the input is not an integer or is less than 0.
```
palindrome(8) => 11
palindrome(281) => 282
palindrome(1029) => 1001
palindrome(1221) => 1221
palindrome("1221") => "Not valid"
```
```Haskell
In Haskell the function should return a Maybe Int with Nothing for cases where the argument is less than zero.
```
Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #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.
Now we will confect a reagent. There are eight materials to choose from, numbered 1,2,..., 8 respectively.
We know the rules of confect:
```
material1 and material2 cannot be selected at the same time
material3 and material4 cannot be selected at the same time
material5 and material6 must be selected at the same time
material7 or material8 must be selected(at least one, or both)
```
# Task
You are given a integer array `formula`. Array contains only digits 1-8 that represents material 1-8. Your task is to determine if the formula is valid. Returns `true` if it's valid, `false` otherwise.
# Example
For `formula = [1,3,7]`, The output should be `true`.
For `formula = [7,1,2,3]`, The output should be `false`.
For `formula = [1,3,5,7]`, The output should be `false`.
For `formula = [1,5,6,7,3]`, The output should be `true`.
For `formula = [5,6,7]`, The output should be `true`.
For `formula = [5,6,7,8]`, The output should be `true`.
For `formula = [6,7,8]`, The output should be `false`.
For `formula = [7,8]`, The output should be `true`.
# Note
- All inputs are valid. Array contains at least 1 digit. Each digit appears at most once.
- Happy Coding `^_^`
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.
Input
The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits.
Output
In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.
Examples
Input
4
Output
3
1 2
1 3
2 3
Input
5
Output
3
1 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.
Have you heard about Megamind? Megamind and Metro Man are two aliens who came to earth. Megamind wanted to destroy the earth, while Metro Man wanted to stop him and protect mankind. After a lot of fighting, Megamind finally threw Metro Man up into the sky. Metro Man was defeated and was never seen again. Megamind wanted to be a super villain. He believed that the difference between a villain and a super villain is nothing but presentation. Megamind became bored, as he had nobody or nothing to fight against since Metro Man was gone. So, he wanted to create another hero against whom he would fight for recreation. But accidentally, another villain named Hal Stewart was created in the process, who also wanted to destroy the earth. Also, at some point Megamind had fallen in love with a pretty girl named Roxanne Ritchi. This changed him into a new man. Now he wants to stop Hal Stewart for the sake of his love. So, the ultimate fight starts now.
* Megamind has unlimited supply of guns named Magic-48. Each of these guns has `shots` rounds of magic spells.
* Megamind has perfect aim. If he shoots a magic spell it will definitely hit Hal Stewart. Once hit, it decreases the energy level of Hal Stewart by `dps` units.
* However, since there are exactly `shots` rounds of magic spells in each of these guns, he may need to swap an old gun with a fully loaded one. This takes some time. Let’s call it swapping period.
* Since Hal Stewart is a mutant, he has regeneration power. His energy level increases by `regen` unit during a swapping period.
* Hal Stewart will be defeated immediately once his energy level becomes zero or negative.
* Hal Stewart initially has the energy level of `hp` and Megamind has a fully loaded gun in his hand.
* Given the values of `hp`, `dps`, `shots` and `regen`, find the minimum number of times Megamind needs to shoot to defeat Hal Stewart. If it is not possible to defeat him, return `-1` instead.
# Example
Suppose, `hp` = 13, `dps` = 4, `shots` = 3 and `regen` = 1. There are 3 rounds of spells in the gun. Megamind shoots all of them. Hal Stewart’s energy level decreases by 12 units, and thus his energy level becomes 1. Since Megamind’s gun is now empty, he will get a new gun and thus it’s a swapping period. At this time, Hal Stewart’s energy level will increase by 1 unit and will become 2. However, when Megamind shoots the next spell, Hal’s energy level will drop by 4 units and will become −2, thus defeating him. So it takes 4 shoots in total to defeat Hal Stewart. However, in this same example if Hal’s regeneration power was 50 instead of 1, it would have been impossible to defeat Hal.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 some other world, today is Christmas Eve.
There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.
He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.
More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?
-----Constraints-----
- 2 \leq K < N \leq 10^5
- 1 \leq h_i \leq 10^9
- h_i is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N K
h_1
h_2
:
h_N
-----Output-----
Print the minimum possible value of h_{max} - h_{min}.
-----Sample Input-----
5 3
10
15
11
14
12
-----Sample Output-----
2
If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 computes the area of a shape represented by the following three lines:
$y = x^2$
$y = 0$
$x = 600$
It is clear that the area is $72000000$, if you use an integral you learn in high school. On the other hand, we can obtain an approximative area of the shape by adding up areas of many rectangles in the shape as shown in the following figure:
<image>
$f(x) = x^2$
The approximative area $s$ where the width of the rectangles is $d$ is:
area of rectangle where its width is $d$ and height is $f(d)$ $+$
area of rectangle where its width is $d$ and height is $f(2d)$ $+$
area of rectangle where its width is $d$ and height is $f(3d)$ $+$
...
area of rectangle where its width is $d$ and height is $f(600 - d)$
The more we decrease $d$, the higer-precision value which is close to $72000000$ we could obtain. Your program should read the integer $d$ which is a divisor of $600$, and print the area $s$.
Input
The input consists of several datasets. Each dataset consists of an integer $d$ in a line. The number of datasets is less than or equal to 20.
Output
For each dataset, print the area $s$ in a line.
Example
Input
20
10
Output
68440000
70210000
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every a minutes, but a train goes to Masha's direction every b minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).
We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.
Help Vasya count to which girlfriend he will go more often.
Input
The first line contains two integers a and b (a ≠ b, 1 ≤ a, b ≤ 106).
Output
Print "Dasha" if Vasya will go to Dasha more frequently, "Masha" if he will go to Masha more frequently, or "Equal" if he will go to both girlfriends with the same frequency.
Examples
Input
3 7
Output
Dasha
Input
5 3
Output
Masha
Input
2 3
Output
Equal
Note
Let's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0, 6], he will go to both girls equally often.
If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute.
If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute.
If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute.
If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction.
In sum Masha and Dasha get equal time — three minutes for each one, thus, Vasya will go to both girlfriends equally often.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to display the given number on the 7-segment display.
This 7-segment display will not change until the next switch instruction is sent. By sending a signal consisting of 7 bits, the display information of each corresponding segment can be switched. Bits have a value of 1 or 0, where 1 stands for "switch" and 0 stands for "as is".
The correspondence between each bit and segment is shown in the figure below. The signal sends 7 bits in the order of "gfedcba". For example, in order to display "0" from the hidden state, "0111111" must be sent to the display as a signal. To change from "0" to "5", send "1010010". If you want to change "5" to "1" in succession, send "1101011".
<image>
Create a program that takes n (1 ≤ n ≤ 100) numbers that you want to display and outputs the signal sequence required to correctly display those numbers di (0 ≤ di ≤ 9) on the 7-segment display. please. It is assumed that the initial state of the 7-segment display is all hidden.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1. Each dataset is given in the following format:
n
d1
d2
::
dn
The number of datasets does not exceed 120.
Output
For each input dataset, output the sequence of signals needed to properly output the numbers to the display.
Example
Input
3
0
5
1
1
0
-1
Output
0111111
1010010
1101011
0111111
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 decided to play a game, where the player runs a railway company.
There are M+1 stations on Snuke Line, numbered 0 through M.
A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train.
For example, if d = 3, the train stops at station 0, 3, 6, 9, and so forth.
There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind of souvenirs can be purchased when the train stops at one of the following stations: stations l_i, l_i+1, l_i+2, ..., r_i.
There are M values of d, the interval between two stops, for trains on Snuke Line: 1, 2, 3, ..., M.
For each of these M values, find the number of the kinds of souvenirs that can be purchased if one takes a train with that value of d at station 0.
Here, assume that it is not allowed to change trains.
-----Constraints-----
- 1 ≦ N ≦ 3 × 10^{5}
- 1 ≦ M ≦ 10^{5}
- 1 ≦ l_i ≦ r_i ≦ M
-----Input-----
The input is given from Standard Input in the following format:
N M
l_1 r_1
:
l_{N} r_{N}
-----Output-----
Print the answer in M lines. The i-th line should contain the maximum number of the kinds of souvenirs that can be purchased if one takes a train stopping every i-th station.
-----Sample Input-----
3 3
1 2
2 3
3 3
-----Sample Output-----
3
2
2
- If one takes a train stopping every station, three kinds of souvenirs can be purchased: kind 1, 2 and 3.
- If one takes a train stopping every second station, two kinds of souvenirs can be purchased: kind 1 and 2.
- If one takes a train stopping every third station, two kinds of souvenirs can be purchased: kind 2 and 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as single character '/'.
A path called normalized if it contains the smallest possible number of characters '/'.
Your task is to transform a given path to the normalized form.
Input
The first line of the input contains only lowercase Latin letters and character '/' — the path to some directory. All paths start with at least one character '/'. The length of the given line is no more than 100 characters, it is not empty.
Output
The path in normalized form.
Examples
Input
//usr///local//nginx/sbin
Output
/usr/local/nginx/sbin
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation.
For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2].
The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation.
Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque.
Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.
Input
The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}).
Output
For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation.
Examples
Input
5 3
1 2 3 4 5
1
2
10
Output
1 2
2 3
5 2
Input
2 0
0 0
Output
Note
Consider all 10 steps for the first test in detail:
1. [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively.
So, 2 we write to the beginning of the deque, and 1 — to the end.
We get the following status of the deque: [2, 3, 4, 5, 1].
2. [2, 3, 4, 5, 1] ⇒ A = 2, B = 3.
3. [3, 4, 5, 1, 2]
4. [4, 5, 1, 2, 3]
5. [5, 1, 2, 3, 4]
6. [5, 2, 3, 4, 1]
7. [5, 3, 4, 1, 2]
8. [5, 4, 1, 2, 3]
9. [5, 1, 2, 3, 4]
10. [5, 2, 3, 4, 1] ⇒ A = 5, B = 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.
While working at DTL, Ela is very aware of her physical and mental health. She started to practice various sports, such as Archery, Yoga, and Football.
Since she started engaging in sports activities, Ela switches to trying a new sport on days she considers being "Luxury" days. She counts the days since she started these activities, in which the day she starts is numbered as day $1$. A "Luxury" day is the day in which the number of this day is a luxurious number.
An integer $x$ is called a luxurious number if it is divisible by ${\lfloor \sqrt{x} \rfloor}$.
Here $\lfloor r \rfloor$ denotes the "floor" of a real number $r$. In other words, it's the largest integer not greater than $r$.
For example: $8$, $56$, $100$ are luxurious numbers, since $8$ is divisible by $\lfloor \sqrt{8} \rfloor = \lfloor 2.8284 \rfloor = 2$, $56$ is divisible $\lfloor \sqrt{56} \rfloor = \lfloor 7.4833 \rfloor = 7$, and $100$ is divisible by $\lfloor \sqrt{100} \rfloor = \lfloor 10 \rfloor = 10$, respectively. On the other hand $5$, $40$ are not, since $5$ are not divisible by $\lfloor \sqrt{5} \rfloor = \lfloor 2.2361 \rfloor = 2$, and $40$ are not divisible by $\lfloor \sqrt{40} \rfloor = \lfloor 6.3246 \rfloor = 6$.
Being a friend of Ela, you want to engage in these fitness activities with her to keep her and yourself accompanied (and have fun together, of course). Between day $l$ and day $r$, you want to know how many times she changes the activities.
-----Input-----
Each test contains multiple test cases. The first line has the number of test cases $t$ ($1 \le t \le 10\ 000$). The description of the test cases follows.
The only line of each test case contains two integers $l$ and $r$ ($1 \le l \le r \le 10^{18}$) — the intervals at which you want to know how many times Ela changes her sports.
-----Output-----
For each test case, output an integer that denotes the answer.
-----Examples-----
Input
5
8 19
8 20
119 121
1 100000000000000000
1234567891011 1000000000000000000
Output
5
6
2
948683296
2996666667
-----Note-----
In the first test case, $5$ luxury numbers in range $[8, 19]$ are: $8, 9, 12, 15, 16$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Our Chef is very happy that his son was selected for training in one of the finest culinary schools of the world.
So he and his wife decide to buy a gift for the kid as a token of appreciation.
Unfortunately, the Chef hasn't been doing good business lately, and is in no mood on splurging money.
On the other hand, the boy's mother wants to buy something big and expensive.
To settle the matter like reasonable parents, they play a game.
They spend the whole day thinking of various gifts and write them down in a huge matrix.
Each cell of the matrix contains the gift's cost.
Then they decide that the mother will choose a row number r while the father will choose a column number c,
the item from the corresponding cell will be gifted to the kid in a couple of days.
The boy observes all of this secretly.
He is smart enough to understand that his parents will ultimately choose a gift whose cost is smallest in its row,
but largest in its column.
If no such gift exists, then our little chef has no option but to keep guessing.
As the matrix is huge, he turns to you for help.
He knows that sometimes the gift is not determined uniquely even if a gift exists whose cost is smallest in its row,
but largest in its column.
However, since the boy is so smart, he realizes that the gift's cost is determined uniquely.
Your task is to tell him the gift's cost which is smallest in its row,
but largest in its column, or to tell him no such gift exists.
-----Input-----
First line contains two integers R and C, the number of rows and columns in the matrix respectively. Then follow R lines, each containing C space separated integers - the costs of different gifts.
-----Output-----
Print a single integer - a value in the matrix that is smallest in its row but highest in its column. If no such value exists, then print "GUESS" (without quotes of course)
-----Constraints-----
1 <= R, C <= 100
All gift costs are positive and less than 100000000 (10^8)
-----Example 1-----
Input:
2 3
9 8 8
2 6 11
Output:
8
-----Example 2-----
Input:
3 3
9 8 11
2 6 34
5 9 11
Output:
GUESS
-----Example 3-----
Input:
2 2
10 10
10 10
Output:
10
-----Explanation of Sample Cases-----
Example 1: The first row contains 9, 8, 8. Observe that both 8 are the minimum. Considering the first 8, look at the corresponding column (containing 8 and 6). Here, 8 is the largest element in that column. So it will be chosen.
Example 2: There is no value in the matrix that is smallest in its row but largest in its column.
Example 3: The required gift in matrix is not determined uniquely, but the required cost is determined uniquely.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider a sequence of integers $a_1, a_2, \ldots, a_n$. In one move, you can select any element of the sequence and delete it. After an element is deleted, all elements to the right are shifted to the left by $1$ position, so there are no empty spaces in the sequence. So after you make a move, the sequence's length decreases by $1$. The indices of the elements after the move are recalculated.
E. g. let the sequence be $a=[3, 2, 2, 1, 5]$. Let's select the element $a_3=2$ in a move. Then after the move the sequence will be equal to $a=[3, 2, 1, 5]$, so the $3$-rd element of the new sequence will be $a_3=1$ and the $4$-th element will be $a_4=5$.
You are given a sequence $a_1, a_2, \ldots, a_n$ and a number $k$. You need to find the minimum number of moves you have to make so that in the resulting sequence there will be at least $k$ elements that are equal to their indices, i. e. the resulting sequence $b_1, b_2, \ldots, b_m$ will contain at least $k$ indices $i$ such that $b_i = i$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.
Each test case consists of two consecutive lines. The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$). The second line contains a sequence of integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$). The numbers in the sequence are not necessarily different.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2000$.
-----Output-----
For each test case output in a single line:
$-1$ if there's no desired move sequence;
otherwise, the integer $x$ ($0 \le x \le n$) — the minimum number of the moves to be made so that the resulting sequence will contain at least $k$ elements that are equal to their indices.
-----Examples-----
Input
4
7 6
1 1 2 3 4 5 6
5 2
5 1 3 2 3
5 2
5 5 5 5 4
8 4
1 2 3 3 2 2 5 5
Output
1
2
-1
2
-----Note-----
In the first test case the sequence doesn't satisfy the desired condition, but it can be provided by deleting the first element, hence the sequence will be $[1, 2, 3, 4, 5, 6]$ and $6$ elements will be equal to their indices.
In the second test case there are two ways to get the desired result in $2$ moves: the first one is to delete the $1$-st and the $3$-rd elements so that the sequence will be $[1, 2, 3]$ and have $3$ elements equal to their indices; the second way is to delete the $2$-nd and the $3$-rd elements to get the sequence $[5, 2, 3]$ with $2$ desired elements.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 held two competitions: Coding Contest and Robot Maneuver.
In each competition, the contestants taking the 3-rd, 2-nd, and 1-st places receive 100000, 200000, and 300000 yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional 400000 yen.
DISCO-Kun took the X-th place in Coding Contest and the Y-th place in Robot Maneuver. Find the total amount of money he earned.
Constraints
* 1 \leq X \leq 205
* 1 \leq Y \leq 205
* X and Y are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
Print the amount of money DISCO-Kun earned, as an integer.
Examples
Input
1 1
Output
1000000
Input
3 101
Output
100000
Input
4 4
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have an integer sequence A, whose length is N.
Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.
Constraints
* 1 \leq N \leq 2 \times 10^5
* -10^9 \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 number of the non-empty contiguous subsequences of A whose sum is 0.
Examples
Input
6
1 3 -4 2 2 -2
Output
3
Input
7
1 -1 1 -1 1 -1 1
Output
12
Input
5
1 -2 3 -4 5
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.
Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101.
The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.
An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
Input
The first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.
Output
Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).
Examples
Input
????
Output
00
01
10
11
Input
1010
Output
10
Input
1?1
Output
01
11
Note
In the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.
In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will 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.
Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.
Print the answer in degrees, but do not print units.
Constraints
* 3 \leq N \leq 100
Input
Input is given from Standard Input in the following format:
N
Output
Print an integer representing the sum of the interior angles of a regular polygon with N sides.
Examples
Input
3
Output
180
Input
100
Output
17640
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
---
# Story
The Pied Piper has been enlisted to play his magical tune and coax all the rats out of town.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
# Legend
* ```P``` = The Pied Piper
* ```O~``` = Rat going left
* ```~O``` = Rat going right
# Example
* ex1 ```~O~O~O~O P``` has 0 deaf rats
* ex2 ```P O~ O~ ~O O~``` has 1 deaf rat
* ex3 ```~O~O~O~OP~O~OO~``` has 2 deaf rats
---
# Series
* [The deaf rats of Hamelin (2D)](https://www.codewars.com/kata/the-deaf-rats-of-hamelin-2d)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem:
You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the following n lines contain two space-separated integers xi and yi (1 ≤ xi ≤ 105, 0 ≤ yi ≤ i - 1, where i is the query's ordinal number; the numeration starts with 1).
If yi = 0 for the query, then the answer to the query will be the number of divisors of the number xi. In this case you do not need to take the previous numbers x into consideration.
Output
For each query print the answer on a single line: the number of positive integers k such that <image>
Examples
Input
6
4 0
3 1
5 2
6 2
18 4
10000 3
Output
3
1
1
2
2
22
Note
Let's write out the divisors that give answers for the first 5 queries:
1) 1, 2, 4
2) 3
3) 5
4) 2, 6
5) 9, 18
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.
Future students will be asked just a single question. They are given a sequence of integer numbers $a_1, a_2, \dots, a_n$, each number is from $1$ to $3$ and $a_i \ne a_{i + 1}$ for each valid $i$. The $i$-th number represents a type of the $i$-th figure:
circle; isosceles triangle with the length of height equal to the length of base; square.
The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that:
$(i + 1)$-th figure is inscribed into the $i$-th one; each triangle base is parallel to OX; the triangle is oriented in such a way that the vertex opposite to its base is at the top; each square sides are parallel to the axes; for each $i$ from $2$ to $n$ figure $i$ has the maximum possible length of side for triangle and square and maximum radius for circle.
Note that the construction is unique for some fixed position and size of just the first figure.
The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?
So can you pass the math test and enroll into Berland State University?
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of figures.
The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3$, $a_i \ne a_{i + 1}$) — types of the figures.
-----Output-----
The first line should contain either the word "Infinite" if the number of distinct points where figures touch is infinite or "Finite" otherwise.
If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type.
-----Examples-----
Input
3
2 1 3
Output
Finite
7
Input
3
1 2 3
Output
Infinite
-----Note-----
Here are the glorious pictures for the examples. Note that the triangle is not equilateral but just isosceles with the length of height equal to the length of base. Thus it fits into a square in a unique way.
The distinct points where figures touch are marked red.
In the second example the triangle and the square touch each other for the whole segment, it contains infinite number of points.
[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.
ABC Gene
There is a gene sequence represented by the string `ABC`. You can rewrite this gene sequence by performing the following operations several times.
* Choose one of the letters `A`,` B`, `C`. Let this be x. Replace all x in the gene sequence with `ABC` at the same time.
Given a string S consisting only of `A`,` B`, and `C`. Determine if the gene sequence can be matched to S.
Constraints
* 1 ≤ | S | ≤ 5,000
* S consists only of `A`,` B`, and `C`.
Input Format
Input is given from standard input in the following format.
S
Output Format
Output `Yes` if the gene sequence can be matched to S, and` No` if it cannot be matched.
Sample Input 1
ABC
Sample Output 1
Yes
The gene sequence is `ABC` from the beginning.
Sample Input 2
AABCC
Sample Output 2
Yes
If you select `B` and perform the operation, it becomes` ABC` → `AABCC`.
Sample Input 3
AABCABC
Sample Output 3
No
For example, even if you select `C` and perform an operation, it does not change from` AABCC` to `AABCABC`. Since all `C`s are replaced with` ABC` at the same time, the actual result is `AABCC` →` AABABCABC`.
Example
Input
ABC
Output
Yes
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he needs to pay 5 and if n = 2 he pays only 1 burle.
As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial n in several parts n_1 + n_2 + ... + n_{k} = n (here k is arbitrary, even k = 1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition n_{i} ≥ 2 should hold for all i from 1 to k.
Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split n in parts.
-----Input-----
The first line of the input contains a single integer n (2 ≤ n ≤ 2·10^9) — the total year income of mr. Funt.
-----Output-----
Print one integer — minimum possible number of burles that mr. Funt has to pay as a tax.
-----Examples-----
Input
4
Output
2
Input
27
Output
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.
Vasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many!
Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size x × y × z, consisting of undestructable cells 1 × 1 × 1. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value.
All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut.
Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most k times.
Vasya's character uses absolutely thin sword with infinite length.
Input
The first line of input contains four integer numbers x, y, z, k (1 ≤ x, y, z ≤ 106, 0 ≤ k ≤ 109).
Output
Output the only number — the answer for the problem.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
2 2 2 3
Output
8
Input
2 2 2 1
Output
2
Note
In the first sample Vasya make 3 pairwise perpendicular cuts. He cuts monster on two parts with the first cut, then he divides each part on two with the second cut, and finally he divides each of the 4 parts on two.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dr .: Peter, I've finally done it.
Peter: What's wrong, Dr. David? Is it a silly invention again?
Dr .: This table, this table.
| Character | Sign
--- | ---
(Blank) | 101
'| 000000
, | 000011
-| 10010001
. | 010001
? | 000001
A | 100101
B | 10011010
| Character | Sign
--- | ---
C | 0101
D | 0001
E | 110
F | 01001
G | 10011011
H | 010000
I | 0111
J | 10011000
| Character | Sign
--- | ---
K | 0110
L | 00100
M | 10011001
N | 10011110
O | 00101
P | 111
Q | 10011111
R | 1000
| Character | Sign
--- | ---
S | 00110
T | 00111
U | 10011100
V | 10011101
W | 000010
X | 10010010
Y | 10010011
Z | 10010000
Peter: What? This table is.
Dr .: Okay, just do what you say. First, write your name on a piece of paper.
Peter: Yes, "PETER POTTER".
Dr .: Then, replace each character with the "code" in this table.
Peter: Well, change "P" to "111" and "E" to "110" ... It's quite annoying.
111 110 00111 110 1000 101 111 00101 00111 00111 110 1000
became. It looks like a barcode.
Dr .: All right. Then connect all the replaced strings and separate them by 5 characters.
Peter: Yes, if you connect and separate.
11111 00011 11101 00010 11110 01010 01110 01111 10100 0
It turned out to be something like this. But what about the last "0" guy?
Dr .: Add 0 to make it 5 letters.
Peter: Well, there is only one 0 at the end, so I should add four more 0s. I was able to do it.
11111 00011 11101 00010 11110 01010 01110 01111 10100 00000
Dr .: Next, use this table.
| Sign | Character
--- | ---
00000 | A
00001 | B
00010 | C
00011 | D
00100 | E
00101 | F
00110 | G
00111 | H
| Sign | Character
--- | ---
01000 | I
01001 | J
01010 | K
01011 | L
01100 | M
01101 | N
01110 | O
01111 | P
| Sign | Character
--- | ---
10000 | Q
10001 | R
10010 | S
10011 | T
10100 | U
10101 | V
10110 | W
10111 | X
| Sign | Character
--- | ---
11000 | Y
11001 | Z
11010 | (blank)
11011 | ..
11100 |,
11101 |-
11110 |'
11111 |?
Peter: How do you use this ... yeah! Now you're going to replace the code with a letter!
Dr .: That's right. If it is "11111", go to "?", If it is "00011", go to "D".
Peter: This is simple ... well, it became "? D-C'KOPUA". But it doesn't make sense.
Dr .: Count the number of characters.
Peter: It's 10 characters. Oh, "PETER POTTER" was 12 characters, but 2 characters are reduced.
Dr .: Yes, you can use this table to reduce the number of letters. Now do the same thing in this sentence.
PETER PIPER PICKED A PECK OF PICKLED PEPPERS. A PECK OF PICKLED PEPPERS
PETER PIPER PICKED. IF PETER PIPER PICKED A PECK OF PICKLED PEPPERS, WHERE'S
THE PECK OF PICKLED PEPPERS PETER PIPER PICKED?
Peter: Gyogyo, the lines are separated, what do you do?
Dr .: Due to space limitations, there are only 3 lines, but think of it as a long line with a space instead of a newline character.
Peter: Yes, yes. There is a blank space between the lines. But it's a hassle ...
Dr .: Then why not let the program do it?
So, instead of Peter, create a program that converts the read character string into a code and outputs it.
input
Given multiple datasets. Each dataset is given a line of strings (consisting of the characters contained in the table). The string contains at least 1 and no more than 100 characters.
The number of datasets does not exceed 200.
output
For each data set, output the converted character string on one line.
Example
Input
PETER POTTER
Output
?D-C'KOPUA
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4⋅ LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D.
You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.
Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
If X is a string, |X| denotes its length.
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.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.
Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement.
You may wish to read the [Wikipedia page about the Longest Common Subsequence problem](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
Input
The first line contains two positive integers n and m (1 ≤ n, m ≤ 5000) — lengths of the two strings A and B.
The second line contains a string consisting of n lowercase Latin letters — string A.
The third line contains a string consisting of m lowercase Latin letters — string B.
Output
Output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B.
Examples
Input
4 5
abba
babab
Output
5
Input
8 10
bbbbabab
bbbabaaaaa
Output
12
Input
7 7
uiibwws
qhtkxcn
Output
0
Note
For the first case:
abb from the first string and abab from the second string have LCS equal to abb.
The result is S(abb, abab) = (4 ⋅ |abb|) - |abb| - |abab| = 4 ⋅ 3 - 3 - 4 = 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.
There are n rings in factory's stock. The i-th ring has inner radius a_{i}, outer radius b_{i} and height h_{i}. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied: Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if b_{j} ≤ b_{i}. Rings should not fall one into the the other. That means one can place ring j on the ring i only if b_{j} > a_{i}. The total height of all rings used should be maximum possible.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of rings in factory's stock.
The i-th of the next n lines contains three integers a_{i}, b_{i} and h_{i} (1 ≤ a_{i}, b_{i}, h_{i} ≤ 10^9, b_{i} > a_{i}) — inner radius, outer radius and the height of the i-th ring respectively.
-----Output-----
Print one integer — the maximum height of the tower that can be obtained.
-----Examples-----
Input
3
1 5 1
2 6 2
3 7 3
Output
6
Input
4
1 2 1
1 3 3
4 6 2
5 7 1
Output
4
-----Note-----
In the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.
In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 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.
Read problems statements in Mandarin Chinese , Russian and Vietnamese
A number is called palindromic if its decimal representation is a palindrome. You are given a range, described by a pair of integers L and R. Find the sum of all palindromic numbers lying in the range [L, R], inclusive of both the extrema.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a pair of space separated integers L and R denoting the range for which you are required to find the sum of the palindromic numbers.
------ Output ------
For each test case, output a single line containing the sum of all the palindromic numbers in the given range.
------ Constraints ------
$1 ≤ T ≤ 100$
$Subtask 1 (34 points) : 1 ≤ L ≤ R ≤ 10^{3}$
$Subtask 2 (66 points) : 1 ≤ L ≤ R ≤ 10^{5}$
----- Sample Input 1 ------
2
1 10
123 150
----- Sample Output 1 ------
45
272
----- explanation 1 ------
Example case 1. The palindromic numbers between 1 and 10 are all numbers except the number 10. Their sum is 45.
Example case 2. The palindromic numbers between 123 and 150 are 131 and 141 and their sum is 272.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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**
You are given a positive integer (`n`), and your task is to find the largest number **less than** `n`, which can be written in the form `a**b`, where `a` can be any non-negative integer and `b` is an integer greater than or equal to `2`. Try not to make the code time out :)
The input range is from `1` to `1,000,000`.
## **Return**
Return your answer in the form `(x, y)` or (`[x, y]`, depending on the language ), where `x` is the value of `a**b`, and `y` is the number of occurrences of `a**b`. By the way ** means ^ or power, so 2 ** 4 = 16.
If you are given a number less than or equal to `4`, that is not `1`, return `(1, -1)`, because there is an infinite number of values for it: `1**2, 1**3, 1**4, ...`.
If you are given `1`, return `(0, -1)`.
## **Examples**
```
3 --> (1, -1) # because it's less than 4
6 --> (4, 1) # because the largest such number below 6 is 4,
# and there is only one way to write it: 2**2
65 --> (64, 3) # because there are three occurrences of 64: 2**6, 4**3, 8**2
90 --> (81, 2) # because the largest such number below 90 is 81,
# and there are two ways of getting it: 3**4, 9**2
```
By the way, after finishing this kata, please try some of my other katas: [here.](https://www.codewars.com/collections/tonylicodings-authored-katas)
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one before and one after, with a space in between. The conversion method is to convert the character before the line in the conversion table to the character after each time it appears in the data and output it. It is converted only once, and even if the converted character becomes the character to be converted again, it is not converted. Characters that do not appear in the conversion table are not converted and are output as they are.
In the input file, the conversion table (first n + 1 line) is followed by the data to be converted (n + 2nd line and after). The number of lines in the conversion table is n on the first line, each line of the following n lines is two characters with a blank, and then the number of lines of data to be converted on the n + second line m, and each line of the following m lines. Is a single character. Let m ≤ 105. Output should be one line without blanks or line breaks as in the output example.
Input example
---
3
A a
0 5
5 4
Ten
A
B
C
0
1
Four
Five
a
b b
A
Output example
aBC5144aba
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
For each data set, the converted character string is output on one line.
Example
Input
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
3
A a
0 5
5 4
10
A
B
C
0
1
4
5
a
b
A
0
Output
aBC5144aba
aBC5144aba
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a tree consisting of $n$ vertices. A number is written on each vertex; the number on vertex $i$ is equal to $a_i$.
Recall that a simple path is a path that visits each vertex at most once. Let the weight of the path be the bitwise XOR of the values written on vertices it consists of. Let's say that a tree is good if no simple path has weight $0$.
You can apply the following operation any number of times (possibly, zero): select a vertex of the tree and replace the value written on it with an arbitrary positive integer. What is the minimum number of times you have to apply this operation in order to make the tree good?
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of vertices.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i < 2^{30}$) — the numbers written on vertices.
Then $n - 1$ lines follow, each containing two integers $x$ and $y$ ($1 \le x, y \le n; x \ne y$) denoting an edge connecting vertex $x$ with vertex $y$. It is guaranteed that these edges form a tree.
-----Output-----
Print a single integer — the minimum number of times you have to apply the operation in order to make the tree good.
-----Examples-----
Input
6
3 2 1 3 2 1
4 5
3 4
1 4
2 1
6 1
Output
2
Input
4
2 1 1 1
1 2
1 3
1 4
Output
0
Input
5
2 2 2 2 2
1 2
2 3
3 4
4 5
Output
2
-----Note-----
In the first example, it is enough to replace the value on the vertex $1$ with $13$, and the value on the vertex $4$ with $42$.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 game called "Unique Bid Auction". You can read more about it here:
https://en.wikipedia.org/wiki/Unique_bid_auction
(though you don't have to do it to solve this problem).
Let's simplify this game a bit. Formally, there are $n$ participants, the $i$-th participant chose the number $a_i$. The winner of the game is such a participant that the number he chose is unique (i. e. nobody else chose this number except him) and is minimal (i. e. among all unique values of $a$ the minimum one is the winning one).
Your task is to find the index of the participant who won the game (or -1 if there is no winner). Indexing is $1$-based, i. e. the participants are numbered from $1$ to $n$.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of participants. The second line of the test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th participant chosen number.
It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer — the index of the participant who won the game (or -1 if there is no winner). Note that the answer is always unique.
-----Examples-----
Input
6
2
1 1
3
2 1 3
4
2 2 2 3
1
1
5
2 3 2 4 2
6
1 1 5 5 4 4
Output
-1
2
4
1
2
-1
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.
Fortunately the child knows how to solve such complicated test. The child will follow the algorithm:
If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great. If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).
You are given a multiple-choice questions, can you predict child's choose?
-----Input-----
The first line starts with "A." (without quotes), then followed the description of choice A. The next three lines contains the descriptions of the other choices in the same format. They are given in order: B, C, D. Please note, that the description goes after prefix "X.", so the prefix mustn't be counted in description's length.
Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_".
-----Output-----
Print a single line with the child's choice: "A", "B", "C" or "D" (without quotes).
-----Examples-----
Input
A.VFleaKing_is_the_author_of_this_problem
B.Picks_is_the_author_of_this_problem
C.Picking_is_the_author_of_this_problem
D.Ftiasch_is_cute
Output
D
Input
A.ab
B.abcde
C.ab
D.abc
Output
C
Input
A.c
B.cc
C.c
D.c
Output
B
-----Note-----
In the first sample, the first choice has length 39, the second one has length 35, the third one has length 37, and the last one has length 15. The choice D (length 15) is twice shorter than all other choices', so it is great choice. There is no other great choices so the child will choose D.
In the second sample, no choice is great, so the child will choose the luckiest choice C.
In the third sample, the choice B (length 2) is twice longer than all other choices', so it is great choice. There is no other great choices so the child will choose 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.
Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.
The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x, y) to one of these four points: to point (x - 1, y) which we will mark by letter "L", to point (x + 1, y) — "R", to point (x, y - 1) — "D", to point (x, y + 1) — "U".
The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".
You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0, 0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of the car's movements from the headquarters to the stall.
Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR".
All movements are given in chronological order.
Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.
Output
Print a single integer — the number of different possible locations of the gang's headquarters.
Examples
Input
3
UR
UL
ULDR
Output
9
Input
2
DR
DL
Output
4
Note
The figure below shows the nine possible positions of the gang headquarters from the first sample:
<image>
For example, the following movements can get the car from point (1, 0) to point (0, 0):
<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.
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the following sequence of numbers: firstly all odd integers from 1 to n (in ascending order), then all even integers from 1 to n (also in ascending order). Help our hero to find out which number will stand at the position number k.
-----Input-----
The only line of input contains integers n and k (1 ≤ k ≤ n ≤ 10^12).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print the number that will stand at the position number k after Volodya's manipulations.
-----Examples-----
Input
10 3
Output
5
Input
7 7
Output
6
-----Note-----
In the first sample Volodya's sequence will look like this: {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}. The third place in the sequence is therefore occupied by the number 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.
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position $x = 0$. Mezo starts sending $n$ commands to Zoma. There are two possible commands: 'L' (Left) sets the position $x: =x - 1$; 'R' (Right) sets the position $x: =x + 1$.
Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position $x$ doesn't change and Mezo simply proceeds to the next command.
For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position $0$; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position $0$ as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position $-2$.
Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.
-----Input-----
The first line contains $n$ $(1 \le n \le 10^5)$ — the number of commands Mezo sends.
The second line contains a string $s$ of $n$ commands, each either 'L' (Left) or 'R' (Right).
-----Output-----
Print one integer — the number of different positions Zoma may end up at.
-----Example-----
Input
4
LRLR
Output
5
-----Note-----
In the example, Zoma may end up anywhere between $-2$ and $2$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have $n$ stacks of blocks. The $i$-th stack contains $h_i$ blocks and it's height is the number of blocks in it. In one move you can take a block from the $i$-th stack (if there is at least one block) and put it to the $i + 1$-th stack. Can you make the sequence of heights strictly increasing?
Note that the number of stacks always remains $n$: stacks don't disappear when they have $0$ blocks.
-----Input-----
First line contains a single integer $t$ $(1 \leq t \leq 10^4)$ — the number of test cases.
The first line of each test case contains a single integer $n$ $(1 \leq n \leq 100)$. The second line of each test case contains $n$ integers $h_i$ $(0 \leq h_i \leq 10^9)$ — starting heights of the stacks.
It's guaranteed that the sum of all $n$ does not exceed $10^4$.
-----Output-----
For each test case output YES if you can make the sequence of heights strictly increasing and NO otherwise.
You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).
-----Examples-----
Input
6
2
1 2
2
1 0
3
4 4 4
2
0 0
3
0 1 0
4
1000000000 1000000000 1000000000 1000000000
Output
YES
YES
YES
NO
NO
YES
-----Note-----
In the first test case there is no need to make any moves, the sequence of heights is already increasing.
In the second test case we need to move one block from the first stack to the second. Then the heights become $0$ $1$.
In the third test case we could move one block from the first stack to the second and then from the second to the third, which would make the heights $3$ $4$ $5$.
In the fourth test case we can't make a move, but the sequence is not increasing, so the answer is NO.
In the fifth test case we can only make one move (from the second to the third stack), which would make the heights $0$ $0$ $1$. Both $0$ $1$ $0$ and $0$ $0$ $1$ are not increasing sequences, so the answer is 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.
Taro made a sugoroku so that everyone can play at the children's association event. In order to make the game interesting, I wrote instructions such as "advance 6" and "back 5" in some of the sugoroku squares other than "Furidashi" and "Agari". Turn the roulette wheel to advance as many times as you can, and if an instruction is written on the stopped square, move according to that instruction. However, it does not follow the instructions of the squares that proceeded according to the instructions.
Roulette shall be able to give a number between 1 and a certain number with equal probability. Also, if you get a larger number than you reach "Agari", or if you follow the instructions and you go beyond "Agari", you will move to "Agari". If you follow the instructions and return before "Furidashi", you will return to "Furidashi".
<image>
However, depending on the instructions of the roulette wheel and the square, it may not be possible to reach the "rise". For example, let's say you made a sugoroku like the one shown in the figure. If you use a roulette wheel that only gives 1 and 2, you can go to "Agari" if you come out in the order of 1 and 2, but if you get 2 first, you will not be able to reach "Agari" forever no matter what comes out. Taro didn't know that and wrote instructions in various squares.
Therefore, on behalf of Taro, please create a program to determine whether or not you may not be able to reach the "rise" depending on the instructions of the roulette and the square.
input
The input consists of multiple datasets. The end of the input is indicated by a single zero line. Each dataset is given in the following format.
max
n
d1
d2
..
..
..
dn
The first line gives the maximum number of roulette wheels max (2 ≤ max ≤ 250), and the second line gives the number of cells other than "starting" and "rising" n (2 ≤ n ≤ 250). .. The next n lines are given the number di (-n ≤ di ≤ n) that represents the indication for each cell. When di is zero, it means that no instruction is written, when it is a positive number, it means | di | forward instruction, and when it is negative, it means | di | back instruction (where | x | is x). Represents an absolute value). All values entered are integers.
The number of datasets does not exceed 100.
output
The judgment result is output to one line for each data set. Depending on the instructions of the roulette and the square, if it may not be possible to reach the "go up", "NG" is output, otherwise "OK" is output.
Example
Input
3
3
-2
1
0
2
4
2
0
-1
-2
2
2
-2
-2
0
Output
OK
NG
NG
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):
* point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y
* point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y
* point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y
* point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y
We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.
Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
Input
The first input line contains the only integer n (1 ≤ n ≤ 200) — the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| ≤ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.
Output
Print the only number — the number of supercentral points of the given set.
Examples
Input
8
1 1
4 2
3 1
1 2
0 2
0 1
1 0
1 3
Output
2
Input
5
0 0
0 1
1 0
0 -1
-1 0
Output
1
Note
In the first sample the supercentral points are only points (1, 1) and (1, 2).
In the second sample there is one supercental point — point (0, 0).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
<image>
My grandmother uses a balance. The balance will balance if you place the same size on both of the two dishes, otherwise it will tilt to the heavier side. The weights of the 10 weights are 1g, 2g, 4g, 8g, 16g, 32g, 64g, 128g, 256g, 512g in order of lightness.
My grandmother says, "Weigh up to about 1 kg in grams." "Then, try to weigh the juice here," and my grandmother put the juice on the left plate and the 8g, 64g, and 128g weights on the right plate to balance. Then he answered, "The total weight is 200g, so the juice is 200g. How is it correct?"
Since the weight of the item to be placed on the left plate is given, create a program that outputs the weight to be placed on the right plate in order of lightness when balancing with the item of the weight given by the balance. However, the weight of the item to be weighed shall be less than or equal to the total weight of all weights (= 1023g).
Hint
The weight of the weight is 2 to the nth power (n = 0, 1, .... 9) g.
Input
Given multiple datasets. For each dataset, the weight of the item to be placed on the left plate is given in one line. Please process until the end of the input. The number of datasets does not exceed 50.
Output
For each data set, separate the weights (ascending order) to be placed on the right plate with one blank and output them on one line.
Example
Input
5
7
127
Output
1 4
1 2 4
1 2 4 8 16 32 64
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.
Help Pasha count the maximum number he can get if he has the time to make at most k swaps.
-----Input-----
The single line contains two integers a and k (1 ≤ a ≤ 10^18; 0 ≤ k ≤ 100).
-----Output-----
Print the maximum number that Pasha can get if he makes at most k swaps.
-----Examples-----
Input
1990 1
Output
9190
Input
300 0
Output
300
Input
1034 2
Output
3104
Input
9090000078001234 6
Output
9907000008001234
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Omkar is creating a mosaic using colored square tiles, which he places in an n × n grid. When the mosaic is complete, each cell in the grid will have either a glaucous or sinoper tile. However, currently he has only placed tiles in some cells.
A completed mosaic will be a mastapeece if and only if each tile is adjacent to exactly 2 tiles of the same color (2 tiles are adjacent if they share a side.) Omkar wants to fill the rest of the tiles so that the mosaic becomes a mastapeece. Now he is wondering, is the way to do this unique, and if it is, what is it?
Input
The first line contains a single integer n (1 ≤ n ≤ 2000).
Then follow n lines with n characters in each line. The i-th character in the j-th line corresponds to the cell in row i and column j of the grid, and will be S if Omkar has placed a sinoper tile in this cell, G if Omkar has placed a glaucous tile, . if it's empty.
Output
On the first line, print UNIQUE if there is a unique way to get a mastapeece, NONE if Omkar cannot create any, and MULTIPLE if there is more than one way to do so. All letters must be uppercase.
If you print UNIQUE, then print n additional lines with n characters in each line, such that the i-th character in the j^{th} line is S if the tile in row i and column j of the mastapeece is sinoper, and G if it is glaucous.
Examples
Input
4
S...
..G.
....
...S
Output
MULTIPLE
Input
6
S.....
....G.
..S...
.....S
....G.
G.....
Output
NONE
Input
10
.S....S...
..........
...SSS....
..........
..........
...GS.....
....G...G.
..........
......G...
..........
Output
UNIQUE
SSSSSSSSSS
SGGGGGGGGS
SGSSSSSSGS
SGSGGGGSGS
SGSGSSGSGS
SGSGSSGSGS
SGSGGGGSGS
SGSSSSSSGS
SGGGGGGGGS
SSSSSSSSSS
Input
1
.
Output
NONE
Note
For the first test case, Omkar can make the mastapeeces
SSSS
SGGS
SGGS
SSSS
and
SSGG
SSGG
GGSS
GGSS.
For the second test case, it can be proven that it is impossible for Omkar to add tiles to create a mastapeece.
For the third case, it can be proven that the given mastapeece is the only mastapeece Omkar can create by adding tiles.
For the fourth test case, it's clearly impossible for the only tile in any mosaic Omkar creates to be adjacent to two tiles of the same color, as it will be adjacent to 0 tiles total.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Aiz Onsen has a bathhouse and a pool. To use the bathhouse, you need to buy a bathing ticket, and to use the pool, you need to buy a pool ticket. Prices for these tickets may vary from day to day. In addition, Aiz Onsen has the following rules.
* Tickets are valid only once on the day of purchase.
* If you buy 5 or more bathing tickets and 2 or more pool tickets at once, you will get a 20% discount on all tickets.
Sadayoshi, who loves hot springs, and his friends go to Aiz Onsen almost every day. They are all capricious and use different numbers from day to day. Aiz Onsen has discount rules, so if you work together as a group and buy well, you may be able to reduce the total price.
Create a program that outputs the cheapest total price when the bathing ticket and pool ticket charges, the number of bathing tickets to be used and the number of pool tickets are given as inputs. However, if buying more tickets than you use will reduce the total price, you do not have to use all the tickets you bought.
input
The input is given in the following format.
N
x1 y1 b1 p1
x2 y2 b2 p2
::
xN yN bN pN
N (1 ≤ N ≤ 365) on the first line is the number of days for which you want to calculate the charge. In the next N lines, the bathing ticket fee xi (100 ≤ xi ≤ 1000) for the i-day day, the pool ticket fee yi (100 ≤ yi ≤ 1000), the number of bathing tickets used bi (0 ≤ bi ≤ 6), The number of pool tickets to use pi (0 ≤ pi ≤ 6) is given. Both bathing tickets and pool tickets are charged in increments of 50 yen.
output
Print the cheapest total price on one line for each day.
Example
Input
2
100 100 1 1
1000 500 5 2
Output
200
4800
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.
A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $n$ stairs, then it is made of $n$ columns, the first column is $1$ cell high, the second column is $2$ cells high, $\ldots$, the $n$-th column if $n$ cells high. The lowest cells of all stairs must be in the same row.
A staircase with $n$ stairs is called nice, if it may be covered by $n$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $7$ stairs looks like: [Image]
Find out the maximal number of different nice staircases, that can be built, using no more than $x$ cells, in total. No cell can be used more than once.
-----Input-----
The first line contains a single integer $t$ $(1 \le t \le 1000)$ — the number of test cases.
The description of each test case contains a single integer $x$ $(1 \le x \le 10^{18})$ — the number of cells for building staircases.
-----Output-----
For each test case output a single integer — the number of different nice staircases, that can be built, using not more than $x$ cells, in total.
-----Example-----
Input
4
1
8
6
1000000000000000000
Output
1
2
1
30
-----Note-----
In the first test case, it is possible to build only one staircase, that consists of $1$ stair. It's nice. That's why the answer is $1$.
In the second test case, it is possible to build two different nice staircases: one consists of $1$ stair, and another consists of $3$ stairs. This will cost $7$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $2$.
In the third test case, it is possible to build only one of two nice staircases: with $1$ stair or with $3$ stairs. In the first case, there will be $5$ cells left, that may be used only to build a staircase with $2$ stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is $1$. If Jett builds a staircase with $3$ stairs, then there are no more cells left, so the answer is $1$ again.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$.
Your problem is to find such pair of indices $i, j$ ($1 \le i < j \le n$) that $lcm(a_i, a_j)$ is minimum possible.
$lcm(x, y)$ is the least common multiple of $x$ and $y$ (minimum positive number such that both $x$ and $y$ are divisors of this number).
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 10^6$) — the number of elements in $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^7$), where $a_i$ is the $i$-th element of $a$.
-----Output-----
Print two integers $i$ and $j$ ($1 \le i < j \le n$) such that the value of $lcm(a_i, a_j)$ is minimum among all valid pairs $i, j$. If there are multiple answers, you can print any.
-----Examples-----
Input
5
2 4 8 3 6
Output
1 2
Input
5
5 2 11 3 7
Output
2 4
Input
6
2 5 10 1 10 2
Output
1 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.
Today, as a friendship gift, Bakry gave Badawy $n$ integers $a_1, a_2, \dots, a_n$ and challenged him to choose an integer $X$ such that the value $\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$ is minimum possible, where $\oplus$ denotes the bitwise XOR operation.
As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of $\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$.
-----Input-----
The first line contains integer $n$ ($1\le n \le 10^5$).
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2^{30}-1$).
-----Output-----
Print one integer — the minimum possible value of $\underset{1 \leq i \leq n}{\max} (a_i \oplus X)$.
-----Examples-----
Input
3
1 2 3
Output
2
Input
2
1 5
Output
4
-----Note-----
In the first sample, we can choose $X = 3$.
In the second sample, we can choose $X = 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.
Taro has decided to move. Taro has a lot of luggage, so I decided to ask a moving company to carry the luggage. Since there are various weights of luggage, I asked them to arrange them in order from the lightest one for easy understanding, but the mover left the luggage in a different order. So Taro tried to sort the luggage, but the luggage is heavy and requires physical strength to carry. Each piece of luggage can be carried from where it is now to any place you like, such as between other pieces of luggage or at the edge of the piece of luggage, but carrying one piece of luggage uses as much physical strength as the weight of that piece of luggage. Taro doesn't have much physical strength, so I decided to think of a way to arrange the luggage in order from the lightest one without using as much physical strength as possible.
Constraints
> 1 ≤ n ≤ 105
> 1 ≤ xi ≤ n (1 ≤ i ≤ n)
> xi ≠ xj (1 ≤ i, j ≤ n and i ≠ j)
>
* All inputs are given as integers
Input
> n
> x1 x2 ... xn
>
* n represents the number of luggage that Taro has
* x1 to xn represent the weight of each piece of luggage, and are currently arranged in the order of x1, x2, ..., xn.
Output
> S
>
* Output the total S of the minimum physical strength required to arrange the luggage in order from the lightest, but output the line break at the end
Examples
Input
4
1 4 2 3
Output
4
Input
5
1 5 3 2 4
Output
7
Input
7
1 2 3 4 5 6 7
Output
0
Input
8
6 2 1 3 8 5 4 7
Output
19
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two moving objects A and B are moving accross the same orbit (those can be anything: two planets, two satellites, two spaceships,two flying saucers, or spiderman with batman if you prefer).
If the two objects start to move from the same point and the orbit is circular, write a function that gives the time the two objects will meet again, given the time the objects A and B need to go through a full orbit, Ta and Tb respectively, and the radius of the orbit r.
As there can't be negative time, the sign of Ta and Tb, is an indication of the direction in which the object moving: positive for clockwise and negative for anti-clockwise.
The function will return a string that gives the time, in two decimal points.
Ta and Tb will have the same unit of measurement so you should not expect it in the solution.
Hint: Use angular velocity "w" rather than the classical "u".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|.
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.
Input
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Output
Print the lexicographically maximum subsequence of string s.
Examples
Input
ababba
Output
bbba
Input
abbcbccacbbcbaaba
Output
cccccbba
Note
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).
The first sample: aBaBBA
The second sample: abbCbCCaCbbCBaaBA
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For given a circle $c$ and a line $l$, print the coordinates of the cross points of them.
Constraints
* $p1$ and $p2$ are different
* The circle and line have at least one cross point
* $1 \leq q \leq 1,000$
* $-10,000 \leq cx, cy, x1, y1, x2, y2 \leq 10,000$
* $1 \leq r \leq 10,000$
Input
The input is given in the following format.
$cx\; cy\; r$
$q$
$Line_1$
$Line_2$
:
$Line_q$
In the first line, the center coordinate of the circle and its radius are given by $cx$, $cy$ and $r$. In the second line, the number of queries $q$ is given.
In the following $q$ lines, as queries, $Line_i$ are given ($1 \leq i \leq q$) in the following format.
$x_1\; y_1\; x_2\; y_2$
Each line is represented by two points $p1$ and $p2$ which the line crosses. The coordinate of $p1$ and $p2$ are given by ($x1$, $y1$) and ($x2$, $y2$) respectively. All input values are given in integers.
Output
For each query, print the coordinates of the cross points in the following rules.
* If there is one cross point, print two coordinates with the same values.
* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.
The output values should be in a decimal fraction with an error less than 0.000001.
Example
Input
2 1 1
2
0 1 4 1
3 0 3 3
Output
1.00000000 1.00000000 3.00000000 1.00000000
3.00000000 1.00000000 3.00000000 1.00000000
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.
Find the size of the maximum clique in such graph.
Input
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.
Output
Print a single number — the number of vertexes in the maximum clique of the given graph.
Examples
Input
4
2 3
3 1
6 1
0 2
Output
3
Note
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test.
<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.
----- Statement -----
You need to find a string which has exactly K positions in it such that the character at that position comes alphabetically later than the character immediately after it. If there are many such strings, print the one which has the shortest length. If there is still a tie, print the string which comes the lexicographically earliest (would occur earlier in a dictionary).
-----Input-----
The first line contains the number of test cases T. Each test case contains an integer K (≤ 100).
-----Output-----
Output T lines, one for each test case, containing the required string. Use only lower-case letters a-z.
-----Sample Input -----
2
1
2
-----Sample Output-----
ba
cba
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a and b can be either painted Red or Blue.
After her painting is done, she will get p chocolates for each tile that is painted Red and q chocolates for each tile that is painted Blue.
Note that she can paint tiles in any order she wants.
Given the required information, find the maximum number of chocolates Joty can get.
-----Input-----
The only line contains five integers n, a, b, p and q (1 ≤ n, a, b, p, q ≤ 10^9).
-----Output-----
Print the only integer s — the maximum number of chocolates Joty can get.
Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.
-----Examples-----
Input
5 2 3 12 15
Output
39
Input
20 2 3 3 5
Output
51
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Remove Duplicates
You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be that 52 appears before 10 in the returned array.
## Assumptions
* All values given are integers (they can be positive or negative).
* You are given an array but it may be empty.
* They array may have duplicates or it may not.
## Example
```python
print unique([1, 5, 2, 0, 2, -3, 1, 10])
[1, 5, 2, 0, -3, 10]
print unique([])
[]
print unique([5, 2, 1, 3])
[5, 2, 1, 3]
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are a number of ways to shuffle a deck of cards. Hanafuda shuffling for Japanese card game 'Hanafuda' is one such example. The following is how to perform Hanafuda shuffling.
There is a deck of n cards. Starting from the p-th card from the top of the deck, c cards are pulled out and put on the top of the deck, as shown in Figure 1. This operation, called a cutting operation, is repeated.
Write a program that simulates Hanafuda shuffling and answers which card will be finally placed on the top of the deck.
<image>
---
Figure 1: Cutting operation
Input
The input consists of multiple data sets. Each data set starts with a line containing two positive integers n (1 <= n <= 50) and r (1 <= r <= 50); n and r are the number of cards in the deck and the number of cutting operations, respectively.
There are r more lines in the data set, each of which represents a cutting operation. These cutting operations are performed in the listed order. Each line contains two positive integers p and c (p + c <= n + 1). Starting from the p-th card from the top of the deck, c cards should be pulled out and put on the top.
The end of the input is indicated by a line which contains two zeros.
Each input line contains exactly two integers separated by a space character. There are no other characters in the line.
Output
For each data set in the input, your program should write the number of the top card after the shuffle. Assume that at the beginning the cards are numbered from 1 to n, from the bottom to the top. Each number should be written in a separate line without any superfluous characters such as leading or following spaces.
Example
Input
5 2
3 1
3 1
10 3
1 10
10 1
8 3
0 0
Output
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.
Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.
A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.[Image]
Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.
Please, tell Ciel if she can draw the crosses in the described way.
-----Input-----
The first line contains an integer n (3 ≤ n ≤ 100) — the size of the board.
Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.
-----Output-----
Output a single line with "YES" if Ciel can draw the crosses in the described way. Otherwise output a single line with "NO".
-----Examples-----
Input
5
.#...
####.
.####
...#.
.....
Output
YES
Input
4
####
####
####
####
Output
NO
Input
6
.#....
####..
.####.
.#.##.
######
.#..#.
Output
YES
Input
6
.#..#.
######
.####.
.####.
######
.#..#.
Output
NO
Input
3
...
...
...
Output
YES
-----Note-----
In example 1, you can draw two crosses. The picture below shows what they look like.[Image]
In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 enthusiastic about the popular web game "Moonlight Ranch". The purpose of this game is to grow crops in the fields, sell them to earn income, and use that income to grow the ranch.
You wanted to grow the field quickly. Therefore, we decided to arrange the crops that can be grown in the game based on the income efficiency per hour.
You have to buy seeds to grow crops. Here, the name of the species of crop i is given by Li, and the price is given by Pi. When seeds are planted in the field, they sprout after time Ai. Young leaves appear 2 hours after the buds emerge. The leaves grow thick after Ci. The flowers bloom 10 hours after the leaves grow. Fruits come out time Ei after the flowers bloom. One seed produces Fi fruits, each of which sells at the price of Si. Some crops are multi-stage crops and bear a total of Mi fruit. In the case of a single-stage crop, it is represented by Mi = 1. Multi-season crops return to leaves after fruiting until the Mith fruit. The income for a seed is the amount of money sold for all the fruits of that seed minus the price of the seed. In addition, the income efficiency of the seed is the value obtained by dividing the income by the time from planting the seed to the completion of all the fruits.
Your job is to write a program that sorts and outputs crop information given as input, sorted in descending order of income efficiency.
Input
The input is a sequence of datasets, and each dataset is given in the following format.
> N
> L1 P1 A1 B1 C1 D1 E1 F1 S1 M1
> L2 P2 A2 B2 C2 D2 E2 F2 S2 M2
> ...
> LN PN AN BN CN DN EN FN SN MN
>
The first line is the number of crops N in the dataset (1 ≤ N ≤ 50).
The N lines that follow contain information about one crop in each line. The meaning of each variable is as described in the problem statement. The crop name Li is a string of up to 20 characters consisting of only lowercase letters, and 1 ≤ Pi, Ai, Bi, Ci, Di, Ei, Fi, Si ≤ 100, 1 ≤ Mi ≤ 5. It can be assumed that no crop has the same name in one case.
The end of the input is represented by a line containing only one zero.
Output
For each dataset, output the crop names, one for each row, in descending order of income efficiency. For crops with the same income efficiency, output their names in ascending dictionary order.
After the output of each data set, output one line consisting of only "#".
Example
Input
5
apple 1 1 1 1 1 1 1 10 1
banana 1 2 2 2 2 2 1 10 1
carrot 1 2 2 2 2 2 1 10 2
durian 1 3 3 3 3 3 1 10 1
eggplant 1 3 3 3 3 3 1 100 1
4
enoki 1 3 3 3 3 3 1 10 1
tomato 1 3 3 3 3 3 1 10 1
potato 1 3 3 3 3 3 1 10 1
onion 1 3 3 3 3 3 1 10 1
3
a 10 1 1 1 1 1 1 10 1
b 10 2 2 2 2 2 2 10 1
c 10 2 2 2 2 2 2 10 1
0
Output
eggplant
apple
carrot
banana
durian
#
enoki
onion
potato
tomato
#
b
c
a
#
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a permutation p_1, p_2, …, p_n.
In one move you can swap two adjacent values.
You want to perform a minimum number of moves, such that in the end there will exist a subsegment 1,2,…, k, in other words in the end there should be an integer i, 1 ≤ i ≤ n-k+1 such that p_i = 1, p_{i+1} = 2, …, p_{i+k-1}=k.
Let f(k) be the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation.
You need to find f(1), f(2), …, f(n).
Input
The first line of input contains one integer n (1 ≤ n ≤ 200 000): the number of elements in the permutation.
The next line of input contains n integers p_1, p_2, …, p_n: given permutation (1 ≤ p_i ≤ n).
Output
Print n integers, the minimum number of moves that you need to make a subsegment with values 1,2,…,k appear in the permutation, for k=1, 2, …, n.
Examples
Input
5
5 4 3 2 1
Output
0 1 3 6 10
Input
3
1 2 3
Output
0 0 0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size $n \times m$ cells on a map (rows of grid are numbered from $1$ to $n$ from north to south, and columns are numbered from $1$ to $m$ from west to east). After that he measured the average height of each cell above Rybinsk sea level and obtained a matrix of heights of size $n \times m$. The cell $(i, j)$ lies on the intersection of the $i$-th row and the $j$-th column and has height $h_{i, j}$.
Seryozha is going to look at the result of his work in the browser. The screen of Seryozha's laptop can fit a subrectangle of size $a \times b$ of matrix of heights ($1 \le a \le n$, $1 \le b \le m$). Seryozha tries to decide how the weather can affect the recreation center — for example, if it rains, where all the rainwater will gather. To do so, he is going to find the cell having minimum height among all cells that are shown on the screen of his laptop.
Help Seryozha to calculate the sum of heights of such cells for all possible subrectangles he can see on his screen. In other words, you have to calculate the sum of minimum heights in submatrices of size $a \times b$ with top left corners in $(i, j)$ over all $1 \le i \le n - a + 1$ and $1 \le j \le m - b + 1$.
Consider the sequence $g_i = (g_{i - 1} \cdot x + y) \bmod z$. You are given integers $g_0$, $x$, $y$ and $z$. By miraculous coincidence, $h_{i, j} = g_{(i - 1) \cdot m + j - 1}$ ($(i - 1) \cdot m + j - 1$ is the index).
-----Input-----
The first line of the input contains four integers $n$, $m$, $a$ and $b$ ($1 \le n, m \le 3\,000$, $1 \le a \le n$, $1 \le b \le m$) — the number of rows and columns in the matrix Seryozha has, and the number of rows and columns that can be shown on the screen of the laptop, respectively.
The second line of the input contains four integers $g_0$, $x$, $y$ and $z$ ($0 \le g_0, x, y < z \le 10^9$).
-----Output-----
Print a single integer — the answer to the problem.
-----Example-----
Input
3 4 2 1
1 2 3 59
Output
111
-----Note-----
The matrix from the first example: $\left. \begin{array}{|c|c|c|c|} \hline 1 & {5} & {13} & {29} \\ \hline 2 & {7} & {17} & {37} \\ \hline 18 & {39} & {22} & {47} \\ \hline \end{array} \right.$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Natasha is planning an expedition to Mars for $n$ people. One of the important tasks is to provide food for each participant.
The warehouse has $m$ daily food packages. Each package has some food type $a_i$.
Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the same food type throughout the expedition. Different participants may eat different (or the same) types of food.
Formally, for each participant $j$ Natasha should select his food type $b_j$ and each day $j$-th participant will eat one food package of type $b_j$. The values $b_j$ for different participants may be different.
What is the maximum possible number of days the expedition can last, following the requirements above?
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 100$, $1 \le m \le 100$) — the number of the expedition participants and the number of the daily food packages available.
The second line contains sequence of integers $a_1, a_2, \dots, a_m$ ($1 \le a_i \le 100$), where $a_i$ is the type of $i$-th food package.
-----Output-----
Print the single integer — the number of days the expedition can last. If it is not possible to plan the expedition for even one day, print 0.
-----Examples-----
Input
4 10
1 5 2 1 1 1 2 5 7 2
Output
2
Input
100 1
1
Output
0
Input
2 5
5 4 3 2 1
Output
1
Input
3 9
42 42 42 42 42 42 42 42 42
Output
3
-----Note-----
In the first example, Natasha can assign type $1$ food to the first participant, the same type $1$ to the second, type $5$ to the third and type $2$ to the fourth. In this case, the expedition can last for $2$ days, since each participant can get two food packages of his food type (there will be used $4$ packages of type $1$, two packages of type $2$ and two packages of type $5$).
In the second example, there are $100$ participants and only $1$ food package. In this case, the expedition can't last even $1$ 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.
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.
You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.
If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.
Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^8), where a_{i} represents the amount of power required for the i-th task.
The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 100), where b_{i} is the number of processors that i-th task will utilize.
-----Output-----
Print a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.
-----Examples-----
Input
6
8 10 9 9 8 10
1 1 1 1 1 1
Output
9000
Input
6
8 10 9 9 8 10
1 10 5 5 1 10
Output
1160
-----Note-----
In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.
In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X.
You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required.
* Choose an integer i such that 1\leq i\leq N-1. Replace the value of X_{i+1} with the value of X_i plus 1.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9(1\leq i\leq N)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
If we can make X equal to A by repeating the operation, print the minimum number of operations required. If we cannot, print -1.
Examples
Input
4
0
1
1
2
Output
3
Input
3
1
2
1
Output
-1
Input
9
0
1
1
0
1
2
2
1
2
Output
8
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you.
Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers.
Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 12) — the number of pairs the first participant communicated to the second and vice versa.
The second line contains n pairs of integers, each between 1 and 9, — pairs of numbers communicated from first participant to the second.
The third line contains m pairs of integers, each between 1 and 9, — pairs of numbers communicated from the second participant to the first.
All pairs within each set are distinct (in particular, if there is a pair (1,2), there will be no pair (2,1) within the same set), and no pair contains the same number twice.
It is guaranteed that the two sets do not contradict the statements, in other words, there is pair from the first set and a pair from the second set that share exactly one number.
Output
If you can deduce the shared number with certainty, print that number.
If you can with certainty deduce that both participants know the shared number, but you do not know it, print 0.
Otherwise print -1.
Examples
Input
2 2
1 2 3 4
1 5 3 4
Output
1
Input
2 2
1 2 3 4
1 5 6 4
Output
0
Input
2 3
1 2 4 5
1 2 1 3 2 3
Output
-1
Note
In the first example the first participant communicated pairs (1,2) and (3,4), and the second communicated (1,5), (3,4). Since we know that the actual pairs they received share exactly one number, it can't be that they both have (3,4). Thus, the first participant has (1,2) and the second has (1,5), and at this point you already know the shared number is 1.
In the second example either the first participant has (1,2) and the second has (1,5), or the first has (3,4) and the second has (6,4). In the first case both of them know the shared number is 1, in the second case both of them know the shared number is 4. You don't have enough information to tell 1 and 4 apart.
In the third case if the first participant was given (1,2), they don't know what the shared number is, since from their perspective the second participant might have been given either (1,3), in which case the shared number is 1, or (2,3), in which case the shared number is 2. While the second participant does know the number with certainty, neither you nor the first participant do, so the output is -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.
Consider the number triangle below, in which each number is equal to the number above plus the number to the left. If there is no number above, assume it's a `0`.
The triangle has `5` rows and the sum of the last row is `sum([1,4,9,14,14]) = 42`.
You will be given an integer `n` and your task will be to return the sum of the last row of a triangle of `n` rows.
In the example above:
More examples in test cases. Good luck!
```if:javascript
### Note
This kata uses native arbitrary precision integer numbers ( `BigInt`, `1n` ).
Unfortunately, the testing framework and even native `JSON` do not fully support them yet.
`console.log(1n)` and `(1n).toString()` work and can be used for debugging.
We apologise for the inconvenience.
```
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.
Input
The first input line contains integer k (1 ≤ k ≤ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000, where |s| is the length of string s.
Output
Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them.
If the solution doesn't exist, print "-1" (without quotes).
Examples
Input
2
aazz
Output
azaz
Input
3
abcabcabz
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The AKS algorithm for testing whether a number is prime is a polynomial-time test based on the following theorem:
A number p is prime if and only if all the coefficients of the polynomial expansion of `(x − 1)^p − (x^p − 1)` are divisible by `p`.
For example, trying `p = 3`:
(x − 1)^3 − (x^3 − 1) = (x^3 − 3x^2 + 3x − 1) − (x^3 − 1) = − 3x^2 + 3x
And all the coefficients are divisible by 3, so 3 is prime.
Your task is to code the test function, wich will be given an integer and should return true or false based on the above theorem. You should efficiently calculate every coefficient one by one and stop when a coefficient is not divisible by p to avoid pointless calculations. The easiest way to calculate coefficients is to take advantage of binomial coefficients: http://en.wikipedia.org/wiki/Binomial_coefficient and pascal triangle: http://en.wikipedia.org/wiki/Pascal%27s_triangle .
You should also take advantage of the symmetry of binomial coefficients. You can look at these kata: http://www.codewars.com/kata/pascals-triangle and http://www.codewars.com/kata/pascals-triangle-number-2
The kata here only use the simple theorem. The general AKS test is way more complex. The simple approach is a good exercie but impractical. The general AKS test will be the subject of another kata as it is one of the best performing primality test algorithms.
The main problem of this algorithm is the big numbers emerging from binomial coefficients in the polynomial expansion. As usual Javascript reach its limit on big integer very fast. (This simple algorithm is far less performing than a trivial algorithm here). You can compare the results with those of this kata: http://www.codewars.com/kata/lucas-lehmer-test-for-mersenne-primes Here, javascript can barely treat numbers bigger than 50, python can treat M13 but not M17.
Read the inputs from 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.