question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K.
Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square.
Below is an example of a checked pattern of side 3:
AtCoDeer has N desires.
The i-th desire is represented by x_i, y_i and c_i.
If c_i is B, it means that he wants to paint the square (x_i,y_i) black; if c_i is W, he wants to paint the square (x_i,y_i) white.
At most how many desires can he satisfy at the same time?
-----Constraints-----
- 1 ≤ N ≤ 10^5
- 1 ≤ K ≤ 1000
- 0 ≤ x_i ≤ 10^9
- 0 ≤ y_i ≤ 10^9
- If i ≠ j, then (x_i,y_i) ≠ (x_j,y_j).
- c_i is B or W.
- N, K, x_i and y_i are integers.
-----Input-----
Input is given from Standard Input in the following format:
N K
x_1 y_1 c_1
x_2 y_2 c_2
:
x_N y_N c_N
-----Output-----
Print the maximum number of desires that can be satisfied at the same time.
-----Sample Input-----
4 3
0 1 W
1 2 W
5 3 B
5 4 B
-----Sample Output-----
4
He can satisfy all his desires by painting as shown in the example above.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:
- Find the maximum value among the N-1 elements other than A_i in the sequence.
-----Constraints-----
- 2 \leq N \leq 200000
- 1 \leq A_i \leq 200000
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1
:
A_N
-----Output-----
Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.
-----Sample Input-----
3
1
4
3
-----Sample Output-----
4
3
4
- The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.
- The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.
- The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We arrange the numbers between 1 and N (1 <= N <= 10000) in increasing order and decreasing order like this:
1 2 3 4 5 6 7 8 9 . . . N
N . . . 9 8 7 6 5 4 3 2 1
Two numbers faced each other form a pair. Your task is to compute the number of pairs P such that both numbers in the pairs are prime.
Input
Input contains several test cases. Each test case consists of an integer N in one line.
Output
For each line of input, output P .
Example
Input
1
4
7
51
Output
0
2
2
6
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a string S representing the day of the week today.
S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.
After how many days is the next Sunday (tomorrow or later)?
-----Constraints-----
- S is SUN, MON, TUE, WED, THU, FRI, or SAT.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the number of days before the next Sunday.
-----Sample Input-----
SAT
-----Sample Output-----
1
It is Saturday today, and tomorrow will be Sunday.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?
-----Constraints-----
- 2 \leq N \leq 10^6
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the answer.
-----Sample Input-----
3
-----Sample Output-----
3
There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.
Let A be a set of positions in the string. Let's call it pretty if following conditions are met: letters on positions from A in the string are all distinct and lowercase; there are no uppercase letters in the string which are situated between positions from A (i.e. there is no such j that s[j] is an uppercase letter, and a_1 < j < a_2 for some a_1 and a_2 from A).
Write a program that will determine the maximum number of elements in a pretty set of positions.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 200) — length of string s.
The second line contains a string s consisting of lowercase and uppercase Latin letters.
-----Output-----
Print maximum number of elements in pretty set of positions for string s.
-----Examples-----
Input
11
aaaaBaabAbA
Output
2
Input
12
zACaAbbaazzC
Output
3
Input
3
ABC
Output
0
-----Note-----
In the first example the desired positions might be 6 and 8 or 7 and 8. Positions 6 and 7 contain letters 'a', position 8 contains letter 'b'. The pair of positions 1 and 8 is not suitable because there is an uppercase letter 'B' between these position.
In the second example desired positions can be 7, 8 and 11. There are other ways to choose pretty set consisting of three elements.
In the third example the given string s does not contain any lowercase letters, so the answer is 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.
Vitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number.
For example, let's say that Vitaly's favourite digits are 1 and 3, then number 12 isn't good and numbers 13 or 311 are. Also, number 111 is excellent and number 11 isn't.
Now Vitaly is wondering, how many excellent numbers of length exactly n are there. As this number can be rather large, he asks you to count the remainder after dividing it by 1000000007 (10^9 + 7).
A number's length is the number of digits in its decimal representation without leading zeroes.
-----Input-----
The first line contains three integers: a, b, n (1 ≤ a < b ≤ 9, 1 ≤ n ≤ 10^6).
-----Output-----
Print a single integer — the answer to the problem modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
1 3 3
Output
1
Input
2 3 10
Output
165
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Nova polynomial add
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5) )
Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. The first element is the zero order factor (the constant).
`p = [a0, a1, a2, a3]` signifies the polynomial `a0 + a1x + a2x^2 + a3*x^3`
In this kata add two polynomials:
```python
poly_add ( [1, 2], [1] ) = [2, 2]
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are positive integers A and B.
Let us choose some number of positive common divisors of A and B.
Here, any two of the chosen divisors must be coprime.
At most, how many divisors can we choose?Definition of common divisor
An integer d is said to be a common divisor of integers x and y when d divides both x and y.Definition of being coprime
Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.Definition of dividing
An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.
-----Constraints-----
- All values in input are integers.
- 1 \leq A, B \leq 10^{12}
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
Print the maximum number of divisors that can be chosen to satisfy the condition.
-----Sample Input-----
12 18
-----Sample Output-----
3
12 and 18 have the following positive common divisors: 1, 2, 3, and 6.
1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 program fails again. This time it gets "Wrong answer on test 233".
This is the easier version of the problem. In this version $1 \le n \le 2000$. You can hack this problem only if you solve and lock both problems.
The problem is about a test containing $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \dots, h_n$ are known to you in this problem.
However, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.
Formally, the mistake moves the answer for the question $i$ to the question $i \bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$.
We call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total.
You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\,244\,353$.
For example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.
-----Input-----
The first line contains two integers $n$, $k$ ($1 \le n \le 2000$, $1 \le k \le 10^9$) — the number of questions and the number of possible answers to each question.
The following line contains $n$ integers $h_1, h_2, \dots, h_n$, ($1 \le h_{i} \le k)$ — answers to the questions.
-----Output-----
Output one integer: the number of answers suits satisfying the given condition, modulo $998\,244\,353$.
-----Examples-----
Input
3 3
1 3 1
Output
9
Input
5 5
1 1 4 2 2
Output
1000
-----Note-----
For the first example, valid answer suits are $[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [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.
problem
A mysterious $ X $ [cm] plant grows in one place. This plant has the following mysterious properties.
* Say "nobiro" to this plant and it will grow $ A $ [cm].
* Say "tidime" to this plant and it will grow $ B $ [cm].
* If you say "karero" to this plant, it will be $ 0 $ [cm].
However, this plant does not have a negative length. Specifically, when it grows from the state of $ C $ [cm] to $ D $ [cm] $ (C + D \ lt 0) $, it is a plant. Stops growing when it reaches $ 0 $ [cm].
Say one of "nobiro", "tidime", "karero" to this plant only once a day for $ N $ days. Find the length [cm] of the plant after $ N $ days.
output
Print the length of the plant after $ N $ days. Also print a newline at the end.
Example
Input
10 30 10
3
nobiro
nobiro
tidime
Output
80
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai > qbi.
Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.
Input
The first input line contains integer n (1 ≤ n ≤ 1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0 ≤ qj ≤ 106)— the employees' qualifications. The following line contains number m (0 ≤ m ≤ 10000) — amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai, bi and ci (1 ≤ ai, bi ≤ n, 0 ≤ ci ≤ 106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai > qbi.
Output
Output the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.
Examples
Input
4
7 2 3 1
4
1 2 5
2 4 1
3 4 1
1 3 5
Output
11
Input
3
1 2 3
2
3 1 2
3 1 3
Output
-1
Note
In the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer 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.
There are $b$ boys and $g$ girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and $n$ participants have accepted the invitation. The organizers do not know how many boys and girls are among them.
Organizers are preparing red badges for girls and blue ones for boys.
Vasya prepared $n+1$ decks of badges. The $i$-th (where $i$ is from $0$ to $n$, inclusive) deck contains $i$ blue badges and $n-i$ red ones. The total number of badges in any deck is exactly $n$.
Determine the minimum number of decks among these $n+1$ that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament.
-----Input-----
The first line contains an integer $b$ ($1 \le b \le 300$), the number of boys.
The second line contains an integer $g$ ($1 \le g \le 300$), the number of girls.
The third line contains an integer $n$ ($1 \le n \le b + g$), the number of the board games tournament participants.
-----Output-----
Output the only integer, the minimum number of badge decks that Vasya could take.
-----Examples-----
Input
5
6
3
Output
4
Input
5
3
5
Output
4
-----Note-----
In the first example, each of 4 decks should be taken: (0 blue, 3 red), (1 blue, 2 red), (2 blue, 1 red), (3 blue, 0 red).
In the second example, 4 decks should be taken: (2 blue, 3 red), (3 blue, 2 red), (4 blue, 1 red), (5 blue, 0 red). Piles (0 blue, 5 red) and (1 blue, 4 red) can not be used.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob begin their day with a quick game. They first choose a starting number X0 ≥ 3 and try to reach one million by the process described below.
Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.
Formally, he or she selects a prime p < Xi - 1 and then finds the minimum Xi ≥ Xi - 1 such that p divides Xi. Note that if the selected prime p already divides Xi - 1, then the number does not change.
Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.
Input
The input contains a single integer X2 (4 ≤ X2 ≤ 106). It is guaranteed that the integer X2 is composite, that is, is not prime.
Output
Output a single integer — the minimum possible X0.
Examples
Input
14
Output
6
Input
20
Output
15
Input
8192
Output
8191
Note
In the first test, the smallest possible starting number is X0 = 6. One possible course of the game is as follows:
* Alice picks prime 5 and announces X1 = 10
* Bob picks prime 7 and announces X2 = 14.
In the second case, let X0 = 15.
* Alice picks prime 2 and announces X1 = 16
* Bob picks prime 5 and announces X2 = 20.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
Given a sequence $ a_i $ of length $ N $. Output all integers $ K (1 \ le K \ le N) $ that satisfy the following conditions.
Condition: Well sorted $ a_1, \ cdots, a_K $ matches $ a_ {N-K + 1}, \ cdots, a_N $.
Example
Input
8
5 2 4 9 4 9 2 5
Output
1 2 4 6 7 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.
Takahashi is doing a research on sets of points in a plane. Takahashi thinks a set S of points in a coordinate plane is a good set when S satisfies both of the following conditions:
* The distance between any two points in S is not \sqrt{D_1}.
* The distance between any two points in S is not \sqrt{D_2}.
Here, D_1 and D_2 are positive integer constants that Takahashi specified.
Let X be a set of points (i,j) on a coordinate plane where i and j are integers and satisfy 0 ≤ i,j < 2N.
Takahashi has proved that, for any choice of D_1 and D_2, there exists a way to choose N^2 points from X so that the chosen points form a good set. However, he does not know the specific way to choose such points to form a good set. Find a subset of X whose size is N^2 that forms a good set.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ D_1 ≤ 2×10^5
* 1 ≤ D_2 ≤ 2×10^5
* All values in the input are integers.
Input
Input is given from Standard Input in the following format:
N D_1 D_2
Output
Print N^2 distinct points that satisfy the condition in the following format:
x_1 y_1
x_2 y_2
:
x_{N^2} y_{N^2}
Here, (x_i,y_i) represents the i-th chosen point. 0 ≤ x_i,y_i < 2N must hold, and they must be integers. The chosen points may be printed in any order. In case there are multiple possible solutions, you can output any.
Examples
Input
2 1 2
Output
0 0
0 2
2 0
2 2
Input
3 1 5
Output
0 0
0 2
0 4
1 1
1 3
1 5
2 0
2 2
2 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write
```python
word_pattern(pattern, string)
```
that given a ```pattern``` and a string ```str```, find if ```str``` follows the same sequence as ```pattern```.
For example:
```python
word_pattern('abab', 'truck car truck car') == True
word_pattern('aaaa', 'dog dog dog dog') == True
word_pattern('abab', 'apple banana banana apple') == False
word_pattern('aaaa', 'cat cat dog cat') == False
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≤ i ≤ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x ≠ a holds.
Input
The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.
The third line contains integer k (0 ≤ k ≤ 105) — the required number of operations.
Output
Print a single number — the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
ab
ab
2
Output
1
Input
ababab
ababab
1
Output
2
Input
ab
ba
2
Output
0
Note
The sought way in the first sample is:
ab → a|b → ba → b|a → ab
In the second sample the two sought ways are:
* ababab → abab|ab → ababab
* ababab → ab|abab → ababab
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Sometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens.
All characters in this game are lowercase English letters. There are two players: Mister B and his competitor.
Initially the players have a string s consisting of the first a English letters in alphabetical order (for example, if a = 5, then s equals to "abcde").
The players take turns appending letters to string s. Mister B moves first.
Mister B must append exactly b letters on each his move. He can arbitrary choose these letters. His opponent adds exactly a letters on each move.
Mister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string s of length a and generates a string t of length a such that all letters in the string t are distinct and don't appear in the considered suffix. From multiple variants of t lexicographically minimal is chosen (if a = 4 and the suffix is "bfdd", the computer chooses string t equal to "aceg"). After that the chosen string t is appended to the end of s.
Mister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string s on the segment between positions l and r, inclusive. Letters of string s are numerated starting from 1.
Input
First and only line contains four space-separated integers: a, b, l and r (1 ≤ a, b ≤ 12, 1 ≤ l ≤ r ≤ 109) — the numbers of letters each player appends and the bounds of the segment.
Output
Print one integer — the minimum possible number of different letters in the segment from position l to position r, inclusive, in string s.
Examples
Input
1 1 1 8
Output
2
Input
4 2 2 6
Output
3
Input
3 7 4 6
Output
1
Note
In the first sample test one of optimal strategies generate string s = "abababab...", that's why answer is 2.
In the second sample test string s = "abcdbcaefg..." can be obtained, chosen segment will look like "bcdbc", that's why answer is 3.
In the third sample test string s = "abczzzacad..." can be obtained, chosen, segment will look like "zzz", that's why answer is 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!
You have $n$ tickets to sell. The price of the $i$-th ticket is $p_i$. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of the tickets). You know that the cinema participates in two ecological restoration programs applying them to the order you chose: The $x\%$ of the price of each the $a$-th sold ticket ($a$-th, $2a$-th, $3a$-th and so on) in the order you chose is aimed for research and spreading of renewable energy sources. The $y\%$ of the price of each the $b$-th sold ticket ($b$-th, $2b$-th, $3b$-th and so on) in the order you chose is aimed for pollution abatement.
If the ticket is in both programs then the $(x + y) \%$ are used for environmental activities. Also, it's known that all prices are multiples of $100$, so there is no need in any rounding.
For example, if you'd like to sell tickets with prices $[400, 100, 300, 200]$ and the cinema pays $10\%$ of each $2$-nd sold ticket and $20\%$ of each $3$-rd sold ticket, then arranging them in order $[100, 200, 300, 400]$ will lead to contribution equal to $100 \cdot 0 + 200 \cdot 0.1 + 300 \cdot 0.2 + 400 \cdot 0.1 = 120$. But arranging them in order $[100, 300, 400, 200]$ will lead to $100 \cdot 0 + 300 \cdot 0.1 + 400 \cdot 0.2 + 200 \cdot 0.1 = 130$.
Nature can't wait, so you decided to change the order of tickets in such a way, so that the total contribution to programs will reach at least $k$ in minimum number of sold tickets. Or say that it's impossible to do so. In other words, find the minimum number of tickets which are needed to be sold in order to earn at least $k$.
-----Input-----
The first line contains a single integer $q$ ($1 \le q \le 100$) — the number of independent queries. Each query consists of $5$ lines.
The first line of each query contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of tickets.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($100 \le p_i \le 10^9$, $p_i \bmod 100 = 0$) — the corresponding prices of tickets.
The third line contains two integers $x$ and $a$ ($1 \le x \le 100$, $x + y \le 100$, $1 \le a \le n$) — the parameters of the first program.
The fourth line contains two integers $y$ and $b$ ($1 \le y \le 100$, $x + y \le 100$, $1 \le b \le n$) — the parameters of the second program.
The fifth line contains single integer $k$ ($1 \le k \le 10^{14}$) — the required total contribution.
It's guaranteed that the total number of tickets per test doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $q$ integers — one per query.
For each query, print the minimum number of tickets you need to sell to make the total ecological contribution of at least $k$ if you can sell tickets in any order.
If the total contribution can not be achieved selling all the tickets, print $-1$.
-----Example-----
Input
4
1
100
50 1
49 1
100
8
100 200 100 200 100 200 100 100
10 2
15 3
107
3
1000000000 1000000000 1000000000
50 1
50 1
3000000000
5
200 100 100 100 100
69 5
31 2
90
Output
-1
6
3
4
-----Note-----
In the first query the total contribution is equal to $50 + 49 = 99 < 100$, so it's impossible to gather enough money.
In the second query you can rearrange tickets in a following way: $[100, 100, 200, 200, 100, 200, 100, 100]$ and the total contribution from the first $6$ tickets is equal to $100 \cdot 0 + 100 \cdot 0.1 + 200 \cdot 0.15 + 200 \cdot 0.1 + 100 \cdot 0 + 200 \cdot 0.25 = 10 + 30 + 20 + 50 = 110$.
In the third query the full price of each ticket goes to the environmental activities.
In the fourth query you can rearrange tickets as $[100, 200, 100, 100, 100]$ and the total contribution from the first $4$ tickets is $100 \cdot 0 + 200 \cdot 0.31 + 100 \cdot 0 + 100 \cdot 0.31 = 62 + 31 = 93$.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball.
The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by a letter c_i.
c_i = W represents the ball is white; c_i = B represents the ball is black.
Takahashi the human wants to achieve the following objective:
- For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the white ball with i written on it is to the left of the white ball with j written on it.
- For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the black ball with i written on it is to the left of the black ball with j written on it.
In order to achieve this, he can perform the following operation:
- Swap two adjacent balls.
Find the minimum number of operations required to achieve the objective.
-----Constraints-----
- 1 ≤ N ≤ 2000
- 1 ≤ a_i ≤ N
- c_i = W or c_i = B.
- If i ≠ j, (a_i,c_i) ≠ (a_j,c_j).
-----Input-----
Input is given from Standard Input in the following format:
N
c_1 a_1
c_2 a_2
:
c_{2N} a_{2N}
-----Output-----
Print the minimum number of operations required to achieve the objective.
-----Sample Input-----
3
B 1
W 2
B 3
W 1
W 3
B 2
-----Sample Output-----
4
The objective can be achieved in four operations, for example, as follows:
- Swap the black 3 and white 1.
- Swap the white 1 and white 2.
- Swap the black 3 and white 3.
- Swap the black 3 and black 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.
Monocarp has got an array $a$ consisting of $n$ integers. Let's denote $k$ as the mathematic mean of these elements (note that it's possible that $k$ is not an integer).
The mathematic mean of an array of $n$ elements is the sum of elements divided by the number of these elements (i. e. sum divided by $n$).
Monocarp wants to delete exactly two elements from $a$ so that the mathematic mean of the remaining $(n - 2)$ elements is still equal to $k$.
Your task is to calculate the number of pairs of positions $[i, j]$ ($i < j$) such that if the elements on these positions are deleted, the mathematic mean of $(n - 2)$ remaining elements is equal to $k$ (that is, it is equal to the mathematic mean of $n$ elements of the original array $a$).
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases.
The first line of each testcase contains one integer $n$ ($3 \le n \le 2 \cdot 10^5$) — the number of elements in the array.
The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{9}$), where $a_i$ is the $i$-th element of the array.
The sum of $n$ over all testcases doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print one integer — the number of pairs of positions $[i, j]$ ($i < j$) such that if the elements on these positions are deleted, the mathematic mean of $(n - 2)$ remaining elements is equal to $k$ (that is, it is equal to the mathematic mean of $n$ elements of the original array $a$).
-----Examples-----
Input
4
4
8 8 8 8
3
50 20 10
5
1 4 7 3 5
7
1 2 3 4 5 6 7
Output
6
0
2
3
-----Note-----
In the first example, any pair of elements can be removed since all of them are equal.
In the second example, there is no way to delete two elements so the mathematic mean doesn't change.
In the third example, it is possible to delete the elements on positions $1$ and $3$, or the elements on positions $4$ and $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.
There are $n$ candles on a Hanukkah menorah, and some of its candles are initially lit. We can describe which candles are lit with a binary string $s$, where the $i$-th candle is lit if and only if $s_i=1$.
Initially, the candle lights are described by a string $a$. In an operation, you select a candle that is currently lit. By doing so, the candle you selected will remain lit, and every other candle will change (if it was lit, it will become unlit and if it was unlit, it will become lit).
You would like to make the candles look the same as string $b$. Your task is to determine if it is possible, and if it is, find the minimum number of operations required.
-----Input-----
The first line contains an integer $t$ ($1\le t\le 10^4$) — the number of test cases. Then $t$ cases follow.
The first line of each test case contains a single integer $n$ ($1\le n\le 10^5$) — the number of candles.
The second line contains a string $a$ of length $n$ consisting of symbols 0 and 1 — the initial pattern of lights.
The third line contains a string $b$ of length $n$ consisting of symbols 0 and 1 — the desired pattern of lights.
It is guaranteed that the sum of $n$ does not exceed $10^5$.
-----Output-----
For each test case, output the minimum number of operations required to transform $a$ to $b$, or $-1$ if it's impossible.
-----Examples-----
Input
5
5
11010
11010
2
01
11
3
000
101
9
100010111
101101100
9
001011011
011010101
Output
0
1
-1
3
4
-----Note-----
In the first test case, the two strings are already equal, so we don't have to perform any operations.
In the second test case, we can perform a single operation selecting the second candle to transform $01$ into $11$.
In the third test case, it's impossible to perform any operations because there are no lit candles to select.
In the fourth test case, we can perform the following operations to transform $a$ into $b$:
Select the $7$-th candle: $100010{1}11\to 011101{ 1}00$.
Select the $2$-nd candle: $0{ 1}1101100\to 1{ 1}0010011$.
Select the $1$-st candle: ${1}10010011\to {1}01101100$.
In the fifth test case, we can perform the following operations to transform $a$ into $b$:
Select the $6$-th candle: $00101{1}011\to 11010{1}100$
Select the $2$-nd candle: $1{1}0101100\to 0{1}1010011$
Select the $8$-th candle: $0110100{1}1\to 1001011{1}0$
Select the $7$-th candle: $100101{1}10\to 011010{1}01$
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 directed graph of $n$ vertices and $m$ edges. Vertices are numbered from $1$ to $n$. There is a token in vertex $1$.
The following actions are allowed: Token movement. To move the token from vertex $u$ to vertex $v$ if there is an edge $u \to v$ in the graph. This action takes $1$ second. Graph transposition. To transpose all the edges in the graph: replace each edge $u \to v$ by an edge $v \to u$. This action takes increasingly more time: $k$-th transposition takes $2^{k-1}$ seconds, i.e. the first transposition takes $1$ second, the second one takes $2$ seconds, the third one takes $4$ seconds, and so on.
The goal is to move the token from vertex $1$ to vertex $n$ in the shortest possible time. Print this time modulo $998\,244\,353$.
-----Input-----
The first line of input contains two integers $n, m$ ($1 \le n, m \le 200\,000$).
The next $m$ lines contain two integers each: $u, v$ ($1 \le u, v \le n; u \ne v$), which represent the edges of the graph. It is guaranteed that all ordered pairs $(u, v)$ are distinct.
It is guaranteed that it is possible to move the token from vertex $1$ to vertex $n$ using the actions above.
-----Output-----
Print one integer: the minimum required time modulo $998\,244\,353$.
-----Examples-----
Input
4 4
1 2
2 3
3 4
4 1
Output
2
Input
4 3
2 1
2 3
4 3
Output
10
-----Note-----
The first example can be solved by transposing the graph and moving the token to vertex $4$, taking $2$ seconds.
The best way to solve the second example is the following: transpose the graph, move the token to vertex $2$, transpose the graph again, move the token to vertex $3$, transpose the graph once more and move the token to vertex $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.
Relative B came to Mr. A's house. He is 3 years old and loves blocks. The block he has is shaped like Figure 1.
<image>
Figure 1
Mr. B is laying blocks on the board. When I asked him, "What are you making?", He replied cheerfully, "Maze !!". The maze he says is the arrangement of blocks that are in contact with each other from the start to the goal and can be traced only by blocks of the same color. Figure 2 shows that the yellow block creates a maze from the upper left (start) to the lower right (goal).
<image>
Figure 2
With Mr. B playing innocently, you, the programmer, decided to see if the blocks were arranged in a maze.
Create a program that inputs the block information, start, and goal coordinates, and outputs OK if the block is a maze, and NG if it is not. The board has the size of w in the horizontal direction and h in the vertical direction, and the upper left coordinate is (1, 1) and the lower right coordinate is (w, h). The blocks are 2x4 rectangles, all the same size. The block color c can be 1 (white), 2 (yellow), 3 (green), 4 (blue), or 5 (red). The orientation d of the block on the board is 0 if it is long horizontally and 1 if it is long vertically. The position of the block is represented by the coordinates (x, y) at the top left of the block. The position of the block does not overlap with other blocks and does not protrude from the board.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
w h
xs ys ys
xg yg
n
c1 d1 x1 y1
c2 d2 x2 y2
::
cn dn xn yn
The board size w, h (4 ≤ w, h ≤ 100) is given on the first line. The second line gives the start coordinates xs, ys, and the third line gives the goal coordinates xg, yg.
The number of blocks n is given on the 4th line. The next n lines are given the color ci, orientation di, position xi, yi of the i-th block.
The number of datasets does not exceed 30.
Output
The discrimination result is output to one line for each input data set.
Example
Input
20 20
1 1
9 9
7
2 0 1 1
5 1 1 3
2 1 3 3
1 1 5 2
5 1 7 3
2 0 2 7
2 0 6 8
20 20
9 9
1 1
6
2 0 1 1
1 0 5 1
2 1 1 3
5 0 1 7
3 1 5 5
4 1 8 5
0 0
Output
OK
NG
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is BMI (Body Mass Index) as an index showing the degree of obesity. The BMI value is calculated using the following formula.
BMI = weight (kg) / (height (m)) 2
The closer the BMI value is to the standard value, the more "ideal body shape" is considered. Therefore, if the standard value of BMI is 22, create a program that inputs the information of the target person and outputs the information of the person closest to the "ideal body shape".
Assuming that the number of target persons is n, each target person is assigned a reception number p that is an integer value between 1 and n so that there is no duplication.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
p1 h1 w1
p2 h2 w2
::
pn hn wn
Number of subjects n (n ≤ 1000) on the first line, reception number pi (1 ≤ pi ≤ n) of the i-th subject on the following n lines, height hi in centimeters (1 ≤ hi ≤ 200), Given a kilogram of body weight wi (1 ≤ wi ≤ 200). All inputs are given as integers.
Output
For each data set, the reception number (integer) of the person closest to the "ideal body shape" is output on one line. If there are two or more people who are closest to the "ideal body shape", the one with the smaller reception number will be output.
Example
Input
6
1 165 66
2 178 60
3 180 72
4 160 65
5 185 62
6 182 62
3
3 160 65
2 180 70
1 170 75
0
Output
3
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Aramic language words can only represent objects.
Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 10^3$) — the number of words in the script.
The second line contains $n$ words $s_1, s_2, \ldots, s_n$ — the script itself. The length of each string does not exceed $10^3$.
It is guaranteed that all characters of the strings are small latin letters.
-----Output-----
Output one integer — the number of different objects mentioned in the given ancient Aramic script.
-----Examples-----
Input
5
a aa aaa ab abb
Output
2
Input
3
amer arem mrea
Output
1
-----Note-----
In the first test, there are two objects mentioned. The roots that represent them are "a","ab".
In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this Kata, you will be given an array of numbers and a number `n`, and your task will be to determine if `any` array elements, when summed (or taken individually), are divisible by `n`.
For example:
* `solve([1,3,4,7,6],9) == true`, because `3 + 6` is divisible by `9`
* `solve([1,2,3,4,5],10) == true` for similar reasons.
* `solve([8,5,3,9],7) == true`, because `7` evenly divides `5 + 9`
* but `solve([8,5,3],7) == false`.
All numbers in the array will be greater than `0`.
More examples in the test cases.
Good luck!
If you like this Kata, please try:
[Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005)
[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them quite large but do not contribute to the semantics of the code, so the process of minification is performed on source files before their delivery to execution to compress sources while preserving their semantics.
You are hired by ICPC to write JS minifier for ICPC. Fortunately, ICPC adheres to very strict programming practices and their JS sources are quite restricted in grammar. They work only on integer algorithms and do not use floating point numbers and strings.
Every JS source contains a sequence of lines. Each line contains zero or more tokens that can be separated by spaces. On each line, a part of the line that starts with a hash character ('#' code 35), including the hash character itself, is treated as a comment and is ignored up to the end of the line.
Each line is parsed into a sequence of tokens from left to right by repeatedly skipping spaces and finding the longest possible token starting at the current parsing position, thus transforming the source code into a sequence of tokens. All the possible tokens are listed below: A reserved token is any kind of operator, separator, literal, reserved word, or a name of a library function that should be preserved during the minification process. Reserved tokens are fixed strings of non-space ASCII characters that do not contain the hash character ('#' code 35). All reserved tokens are given as an input to the minification process. A number token consists of a sequence of digits, where a digit is a character from zero ('0') to nine ('9') inclusive. A word token consists of a sequence of characters from the following set: lowercase letters, uppercase letters, digits, underscore ('_' code 95), and dollar sign ('$' code 36). A word does not start with a digit.
Note, that during parsing the longest sequence of characters that satisfies either a number or a word definition, but that appears in the list of reserved tokens, is considered to be a reserved token instead.
During the minification process words are renamed in a systematic fashion using the following algorithm: Take a list of words that consist only of lowercase letters ordered first by their length, then lexicographically: "a", "b", ..., "z", "aa", "ab", ..., excluding reserved tokens, since they are not considered to be words. This is the target word list. Rename the first word encountered in the input token sequence to the first word in the target word list and all further occurrences of the same word in the input token sequence, too. Rename the second new word encountered in the input token sequence to the second word in the target word list, and so on.
The goal of the minification process is to convert the given source to the shortest possible line (counting spaces) that still parses to the same sequence of tokens with the correspondingly renamed words using these JS parsing rules.
-----Input-----
The first line of the input contains a single integer $n$ ($0 \le n \le 40$) — the number of reserved tokens.
The second line of the input contains the list of reserved tokens separated by spaces without repetitions in the list. Each reserved token is at least one and at most 20 characters long and contains only characters with ASCII codes from 33 (exclamation mark) to 126 (tilde) inclusive, with exception of a hash character ('#' code 35).
The third line of the input contains a single integer $m$ ($1 \le m \le 40$) — the number of lines in the input source code.
Next $m$ lines contain the input source, each source line is at most 80 characters long (counting leading and trailing spaces). Each line contains only characters with ASCII codes from 32 (space) to 126 (tilde) inclusive. The source code is valid and fully parses into a sequence of tokens.
-----Output-----
Write to the output a single line that is the result of the minification process on the input source code. The output source line shall parse to the same sequence of tokens as the input source with the correspondingly renamed words and shall contain the minimum possible number of spaces needed for that. If there are multiple ways to insert the minimum possible number of spaces into the output, use any way.
-----Examples-----
Input
16
fun while return var { } ( ) , ; > = + ++ - --
9
fun fib(num) { # compute fibs
var return_value = 1, prev = 0, temp;
while (num > 0) {
temp = return_value; return_value = return_value + prev;
prev = temp;
num--;
}
return return_value;
}
Output
fun a(b){var c=1,d=0,e;while(b>0){e=c;c=c+d;d=e;b--;}return c;}
Input
10
( ) + ++ : -> >> >>: b c)
2
($val1++ + +4 kb) >> :out
b-> + 10 >>: t # using >>:
Output
(a+++ +4c )>> :d b->+10>>:e
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
n! = n × (n − 1) × (n − 2) × ... × 3 × 2 × 1
Is called the factorial of n. For example, the factorial of 12
12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600
And there are two consecutive 0s at the end.
Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of n !. However, n is a positive integer less than or equal to 20000.
Input
Multiple data are given. Each piece of data is given n (n ≤ 20000) on one line. When n is 0, it is the last input.
The number of data does not exceed 20.
Output
For each data, output the number of 0s that are consecutively arranged at the end of n! On one line.
Example
Input
2
12
10000
0
Output
0
2
2499
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Tower of Hanoi is a well-known mathematical puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: Only one disk can be moved at a time. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2^{n} - 1, where n is the number of disks. (c) Wikipedia.
SmallY's puzzle is very similar to the famous Tower of Hanoi. In the Tower of Hanoi puzzle you need to solve a puzzle in minimum number of moves, in SmallY's puzzle each move costs some money and you need to solve the same puzzle but for minimal cost. At the beginning of SmallY's puzzle all n disks are on the first rod. Moving a disk from rod i to rod j (1 ≤ i, j ≤ 3) costs t_{ij} units of money. The goal of the puzzle is to move all the disks to the third rod.
In the problem you are given matrix t and an integer n. You need to count the minimal cost of solving SmallY's puzzle, consisting of n disks.
-----Input-----
Each of the first three lines contains three integers — matrix t. The j-th integer in the i-th line is t_{ij} (1 ≤ t_{ij} ≤ 10000; i ≠ j). The following line contains a single integer n (1 ≤ n ≤ 40) — the number of disks.
It is guaranteed that for all i (1 ≤ i ≤ 3), t_{ii} = 0.
-----Output-----
Print a single integer — the minimum cost of solving SmallY's puzzle.
-----Examples-----
Input
0 1 1
1 0 1
1 1 0
3
Output
7
Input
0 2 2
1 0 100
1 2 0
3
Output
19
Input
0 2 1
1 0 100
1 2 0
5
Output
87
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer m as a product of integers a1, a2, ... an <image>. Your task is to find the number of distinct decompositions of number m into the product of n ordered positive integers.
Decomposition into n products, given in the input, must also be considered in the answer. As the answer can be very large, print it modulo 1000000007 (109 + 7).
Input
The first line contains positive integer n (1 ≤ n ≤ 500). The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
In a single line print a single number k — the number of distinct decompositions of number m into n ordered multipliers modulo 1000000007 (109 + 7).
Examples
Input
1
15
Output
1
Input
3
1 1 2
Output
3
Input
2
5 7
Output
4
Note
In the second sample, the get a decomposition of number 2, you need any one number out of three to equal 2, and the rest to equal 1.
In the third sample, the possible ways of decomposing into ordered multipliers are [7,5], [5,7], [1,35], [35,1].
A decomposition of positive integer m into n ordered multipliers is a cortege of positive integers b = {b1, b2, ... bn} such that <image>. Two decompositions b and c are considered different, if there exists index i such that bi ≠ ci.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Arpa is researching the Mexican wave.
There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0.
At time 1, the first spectator stands. At time 2, the second spectator stands. ... At time k, the k-th spectator stands. At time k + 1, the (k + 1)-th spectator stands and the first spectator sits. At time k + 2, the (k + 2)-th spectator stands and the second spectator sits. ... At time n, the n-th spectator stands and the (n - k)-th spectator sits. At time n + 1, the (n + 1 - k)-th spectator sits. ... At time n + k, the n-th spectator sits.
Arpa wants to know how many spectators are standing at time t.
-----Input-----
The first line contains three integers n, k, t (1 ≤ n ≤ 10^9, 1 ≤ k ≤ n, 1 ≤ t < n + k).
-----Output-----
Print single integer: how many spectators are standing at time t.
-----Examples-----
Input
10 5 3
Output
3
Input
10 5 7
Output
5
Input
10 5 12
Output
3
-----Note-----
In the following a sitting spectator is represented as -, a standing spectator is represented as ^.
At t = 0 ---------- $\Rightarrow$ number of standing spectators = 0. At t = 1 ^--------- $\Rightarrow$ number of standing spectators = 1. At t = 2 ^^-------- $\Rightarrow$ number of standing spectators = 2. At t = 3 ^^^------- $\Rightarrow$ number of standing spectators = 3. At t = 4 ^^^^------ $\Rightarrow$ number of standing spectators = 4. At t = 5 ^^^^^----- $\Rightarrow$ number of standing spectators = 5. At t = 6 -^^^^^---- $\Rightarrow$ number of standing spectators = 5. At t = 7 --^^^^^--- $\Rightarrow$ number of standing spectators = 5. At t = 8 ---^^^^^-- $\Rightarrow$ number of standing spectators = 5. At t = 9 ----^^^^^- $\Rightarrow$ number of standing spectators = 5. At t = 10 -----^^^^^ $\Rightarrow$ number of standing spectators = 5. At t = 11 ------^^^^ $\Rightarrow$ number of standing spectators = 4. At t = 12 -------^^^ $\Rightarrow$ number of standing spectators = 3. At t = 13 --------^^ $\Rightarrow$ number of standing spectators = 2. At t = 14 ---------^ $\Rightarrow$ number of standing spectators = 1. At t = 15 ---------- $\Rightarrow$ number of standing spectators = 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.
A robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly $1$ meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot can choose any of the four directions, but then at the end of every second it has to turn 90 degrees left or right with respect to the direction it just moved in. For example, if the robot has just moved north or south, the next step it takes has to be either west or east, and vice versa.
The robot makes exactly $n$ steps from its starting position according to the rules above. How many different points can the robot arrive to at the end? The final orientation of the robot can be ignored.
-----Input-----
The only line contains a single integer $n$ ($1 \leq n \leq 1000$) — the number of steps the robot makes.
-----Output-----
Print a single integer — the number of different possible locations after exactly $n$ steps.
-----Examples-----
Input
1
Output
4
Input
2
Output
4
Input
3
Output
12
-----Note-----
In the first sample case, the robot will end up 1 meter north, south, west, or east depending on its initial direction.
In the second sample case, the robot will always end up $\sqrt{2}$ meters north-west, north-east, south-west, or south-east.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2^{n} members and coincidentally Natalia Fan Club also has 2^{n} members. Each member of MDC is assigned a unique id i from 0 to 2^{n} - 1. The same holds for each member of NFC.
One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (a, b) such that member a from MDC dances with member b from NFC.
The complexity of a pairs' assignment is the number of pairs of dancing pairs (a, b) and (c, d) such that a < c and b > d.
You are given a binary number of length n named x. We know that member i from MDC dances with member $i \oplus x$ from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (10^9 + 7).
Expression $x \oplus y$ denotes applying «XOR» to numbers x and y. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as «^», in Pascal — «xor».
-----Input-----
The first line of input contains a binary number x of lenght n, (1 ≤ n ≤ 100).
This number may contain leading zeros.
-----Output-----
Print the complexity of the given dance assignent modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
11
Output
6
Input
01
Output
2
Input
1
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp takes part in a math show. He is given n tasks, each consists of k subtasks, numbered 1 through k. It takes him t_{j} minutes to solve the j-th subtask of any task. Thus, time required to solve a subtask depends only on its index, but not on the task itself. Polycarp can solve subtasks in any order.
By solving subtask of arbitrary problem he earns one point. Thus, the number of points for task is equal to the number of solved subtasks in it. Moreover, if Polycarp completely solves the task (solves all k of its subtasks), he recieves one extra point. Thus, total number of points he recieves for the complete solution of the task is k + 1.
Polycarp has M minutes of time. What is the maximum number of points he can earn?
-----Input-----
The first line contains three integer numbers n, k and M (1 ≤ n ≤ 45, 1 ≤ k ≤ 45, 0 ≤ M ≤ 2·10^9).
The second line contains k integer numbers, values t_{j} (1 ≤ t_{j} ≤ 1000000), where t_{j} is the time in minutes required to solve j-th subtask of any task.
-----Output-----
Print the maximum amount of points Polycarp can earn in M minutes.
-----Examples-----
Input
3 4 11
1 2 3 4
Output
6
Input
5 5 10
1 2 4 8 16
Output
7
-----Note-----
In the first example Polycarp can complete the first task and spend 1 + 2 + 3 + 4 = 10 minutes. He also has the time to solve one subtask of the second task in one minute.
In the second example Polycarp can solve the first subtask of all five tasks and spend 5·1 = 5 minutes. Also he can solve the second subtasks of two tasks and spend 2·2 = 4 minutes. Thus, he earns 5 + 2 = 7 points in total.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.
There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.
Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.
Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.
-----Input-----
The first line contains a single integer n — the number of nodes in the tree (1 ≤ n ≤ 2·10^5).
Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n) — the ends of the edge of the tree; the edge leads from node u_{i} to node v_{i}. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.
-----Output-----
Print two space-separated integers — the maximum possible and the minimum possible result of the game.
-----Examples-----
Input
5
1 2
1 3
2 4
2 5
Output
3 2
Input
6
1 2
1 3
3 4
1 5
5 6
Output
3 3
-----Note-----
Consider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.
In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 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.
We have N non-negative integers: A_1, A_2, ..., A_N.
Consider painting at least one and at most N-1 integers among them in red, and painting the rest in blue.
Let the beauty of the painting be the \mbox{XOR} of the integers painted in red, plus the \mbox{XOR} of the integers painted in blue.
Find the maximum possible beauty of the painting.What is \mbox{XOR}?
The bitwise \mbox{XOR} x_1 \oplus x_2 \oplus \ldots \oplus x_n of n non-negative integers x_1, x_2, \ldots, x_n is defined as follows:
- When x_1 \oplus x_2 \oplus \ldots \oplus x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.
For example, 3 \oplus 5 = 6.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10^5
- 0 \leq A_i < 2^{60}\ (1 \leq i \leq N)
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
-----Output-----
Print the maximum possible beauty of the painting.
-----Sample Input-----
3
3 6 5
-----Sample Output-----
12
If we paint 3, 6, 5 in blue, red, blue, respectively, the beauty will be (6) + (3 \oplus 5) = 12.
There is no way to paint the integers resulting in greater beauty than 12, so the answer is 12.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function which checks a number for three different properties.
- is the number prime?
- is the number even?
- is the number a multiple of 10?
Each should return either true or false, which should be given as an array. Remark: The Haskell variant uses `data Property`.
### Examples
```python
number_property(7) # ==> [true, false, false]
number_property(10) # ==> [false, true, true]
```
The number will always be an integer, either positive or negative. Note that negative numbers cannot be primes, but they can be multiples of 10:
```python
number_property(-7) # ==> [false, false, false]
number_property(-10) # ==> [false, true, true]
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The girl Taylor has a beautiful calendar for the year y. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
The calendar is so beautiful that she wants to know what is the next year after y when the calendar will be exactly the same. Help Taylor to find that year.
Note that leap years has 366 days. The year is leap if it is divisible by 400 or it is divisible by 4, but not by 100 (https://en.wikipedia.org/wiki/Leap_year).
-----Input-----
The only line contains integer y (1000 ≤ y < 100'000) — the year of the calendar.
-----Output-----
Print the only integer y' — the next year after y when the calendar will be the same. Note that you should find the first year after y with the same calendar.
-----Examples-----
Input
2016
Output
2044
Input
2000
Output
2028
Input
50501
Output
50507
-----Note-----
Today is Monday, the 13th of June, 2016.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Note that girls in Arpa’s land are really attractive.
Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair.
<image>
There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that:
* Each person had exactly one type of food,
* No boy had the same type of food as his girlfriend,
* Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive.
Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
Input
The first line contains an integer n (1 ≤ n ≤ 105) — the number of pairs of guests.
The i-th of the next n lines contains a pair of integers ai and bi (1 ≤ ai, bi ≤ 2n) — the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.
Output
If there is no solution, print -1.
Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2.
If there are multiple solutions, print any of them.
Example
Input
3
1 4
2 5
3 6
Output
1 2
2 1
1 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.
For a set $S$ of integers, perform a sequence of the following operations. Note that each value in $S$ must be unique.
* insert($x$): Insert $x$ to $S$ and report the number of elements in $S$ after the operation.
* find($x$): Report the number of $x$ in $S$ (0 or 1).
Constraints
* $1 \leq q \leq 200,000$
* $0 \leq x \leq 1,000,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $x$
or
1 $x$
where the first digits 0 and 1 represent insert and find operations respectively.
Output
For each insert operation, print the number of elements in $S$.
For each find operation, print the number of specified elements in $S$.
Example
Input
7
0 1
0 2
0 3
0 2
0 4
1 3
1 10
Output
1
2
3
3
4
1
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Maria participates in a bicycle race.
The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.
Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).
Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.
Help Maria get ready for the competition — determine the number of dangerous turns on the track.
-----Input-----
The first line of the input contains an integer n (4 ≤ n ≤ 1000) — the number of straight sections of the track.
The following (n + 1)-th line contains pairs of integers (x_{i}, y_{i}) ( - 10 000 ≤ x_{i}, y_{i} ≤ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (x_{i}, y_{i}) and ends at the point (x_{i} + 1, y_{i} + 1).
It is guaranteed that:
the first straight section is directed to the north; the southernmost (and if there are several, then the most western of among them) point of the track is the first point; the last point coincides with the first one (i.e., the start position); any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point); no pair of points (except for the first and last one) is the same; no two adjacent straight sections are directed in the same direction or in opposite directions.
-----Output-----
Print a single integer — the number of dangerous turns on the track.
-----Examples-----
Input
6
0 0
0 1
1 1
1 2
2 2
2 0
0 0
Output
1
Input
16
1 1
1 5
3 5
3 7
2 7
2 9
6 9
6 7
5 7
5 3
4 3
4 4
3 4
3 2
5 2
5 1
1 1
Output
6
-----Note-----
The first sample corresponds to the picture:
[Image]
The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer 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.
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (x_{i}, y_{i}). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0, 0). Initially, the robot is at point with coordinates (0, 0). Also, let's mark the robot's current position as (x, y). In order to destroy all the bombs, the robot can perform three types of operations: Operation has format "1 k dir". To perform the operation robot have to move in direction dir k (k ≥ 1) times. There are only 4 directions the robot can move in: "R", "L", "U", "D". During one move the robot can move from the current point to one of following points: (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) (corresponding to directions). It is forbidden to move from point (x, y), if at least one point on the path (besides the destination point) contains a bomb. Operation has format "2". To perform the operation robot have to pick a bomb at point (x, y) and put it in a special container. Thus, the robot can carry the bomb from any point to any other point. The operation cannot be performed if point (x, y) has no bomb. It is forbidden to pick a bomb if the robot already has a bomb in its container. Operation has format "3". To perform the operation robot have to take a bomb out of the container and destroy it. You are allowed to perform this operation only if the robot is at point (0, 0). It is forbidden to perform the operation if the container has no bomb.
Help the robot and find the shortest possible sequence of operations he can perform to destroy all bombs on the coordinate plane.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of bombs on the coordinate plane. Next n lines contain two integers each. The i-th line contains numbers (x_{i}, y_{i}) ( - 10^9 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th bomb. It is guaranteed that no two bombs are located at the same point and no bomb is at point (0, 0).
-----Output-----
In a single line print a single integer k — the minimum number of operations needed to destroy all bombs. On the next lines print the descriptions of these k operations. If there are multiple sequences, you can print any of them. It is guaranteed that there is the solution where k ≤ 10^6.
-----Examples-----
Input
2
1 1
-1 -1
Output
12
1 1 R
1 1 U
2
1 1 L
1 1 D
3
1 1 L
1 1 D
2
1 1 R
1 1 U
3
Input
3
5 0
0 5
1 0
Output
12
1 1 R
2
1 1 L
3
1 5 R
2
1 5 L
3
1 5 U
2
1 5 D
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.
Let $f(x)$ be the sum of digits of a decimal number $x$.
Find the smallest non-negative integer $x$ such that $f(x) + f(x + 1) + \dots + f(x + k) = n$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 150$) — the number of test cases.
Each test case consists of one line containing two integers $n$ and $k$ ($1 \le n \le 150$, $0 \le k \le 9$).
-----Output-----
For each test case, print one integer without leading zeroes. If there is no such $x$ that $f(x) + f(x + 1) + \dots + f(x + k) = n$, print $-1$; otherwise, print the minimum $x$ meeting that constraint.
-----Example-----
Input
7
1 0
1 1
42 7
13 7
99 1
99 0
99 2
Output
1
0
4
-1
599998
99999999999
7997
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.
You are to implement the alignment in the shortest possible time. Good luck!
Input
The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.
Output
Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.
Examples
Input
This is
Codeforces
Beta
Round
5
Output
************
* This is *
* *
*Codeforces*
* Beta *
* Round *
* 5 *
************
Input
welcome to the
Codeforces
Beta
Round 5
and
good luck
Output
****************
*welcome to the*
* Codeforces *
* Beta *
* Round 5 *
* *
* and *
* good luck *
****************
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The hero of justice, the Spider, can pull a rope out of his arm and jump from building to building. However, due to the short rope, you can only move to buildings that are less than 50 distances from you. To move to a building farther away, you have to jump to another building.
<image>
Create a program that inputs the information of n and n buildings, the start position and destination of the spider's movement, and outputs the shortest route of the movement. If you cannot move to the target building no matter how you go through the building, output NA. Each building is treated as a point, and there can be no more than one way to go through the building that travels the shortest distance.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
b1 x1 y1
b2 x2 y2
::
bn xn yn
m
s1 g1
s2 g2
::
sm gm
The number of buildings n (1 ≤ n ≤ 100) on the first line, the building number bi (1 ≤ bi ≤ n) of the i-th building on the following n lines, and the integers xi, yi representing the x and y coordinates of that building. (-1000 ≤ xi, yi ≤ 1000) is given, separated by spaces.
The number of movement information m (1 ≤ m ≤ 100) is given to the following line, and the i-th movement information is given to the following m line. As each move information, the number si of the building to start the move and the number gi of the destination building are given, separated by blanks.
The number of datasets does not exceed 10.
Output
Outputs in the following format for each input dataset.
The route or NA for the i-th movement information is output to the i-th line on the i-th line. Each route is output in the following format.
si bri1 bri2 ... gi
brij represents the number of the building that goes through the jth in the ith movement information.
Example
Input
4
1 0 0
2 30 0
3 60 40
4 0 60
2
1 3
1 4
22
1 0 0
2 150 40
3 30 20
4 180 150
5 40 80
6 130 130
7 72 28
8 172 118
9 50 50
10 160 82
11 90 105
12 144 131
13 130 64
14 80 140
15 38 117
16 190 90
17 60 100
18 100 70
19 130 100
20 71 69
21 200 110
22 120 150
1
1 22
0
Output
1 2 3
NA
1 3 9 20 11 6 22
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
< PREVIOUS KATA
NEXT KATA >
## Task:
You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows.
* Note:```Returning``` the pattern is not the same as ```Printing``` the pattern.
### Parameters:
pattern( n , x , y );
^ ^ ^
| | |
Term upto which Number of times Number of times
Basic Pattern Basic Pattern Basic Pattern
should be should be should be
created repeated repeated
horizontally vertically
* Note: `Basic Pattern` means what we created in Complete The Pattern #12
## Rules/Note:
* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. empty string.
* If `x <= 1` then the basic pattern should not be repeated horizontally.
* If `y <= 1` then the basic pattern should not be repeated vertically.
* `The length of each line is same`, and is equal to the length of longest line in the pattern.
* Range of Parameters (for the sake of CW Compiler) :
+ `n ∈ (-∞,25]`
+ `x ∈ (-∞,10]`
+ `y ∈ (-∞,10]`
* If only two arguments are passed then the function `pattern` should run as if `y <= 1`.
* If only one argument is passed then the function `pattern` should run as if `x <= 1` & `y <= 1`.
* The function `pattern` should work when extra arguments are passed, by ignoring the extra arguments.
## Examples:
* Having Three Arguments-
+ pattern(4,3,2):
1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4
3 3 3 3 3 3
2 2 2 2 2 2
1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4
3 3 3 3 3 3
2 2 2 2 2 2
1 1 1 1
* Having Two Arguments-
+ pattern(10,2):
1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
9 9 9 9
0 0
9 9 9 9
8 8 8 8
7 7 7 7
6 6 6 6
5 5 5 5
4 4 4 4
3 3 3 3
2 2 2 2
1 1 1
* Having Only One Argument-
+ pattern(25):
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
0 0
1 1
2 2
3 3
4 4
5
4 4
3 3
2 2
1 1
0 0
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
0 0
9 9
8 8
7 7
6 6
5 5
4 4
3 3
2 2
1 1
>>>LIST OF ALL MY 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.
You are given a grid, consisting of $2$ rows and $n$ columns. Each cell of this grid should be colored either black or white.
Two cells are considered neighbours if they have a common border and share the same color. Two cells $A$ and $B$ belong to the same component if they are neighbours, or if there is a neighbour of $A$ that belongs to the same component with $B$.
Let's call some bicoloring beautiful if it has exactly $k$ components.
Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $998244353$.
-----Input-----
The only line contains two integers $n$ and $k$ ($1 \le n \le 1000$, $1 \le k \le 2n$) — the number of columns in a grid and the number of components required.
-----Output-----
Print a single integer — the number of beautiful bicolorings modulo $998244353$.
-----Examples-----
Input
3 4
Output
12
Input
4 1
Output
2
Input
1 2
Output
2
-----Note-----
One of possible bicolorings in sample $1$: [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.
You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.
There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.
According to an examination beforehand, you know that a pair of attendees satisfying the condition below will make the transaction.
- The absolute difference of their attendee numbers is equal to the sum of their heights.
There are \frac{N(N-1)}{2} ways to choose two from the N attendees and make a pair. Among them, how many satisfy the condition above?
P.S.: We cannot let you know the secret.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 2 \times 10^5
- 1 \leq A_i \leq 10^9\ (1 \leq i \leq N)
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 \dots A_N
-----Output-----
Print the number of pairs satisfying the condition.
-----Sample Input-----
6
2 3 3 1 3 1
-----Sample Output-----
3
- A_1 + A_4 = 3, so the pair of Attendee 1 and 4 satisfy the condition.
- A_2 + A_6 = 4, so the pair of Attendee 2 and 6 satisfy the condition.
- A_4 + A_6 = 2, so the pair of Attendee 4 and 6 satisfy the condition.
No other pair satisfies the condition, so you should print 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.
Let's say take 2 strings, A and B, and define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings `abc` and `abd` is 2, while the similarity of strings `aaa` and `aaab` is 3.
write a function that calculates the sum of similarities of a string S with each of it's **suffixes**.
```python
string_suffix('ababaa') => returns 11
string_suffix('abc') => returns 3
```
Explanation:
In the first case, the suffixes of the string are `ababaa`, `babaa`, `abaa`, `baa`, `aa` and `a`. The similarities of each of these strings with the string `ababaa` are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is simply 3 + 0 + 0 = 3.
Note : Each string will have at least one character - no need to check for empty strings :)
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 long seat of width X centimeters.
There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters.
We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two people, and between the end of the seat and a person.
At most how many people can sit on the seat?
-----Constraints-----
- All input values are integers.
- 1 \leq X, Y, Z \leq 10^5
- Y+2Z \leq X
-----Input-----
Input is given from Standard Input in the following format:
X Y Z
-----Output-----
Print the answer.
-----Sample Input-----
13 3 1
-----Sample Output-----
3
There is just enough room for three, as shown below:
Figure
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 simple undirected graph consisting of $n$ vertices and $m$ edges. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
Let's make a definition.
Let $v_1$ and $v_2$ be two some nonempty subsets of vertices that do not intersect. Let $f(v_{1}, v_{2})$ be true if and only if all the conditions are satisfied: There are no edges with both endpoints in vertex set $v_1$. There are no edges with both endpoints in vertex set $v_2$. For every two vertices $x$ and $y$ such that $x$ is in $v_1$ and $y$ is in $v_2$, there is an edge between $x$ and $y$.
Create three vertex sets ($v_{1}$, $v_{2}$, $v_{3}$) which satisfy the conditions below; All vertex sets should not be empty. Each vertex should be assigned to only one vertex set. $f(v_{1}, v_{2})$, $f(v_{2}, v_{3})$, $f(v_{3}, v_{1})$ are all true.
Is it possible to create such three vertex sets? If it's possible, print matching vertex set for each vertex.
-----Input-----
The first line contains two integers $n$ and $m$ ($3 \le n \le 10^{5}$, $0 \le m \le \text{min}(3 \cdot 10^{5}, \frac{n(n-1)}{2})$) — the number of vertices and edges in the graph.
The $i$-th of the next $m$ lines contains two integers $a_{i}$ and $b_{i}$ ($1 \le a_{i} \lt b_{i} \le n$) — it means there is an edge between $a_{i}$ and $b_{i}$. The graph doesn't contain self-loops, there is at most one edge between a pair of vertices. The given graph can be disconnected.
-----Output-----
If the answer exists, print $n$ integers. $i$-th integer means the vertex set number (from $1$ to $3$) of $i$-th vertex. Otherwise, print $-1$.
If there are multiple answers, print any.
-----Examples-----
Input
6 11
1 2
1 3
1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
Output
1 2 2 3 3 3
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
-----Note-----
In the first example, if $v_{1} = \{ 1 \}$, $v_{2} = \{ 2, 3 \}$, and $v_{3} = \{ 4, 5, 6 \}$ then vertex sets will satisfy all conditions. But you can assign vertices to vertex sets in a different way; Other answers like "2 3 3 1 1 1" will be accepted as well. [Image]
In the second example, it's impossible to make such vertex sets.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.
Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2^{i} - 1 liters and costs c_{i} roubles. The number of bottles of each type in the store can be considered infinite.
You want to buy at least L liters of lemonade. How many roubles do you have to spend?
-----Input-----
The first line contains two integers n and L (1 ≤ n ≤ 30; 1 ≤ L ≤ 10^9) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively.
The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^9) — the costs of bottles of different types.
-----Output-----
Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.
-----Examples-----
Input
4 12
20 30 70 90
Output
150
Input
4 3
10000 1000 100 10
Output
10
Input
4 3
10 100 1000 10000
Output
30
Input
5 787787787
123456789 234567890 345678901 456789012 987654321
Output
44981600785557577
-----Note-----
In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles.
In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles.
In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds t.
-----Input-----
The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 10^4). Then follow n lines, each containing two integers l_{i} and r_{i} (0 ≤ l_{i}, r_{i} ≤ 1). Number l_{i} equals one, if the left door of the i-th cupboard is opened, otherwise number l_{i} equals zero. Similarly, number r_{i} equals one, if the right door of the i-th cupboard is opened, otherwise number r_{i} equals zero.
The numbers in the lines are separated by single spaces.
-----Output-----
In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.
-----Examples-----
Input
5
0 1
1 0
0 1
1 1
0 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.
The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $h$ hours and each hour lasts $m$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $0$ to $h-1$ and minutes are numbered from $0$ to $m-1$.
That's how the digits are displayed on the clock. Please note that digit $1$ is placed in the middle of its position.
A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).
The image of the clocks in the mirror is reflected against a vertical axis.
The reflection is not a valid time.
The reflection is a valid time with $h=24$, $m = 60$. However, for example, if $h=10$, $m=60$, then the reflection is not a valid time.
An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $s$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.
It can be shown that with any $h$, $m$, $s$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.
You are asked to solve the problem for several test cases.
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 100$) — the number of test cases.
The next $2 \cdot T$ lines contain the description of test cases. The description of each test case consists of two lines.
The first line of a test case contains two integers $h$, $m$ ($1 \le h, m \le 100$).
The second line contains the start time $s$ in the described format HH:MM.
-----Output-----
For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.
-----Examples-----
Input
5
24 60
12:21
24 60
23:59
90 80
52:26
1 100
00:01
10 10
04:04
Output
12:21
00:00
52:28
00:00
00:00
-----Note-----
In the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number.
For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are:
* b: 2
* c: 3, 10
* d: 4, 8
* e: 6
* f: 7
* z: 1, 5, 9
* Lists of positions of letters a, g, h, ..., y are empty.
This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4.
Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.
Find the lexicographically minimal lucky string whose length equals n.
Input
The single line contains a positive integer n (1 ≤ n ≤ 105) — the length of the sought string.
Output
Print on the single line the lexicographically minimal lucky string whose length equals n.
Examples
Input
5
Output
abcda
Input
3
Output
abc
Note
The lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 trampoline park with $n$ trampolines in a line. The $i$-th of which has strength $S_i$.
Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice.
If at the moment Pekora jumps on trampoline $i$, the trampoline will launch her to position $i + S_i$, and $S_i$ will become equal to $\max(S_i-1,1)$. In other words, $S_i$ will decrease by $1$, except of the case $S_i=1$, when $S_i$ will remain equal to $1$.
If there is no trampoline in position $i + S_i$, then this pass is over. Otherwise, Pekora will continue the pass by jumping from the trampoline at position $i + S_i$ by the same rule as above.
Pekora can't stop jumping during the pass until she lands at the position larger than $n$ (in which there is no trampoline). Poor Pekora!
Pekora is a naughty rabbit and wants to ruin the trampoline park by reducing all $S_i$ to $1$. What is the minimum number of passes she needs to reduce all $S_i$ to $1$?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 500$) — the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \leq n \leq 5000$) — the number of trampolines.
The second line of each test case contains $n$ integers $S_1, S_2, \dots, S_n$ ($1 \le S_i \le 10^9$), where $S_i$ is the strength of the $i$-th trampoline.
It's guaranteed that the sum of $n$ over all test cases doesn't exceed $5000$.
-----Output-----
For each test case, output a single integer — the minimum number of passes Pekora needs to do to reduce all $S_i$ to $1$.
-----Examples-----
Input
3
7
1 4 2 2 2 2 2
2
2 3
5
1 1 1 1 1
Output
4
3
0
-----Note-----
For the first test case, here is an optimal series of passes Pekora can take. (The bolded numbers are the positions that Pekora jumps into during these passes.)
$[1,4,\textbf{2},2,\textbf{2},2,\textbf{2}]$
$[1,\textbf{4},1,2,1,\textbf{2},1]$
$[1,\textbf{3},1,2,\textbf{1},\textbf{1},\textbf{1}]$
$[1,\textbf{2},1,\textbf{2},1,\textbf{1},\textbf{1}]$
For the second test case, the optimal series of passes is show below.
$[\textbf{2},3]$
$[1,\textbf{3}]$
$[1,\textbf{2}]$
For the third test case, all $S_i$ are already equal to $1$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke is playing a puzzle game.
In this game, you are given a rectangular board of dimensions R × C, filled with numbers. Each integer i from 1 through N is written twice, at the coordinates (x_{i,1},y_{i,1}) and (x_{i,2},y_{i,2}).
The objective is to draw a curve connecting the pair of points where the same integer is written, for every integer from 1 through N.
Here, the curves may not go outside the board or cross each other.
Determine whether this is possible.
-----Constraints-----
- 1 ≤ R,C ≤ 10^8
- 1 ≤ N ≤ 10^5
- 0 ≤ x_{i,1},x_{i,2} ≤ R(1 ≤ i ≤ N)
- 0 ≤ y_{i,1},y_{i,2} ≤ C(1 ≤ i ≤ N)
- All given points are distinct.
- All input values are integers.
-----Input-----
Input is given from Standard Input in the following format:
R C N
x_{1,1} y_{1,1} x_{1,2} y_{1,2}
:
x_{N,1} y_{N,1} x_{N,2} y_{N,2}
-----Output-----
Print YES if the objective is achievable; print NO otherwise.
-----Sample Input-----
4 2 3
0 1 3 1
1 1 4 1
2 0 2 2
-----Sample Output-----
YES
The above figure shows a possible solution.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure.
The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every year and is given by a polynomial f(x) of the year x.
Your task is, given the network structure, to write a program to calculate the maximal bandwidth between the 1-st and N-th base stations as a polynomial of x.
Input
The input consists of multiple datasets. Each dataset has the following format:
N M
u1 v1 p1
...
uM vM pM
The first line of each dataset contains two integers N (2 ≤ N ≤ 50) and M (0 ≤ M ≤ 500), which indicates the number of base stations and lines respectively. The following M lines describe the network structure. The i-th of them corresponds to the i-th network line and contains two integers ui and vi and a polynomial pi. ui and vi indicate the indices of base stations (1 ≤ ui, vi ≤ N); pi indicates the network bandwidth.
Each polynomial has the form of:
aLxL + aL-1xL-1 + ... + a2x2 + a1x + a0
where L (0 ≤ L ≤ 50) is the degree and ai's (0 ≤ i ≤ L, 0 ≤ ai ≤ 100) are the coefficients. In the input,
* each term aixi (for i ≥ 2) is represented as <ai>x^<i>
* the linear term (a1x) is represented as <a1>x;
* the constant (a0) is represented just by digits;
* these terms are given in the strictly decreasing order of the degrees and connected by a plus sign ("+");
* just like the standard notations, the <ai> is omitted if ai = 1 for non-constant terms;
* similarly, the entire term is omitted if ai = 0 for any terms; and
* the polynomial representations contain no space or characters other than digits, "x", "^", and "+".
For example, 2x2 + 3x + 5 is represented as 2x^2+3x+5; 2x3 + x is represented as 2x^3+x, not 2x^3+0x^2+1x+0 or the like. No polynomial is a constant zero, i.e. the one with all the coefficients being zero.
The end of input is indicated by a line with two zeros. This line is not part of any dataset.
Output
For each dataset, print the maximal bandwidth as a polynomial of x. The polynomial should be represented in the same way as the input format except that a constant zero is possible and should be represented by "0" (without quotes).
Example
Input
3 3
1 2 x+2
2 3 2x+1
3 1 x+1
2 0
3 2
1 2 x
2 3 2
4 3
1 2 x^3+2x^2+3x+4
2 3 x^2+2x+3
3 4 x+2
0 0
Output
2x+3
0
2
x+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.
Mike is trying rock climbing but he is awful at it.
There are n holds on the wall, i-th hold is at height a_{i} off the ground. Besides, let the sequence a_{i} increase, that is, a_{i} < a_{i} + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a_1, ..., a_{n} has difficulty $d = \operatorname{max}_{1 \leq i \leq n - 1}(a_{i + 1} - a_{i})$. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights a_1, ..., a_{n}. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
-----Input-----
The first line contains a single integer n (3 ≤ n ≤ 100) — the number of holds.
The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 1000), where a_{i} is the height where the hold number i hangs. The sequence a_{i} is increasing (i.e. each element except for the first one is strictly larger than the previous one).
-----Output-----
Print a single number — the minimum difficulty of the track after removing a single hold.
-----Examples-----
Input
3
1 4 6
Output
5
Input
5
1 2 3 4 5
Output
2
Input
5
1 2 3 7 8
Output
4
-----Note-----
In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.
In the second test after removing every hold the difficulty equals 2.
In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer — 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.
Polycarp is a great fan of television.
He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment l_{i} and ends at moment r_{i}.
Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.
Polycarp wants to check out all n shows. Are two TVs enough to do so?
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 2·10^5) — the number of shows.
Each of the next n lines contains two integers l_{i} and r_{i} (0 ≤ l_{i} < r_{i} ≤ 10^9) — starting and ending time of i-th show.
-----Output-----
If Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).
-----Examples-----
Input
3
1 2
2 3
4 5
Output
YES
Input
4
1 2
2 3
2 3
1 2
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.
You gave the twins Ai and Zu a program of games using strings. In this game, Ai and Zu each select a substring from the character string, compare them, and the person who chooses the smaller one will get points. The two competed and played the game many times. However, I got tired of playing games for the same string many times. So you decided to modify the program so that the strings change.
Given a string U of length N and Q statements, write a program that processes the following instructions.
* Replaces all characters in the specified range of string U with the specified characters.
* Compares the two specified substrings S and T of the string U in lexicographical order and outputs their magnitude relations.
Input
The input is given in the following format.
N
U
Q
query1
query2
::
queryQ
The string length N (1 ≤ N ≤ 200000) is given on the first line, and the string U (string containing only lowercase letters) is given on the second line. The number of instructions Q (1 ≤ Q ≤ 100000) is given on the third line. The following Q line is given the i-th instruction queryi. Each queryi is given in one of the following formats:
set x y z
Or
comp a b c d
set x y z means to replace the xth to yth characters of the string U with the specified character z. Where 1 ≤ x ≤ y ≤ N and z is lowercase.
comp abcd is a string S and a string, where S is the substring from the a to b of the string U and T is the substring of the string U from the c to the d. Represents comparing T in lexical order. Where 1 ≤ a ≤ b ≤ N and 1 ≤ c ≤ d ≤ N.
Output
For each comp instruction, if S is smaller, "s" is output, if T is smaller, "t" is output, and if both match, "e" is output on one line.
Example
Input
13
aizualgorithm
9
comp 1 1 4 5
comp 2 6 1 5
set 9 12 b
comp 9 9 10 10
comp 5 8 1 4
set 1 10 z
set 11 13 x
comp 8 10 1 5
comp 1 5 1 5
Output
s
t
e
t
s
e
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have $a$ strings "a", $b$ strings "b" and $c$ strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
-----Input-----
The first line contains three positive integers $a$, $b$, $c$ ($1 \leq a, b, c \leq 10^9$) — the number of strings "a", "b" and "ab" respectively.
-----Output-----
Print a single number — the maximum possible length of the good string you can obtain.
-----Examples-----
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
-----Note-----
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side n. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: (0, 0), (n, 0), (0, n) and (n, n).
Input
The single line contains 5 space-separated integers: n, x1, y1, x2, y2 (1 ≤ n ≤ 1000, 0 ≤ x1, y1, x2, y2 ≤ n) which correspondingly represent a side of the square, the coordinates of the first point and the coordinates of the second point. It is guaranteed that the points lie on the sides of the square.
Output
You must print on a single line the shortest distance between the points.
Examples
Input
2 0 0 1 0
Output
1
Input
2 0 1 2 1
Output
4
Input
100 0 0 100 100
Output
200
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 amount of information on the World Wide Web is growing quite rapidly. In this information explosion age, we must survive by accessing only the Web pages containing information relevant to our own needs. One of the key technologies for this purpose is keyword search. By using well-known search engines, we can easily access those pages containing useful information about the topic we want to know.
There are many variations in keyword search problems. If a single string is searched in a given text, the problem is quite easy. If the pattern to be searched consists of multiple strings, or is given by some powerful notation such as regular expressions, the task requires elaborate algorithms to accomplish efficiently.
In our problem, a number of strings (element strings) are given, but they are not directly searched for. Concatenations of all the element strings in any order are the targets of the search here.
For example, consider three element strings aa, b and ccc are given. In this case, the following six concatenated strings are the targets of the search, i.e. they should be searched in the text.
aabccc
aacccb
baaccc
bcccaa
cccaab
cccbaa
The text may contain several occurrences of these strings. You are requested to count the number of occurrences of these strings, or speaking more precisely, the number of positions of occurrences in the text.
Two or more concatenated strings may be identical. In such cases, it is necessary to consider subtle aspects of the above problem statement. For example, if two element strings are x and xx, the string xxx is an occurrence of both the concatenation of x and xx and that of xx and x. Since the number of positions of occurrences should be counted, this case is counted as one, not two.
Two occurrences may overlap. For example, the string xxxx has occurrences of the concatenation xxx in two different positions. This case is counted as two.
Input
The input consists of a number of datasets, each giving a set of element strings and a text. The format of a dataset is as follows.
n m
e1
e2
.
.
.
en
t1
t2
.
.
.
tm
The first line contains two integers separated by a space. n is the number of element strings. m is the number of lines used to represent the text. n is between 1 and 12, inclusive.
Each of the following n lines gives an element string. The length (number of characters) of an element string is between 1 and 20, inclusive. The last m lines as a whole give the text. Since it is not desirable to have a very long line, the text is separated into m lines by newlines, but these newlines should be ignored. They are not parts of the text. The length of each of these lines (not including the newline) is between 1 and 100, inclusive. The length of the text is between 1 and 5000, inclusive.
The element strings and the text do not contain characters other than lowercase letters.
The end of the input is indicated by a line containing two zeros separated by a space.
CAUTION! Although the sample input contains only small datasets, note that 12! × 5000 is far larger than 231 .
Output
For each dataset in the input, one line containing the number of matched positions should be output. An output line should not contain extra characters.
Example
Input
3 1
aa
b
ccc
aabccczbaacccbaazaabbcccaa
3 1
a
b
c
cbbcbcbabaacabccaccbaacbccbcaaaccccbcbcbbcacbaacccaccbbcaacbbabbabaccc
3 4
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
0 0
Output
5
12
197
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 History Lesson
Soundex is an interesting phonetic algorithm developed nearly 100 years ago for indexing names as they are pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling.
Reference: https://en.wikipedia.org/wiki/Soundex
# Preface
I first read about Soundex over 30 years ago. At the time it seemed to me almost like A.I. that you could just type in somebody's name the way it sounded and there was still a pretty good chance it could match the correct person record. That was about the same year as the first "Terminator" movie so it was easy for me to put 2 and 2 together and conclude that Arnie must have had some kind of futuristic Soundex chip in his titanium skull helping him to locate ```Serah Coner```... or was it ```Sarh Connor```... or maybe ```Sayra Cunnarr```...
:-)
# Task
In this Kata you will encode strings using a Soundex variation called "American Soundex" using the following (case insensitive) steps:
* Save the first letter. Remove all occurrences of ```h``` and ```w``` except first letter.
* Replace all consonants (include the first letter) with digits as follows:
* ```b```, ```f```, ```p```, ```v``` = 1
* ```c```, ```g```, ```j```, ```k```, ```q```, ```s```, ```x```, ```z``` = 2
* ```d```, ```t``` = 3
* ```l``` = 4
* ```m```, ```n``` = 5
* ```r``` = 6
* Replace all adjacent same digits with one digit.
* Remove all occurrences of ```a```, ```e```, ```i```, ```o```, ```u```, ```y``` except first letter.
* If first symbol is a digit replace it with letter saved on step 1.
* Append 3 zeros if result contains less than 3 digits. Remove all except first letter and 3 digits after it
## Input
A space separated string of one or more names. E.g.
```Sarah Connor```
## Output
Space separated string of equivalent Soundex codes (the first character of each code must be uppercase). E.g.
```S600 C560```
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Call two arms equally strong if the heaviest weights they each are able to lift are equal.
Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms.
Given your and your friend's arms' lifting capabilities find out if you two are equally strong.
# Example
For `yourLeft = 10, yourRight = 15, friendsLeft = 15 and friendsRight = 10`, the output should be `true`;
For `yourLeft = 15, yourRight = 10, friendsLeft = 15 and friendsRight = 10`, the output should be `true`;
For `yourLeft = 15, yourRight = 10, friendsLeft = 15 and friendsRight = 9,` the output should be `false`.
# Input/Output
- `[input]` integer `yourLeft`
A non-negative integer representing the heaviest weight you can lift with your left arm.
- `[input]` integer `yourRight`
A non-negative integer representing the heaviest weight you can lift with your right arm.
- `[input]` integer `friendsLeft`
A non-negative integer representing the heaviest weight your friend can lift with his or her left arm.
- `[input]` integer `friendsRight`
A non-negative integer representing the heaviest weight your friend can lift with his or her right arm.
- `[output]` a boolean value
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has n nodes (numbered 1 to n, with some node r as its root). There are a_i presents are hanging from the i-th node.
Before beginning the game, a special integer k is chosen. The game proceeds as follows:
* Alice begins the game, with moves alternating each turn;
* in any move, the current player may choose some node (for example, i) which has depth at least k. Then, the player picks some positive number of presents hanging from that node, let's call it m (1 ≤ m ≤ a_i);
* the player then places these m presents on the k-th ancestor (let's call it j) of the i-th node (the k-th ancestor of vertex i is a vertex j such that i is a descendant of j, and the difference between the depth of j and the depth of i is exactly k). Now, the number of presents of the i-th node (a_i) is decreased by m, and, correspondingly, a_j is increased by m;
* Alice and Bob both play optimally. The player unable to make a move loses the game.
For each possible root of the tree, find who among Alice or Bob wins the game.
Note: The depth of a node i in a tree with root r is defined as the number of edges on the simple path from node r to node i. The depth of root r itself is zero.
Input
The first line contains two space-separated integers n and k (3 ≤ n ≤ 10^5, 1 ≤ k ≤ 20).
The next n-1 lines each contain two integers x and y (1 ≤ x, y ≤ n, x ≠ y), denoting an undirected edge between the two nodes x and y. These edges form a tree of n nodes.
The next line contains n space-separated integers denoting the array a (0 ≤ a_i ≤ 10^9).
Output
Output n integers, where the i-th integer is 1 if Alice wins the game when the tree is rooted at node i, or 0 otherwise.
Example
Input
5 1
1 2
1 3
5 2
4 3
0 3 2 4 4
Output
1 0 0 1 1
Note
Let us calculate the answer for sample input with root node as 1 and as 2.
Root node 1
Alice always wins in this case. One possible gameplay between Alice and Bob is:
* Alice moves one present from node 4 to node 3.
* Bob moves four presents from node 5 to node 2.
* Alice moves four presents from node 2 to node 1.
* Bob moves three presents from node 2 to node 1.
* Alice moves three presents from node 3 to node 1.
* Bob moves three presents from node 4 to node 3.
* Alice moves three presents from node 3 to node 1.
Bob is now unable to make a move and hence loses.
Root node 2
Bob always wins in this case. One such gameplay is:
* Alice moves four presents from node 4 to node 3.
* Bob moves four presents from node 5 to node 2.
* Alice moves six presents from node 3 to node 1.
* Bob moves six presents from node 1 to node 2.
Alice is now unable to make a move and hence loses.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.
He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.
Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.
-----Constraints-----
- 3 ≦ N ≦ 10^{5}
- N is odd.
- 1 ≦ A_i ≦ 10^{5}
- A_i is an integer.
-----Input-----
The input is given from Standard Input in the following format:
N
A_1 A_2 A_3 ... A_{N}
-----Output-----
Print the answer.
-----Sample Input-----
5
1 2 1 3 7
-----Sample Output-----
3
One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 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.
Read problems statements in Mandarin Chinese and Russian.
Sereja is playing a game called Winner Eats Sandwich with his friends. There are N persons in total, including Sereja. Sereja is allotted the number 1, while his friends are allotted numbers from 2 to N. A set of this game consists of M parts. Probability that a player numbered i wins part j of any set is p[i][j]. Sereja and his friends play all the M parts of the first set. If someone wins all the parts, he is declared the winner of the match. Otherwise, another set of the game is played. A match of the game continues until someone wins a set. The winner of the set is then declared the winner of the game, and gets to eat the sandwich.
Now Sereja is interested in the probability with which he can win the match in no more than 10^(10^(10^(10^(10^{10})))) sets. This is because the sandwich gets cold by the end of these many sets, and Sereja hates cold sandwiches.
------ Input ------
First line contains the number of test cases, T. The description of the T tests follows. First line of each test case contains two space separated integers N, M. Each of the next N lines contain M space-separated numbers, with the j^{th} number of the i^{th} line denoting p[i][j]. All numbers will be given with not more than 4 digits after the decimal point.
------ Output ------
For each test case, output the probability Sereja is interested in, with 6 digits after the decimal point.
------ Constraints ------
$1 ≤ T ≤ 3$
$1 ≤ N ≤ 13$
$1 ≤ M ≤ 10000$
$it is guaranteed that for each j, the sum p[1][j] + p[2][j] + ... + p[N][j] is 1$
Subtask 1 (10 points)
$1 ≤ N, M ≤ 4$
Subtask 2 (90 points)
$Original constrains$
------ Example ------
Input:
2
2 2
1.0000 1.0000
0.0000 0.0000
2 3
0.5000 0.5000 0.5000
0.5000 0.5000 0.5000
Output:
1.000000
0.500000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N towns in Snuke Kingdom, conveniently numbered 1 through N. Town 1 is the capital.
Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place. The destination of the Teleporter of town i is town a_i (1≤a_i≤N). It is guaranteed that one can get to the capital from any town by using the Teleporters some number of times.
King Snuke loves the integer K. The selfish king wants to change the destination of the Teleporters so that the following holds:
* Starting from any town, one will be at the capital after using the Teleporters exactly K times in total.
Find the minimum number of the Teleporters whose destinations need to be changed in order to satisfy the king's desire.
Constraints
* 2≤N≤10^5
* 1≤a_i≤N
* One can get to the capital from any town by using the Teleporters some number of times.
* 1≤K≤10^9
Input
The input is given from Standard Input in the following format:
N K
a_1 a_2 ... a_N
Output
Print the minimum number of the Teleporters whose destinations need to be changed in order to satisfy King Snuke's desire.
Examples
Input
3 1
2 3 1
Output
2
Input
4 2
1 1 2 2
Output
0
Input
8 2
4 1 2 3 1 2 3 4
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.
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.
There are n stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks.
Each photo is described by two non-negative integers a and b, indicating that it is worth a units of happiness to Alice and b units of happiness to Bonnie. Values of a and b might differ for different photos.
It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.
The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has x happiness and Bonnie has y happiness at the end, you should print x - y.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the number of two-photo stacks. Then follow n lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers a1, b1, a2 and b2, each not exceeding 109. a1 and b1 describe the top photo in the stack, while a2 and b2 describe the bottom photo in the stack.
Output
Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.
Examples
Input
2
12 3 4 7
1 15 9 1
Output
1
Input
2
5 4 8 8
4 12 14 0
Output
4
Input
1
0 10 0 10
Output
-10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day in the IT lesson Anna and Maria learned about the lexicographic order.
String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages.
The teacher gave Anna and Maria homework. She gave them a string of length n. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the k-th string from the list. Help Anna and Maria do the homework.
Input
The first line contains a non-empty string that only consists of small Latin letters ("a"-"z"), whose length does not exceed 105. The second line contains the only integer k (1 ≤ k ≤ 105).
Output
Print the string Anna and Maria need — the k-th (in the lexicographical order) substring of the given string. If the total number of substrings is less than k, print a string saying "No such line." (without the quotes).
Examples
Input
aa
2
Output
a
Input
abc
5
Output
bc
Input
abab
7
Output
b
Note
In the second sample before string "bc" follow strings "a", "ab", "abc", "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.
A conglomerate consists of $n$ companies. To make managing easier, their owners have decided to merge all companies into one. By law, it is only possible to merge two companies, so the owners plan to select two companies, merge them into one, and continue doing so until there is only one company left.
But anti-monopoly service forbids to merge companies if they suspect unfriendly absorption. The criterion they use is the difference in maximum salaries between two companies. Merging is allowed only if the maximum salaries are equal.
To fulfill the anti-monopoly requirements, the owners can change salaries in their companies before merging. But the labor union insists on two conditions: it is only allowed to increase salaries, moreover all the employees in one company must get the same increase.
Sure enough, the owners want to minimize the total increase of all salaries in all companies. Help them find the minimal possible increase that will allow them to merge companies into one.
-----Input-----
The first line contains a single integer $n$ — the number of companies in the conglomerate ($1 \le n \le 2 \cdot 10^5$). Each of the next $n$ lines describes a company.
A company description start with an integer $m_i$ — the number of its employees ($1 \le m_i \le 2 \cdot 10^5$). Then $m_i$ integers follow: the salaries of the employees. All salaries are positive and do not exceed $10^9$.
The total number of employees in all companies does not exceed $2 \cdot 10^5$.
-----Output-----
Output a single integer — the minimal total increase of all employees that allows to merge all companies.
-----Example-----
Input
3
2 4 3
2 2 1
3 1 1 1
Output
13
-----Note-----
One of the optimal merging strategies is the following. First increase all salaries in the second company by $2$, and merge the first and the second companies. Now the conglomerate consists of two companies with salaries $[4, 3, 4, 3]$ and $[1, 1, 1]$. To merge them, increase the salaries in the second of those by $3$. The total increase is $2 + 2 + 3 + 3 + 3 = 13$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bob is a theoretical coder - he doesn't write code, but comes up with theories, formulas and algorithm ideas. You are his secretary, and he has tasked you with writing the code for his newest project - a method for making the short form of a word. Write a function ```shortForm```(C# ```ShortForm```, Python ```short_form```) that takes a string and returns it converted into short form using the rule: Remove all vowels, except for those that are the first or last letter. Do not count 'y' as a vowel, and ignore case. Also note, the string given will not have any spaces; only one word, and only Roman letters.
Example:
```
shortForm("assault");
short_form("assault")
ShortForm("assault");
// should return "asslt"
```
Also, FYI: I got all the words with no vowels from
https://en.wikipedia.org/wiki/English_words_without_vowels
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.
You can use the following theorem:
Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.
-----Constraints-----
- All values in input are integers.
- 3 \leq N \leq 10
- 1 \leq L_i \leq 100
-----Input-----
Input is given from Standard Input in the following format:
N
L_1 L_2 ... L_N
-----Output-----
If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.
-----Sample Input-----
4
3 8 5 1
-----Sample Output-----
Yes
Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
###BACKGROUND:
Jacob recently decided to get healthy and lose some weight. He did a lot of reading and research and after focusing on steady exercise and a healthy diet for several months, was able to shed over 50 pounds! Now he wants to share his success, and has decided to tell his friends and family how much weight they could expect to lose if they used the same plan he followed.
Lots of people are really excited about Jacob's program and they want to know how much weight they would lose if they followed his plan. Unfortunately, he's really bad at math, so he's turned to you to help write a program that will calculate the expected weight loss for a particular person, given their weight and how long they think they want to continue the plan.
###TECHNICAL DETAILS:
Jacob's weight loss protocol, if followed closely, yields loss according to a simple formulae, depending on gender. Men can expect to lose 1.5% of their current body weight each week they stay on plan. Women can expect to lose 1.2%. (Children are advised to eat whatever they want, and make sure to play outside as much as they can!)
###TASK:
Write a function that takes as input:
```
- The person's gender ('M' or 'F');
- Their current weight (in pounds);
- How long they want to stay true to the protocol (in weeks);
```
and then returns the expected weight at the end of the program.
###NOTES:
Weights (both input and output) should be decimals, rounded to the nearest tenth.
Duration (input) should be a whole number (integer). If it is not, the function should round to the nearest whole number.
When doing input parameter validity checks, evaluate them in order or your code will not pass final tests.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 H-by-W matrix. Let a_{ij} be the element at the i-th row from the top and j-th column from the left. In this matrix, each a_{ij} is a lowercase English letter.
Snuke is creating another H-by-W matrix, A', by freely rearranging the elements in A. Here, he wants to satisfy the following condition:
* Every row and column in A' can be read as a palindrome.
Determine whether he can create a matrix satisfying the condition.
Constraints
* 1 ≤ H, W ≤ 100
* a_{ij} is a lowercase English letter.
Input
Input is given from Standard Input in the following format:
H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}
Output
If Snuke can create a matrix satisfying the condition, print `Yes`; otherwise, print `No`.
Examples
Input
3 4
aabb
aabb
aacc
Output
Yes
Input
2 2
aa
bb
Output
No
Input
5 1
t
w
e
e
t
Output
Yes
Input
2 5
abxba
abyba
Output
No
Input
1 1
z
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.
Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.
To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.
-----Constraints-----
- 1≦A,B,C≦10
-----Input-----
The input is given from Standard Input in the following format:
A B C
-----Output-----
If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.
-----Sample Input-----
5 5 7
-----Sample Output-----
YES
Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Problem
Determine whether a positive integer number is **colorful** or not.
`263` is a colorful number because `[2, 6, 3, 2*6, 6*3, 2*6*3]` are all different; whereas `236` is not colorful, because `[2, 3, 6, 2*3, 3*6, 2*3*6]` have `6` twice.
So take all consecutive subsets of digits, take their product and ensure all the products are different.
## Examples
```pyhton
263 --> true
236 --> false
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem statement
Given the string $ S $. Find the number of all anagrams in $ S $ that are palindromic.
An anagram of the string $ X $ is an anagram of $ Y $, which means that $ X $ is equal to $ Y $, or that the rearranged characters of $ X $ are equal to $ Y $. For example, for the string abcd, abcd and cbda are anagrams, but abed, cab and abcdd are not anagrams.
When the string $ X $ is a palindrome, it means that the reverse reading of $ X $ is equal to $ X $ itself. For example, abc and ab are not palindromes, and a and abccba are palindromes.
Constraint
* $ 1 \ leq | S | \ leq 40 $ ($ | S | $ is the length of the string $ S $)
* $ S $ contains only lowercase letters.
* The answer is guaranteed to be less than $ 2 ^ {63} $.
input
Input follows the following format.
$ S $
output
Output the number on one line.
Examples
Input
ab
Output
0
Input
abba
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:
- Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?
-----Notes-----
A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.
For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.
-----Constraints-----
- 2 \leq N \leq 10^5
- 1 \leq Q \leq 10^5
- S is a string of length N.
- Each character in S is A, C, G or T.
- 1 \leq l_i < r_i \leq N
-----Input-----
Input is given from Standard Input in the following format:
N Q
S
l_1 r_1
:
l_Q r_Q
-----Output-----
Print Q lines. The i-th line should contain the answer to the i-th query.
-----Sample Input-----
8 3
ACACTACG
3 7
2 3
1 8
-----Sample Output-----
2
0
3
- Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.
- Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.
- Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $p$. For example, if $n = 3$, then $p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence will be $n \cdot n!$.
Let $1 \leq i \leq j \leq n \cdot n!$ be a pair of indices. We call the sequence $(p_i, p_{i+1}, \dots, p_{j-1}, p_j)$ a subarray of $p$. Its length is defined as the number of its elements, i.e., $j - i + 1$. Its sum is the sum of all its elements, i.e., $\sum_{k=i}^j p_k$.
You are given $n$. Find the number of subarrays of $p$ of length $n$ having sum $\frac{n(n+1)}{2}$. Since this number may be large, output it modulo $998244353$ (a prime number).
-----Input-----
The only line contains one integer $n$ ($1 \leq n \leq 10^6$), as described in the problem statement.
-----Output-----
Output a single integer — the number of subarrays of length $n$ having sum $\frac{n(n+1)}{2}$, modulo $998244353$.
-----Examples-----
Input
3
Output
9
Input
4
Output
56
Input
10
Output
30052700
-----Note-----
In the first sample, there are $16$ subarrays of length $3$. In order of appearance, they are:
$[1, 2, 3]$, $[2, 3, 1]$, $[3, 1, 3]$, $[1, 3, 2]$, $[3, 2, 2]$, $[2, 2, 1]$, $[2, 1, 3]$, $[1, 3, 2]$, $[3, 2, 3]$, $[2, 3, 1]$, $[3, 1, 3]$, $[1, 3, 1]$, $[3, 1, 2]$, $[1, 2, 3]$, $[2, 3, 2]$, $[3, 2, 1]$.
Their sums are $6$, $6$, $7$, $6$, $7$, $5$, $6$, $6$, $8$, $6$, $7$, $5$, $6$, $6$, $7$, $6$. As $\frac{n(n+1)}{2} = 6$, the answer is $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.
A chess board is normally played with 16 pawns and 16 other pieces, for this kata a variant will be played with only the pawns. All other pieces will not be on the board.
For information on how pawns move, refer [here](http://www.chesscorner.com/tutorial/basic/pawn/pawn.htm)
Write a function that can turn a list of pawn moves into a visual representation of the resulting board.
A chess move will be represented by a string,
```
"c3"
```
This move represents a pawn moving to `c3`. If it was white to move, the move would represent a pawn from `c2` moving to `c3`. If it was black to move, a pawn would move from `c4` to `c3`, because black moves in the other direction.
The first move in the list and every other move will be for white's pieces.
The letter represents the column, while the number represents the row of the square where the piece is moving
Captures are represented differently from normal moves:
```
"bxc3"
```
represents a pawn on the column represented by 'b' (the second column) capturing a pawn on `c3`.
For the sake of this kata a chess board will be represented by a list like this one:
```
[[".",".",".",".",".",".",".","."],
["p","p","p","p","p","p","p","p"],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".","."],
["P","P","P","P","P","P","P","P"],
[".",".",".",".",".",".",".","."]]
```
Here is an example of the board with the squares labeled:
```
[["a8","b8","c8","d8","e8","f8","g8","h8"],
["a7","b7","c7","d7","e7","f7","g7","h7"],
["a6","b6","c6","d6","e6","f6","g6","h6"],
["a5","b5","c5","d5","e5","f5","g5","h5"],
["a4","b4","c4","d4","e4","f4","g4","h4"],
["a3","b3","c3","d3","e3","f3","g3","h3"],
["a2","b2","c2","d2","e2","f2","g2","h2"],
["a1","b1","c1","d1","e1","f1","g1","h1"]]
```
White pawns are represented by capital `'P'` while black pawns are lowercase `'p'`.
A few examples
```
If the list/array of moves is: ["c3"]
>>>
[[".",".",".",".",".",".",".","."],
["p","p","p","p","p","p","p","p"],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".","."],
[".",".",".",".",".",".",".","."],
[".",".","P",".",".",".",".","."],
["P","P",".","P","P","P","P","P"],
[".",".",".",".",".",".",".","."]]
```
add a few more moves,
```
If the list/array of moves is: ["d4", "d5", "f3", "c6", "f4"]
>>>
[[".",".",".",".",".",".",".","."],
["p","p",".",".","p","p","p","p"],
[".",".","p",".",".",".",".","."],
[".",".",".","p",".",".",".","."],
[".",".",".","P",".","P",".","."],
[".",".",".",".",".",".",".","."],
["P","P","P",".","P",".","P","P"],
[".",".",".",".",".",".",".","."]]
```
now to add a capture...
```
If the list/array of moves is: ["d4", "d5", "f3", "c6", "f4", "c5", "dxc5"]
>>>
[[".",".",".",".",".",".",".","."],
["p","p",".",".","p","p","p","p"],
[".",".",".",".",".",".",".","."],
[".",".","P","p",".",".",".","."],
[".",".",".",".",".","P",".","."],
[".",".",".",".",".",".",".","."],
["P","P","P",".","P",".","P","P"],
[".",".",".",".",".",".",".","."]]
```
If an invalid move (a move is added that no pawn could perform, a capture where there is no piece, a move to a square where there is already a piece, etc.) is found in the list of moves, return '(move) is invalid'.
```python
If the list/array of moves is: ["e6"]
>>>
"e6 is invalid"
```
```python
If the list/array of moves is: ["e4", "d5", "exf5"]
>>>
"exf5 is invalid"
```
The list passed to `pawn_move_tracker / PawnMoveTracker.movePawns` will always be a list of strings in the form (regex pattern): `[a-h][1-8]` or `[a-h]x[a-h][1-8]`.
Notes:
* In the case of a capture, the first lowercase letter will always be adjacent to the second in the alphabet, a move like `axc5` will never be passed.
* A pawn can move two spaces on its first move
* There are no cases with the 'en-passant' rule.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: Swap two neighboring matrix rows, that is, rows with indexes i and i + 1 for some integer i (1 ≤ i < 5). Swap two neighboring matrix columns, that is, columns with indexes j and j + 1 for some integer j (1 ≤ j < 5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
-----Input-----
The input consists of five lines, each line contains five integers: the j-th integer in the i-th line of the input represents the element of the matrix that is located on the intersection of the i-th row and the j-th column. It is guaranteed that the matrix consists of 24 zeroes and a single number one.
-----Output-----
Print a single integer — the minimum number of moves needed to make the matrix beautiful.
-----Examples-----
Input
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Output
3
Input
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
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.
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.
There are $n$ banknote denominations on Mars: the value of $i$-th banknote is $a_i$. Natasha has an infinite number of banknotes of each denomination.
Martians have $k$ fingers on their hands, so they use a number system with base $k$. In addition, the Martians consider the digit $d$ (in the number system with base $k$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $k$ is $d$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.
Determine for which values $d$ Natasha can make the Martians happy.
Natasha can use only her banknotes. Martians don't give her change.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 100\,000$, $2 \le k \le 100\,000$) — the number of denominations of banknotes and the base of the number system on Mars.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — denominations of banknotes on Mars.
All numbers are given in decimal notation.
-----Output-----
On the first line output the number of values $d$ for which Natasha can make the Martians happy.
In the second line, output all these values in increasing order.
Print all numbers in decimal notation.
-----Examples-----
Input
2 8
12 20
Output
2
0 4
Input
3 10
10 20 30
Output
1
0
-----Note-----
Consider the first test case. It uses the octal number system.
If you take one banknote with the value of $12$, you will get $14_8$ in octal system. The last digit is $4_8$.
If you take one banknote with the value of $12$ and one banknote with the value of $20$, the total value will be $32$. In the octal system, it is $40_8$. The last digit is $0_8$.
If you take two banknotes with the value of $20$, the total value will be $40$, this is $50_8$ in the octal system. The last digit is $0_8$.
No other digits other than $0_8$ and $4_8$ can be obtained. Digits $0_8$ and $4_8$ could also be obtained in other ways.
The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are wandering in the explorer space of the 2050 Conference.
The explorer space can be viewed as an undirected weighted grid graph with size n× m. The set of vertices is \{(i, j)|1≤ i≤ n, 1≤ j≤ m\}. Two vertices (i_1,j_1) and (i_2, j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1.
At each step, you can walk to any vertex connected by an edge with your current vertex. On each edge, there are some number of exhibits. Since you already know all the exhibits, whenever you go through an edge containing x exhibits, your boredness increases by x.
For each starting vertex (i, j), please answer the following question: What is the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps?
You can use any edge for multiple times but the boredness on those edges are also counted for multiple times. At each step, you cannot stay on your current vertex. You also cannot change direction while going through an edge. Before going back to your starting vertex (i, j) after k steps, you can visit (i, j) (or not) freely.
Input
The first line contains three integers n, m and k (2≤ n, m≤ 500, 1≤ k≤ 20).
The j-th number (1≤ j ≤ m - 1) in the i-th line of the following n lines is the number of exibits on the edge between vertex (i, j) and vertex (i, j+1).
The j-th number (1≤ j≤ m) in the i-th line of the following n-1 lines is the number of exibits on the edge between vertex (i, j) and vertex (i+1, j).
The number of exhibits on each edge is an integer between 1 and 10^6.
Output
Output n lines with m numbers each. The j-th number in the i-th line, answer_{ij}, should be the minimum possible boredness if you walk from (i, j) and go back to it after exactly k steps.
If you cannot go back to vertex (i, j) after exactly k steps, answer_{ij} should be -1.
Examples
Input
3 3 10
1 1
1 1
1 1
1 1 1
1 1 1
Output
10 10 10
10 10 10
10 10 10
Input
2 2 4
1
3
4 2
Output
4 4
10 6
Input
2 2 3
1
2
3 4
Output
-1 -1
-1 -1
Note
In the first example, the answer is always 10 no matter how you walk.
In the second example, answer_{21} = 10, the path is (2,1) → (1,1) → (1,2) → (2,2) → (2,1), the boredness is 4 + 1 + 2 + 3 = 10.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Hint
In solving this problem, the following may be referred to. Shows how to convert an integer value to a string. Assign value as a string to str.
For C
include <stdio.h>
int main () {
int value = 123; // Convert this value to a string
char str [6]; // This variable contains a string of value
sprintf (str, "% d", value);
return 0;
}
For C ++
include <sstream>
using namespace std;
int main () {
int value = 123; // Convert this value to a string
string str; // This variable contains a string of value
stringstream ss;
ss << value;
ss >> str;
return 0;
}
For JAVA
class Main {
public static void main (String args []) {
int value = 123; // Convert this value to a string
String str = new Integer (value) .toString (); // This variable contains a string of value
}
}
Constraints
The input satisfies the following conditions.
* 1 ≤ n ≤ 5
* 0 ≤ m ≤ 500
* 1 ≤ ci ≤ 1000 (0 ≤ i ≤ 9)
Input
n m
c0 c1 c2 ... c9
Two integers n and m are given on the first line, separated by blanks. n is the number of plates to purchase, and m is the amount of money you have.
On the second line, 10 integers are given, separated by blanks. ci (i is 0 or more and 9 or less) represents the price of the plate with i written in the table.
Output
Buy n plates and put them in any order to output the minimum number of values you can.
If some 0s are included at the beginning, output as it is. (For example, if the answer is 0019, output 0019 as it is instead of removing the leading 0 to make it 19.) If you cannot purchase n plates with the amount of money you have, output "NA".
Examples
Input
1 10
1 2 3 4 5 6 7 8 9 10
Output
0
Input
3 10
8 4 5 3 5 6 9 10 11 2
Output
119
Input
5 30
25 51 32 9 2 1 10 2 5 10
Output
04555
Input
5 100
101 101 101 101 101 101 101 101 101 101
Output
NA
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.
More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.
Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.
Constraints
* 2 \leq N \leq 200,000
* 2 \leq K \leq N
* (p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
p_1 p_2 ... p_N
Output
Print the expected value modulo 998244353.
Examples
Input
3 2
1 2 3
Output
1
Input
10 3
1 8 4 9 2 3 7 10 5 6
Output
164091855
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.
You are given a connected undirected graph with $n$ vertices and $m$ weighted edges. There are $k$ special vertices: $x_1, x_2, \ldots, x_k$.
Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them.
For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.
The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.
-----Input-----
The first line contains three integers $n$, $m$ and $k$ ($2 \leq k \leq n \leq 10^5$, $n-1 \leq m \leq 10^5$) — the number of vertices, the number of edges and the number of special vertices.
The second line contains $k$ distinct integers $x_1, x_2, \ldots, x_k$ ($1 \leq x_i \leq n$).
Each of the following $m$ lines contains three integers $u$, $v$ and $w$ ($1 \leq u,v \leq n, 1 \leq w \leq 10^9$), denoting there is an edge between $u$ and $v$ of weight $w$. The given graph is undirected, so an edge $(u, v)$ can be used in the both directions.
The graph may have multiple edges and self-loops.
It is guaranteed, that the graph is connected.
-----Output-----
The first and only line should contain $k$ integers. The $i$-th integer is the distance between $x_i$ and the farthest special vertex from it.
-----Examples-----
Input
2 3 2
2 1
1 2 3
1 2 2
2 2 1
Output
2 2
Input
4 5 3
1 2 3
1 2 5
4 2 1
2 3 2
1 4 4
1 3 3
Output
3 3 3
-----Note-----
In the first example, the distance between vertex $1$ and $2$ equals to $2$ because one can walk through the edge of weight $2$ connecting them. So the distance to the farthest node for both $1$ and $2$ equals to $2$.
In the second example, one can find that distance between $1$ and $2$, distance between $1$ and $3$ are both $3$ and the distance between $2$ and $3$ is $2$.
The graph may have multiple edges between and self-loops, as in the first example.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A famous gang of pirates, Sea Dogs, has come back to their hideout from one of their extravagant plunders. They want to split their treasure fairly amongst themselves, that is why You, their trusted financial advisor, devised a game to help them:
All of them take a sit at their round table, some of them with the golden coins they have just stolen. At each iteration of the game if one of them has equal or more than 2 coins, he is eligible to the splitting and he gives one coin to each pirate sitting next to him. If there are more candidates (pirates with equal or more than 2 coins) then You are the one that chooses which one of them will do the splitting in that iteration. The game ends when there are no more candidates eligible to do the splitting.
Pirates can call it a day, only when the game ends. Since they are beings with a finite amount of time at their disposal, they would prefer if the game that they are playing can end after finite iterations, and if so, they call it a good game. On the other hand, if no matter how You do the splitting, the game cannot end in finite iterations, they call it a bad game. Can You help them figure out before they start playing if the game will be good or bad?
Input
The first line of input contains two integer numbers n and k (1 ≤ n ≤ 10^{9}, 0 ≤ k ≤ 2⋅10^5), where n denotes total number of pirates and k is the number of pirates that have any coins.
The next k lines of input contain integers a_i and b_i (1 ≤ a_i ≤ n, 1 ≤ b_i ≤ 10^{9}), where a_i denotes the index of the pirate sitting at the round table (n and 1 are neighbours) and b_i the total number of coins that pirate a_i has at the start of the game.
Output
Print 1 if the game is a good game: There is a way to do the splitting so the game ends after finite number of iterations.
Print -1 if the game is a bad game: No matter how You do the splitting the game does not end in finite number of iterations.
Examples
Input
4 2
1 2
2 2
Output
1
Input
6 2
2 3
4 1
Output
1
Input
3 2
1 1
2 2
Output
-1
Note
In the third example the game has no end, because You always only have only one candidate, after whose splitting you end up in the same position as the starting one.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Suzuki has opened a new mobile sales shop for freshly squeezed milk in the Aizu area. It is assumed that all the customers who come to buy that day are already in the store with bottles to take home and will not increase any more. Customers only order once each. There is only one faucet in the tank, so you have to sell them one by one. Therefore, Mr. Suzuki wants to reduce the waiting time for customers in line as much as possible.
The number of customers and the time it takes for the customer to pour milk are given as inputs. You check the order of orders to minimize the customer's "total waiting time" (hereinafter referred to as "total waiting time") on behalf of Mr. Suzuki, and then "total waiting time" at that time. Please create a program that outputs "" and exits. However, the number of customers is 10,000 or less, and the time required for each person is 60 minutes or less.
For example, if the number of customers is 5, and the time required for each customer is 2,6,4,3,9 minutes in order, the "total waiting time" will be 37 minutes in that order. The following example swaps the second and third people in the order of the first column. In this case, the total wait time is 35 minutes. The optimal order takes 31 minutes.
Waiting time |
--- | --- | ---
1st person 2 minutes | 0 minutes |
2nd person 6 minutes | 2 minutes |
3rd person 4 minutes | 8 minutes |
4th person 3 minutes | 12 minutes |
5th person 9 minutes | 15 minutes |
37 minutes | ← "Total waiting time"
Example of swapping the second and third person
Waiting time |
--- | --- | ---
1st person 2 minutes | 0 minutes |
2nd person 4 minutes | 2 minutes |
3rd person 6 minutes | 6 minutes |
4th person 3 minutes | 12 minutes |
5th person 9 minutes | 15 minutes |
| 35 minutes | ← "Total waiting time"
Input
Given multiple datasets. Each dataset is given in the following format:
n
t1
t2
::
tn
The first line gives the number of customers n (n ≤ 10,000). The next n lines are given the integer ti (0 ≤ ti ≤ 60), which represents the time required by the i-th customer, in each line.
The input ends with a line containing one 0. The number of datasets does not exceed 50.
Output
For each data set, output the total waiting time (integer) on one line.
Example
Input
5
2
6
4
3
9
0
Output
31
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a rooted tree, find the lowest common ancestor of two nodes u and v.
The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
Input
n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.
In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.
Output
For each query, print the LCA of u and v in a line.
Example
Input
8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2
Output
1
1
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.
You are given a string S consisting of 0 and 1.
Find the maximum integer K not greater than |S| such that we can turn all the characters of S into 0 by repeating the following operation some number of times.
- Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfied). For each integer i such that l\leq i\leq r, do the following: if S_i is 0, replace it with 1; if S_i is 1, replace it with 0.
-----Constraints-----
- 1\leq |S|\leq 10^5
- S_i(1\leq i\leq N) is either 0 or 1.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the maximum integer K such that we can turn all the characters of S into 0 by repeating the operation some number of times.
-----Sample Input-----
010
-----Sample Output-----
2
We can turn all the characters of S into 0 by the following operations:
- Perform the operation on the segment S[1,3] with length 3. S is now 101.
- Perform the operation on the segment S[1,2] with length 2. S is now 011.
- Perform the operation on the segment S[2,3] with length 2. S is now 000.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from a_{i} to b_{i}. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.
Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends.
Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers a_{i} and b_{i} (1 ≤ a_{i} ≤ b_{i} ≤ 366), providing that the i-th friend can come to the party from day a_{i} to day b_{i} inclusive.
-----Output-----
Print the maximum number of people that may come to Famil Door's party.
-----Examples-----
Input
4
M 151 307
F 343 352
F 117 145
M 24 128
Output
2
Input
6
M 128 130
F 128 131
F 131 140
F 131 141
M 131 200
M 140 200
Output
4
-----Note-----
In the first sample, friends 3 and 4 can come on any day in range [117, 128].
In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by A grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts C[i] because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of K grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output -1.
Input
The first one contains two integer numbers, integers N (1 ≤ N ≤ 10^5) and K (1 ≤ K ≤ 10^5) – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains N integer numbers X[i] (1 ≤ X[i] ≤ 10^9) separated by a single space representing how many grams Alan wants to lift on day i. The third line contains one integer number A (1 ≤ A ≤ 10^9) representing permanent performance gains from a single drink. The last line contains N integer numbers C[i] (1 ≤ C[i] ≤ 10^9) , representing cost of performance booster drink in the gym he visits on day i.
Output
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
Examples
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
Note
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 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.
When Masha came to math classes today, she saw two integer sequences of length $n - 1$ on the blackboard. Let's denote the elements of the first sequence as $a_i$ ($0 \le a_i \le 3$), and the elements of the second sequence as $b_i$ ($0 \le b_i \le 3$).
Masha became interested if or not there is an integer sequence of length $n$, which elements we will denote as $t_i$ ($0 \le t_i \le 3$), so that for every $i$ ($1 \le i \le n - 1$) the following is true: $a_i = t_i | t_{i + 1}$ (where $|$ denotes the bitwise OR operation) and $b_i = t_i \& t_{i + 1}$ (where $\&$ denotes the bitwise AND operation).
The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence $t_i$ of length $n$ exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 10^5$) — the length of the sequence $t_i$.
The second line contains $n - 1$ integers $a_1, a_2, \ldots, a_{n-1}$ ($0 \le a_i \le 3$) — the first sequence on the blackboard.
The third line contains $n - 1$ integers $b_1, b_2, \ldots, b_{n-1}$ ($0 \le b_i \le 3$) — the second sequence on the blackboard.
-----Output-----
In the first line print "YES" (without quotes), if there is a sequence $t_i$ that satisfies the conditions from the statements, and "NO" (without quotes), if there is no such sequence.
If there is such a sequence, on the second line print $n$ integers $t_1, t_2, \ldots, t_n$ ($0 \le t_i \le 3$) — the sequence that satisfies the statements conditions.
If there are multiple answers, print any of them.
-----Examples-----
Input
4
3 3 2
1 2 0
Output
YES
1 3 2 0
Input
3
1 3
3 2
Output
NO
-----Note-----
In the first example it's easy to see that the sequence from output satisfies the given conditions: $t_1 | t_2 = (01_2) | (11_2) = (11_2) = 3 = a_1$ and $t_1 \& t_2 = (01_2) \& (11_2) = (01_2) = 1 = b_1$; $t_2 | t_3 = (11_2) | (10_2) = (11_2) = 3 = a_2$ and $t_2 \& t_3 = (11_2) \& (10_2) = (10_2) = 2 = b_2$; $t_3 | t_4 = (10_2) | (00_2) = (10_2) = 2 = a_3$ and $t_3 \& t_4 = (10_2) \& (00_2) = (00_2) = 0 = b_3$.
In the second example there is no such sequence.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 can change a string t of length N into a string t' of length N - 1 under the following rule:
* For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.
There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same. Find the minimum necessary number of operations.
Constraints
* 1 ≤ |s| ≤ 100
* s consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
Output
Print the minimum necessary number of operations to achieve the objective.
Examples
Input
serval
Output
3
Input
jackal
Output
2
Input
zzz
Output
0
Input
whbrjpjyhsrywlqjxdbrbaomnw
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.
Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!
You are given an array $a$ of $n$ integers. You are also given $q$ queries of two types:
Replace $i$-th element in the array with integer $x$.
Replace each element in the array with integer $x$.
After performing each query you have to calculate the sum of all elements in the array.
-----Input-----
The first line contains two integers $n$ and $q$ ($1 \le n, q \le 2 \cdot 10^5$) — the number of elements in the array and the number of queries, respectively.
The second line contains $n$ integers $a_1, \ldots, a_n$ ($1 \le a_i \le 10^9$) — elements of the array $a$.
Each of the following $q$ lines contains a description of the corresponding query. Description begins with integer $t$ ($t \in \{1, 2\}$) which denotes a type of the query:
If $t = 1$, then two integers $i$ and $x$ are following ($1 \le i \le n$, $1 \le x \le 10^9$) — position of replaced element and it's new value.
If $t = 2$, then integer $x$ is following ($1 \le x \le 10^9$) — new value of each element in the array.
-----Output-----
Print $q$ integers, each on a separate line. In the $i$-th line print the sum of all elements in the array after performing the first $i$ queries.
-----Examples-----
Input
5 5
1 2 3 4 5
1 1 5
2 10
1 5 11
1 4 1
2 1
Output
19
50
51
42
5
-----Note-----
Consider array from the example and the result of performing each query:
Initial array is $[1, 2, 3, 4, 5]$.
After performing the first query, array equals to $[5, 2, 3, 4, 5]$. The sum of all elements is $19$.
After performing the second query, array equals to $[10, 10, 10, 10, 10]$. The sum of all elements is $50$.
After performing the third query, array equals to $[10, 10, 10, 10, 11$]. The sum of all elements is $51$.
After performing the fourth query, array equals to $[10, 10, 10, 1, 11]$. The sum of all elements is $42$.
After performing the fifth query, array equals to $[1, 1, 1, 1, 1]$. The sum of all elements is $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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.