question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 Γ 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone β neither any other statues, nor Anna, nor Maria.
Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is β to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared.
At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner.
Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error.
Input
You are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one β for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S".
It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S".
Output
If Maria wins, print string "WIN". If the statues win, print string "LOSE".
Examples
Input
.......A
........
........
........
........
........
........
M.......
Output
WIN
Input
.......A
........
........
........
........
........
SS......
M.......
Output
LOSE
Input
.......A
........
........
........
........
.S......
S.......
MS......
Output
LOSE
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has a string $s$ consisting of lowercase English letters. He defines $s'$ to be the string after removing all "a" characters from $s$ (keeping all other characters in the same order). He then generates a new string $t$ by concatenating $s$ and $s'$. In other words, $t=s+s'$ (look at notes for an example).
You are given a string $t$. Your task is to find some $s$ that Bob could have used to generate $t$. It can be shown that if an answer exists, it will be unique.
-----Input-----
The first line of input contains a string $t$ ($1 \leq |t| \leq 10^5$) consisting of lowercase English letters.
-----Output-----
Print a string $s$ that could have generated $t$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters).
-----Examples-----
Input
aaaaa
Output
aaaaa
Input
aacaababc
Output
:(
Input
ababacacbbcc
Output
ababacac
Input
baba
Output
:(
-----Note-----
In the first example, we have $s = $ "aaaaa", and $s' = $ "".
In the second example, no such $s$ can work that will generate the given $t$.
In the third example, we have $s = $ "ababacac", and $s' = $ "bbcc", and $t = s + s' = $ "ababacacbbcc".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 a sequence of items and a specific item in that sequence, return the item immediately following the item specified. If the item occurs more than once in a sequence, return the item after the first occurence. This should work for a sequence of any type.
When the item isn't present or nothing follows it, the function should return nil in Clojure and Elixir, Nothing in Haskell, undefined in JavaScript, None in Python.
```python
next_item([1, 2, 3, 4, 5, 6, 7], 3) # => 4
next_item(['Joe', 'Bob', 'Sally'], 'Bob') # => "Sally"
```
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 will play a one-player game using a number line and N pieces.
First, we place each of these pieces at some integer coordinate.
Here, multiple pieces can be placed at the same coordinate.
Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:
Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.
Note that the coordinates where we initially place the pieces are already regarded as visited.
Find the minimum number of moves required to achieve the objective.
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 10^5
- 1 \leq M \leq 10^5
- -10^5 \leq X_i \leq 10^5
- X_1, X_2, ..., X_M are all different.
-----Input-----
Input is given from Standard Input in the following format:
N M
X_1 X_2 ... X_M
-----Output-----
Find the minimum number of moves required to achieve the objective.
-----Sample Input-----
2 5
10 12 1 2 14
-----Sample Output-----
5
The objective can be achieved in five moves as follows, and this is the minimum number of moves required.
- Initially, put the two pieces at coordinates 1 and 10.
- Move the piece at coordinate 1 to 2.
- Move the piece at coordinate 10 to 11.
- Move the piece at coordinate 11 to 12.
- Move the piece at coordinate 12 to 13.
- Move the piece at coordinate 13 to 14.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.
One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.
Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.
Input
The first input line contains an integer n (2 β€ n β€ 100). The second line contains n - 1 integers di (1 β€ di β€ 100). The third input line contains two integers a and b (1 β€ a < b β€ n). The numbers on the lines are space-separated.
Output
Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.
Examples
Input
3
5 6
1 2
Output
5
Input
3
5 6
1 3
Output
11
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 will have a list of rationals in the form
```
lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ]
```
or
```
lst = [ (numer_1, denom_1) , ... , (numer_n, denom_n) ]
```
where all numbers are positive integers. You have to produce their sum `N / D` in an irreducible form: this means that `N` and `D` have only `1` as a common divisor.
Return the result in the form:
- `[N, D]` in Ruby, Crystal, Python, Clojure, JS, CS, PHP, Julia
- `Just "N D"` in Haskell, PureScript
- `"[N, D]"` in Java, CSharp, TS, Scala, PowerShell, Kotlin
- `"N/D"` in Go, Nim
- `{N, D}` in C++, Elixir
- `{N, D}` in C
- `Some((N, D))` in Rust
- `Some "N D"` in F#, Ocaml
- `c(N, D)` in R
- `(N, D)` in Swift
- `'(N D)` in Racket
If the result is an integer (`D` evenly divides `N`) return:
- an integer in Ruby, Crystal, Elixir, Clojure, Python, JS, CS, PHP, R, Julia
- `Just "n"` (Haskell, PureScript)
- `"n"` Java, CSharp, TS, Scala, PowerShell, Go, Nim, Kotlin
- `{n, 1}` in C++
- `{n, 1}` in C
- `Some((n, 1))` in Rust
- `Some "n"` in F#, Ocaml,
- `(n, 1)` in Swift
- `n` in Racket
If the input list is empty, return
- `nil/None/null/Nothing`
- `{0, 1}` in C++
- `{0, 1}` in C
- `"0"` in Scala, PowerShell, Go, Nim
- `O` in Racket
- `""` in Kotlin
### Example:
```
[ [1, 2], [1, 3], [1, 4] ] --> [13, 12]
1/2 + 1/3 + 1/4 = 13/12
```
### Note
See sample tests for more examples and the form of results.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.
For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.
There are <image> non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.
Input
The first line of the input contains a single integer n (1 β€ n β€ 5000) β the number of balls.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ n) where ti is the color of the i-th ball.
Output
Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.
Examples
Input
4
1 2 1 2
Output
7 3 0 0
Input
3
1 1 1
Output
6 0 0
Note
In the first sample, color 2 is dominant in three intervals:
* An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color.
* An interval [4, 4] contains one ball, with color 2 again.
* An interval [2, 4] contains two balls of color 2 and one ball of color 1.
There are 7 more intervals and color 1 is dominant in all of them.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence a_1, a_2, β¦, a_n of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.
Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.
Let's denote the fingers of hand by numbers from 1 to 5. We call a fingering any sequence b_1, β¦, b_n of fingers numbers. A fingering is convenient if for all 1β€ i β€ n - 1 the following holds:
* if a_i < a_{i+1} then b_i < b_{i+1}, because otherwise Paul needs to take his hand off the keyboard to play the (i+1)-st note;
* if a_i > a_{i+1} then b_i > b_{i+1}, because of the same;
* if a_i = a_{i+1} then b_iβ b_{i+1}, because using the same finger twice in a row is dumb. Please note that there is β , not = between b_i and b_{i+1}.
Please provide any convenient fingering or find out that there is none.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) denoting the number of notes.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2β
10^5) denoting the positions of notes on the keyboard.
Output
If there is no convenient fingering, print -1. Otherwise, print n numbers b_1, b_2, β¦, b_n, each from 1 to 5, denoting a convenient fingering, separated by spaces.
Examples
Input
5
1 1 4 2 2
Output
1 4 5 4 5
Input
7
1 5 7 8 10 3 1
Output
1 2 3 4 5 4 3
Input
19
3 3 7 9 8 8 8 8 7 7 7 7 5 3 3 3 3 8 8
Output
1 3 4 5 4 5 4 5 4 5 4 5 4 3 5 4 3 5 4
Note
The third sample test is kinda "Non stop" song by Reflex.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequence of non-negative integers a_1, a_2, ..., a_{n} of length n is called a wool sequence if and only if there exists two integers l and r (1 β€ l β€ r β€ n) such that $a_{l} \oplus a_{l + 1} \oplus \cdots \oplus a_{r} = 0$. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.
The expression $x \oplus y$ means applying the operation of a bitwise xor to numbers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal β as "xor".
In this problem you are asked to compute the number of sequences made of n integers from 0 to 2^{m} - 1 that are not a wool sequence. You should print this number modulo 1000000009 (10^9 + 9).
-----Input-----
The only line of input contains two space-separated integers n and m (1 β€ n, m β€ 10^5).
-----Output-----
Print the required number of sequences modulo 1000000009 (10^9 + 9) on the only line of output.
-----Examples-----
Input
3 2
Output
6
-----Note-----
Sequences of length 3 made of integers 0, 1, 2 and 3 that are not a wool sequence are (1, 3, 1), (1, 2, 1), (2, 1, 2), (2, 3, 2), (3, 1, 3) and (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.
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?
-----Input-----
The first line of input contains an integer t (0 < t < 180) β the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) β the angle the robot can make corners at measured in degrees.
-----Output-----
For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.
-----Examples-----
Input
3
30
60
90
Output
NO
YES
YES
-----Note-----
In the first test case, it is impossible to build the fence, since there is no regular polygon with angle $30^{\circ}$.
In the second test case, the fence is a regular triangle, and in the last test case β a square.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 final match of the Berland Football Cup has been held recently. The referee has shown $n$ yellow cards throughout the match. At the beginning of the match there were $a_1$ players in the first team and $a_2$ players in the second team.
The rules of sending players off the game are a bit different in Berland football. If a player from the first team receives $k_1$ yellow cards throughout the match, he can no longer participate in the match β he's sent off. And if a player from the second team receives $k_2$ yellow cards, he's sent off. After a player leaves the match, he can no longer receive any yellow cards. Each of $n$ yellow cards was shown to exactly one player. Even if all players from one team (or even from both teams) leave the match, the game still continues.
The referee has lost his records on who has received each yellow card. Help him to determine the minimum and the maximum number of players that could have been thrown out of the game.
-----Input-----
The first line contains one integer $a_1$ $(1 \le a_1 \le 1\,000)$ β the number of players in the first team.
The second line contains one integer $a_2$ $(1 \le a_2 \le 1\,000)$ β the number of players in the second team.
The third line contains one integer $k_1$ $(1 \le k_1 \le 1\,000)$ β the maximum number of yellow cards a player from the first team can receive (after receiving that many yellow cards, he leaves the game).
The fourth line contains one integer $k_2$ $(1 \le k_2 \le 1\,000)$ β the maximum number of yellow cards a player from the second team can receive (after receiving that many yellow cards, he leaves the game).
The fifth line contains one integer $n$ $(1 \le n \le a_1 \cdot k_1 + a_2 \cdot k_2)$ β the number of yellow cards that have been shown during the match.
-----Output-----
Print two integers β the minimum and the maximum number of players that could have been thrown out of the game.
-----Examples-----
Input
2
3
5
1
8
Output
0 4
Input
3
1
6
7
25
Output
4 4
Input
6
4
9
10
89
Output
5 9
-----Note-----
In the first example it could be possible that no player left the game, so the first number in the output is $0$. The maximum possible number of players that could have been forced to leave the game is $4$ β one player from the first team, and three players from the second.
In the second example the maximum possible number of yellow cards has been shown $(3 \cdot 6 + 1 \cdot 7 = 25)$, so in any case all players were sent off.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Areas on the Cross-Section Diagram
Your task is to simulate a flood damage.
For a given cross-section diagram, reports areas of flooded sections.
<image>
Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides. For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.
output
Report the areas of floods in the following format:
$A$
$k$ $L_1$ $L_2$ ... $L_k$
In the first line, print the total area $A$ of created floods.
In the second line, print the number of floods $k$ and areas $L_i (i = 1, 2, ..., k)$ for each flood from the left side of the cross-section diagram. Print a space character before $L_i$.
Constraints
* $1 \leq$ length of the string $\leq 20,000$
Input
A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\\///\\_/\/\\\\\\\/_/\\\///__\\\\\\_\\\/_\/_/\".
Examples
Input
\\//
Output
4
1 4
Input
\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\
Output
35
5 4 2 1 19 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.
You will be given a string and you task is to check if it is possible to convert that string into a palindrome by removing a single character. If the string is already a palindrome, return `"OK"`. If it is not, and we can convert it to a palindrome by removing one character, then return `"remove one"`, otherwise return `"not possible"`. The order of the characters should not be changed.
For example:
```Haskell
solve("abba") = "OK". -- This is a palindrome
solve("abbaa") = "remove one". -- remove the 'a' at the extreme right.
solve("abbaab") = "not possible".
```
More examples in the test cases.
Good luck!
If you like this Kata, please try [Single Character Palindromes II](https://www.codewars.com/kata/5a66ea69e6be38219f000110)
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.
The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.
- Each player plays at most one matches in a day.
- Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.
-----Constraints-----
- 3 \leq N \leq 1000
- 1 \leq A_{i, j} \leq N
- A_{i, j} \neq i
- A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.
-----Input-----
Input is given from Standard Input in the following format:
N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}
-----Output-----
If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.
-----Sample Input-----
3
2 3
1 3
1 2
-----Sample Output-----
3
All the conditions can be satisfied if the matches are scheduled for three days as follows:
- Day 1: Player 1 vs Player 2
- Day 2: Player 1 vs Player 3
- Day 3: Player 2 vs Player 3
This is the minimum number of days required.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 β€ p1 < p2 < ... < pk β€ |s|) a subsequence of string s = s1s2... s|s|, where |s| is the length of string s. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".
String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y| if either |x| > |y| and x1 = y1, x2 = y2, ..., x|y| = y|y|, or there exists such number r (r < |x|, r < |y|) that x1 = y1, x2 = y2, ..., xr = yr and xr + 1 > yr + 1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".
String s = s1s2... s|s| is a palindrome if it matches string rev(s) = s|s|s|s| - 1... s1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".
Input
The only input line contains a non-empty string s consisting of lowercase English letters only. Its length does not exceed 10.
Output
Print the lexicographically largest palindromic subsequence of string s.
Examples
Input
radar
Output
rr
Input
bowwowwow
Output
wwwww
Input
codeforces
Output
s
Input
mississipp
Output
ssss
Note
Among all distinct subsequences of string "radar" the following ones are palindromes: "a", "d", "r", "aa", "rr", "ada", "rar", "rdr", "raar" and "radar". The lexicographically largest of them is "rr".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tsumugi brought $n$ delicious sweets to the Light Music Club. They are numbered from $1$ to $n$, where the $i$-th sweet has a sugar concentration described by an integer $a_i$.
Yui loves sweets, but she can eat at most $m$ sweets each day for health reasons.
Days are $1$-indexed (numbered $1, 2, 3, \ldots$). Eating the sweet $i$ at the $d$-th day will cause a sugar penalty of $(d \cdot a_i)$, as sweets become more sugary with time. A sweet can be eaten at most once.
The total sugar penalty will be the sum of the individual penalties of each sweet eaten.
Suppose that Yui chooses exactly $k$ sweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?
Since Yui is an undecided girl, she wants you to answer this question for every value of $k$ between $1$ and $n$.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le m \le n \le 200\ 000$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 200\ 000$).
-----Output-----
You have to output $n$ integers $x_1, x_2, \ldots, x_n$ on a single line, separed by spaces, where $x_k$ is the minimum total sugar penalty Yui can get if she eats exactly $k$ sweets.
-----Examples-----
Input
9 2
6 19 3 4 4 2 6 7 8
Output
2 5 11 18 30 43 62 83 121
Input
1 1
7
Output
7
-----Note-----
Let's analyze the answer for $k = 5$ in the first example. Here is one of the possible ways to eat $5$ sweets that minimize total sugar penalty: Day $1$: sweets $1$ and $4$ Day $2$: sweets $5$ and $3$ Day $3$ : sweet $6$
Total penalty is $1 \cdot a_1 + 1 \cdot a_4 + 2 \cdot a_5 + 2 \cdot a_3 + 3 \cdot a_6 = 6 + 4 + 8 + 6 + 6 = 30$. We can prove that it's the minimum total sugar penalty Yui can achieve if she eats $5$ sweets, hence $x_5 = 30$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:
(β») After each turn, (the number of times the player has played Paper)β¦(the number of times the player has played Rock).
Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.
(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)
With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.
The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1β¦iβ¦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1β¦iβ¦N) character of s in p, TopCoDeer will play Paper in the i-th turn.
-----Constraints-----
- 1β¦Nβ¦10^5
- N=|s|
- Each character in s is g or p.
- The gestures represented by s satisfy the condition (β»).
-----Input-----
The input is given from Standard Input in the following format:
s
-----Output-----
Print the AtCoDeer's maximum possible score.
-----Sample Input-----
gpg
-----Sample Output-----
0
Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
### Unfinished Loop - Bug Fixing #1
Oh no, Timmy's created an infinite loop! Help Timmy find and fix the bug in his unfinished for loop!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Haiku is a genre of Japanese traditional poetry.
A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.
To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".
Three phases from a certain poem are given. Determine whether it is haiku or not.
Input
The input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.
Output
Print "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).
Examples
Input
on codeforces
beta round is running
a rustling of keys
Output
YES
Input
how many gallons
of edo s rain did you drink
cuckoo
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.
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game.
The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins.
You have to calculate how many fights will happen and who will win the game, or state that game won't end.
-----Input-----
First line contains a single integer n (2 β€ n β€ 10), the number of cards.
Second line contains integer k_1 (1 β€ k_1 β€ n - 1), the number of the first soldier's cards. Then follow k_1 integers that are the values on the first soldier's cards, from top to bottom of his stack.
Third line contains integer k_2 (k_1 + k_2 = n), the number of the second soldier's cards. Then follow k_2 integers that are the values on the second soldier's cards, from top to bottom of his stack.
All card values are different.
-----Output-----
If somebody wins in this game, print 2 integers where the first one stands for the number of fights before end of game and the second one is 1 or 2 showing which player has won.
If the game won't end and will continue forever output - 1.
-----Examples-----
Input
4
2 1 3
2 4 2
Output
6 2
Input
3
1 2
2 1 3
Output
-1
-----Note-----
First sample: [Image]
Second sample: [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.
n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
Input
The first line contains integer n (2 β€ n β€ 100) β amount of soldiers. Then follow the heights of the soldiers in their order in the circle β n space-separated integers a1, a2, ..., an (1 β€ ai β€ 1000). The soldier heights are given in clockwise or counterclockwise direction.
Output
Output two integers β indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.
Examples
Input
5
10 12 13 15 10
Output
5 1
Input
4
10 20 30 40
Output
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.
β Thanks a lot for today.
β I experienced so many great things.
β You gave me memories like dreams... But I have to leave now...
β One last request, can you...
β Help me solve a Codeforces problem?
β ......
β What?
Chtholly has been thinking about a problem for days:
If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.
Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.
Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!
-----Input-----
The first line contains two integers k and p (1 β€ k β€ 10^5, 1 β€ p β€ 10^9).
-----Output-----
Output single integerΒ β answer to the problem.
-----Examples-----
Input
2 100
Output
33
Input
5 30
Output
15
-----Note-----
In the first example, the smallest zcy number is 11, and the second smallest zcy number is 22.
In the second example, $(11 + 22 + 33 + 44 + 55) \operatorname{mod} 30 = 15$.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.
Here, a ACGT string is a string that contains no characters other than A, C, G and T.
-----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-----
- S is a string of length between 1 and 10 (inclusive).
- Each character in S is an uppercase English letter.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the length of the longest ACGT string that is a substring of S.
-----Sample Input-----
ATCODER
-----Sample Output-----
3
Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.
Help Yaroslav.
-----Input-----
The first line contains integer n (1 β€ n β€ 100) β the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 1000) β the array elements.
-----Output-----
In the single line print "YES" (without the quotes) if Yaroslav can obtain the array he needs, and "NO" (without the quotes) otherwise.
-----Examples-----
Input
1
1
Output
YES
Input
3
1 1 2
Output
YES
Input
4
7 7 7 7
Output
NO
-----Note-----
In the first sample the initial array fits well.
In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.
In the third sample Yarosav can't get the array he needs.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 three-digit positive integer N.
Determine whether N is a palindromic number.
Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.
-----Constraints-----
- 100β€Nβ€999
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
If N is a palindromic number, print Yes; otherwise, print No.
-----Sample Input-----
575
-----Sample Output-----
Yes
N=575 is also 575 when read backward, so it is a palindromic number. You should print 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.
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 Γ 2 square consisting of black pixels is formed.
Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 Γ 2 square consisting of black pixels is formed.
-----Input-----
The first line of the input contains three integers n, m, k (1 β€ n, m β€ 1000, 1 β€ k β€ 10^5)Β β the number of rows, the number of columns and the number of moves that Pasha is going to perform.
The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 β€ i β€ n, 1 β€ j β€ m), representing the row number and column number of the pixel that was painted during a move.
-----Output-----
If Pasha loses, print the number of the move when the 2 Γ 2 square consisting of black pixels is formed.
If Pasha doesn't lose, that is, no 2 Γ 2 square consisting of black pixels is formed during the given k moves, print 0.
-----Examples-----
Input
2 2 4
1 1
1 2
2 1
2 2
Output
4
Input
2 3 6
2 3
2 2
1 3
2 2
1 2
1 1
Output
5
Input
5 3 7
2 3
1 2
1 1
4 1
3 1
5 3
3 2
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$, consisting only of characters '0' or '1'. Let $|s|$ be the length of $s$.
You are asked to choose some integer $k$ ($k > 0$) and find a sequence $a$ of length $k$ such that:
$1 \le a_1 < a_2 < \dots < a_k \le |s|$;
$a_{i-1} + 1 < a_i$ for all $i$ from $2$ to $k$.
The characters at positions $a_1, a_2, \dots, a_k$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $a$ should not be adjacent.
Let the resulting string be $s'$. $s'$ is called sorted if for all $i$ from $2$ to $|s'|$ $s'_{i-1} \le s'_i$.
Does there exist such a sequence $a$ that the resulting string $s'$ is sorted?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) β the number of testcases.
Then the descriptions of $t$ testcases follow.
The only line of each testcase contains a string $s$ ($2 \le |s| \le 100$). Each character is either '0' or '1'.
-----Output-----
For each testcase print "YES" if there exists a sequence $a$ such that removing the characters at positions $a_1, a_2, \dots, a_k$ and concatenating the parts without changing the order produces a sorted string.
Otherwise, print "NO".
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
-----Examples-----
Input
5
10101011011
0000
11111
110
1100
Output
YES
YES
YES
YES
NO
-----Note-----
In the first testcase you can choose a sequence $a=[1,3,6,9]$. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.
In the second and the third testcases the sequences are already sorted.
In the fourth testcase you can choose a sequence $a=[3]$. $s'=$ "11", which is sorted.
In the fifth testcase there is no way to choose a sequence $a$ such that $s'$ is sorted.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 taxi driver, Nakamura, was so delighted because he got a passenger who wanted to go to a city thousands of kilometers away. However, he had a problem. As you may know, most taxis in Japan run on liquefied petroleum gas (LPG) because it is cheaper than gasoline. There are more than 50,000 gas stations in the country, but less than one percent of them sell LPG. Although the LPG tank of his car was full, the tank capacity is limited and his car runs 10 kilometer per liter, so he may not be able to get to the destination without filling the tank on the way. He knew all the locations of LPG stations. Your task is to write a program that finds the best way from the current location to the destination without running out of gas.
Input
The input consists of several datasets, and each dataset is in the following format.
N M cap
src dest
c1,1 c1,2 d1
c2,1 c2,2 d2
.
.
.
cN,1 cN,2 dN
s1
s2
.
.
.
sM
The first line of a dataset contains three integers (N, M, cap), where N is the number of roads (1 β€ N β€ 3000),M is the number of LPG stations (1β€ M β€ 300), and cap is the tank capacity (1 β€ cap β€ 200) in liter. The next line contains the name of the current city (src) and the name of the destination city (dest). The destination city is always different from the current city. The following N lines describe roads that connect cities. The road i (1 β€ i β€ N) connects two different cities ci,1 and ci,2 with an integer distance di (0 < di β€ 2000) in kilometer, and he can go from either city to the other. You can assume that no two different roads connect the same pair of cities. The columns are separated by a single space. The next M lines (s1,s2,...,sM) indicate the names of the cities with LPG station. You can assume that a city with LPG station has at least one road.
The name of a city has no more than 15 characters. Only English alphabet ('A' to 'Z' and 'a' to 'z', case sensitive) is allowed for the name.
A line with three zeros terminates the input.
Output
For each dataset, output a line containing the length (in kilometer) of the shortest possible journey from the current city to the destination city. If Nakamura cannot reach the destination, output "-1" (without quotation marks). You must not output any other characters. The actual tank capacity is usually a little bit larger than that on the specification sheet, so you can assume that he can reach a city even when the remaining amount of the gas becomes exactly zero. In addition, you can always fill the tank at the destination so you do not have to worry about the return trip.
Example
Input
6 3 34
Tokyo Kyoto
Tokyo Niigata 335
Tokyo Shizuoka 174
Shizuoka Nagoya 176
Nagoya Kyoto 195
Toyama Niigata 215
Toyama Kyoto 296
Nagoya
Niigata
Toyama
6 3 30
Tokyo Kyoto
Tokyo Niigata 335
Tokyo Shizuoka 174
Shizuoka Nagoya 176
Nagoya Kyoto 195
Toyama Niigata 215
Toyama Kyoto 296
Nagoya
Niigata
Toyama
0 0 0
Output
846
-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.
Mr. Simpson got up with a slight feeling of tiredness. It was the start of another day of hard work. A bunch of papers were waiting for his inspection on his desk in his office. The papers contained his students' answers to questions in his Math class, but the answers looked as if they were just stains of ink.
His headache came from the ``creativity'' of his students. They provided him a variety of ways to answer each problem. He has his own answer to each problem, which is correct, of course, and the best from his aesthetic point of view.
Some of his students wrote algebraic expressions equivalent to the expected answer, but many of them look quite different from Mr. Simpson's answer in terms of their literal forms. Some wrote algebraic expressions not equivalent to his answer, but they look quite similar to it. Only a few of the students' answers were exactly the same as his.
It is his duty to check if each expression is mathematically equivalent to the answer he has prepared. This is to prevent expressions that are equivalent to his from being marked as ``incorrect'', even if they are not acceptable to his aesthetic moral.
He had now spent five days checking the expressions. Suddenly, he stood up and yelled, ``I've had enough! I must call for help.''
Your job is to write a program to help Mr. Simpson to judge if each answer is equivalent to the ``correct'' one. Algebraic expressions written on the papers are multi-variable polynomials over variable symbols a, b,..., z with integer coefficients, e.g., (a + b2)(a - b2), ax2 +2bx + c and (x2 +5x + 4)(x2 + 5x + 6) + 1.
Mr. Simpson will input every answer expression as it is written on the papers; he promises you that an algebraic expression he inputs is a sequence of terms separated by additive operators `+' and `-', representing the sum of the terms with those operators, if any; a term is a juxtaposition of multiplicands, representing their product; and a multiplicand is either (a) a non-negative integer as a digit sequence in decimal, (b) a variable symbol (one of the lowercase letters `a' to `z'), possibly followed by a symbol `^' and a non-zero digit, which represents the power of that variable, or (c) a parenthesized algebraic expression, recursively. Note that the operator `+' or `-' appears only as a binary operator and not as a unary operator to specify the sing of its operand.
He says that he will put one or more space characters before an integer if it immediately follows another integer or a digit following the symbol `^'. He also says he may put spaces here and there in an expression as an attempt to make it readable, but he will never put a space between two consecutive digits of an integer. He remarks that the expressions are not so complicated, and that any expression, having its `-'s replaced with `+'s, if any, would have no variable raised to its 10th power, nor coefficient more than a billion, even if it is fully expanded into a form of a sum of products of coefficients and powered variables.
Input
The input to your program is a sequence of blocks of lines. A block consists of lines, each containing an expression, and a terminating line. After the last block, there is another terminating line. A terminating line is a line solely consisting of a period symbol.
The first expression of a block is one prepared by Mr. Simpson; all that follow in a block are answers by the students. An expression consists of lowercase letters, digits, operators `+', `-' and `^', parentheses `(' and `)', and spaces. A line containing an expression has no more than 80 characters.
Output
Your program should produce a line solely consisting of ``yes'' or ``no'' for each answer by the students corresponding to whether or not it is mathematically equivalent to the expected answer. Your program should produce a line solely containing a period symbol after each block.
Example
Input
a+b+c
(a+b)+c
a- (b-c)+2
.
4ab
(a - b) (0-b+a) - 1a ^ 2 - b ^ 2
2 b 2 a
.
108 a
2 2 3 3 3 a
4 a^1 27
.
.
Output
yes
no
.
no
yes
.
yes
yes
.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian as well.
There are 100 houses located on a straight line. The first house is numbered 1 and the last one is numbered 100. Some M houses out of these 100 are occupied by cops.
Thief Devu has just stolen PeePee's bag and is looking for a house to hide in.
PeePee uses fast 4G Internet and sends the message to all the cops that a thief named Devu has just stolen her bag and ran into some house.
Devu knows that the cops run at a maximum speed of x houses per minute in a straight line and they will search for a maximum of y minutes. Devu wants to know how many houses are safe for him to escape from the cops. Help him in getting this information.
------ Input ------
First line contains T, the number of test cases to follow.
First line of each test case contains 3 space separated integers: M, x and y.
For each test case, the second line contains M space separated integers which represent the house numbers where the cops are residing.
------ Output ------
For each test case, output a single line containing the number of houses which are safe to hide from cops.
------ Constraints ------
$1 β€ T β€ 10^{4}$
$1 β€ x, y, M β€ 10$
----- Sample Input 1 ------
3
4 7 8
12 52 56 8
2 10 2
21 75
2 5 8
10 51
----- Sample Output 1 ------
0
18
9
----- explanation 1 ------
Test case $1$: Based on the speed, each cop can cover $56$ houses on each side. These houses are:
- Cop in house $12$ can cover houses $1$ to $11$ if he travels left and houses $13$ to $68$ if he travels right. Thus, this cop can cover houses numbered $1$ to $68$.
- Cop in house $52$ can cover houses $1$ to $51$ if he travels left and houses $53$ to $100$ if he travels right. Thus, this cop can cover houses numbered $1$ to $100$.
- Cop in house $56$ can cover houses $1$ to $55$ if he travels left and houses $57$ to $100$ if he travels right. Thus, this cop can cover houses numbered $1$ to $100$.
- Cop in house $8$ can cover houses $1$ to $7$ if he travels left and houses $9$ to $64$ if he travels right. Thus, this cop can cover houses numbered $1$ to $64$.
Thus, there is no house which is not covered by any of the cops.
Test case $2$: Based on the speed, each cop can cover $20$ houses on each side. These houses are:
- Cop in house $21$ can cover houses $1$ to $20$ if he travels left and houses $22$ to $41$ if he travels right. Thus, this cop can cover houses numbered $1$ to $41$.
- Cop in house $75$ can cover houses $55$ to $74$ if he travels left and houses $76$ to $95$ if he travels right. Thus, this cop can cover houses numbered $55$ to $95$.
Thus, the safe houses are house number $42$ to $54$ and $96$ to $100$. There are $18$ safe houses.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
-----Input-----
The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each.
-----Output-----
Write a single integer to output, denoting how many integers ti are divisible by k.
-----Example-----
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N points in a D-dimensional space.
The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).
The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.
How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10
- 1 \leq D \leq 10
- -20 \leq X_{ij} \leq 20
- No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.
-----Input-----
Input is given from Standard Input in the following format:
N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}
-----Output-----
Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.
-----Sample Input-----
3 2
1 2
5 5
-2 8
-----Sample Output-----
1
The number of pairs with an integer distance is one, as follows:
- The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.
- The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.
- The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
2332
110011
54322345
For this kata, single digit numbers will not be considered numerical palindromes.
For a given number ```num```, write a function to test if the number contains a numerical palindrome or not and return a boolean (true if it does and false if does not). Return "Not valid" if the input is not an integer or is less than 0.
Note: Palindromes should be found without permutating ```num```.
```
palindrome(5) => false
palindrome(1221) => true
palindrome(141221001) => true
palindrome(1215) => true
palindrome(1294) => false
palindrome("109982") => "Not valid"
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Luntik has decided to try singing. He has $a$ one-minute songs, $b$ two-minute songs and $c$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.
He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.
Please help Luntik and find the minimal possible difference in minutes between the concerts durations.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) β the number of test cases.
Each test case consists of one line containing three integers $a, b, c$ $(1 \le a, b, c \le 10^9)$ β the number of one-minute, two-minute and three-minute songs.
-----Output-----
For each test case print the minimal possible difference in minutes between the concerts durations.
-----Examples-----
Input
4
1 1 1
2 1 3
5 5 5
1 1 2
Output
0
1
0
1
-----Note-----
In the first test case, Luntik can include a one-minute song and a two-minute song into the first concert, and a three-minute song into the second concert. Then the difference will be equal to $0$.
In the second test case, Luntik can include two one-minute songs and a two-minute song and a three-minute song into the first concert, and two three-minute songs into the second concert. The duration of the first concert will be $1 + 1 + 2 + 3 = 7$, the duration of the second concert will be $6$. The difference of them is $|7-6| = 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.
###Instructions
A time period starting from ```'hh:mm'``` lasting until ```'hh:mm'``` is stored in an array:
```
['08:14', '11:34']
```
A set of different time periods is then stored in a 2D Array like so, each in its own sub-array:
```
[['08:14','11:34'], ['08:16','08:18'], ['22:18','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']]
```
Write a function that will take a 2D Array like the above as argument and return a 2D Array of the argument's sub-arrays sorted in ascending order.
Take note of the following:
* The first time period starts at the earliest time possible ```('00:00'+)```.
* The next time period is the one that starts the soonest **after** the prior time period finishes. If several time periods begin at the same hour, pick the first one showing up in the original array.
* The next time period can start the same time the last one finishes.
This:
```
[['08:14','11:34'], ['08:16','08:18'], ['13:48','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']]
```
Should return:
```
[['01:12','01:14'], ['04:23','05:11'], ['08:14','11:34'], ['11:48','13:48'], ['13:48','01:14'], ['08:16','08:18'], ['09:30','10:32'], ['01:13','08:15']]
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alicia has an array, $a_1, a_2, \ldots, a_n$, of non-negative integers. For each $1 \leq i \leq n$, she has found a non-negative integer $x_i = max(0, a_1, \ldots, a_{i-1})$. Note that for $i=1$, $x_i = 0$.
For example, if Alicia had the array $a = \{0, 1, 2, 0, 3\}$, then $x = \{0, 0, 1, 2, 2\}$.
Then, she calculated an array, $b_1, b_2, \ldots, b_n$: $b_i = a_i - x_i$.
For example, if Alicia had the array $a = \{0, 1, 2, 0, 3\}$, $b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}$.
Alicia gives you the values $b_1, b_2, \ldots, b_n$ and asks you to restore the values $a_1, a_2, \ldots, a_n$. Can you help her solve the problem?
-----Input-----
The first line contains one integer $n$ ($3 \leq n \leq 200\,000$)Β β the number of elements in Alicia's array.
The next line contains $n$ integers, $b_1, b_2, \ldots, b_n$ ($-10^9 \leq b_i \leq 10^9$).
It is guaranteed that for the given array $b$ there is a solution $a_1, a_2, \ldots, a_n$, for all elements of which the following is true: $0 \leq a_i \leq 10^9$.
-----Output-----
Print $n$ integers, $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 10^9$), such that if you calculate $x$ according to the statement, $b_1$ will be equal to $a_1 - x_1$, $b_2$ will be equal to $a_2 - x_2$, ..., and $b_n$ will be equal to $a_n - x_n$.
It is guaranteed that there exists at least one solution for the given tests. It can be shown that the solution is unique.
-----Examples-----
Input
5
0 1 1 -2 1
Output
0 1 2 0 3
Input
3
1000 999999000 -1000000000
Output
1000 1000000000 0
Input
5
2 1 2 2 3
Output
2 3 5 7 10
-----Note-----
The first test was described in the problem statement.
In the second test, if Alicia had an array $a = \{1000, 1000000000, 0\}$, then $x = \{0, 1000, 1000000000\}$ and $b = \{1000-0, 1000000000-1000, 0-1000000000\} = \{1000, 999999000, -1000000000\}$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let p (i) be the i-th prime number from the smallest. For example, 7 is the fourth prime number from the smallest, 2, 3, 5, 7, so p (4) = 7.
Given n, the sum of p (i) from i = 1 to n s
s = p (1) + p (2) + .... + p (n)
Create a program that outputs. For example, when n = 9, s = 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 = 100.
Input
Given multiple datasets. Each dataset is given the integer n (n β€ 10000). When n is 0, it is the last input. The number of datasets does not exceed 50.
Output
For n in each dataset, print s on one line.
Example
Input
2
9
0
Output
5
100
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n Γ m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.
Input
The first line contains space-separated integers n, m and k (1 β€ n, m β€ 1000, 1 β€ k β€ 106) β the board's vertical and horizontal sizes and the number of colors respectively.
Output
Print the answer to the problem. As the answer can be quite a large number, you should print it modulo 109 + 7 (1000000007).
Examples
Input
2 2 1
Output
1
Input
2 2 2
Output
8
Input
3 2 2
Output
40
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 32 letters in the Polish alphabet: 9 vowels and 23 consonants.
Your task is to change the letters with diacritics:
```
Δ
-> a,
Δ -> c,
Δ -> e,
Ε -> l,
Ε -> n,
Γ³ -> o,
Ε -> s,
ΕΊ -> z,
ΕΌ -> z
```
and print out the string without the use of the Polish letters.
For example:
```
"JΔdrzej BΕΔ
dziΕski" --> "Jedrzej Bladzinski"
```
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange taskΒ β she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.
Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.
The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes $l$ nanoseconds, where $l$ is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take $2$ nanoseconds).
Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^6$)Β β the length of Dima's sequence.
The second line contains string of length $n$, consisting of characters "(" and ")" only.
-----Output-----
Print a single integerΒ β the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.
-----Examples-----
Input
8
))((())(
Output
6
Input
3
(()
Output
-1
-----Note-----
In the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is $4 + 2 = 6$ nanoseconds.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.
Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.
You need to process m queries, the i-th results in that the character at position x_{i} (1 β€ x_{i} β€ n) of string s is assigned value c_{i}. After each operation you have to calculate and output the value of f(s).
Help Daniel to process all queries.
-----Input-----
The first line contains two integers n and m (1 β€ n, m β€ 300 000) the length of the string and the number of queries.
The second line contains string s, consisting of n lowercase English letters and period signs.
The following m lines contain the descriptions of queries. The i-th line contains integer x_{i} and c_{i} (1 β€ x_{i} β€ n, c_{i} β a lowercas English letter or a period sign), describing the query of assigning symbol c_{i} to position x_{i}.
-----Output-----
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
-----Examples-----
Input
10 3
.b..bz....
1 h
3 c
9 f
Output
4
3
1
Input
4 4
.cc.
2 .
3 .
2 a
1 a
Output
1
3
1
1
-----Note-----
Note to the first sample test (replaced periods are enclosed in square brackets).
The original string is ".b..bz....". after the first query f(hb..bz....) = 4Β Β Β Β ("hb[..]bz...." β "hb.bz[..].." β "hb.bz[..]." β "hb.bz[..]" β "hb.bz.") after the second query f(hbΡ.bz....) = 3Β Β Β Β ("hbΡ.bz[..].." β "hbΡ.bz[..]." β "hbΡ.bz[..]" β "hbΡ.bz.") after the third query f(hbΡ.bz..f.) = 1Β Β Β Β ("hbΡ.bz[..]f." β "hbΡ.bz.f.")
Note to the second sample test.
The original string is ".cc.". after the first query: f(..c.) = 1Β Β Β Β ("[..]c." β ".c.") after the second query: f(....) = 3Β Β Β Β ("[..].." β "[..]." β "[..]" β ".") after the third query: f(.a..) = 1Β Β Β Β (".a[..]" β ".a.") after the fourth query: f(aa..) = 1Β Β Β Β ("aa[..]" β "aa.")
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko β W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
Input
The only line of the input file contains two natural numbers Y and W β the results of Yakko's and Wakko's die rolls.
Output
Output the required probability in the form of irreducible fraction in format Β«A/BΒ», where A β the numerator, and B β the denominator. If the required probability equals to zero, output Β«0/1Β». If the required probability equals to 1, output Β«1/1Β».
Examples
Input
4 2
Output
1/2
Note
Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Greg has an array a = a_1, a_2, ..., a_{n} and m operations. Each operation looks as: l_{i}, r_{i}, d_{i}, (1 β€ l_{i} β€ r_{i} β€ n). To apply operation i to the array means to increase all array elements with numbers l_{i}, l_{i} + 1, ..., r_{i} by value d_{i}.
Greg wrote down k queries on a piece of paper. Each query has the following form: x_{i}, y_{i}, (1 β€ x_{i} β€ y_{i} β€ m). That means that one should apply operations with numbers x_{i}, x_{i} + 1, ..., y_{i} to the array.
Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.
-----Input-----
The first line contains integers n, m, k (1 β€ n, m, k β€ 10^5). The second line contains n integers: a_1, a_2, ..., a_{n} (0 β€ a_{i} β€ 10^5) β the initial array.
Next m lines contain operations, the operation number i is written as three integers: l_{i}, r_{i}, d_{i}, (1 β€ l_{i} β€ r_{i} β€ n), (0 β€ d_{i} β€ 10^5).
Next k lines contain the queries, the query number i is written as two integers: x_{i}, y_{i}, (1 β€ x_{i} β€ y_{i} β€ m).
The numbers in the lines are separated by single spaces.
-----Output-----
On a single line print n integers a_1, a_2, ..., a_{n} β the array after executing all the queries. Separate the printed numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
-----Examples-----
Input
3 3 3
1 2 3
1 2 1
1 3 2
2 3 4
1 2
1 3
2 3
Output
9 18 17
Input
1 1 1
1
1 1 1
1 1
Output
2
Input
4 3 6
1 2 3 4
1 2 1
2 3 2
3 4 4
1 2
1 3
2 3
1 2
1 3
2 3
Output
5 18 31 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.
You are given a string $s$ consisting of $n$ lowercase Latin letters. Polycarp wants to remove exactly $k$ characters ($k \le n$) from the string $s$. Polycarp uses the following algorithm $k$ times:
if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $k$ times, thus removing exactly $k$ characters.
Help Polycarp find the resulting string.
-----Input-----
The first line of input contains two integers $n$ and $k$ ($1 \le k \le n \le 4 \cdot 10^5$) β the length of the string and the number of letters Polycarp will remove.
The second line contains the string $s$ consisting of $n$ lowercase Latin letters.
-----Output-----
Print the string that will be obtained from $s$ after Polycarp removes exactly $k$ letters using the above algorithm $k$ times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
-----Examples-----
Input
15 3
cccaabababaccbc
Output
cccbbabaccbc
Input
15 9
cccaabababaccbc
Output
cccccc
Input
1 1
u
Output
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array of positive integers a1, a2, ..., an Γ T of length n Γ T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array.
Input
The first line contains two space-separated integers: n, T (1 β€ n β€ 100, 1 β€ T β€ 107). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 300).
Output
Print a single number β the length of a sought sequence.
Examples
Input
4 3
3 1 4 2
Output
5
Note
The array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.
These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet.
This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $x$ satoshi (1 bitcoin = $10^8$ satoshi). She can create new public address wallets for free and is willing to pay $f$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal.
-----Input-----
First line contains number $N$ ($1 \leq N \leq 200\,000$) representing total number of public addresses Alice has.
Next line contains $N$ integer numbers $a_i$ ($1 \leq a_i \leq 10^9$) separated by a single space, representing how many satoshi Alice has in her public addresses.
Last line contains two numbers $x$, $f$ ($1 \leq f < x \leq 10^9$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction.
-----Output-----
Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal.
-----Example-----
Input
3
13 7 6
6 2
Output
4
-----Note-----
Alice can make two transactions in a following way:
0. 13 7 6 (initial state)
1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)
2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)
Since cost per transaction is 2 satoshies, total fee 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.
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.
You are standing in the m-th position in the line. Before the process starts, you may choose up to k different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.
Suppose that you're doing your choices optimally. What is the greatest integer x such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to x?
Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 1000) β the number of test cases. The description of the test cases follows.
The first line of each test case contains three space-separated integers n, m and k (1 β€ m β€ n β€ 3500, 0 β€ k β€ n - 1) β the number of elements in the array, your position in line and the number of people whose choices you can fix.
The second line of each test case contains n positive integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9) β elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 3500.
Output
For each test case, print the largest integer x such that you can guarantee to obtain at least x.
Example
Input
4
6 4 2
2 9 2 3 8 5
4 4 1
2 13 60 4
4 1 3
1 2 2 1
2 2 0
1 2
Output
8
4
1
1
Note
In the first test case, an optimal strategy is to force the first person to take the last element and the second person to take the first element.
* the first person will take the last element (5) because he or she was forced by you to take the last element. After this turn the remaining array will be [2, 9, 2, 3, 8];
* the second person will take the first element (2) because he or she was forced by you to take the first element. After this turn the remaining array will be [9, 2, 3, 8];
* if the third person will choose to take the first element (9), at your turn the remaining array will be [2, 3, 8] and you will take 8 (the last element);
* if the third person will choose to take the last element (8), at your turn the remaining array will be [9, 2, 3] and you will take 9 (the first element).
Thus, this strategy guarantees to end up with at least 8. We can prove that there is no strategy that guarantees to end up with at least 9. Hence, the answer is 8.
In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The only difference between the easy and the hard version is the constraint on $n$.
You are given an undirected complete graph on $n$ vertices. A complete graph is a graph where each pair of vertices is connected by an edge. You have to paint the edges of the graph into two colors, red and blue (each edge will have one color).
A set of vertices $S$ is red-connected if, for every pair of vertices $(v_1, v_2)$ such that $v_1 \in S$ and $v_2 \in S$, there exists a path from $v_1$ to $v_2$ that goes only through red edges and vertices from $S$. Similarly, a set of vertices $S$ is blue-connected if, for every pair of vertices $(v_1, v_2)$ such that $v_1 \in S$ and $v_2 \in S$, there exists a path from $v_1$ to $v_2$ that goes only through blue edges and vertices from $S$.
You have to paint the graph in such a way that:
there is at least one red edge;
there is at least one blue edge;
for each set of vertices $S$ such that $|S| \ge 2$, $S$ is either red-connected or blue-connected, but not both.
Calculate the number of ways to paint the graph, and print it modulo $998244353$.
-----Input-----
The first (and only) line contains one integer $n$ ($3 \le n \le 5 \cdot 10^3$).
-----Output-----
Print one integer β the number of ways to paint the graph, taken modulo $998244353$.
-----Examples-----
Input
3
Output
6
Input
4
Output
50
Input
100
Output
878752271
Input
1337
Output
520628749
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The winter in Berland lasts n days. For each day we know the forecast for the average air temperature that day.
Vasya has a new set of winter tires which allows him to drive safely no more than k days at any average air temperature. After k days of using it (regardless of the temperature of these days) the set of winter tires wears down and cannot be used more. It is not necessary that these k days form a continuous segment of days.
Before the first winter day Vasya still uses summer tires. It is possible to drive safely on summer tires any number of days when the average air temperature is non-negative. It is impossible to drive on summer tires at days when the average air temperature is negative.
Vasya can change summer tires to winter tires and vice versa at the beginning of any day.
Find the minimum number of times Vasya needs to change summer tires to winter tires and vice versa to drive safely during the winter. At the end of the winter the car can be with any set of tires.
-----Input-----
The first line contains two positive integers n and k (1 β€ n β€ 2Β·10^5, 0 β€ k β€ n)Β β the number of winter days and the number of days winter tires can be used. It is allowed to drive on winter tires at any temperature, but no more than k days in total.
The second line contains a sequence of n integers t_1, t_2, ..., t_{n} ( - 20 β€ t_{i} β€ 20)Β β the average air temperature in the i-th winter day.
-----Output-----
Print the minimum number of times Vasya has to change summer tires to winter tires and vice versa to drive safely during all winter. If it is impossible, print -1.
-----Examples-----
Input
4 3
-5 20 -3 0
Output
2
Input
4 2
-5 20 -3 0
Output
4
Input
10 6
2 -5 1 3 0 0 -4 -3 1 0
Output
3
-----Note-----
In the first example before the first winter day Vasya should change summer tires to winter tires, use it for three days, and then change winter tires to summer tires because he can drive safely with the winter tires for just three days. Thus, the total number of tires' changes equals two.
In the second example before the first winter day Vasya should change summer tires to winter tires, and then after the first winter day change winter tires to summer tires. After the second day it is necessary to change summer tires to winter tires again, and after the third day it is necessary to change winter tires to summer tires. Thus, the total number of tires' changes equals four.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 number `1035` is the smallest integer that exhibits a non frequent property: one its multiples, `3105 = 1035 * 3`, has its same digits but in different order, in other words, `3105`, is one of the permutations of `1035`.
The number `125874` is the first integer that has this property when the multiplier is `2`, thus: `125874 * 2 = 251748`
Make the function `search_permMult()`, that receives an upper bound, nMax and a factor k and will output the amount of pairs bellow nMax that are permuted when an integer of this range is multiplied by `k`. The pair will be counted if the multiple is less than `nMax`, too
Let'see some cases:
```python
search_permMult(10000, 7) === 1 # because we have the pair 1359, 9513
search_permMult(5000, 7) === 0 # no pairs found, as 9513 > 5000
search_permMult(10000, 4) === 2 # we have two pairs (1782, 7128) and (2178, 8712)
search_permMult(8000, 4) === 1 # only the pair (1782, 7128)
search_permMult(5000, 3) === 1 # only the pair (1035, 3105)
search_permMult(10000, 3) === 2 # found pairs (1035, 3105) and (2475, 7425)
```
Features of the random Tests:
```
10000 <= nMax <= 100000
3 <= k <= 7
```
Enjoy it and happy coding!!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.
The i-th dish (1 \leq i \leq N) he ate was Dish A_i.
When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.
Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.
Find the sum of the satisfaction points he gained.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 20
- 1 \leq A_i \leq N
- A_1, A_2, ..., A_N are all different.
- 1 \leq B_i \leq 50
- 1 \leq C_i \leq 50
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}
-----Output-----
Print the sum of the satisfaction points Takahashi gained, as an integer.
-----Sample Input-----
3
3 1 2
2 5 4
3 6
-----Sample Output-----
14
Takahashi gained 14 satisfaction points in total, as follows:
- First, he ate Dish 3 and gained 4 satisfaction points.
- Next, he ate Dish 1 and gained 2 satisfaction points.
- Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.
The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.
You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \leftβ(w_i)/(2)\rightβ).
Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.
Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make β_{v β leaves} w(root, v) β€ S, where leaves is the list of all leaves.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and S (2 β€ n β€ 10^5; 1 β€ S β€ 10^{16}) β the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 β€ v_i, u_i β€ n; 1 β€ w_i β€ 10^6; 1 β€ c_i β€ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge.
It is guaranteed that the sum of n does not exceed 10^5 (β n β€ 10^5).
Output
For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S.
Example
Input
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
Output
0
0
11
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.
Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:
* 1 \leq x,y,z
* x^2 + y^2 + z^2 + xy + yz + zx = n
Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^4
Input
Input is given from Standard Input in the following format:
N
Output
Print N lines. The i-th line should contain the value f(i).
Example
Input
20
Output
0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
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 already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.
The track's map is represented by a rectangle n Γ m in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters S) and the terminating square (it is marked with a capital Latin letter T). The time of movement from one square to another is equal to 1 minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than k different types of squares (squares of one type can be visited an infinite number of times). Squares marked with S and T have no type, so they are not counted. But S must be visited exactly once β at the very beginning, and T must be visited exactly once β at the very end.
Your task is to find the path from the square S to the square T that takes minimum time. Among all shortest paths you should choose the lexicographically minimal one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types.
Input
The first input line contains three integers n, m and k (1 β€ n, m β€ 50, nΒ·m β₯ 2, 1 β€ k β€ 4). Then n lines contain the map. Each line has the length of exactly m characters and consists of lowercase Latin letters and characters S and T. It is guaranteed that the map contains exactly one character S and exactly one character T.
Pretest 12 is one of the maximal tests for this problem.
Output
If there is a path that satisfies the condition, print it as a sequence of letters β the plot types. Otherwise, print "-1" (without quotes). You shouldn't print the character S in the beginning and T in the end.
Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.
Examples
Input
5 3 2
Sba
ccc
aac
ccc
abT
Output
bcccc
Input
3 4 1
Sxyy
yxxx
yyyT
Output
xxxx
Input
1 3 3
TyS
Output
y
Input
1 4 1
SxyT
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.
Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.
In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).
Your task is to read a sequence A and perform the Partition based on the following pseudocode:
Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1
Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].
Constraints
* 1 β€ n β€ 100,000
* 0 β€ Ai β€ 100,000
Input
The first line of the input includes an integer n, the number of elements in the sequence A.
In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.
Output
Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [ ].
Example
Input
12
13 19 9 5 12 8 7 4 21 2 6 11
Output
9 5 8 7 4 2 6 [11] 21 13 19 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.
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are n lanes of m desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to n from the left to the right, the desks in a lane are numbered from 1 to m starting from the blackboard. Note that the lanes go perpendicularly to the blackboard, not along it (see picture).
The organizers numbered all the working places from 1 to 2nm. The places are numbered by lanes (i.Β e. all the places of the first lane go first, then all the places of the second lane, and so on), in a lane the places are numbered starting from the nearest to the blackboard (i.Β e. from the first desk in the lane), at each desk, the place on the left is numbered before the place on the right. [Image] The picture illustrates the first and the second samples.
Santa Clause knows that his place has number k. Help him to determine at which lane at which desk he should sit, and whether his place is on the left or on the right!
-----Input-----
The only line contains three integers n, m and k (1 β€ n, m β€ 10 000, 1 β€ k β€ 2nm)Β β the number of lanes, the number of desks in each lane and the number of Santa Claus' place.
-----Output-----
Print two integers: the number of lane r, the number of desk d, and a character s, which stands for the side of the desk Santa Claus. The character s should be "L", if Santa Clause should sit on the left, and "R" if his place is on the right.
-----Examples-----
Input
4 3 9
Output
2 2 L
Input
4 3 24
Output
4 3 R
Input
2 4 4
Output
1 2 R
-----Note-----
The first and the second samples are shown on the picture. The green place corresponds to Santa Claus' place in the first example, the blue place corresponds to Santa Claus' place in the second example.
In the third sample there are two lanes with four desks in each, and Santa Claus has the fourth place. Thus, his place is in the first lane at the second desk on the right.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ points on a coordinate axis $OX$. The $i$-th point is located at the integer point $x_i$ and has a speed $v_i$. It is guaranteed that no two points occupy the same coordinate. All $n$ points move with the constant speed, the coordinate of the $i$-th point at the moment $t$ ($t$ can be non-integer) is calculated as $x_i + t \cdot v_i$.
Consider two points $i$ and $j$. Let $d(i, j)$ be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points $i$ and $j$ coincide at some moment, the value $d(i, j)$ will be $0$.
Your task is to calculate the value $\sum\limits_{1 \le i < j \le n}$ $d(i, j)$ (the sum of minimum distances over all pairs of points).
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) β the number of points.
The second line of the input contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^8$), where $x_i$ is the initial coordinate of the $i$-th point. It is guaranteed that all $x_i$ are distinct.
The third line of the input contains $n$ integers $v_1, v_2, \dots, v_n$ ($-10^8 \le v_i \le 10^8$), where $v_i$ is the speed of the $i$-th point.
-----Output-----
Print one integer β the value $\sum\limits_{1 \le i < j \le n}$ $d(i, j)$ (the sum of minimum distances over all pairs of points).
-----Examples-----
Input
3
1 3 2
-100 2 3
Output
3
Input
5
2 1 4 3 5
2 2 2 3 4
Output
19
Input
2
2 1
-3 0
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
Sometimes mysteries happen. Chef found a directed graph with N vertices and M edges in his kitchen!
The evening was boring and chef has nothing else to do, so to entertain himself, Chef thought about a question "What is the minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to vertex N, where the vertices are numbered from 1 to N.
------ Input ------
Each test file contains only one test case.
The first line of the input contains two space separated integers N and M, denoting the number of vertices and the number of edges in the graph respectively. The i^{th} line of the next M lines contains two space separated integers X_{i} and Y_{i}, denoting that the i^{th} edge connects vertices from X_{i} to Y_{i}.
------ Output ------
In a single line, print the minimum number of edges we need to revert. If there is no way of having at least one path from 1 to N, print -1.
------ Constraints ------
$1 β€ N, M β€ 100000 = 10^{5}$
$1 β€ X_{i}, Y_{i} β€ N$
$There can be multiple edges connecting the same pair of vertices, There can be self loops too i.e. X_{i} = Y_{i} $
----- Sample Input 1 ------
7 7
1 2
3 2
3 4
7 4
6 2
5 6
7 5
----- Sample Output 1 ------
2
----- explanation 1 ------
We can consider two paths from 1 to 7:
1-2-3-4-7
1-2-6-5-7
In the first one we need to revert edges (3-2), (7-4). In the second one - (6-2), (5-6), (7-5). So the answer is min(2, 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.
You are walking through a parkway near your house. The parkway has $n+1$ benches in a row numbered from $1$ to $n+1$ from left to right. The distance between the bench $i$ and $i+1$ is $a_i$ meters.
Initially, you have $m$ units of energy. To walk $1$ meter of distance, you spend $1$ unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by sitting on benches (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy can exceed $m$.
Your task is to find the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $n+1$ from the bench $1$ (and end your walk).
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 100$) β the number of test cases. Then $t$ test cases follow.
The first line of the test case contains two integers $n$ and $m$ ($1 \le n \le 100$; $1 \le m \le 10^4$).
The second line of the test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the distance between benches $i$ and $i+1$.
-----Output-----
For each test case, print one integer β the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $n+1$ from the bench $1$ (and end your walk) in the corresponding test case.
-----Examples-----
Input
3
3 1
1 2 1
4 5
3 3 5 2
5 16
1 2 3 4 5
Output
3
8
0
-----Note-----
In the first test case of the example, you can walk to the bench $2$, spending $1$ unit of energy, then restore $2$ units of energy on the second bench, walk to the bench $3$, spending $2$ units of energy, restore $1$ unit of energy and go to the bench $4$.
In the third test case of the example, you have enough energy to just go to the bench $6$ without sitting at all.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Slime has a sequence of positive integers $a_1, a_2, \ldots, a_n$.
In one operation Orac can choose an arbitrary subsegment $[l \ldots r]$ of this sequence and replace all values $a_l, a_{l + 1}, \ldots, a_r$ to the value of median of $\{a_l, a_{l + 1}, \ldots, a_r\}$.
In this problem, for the integer multiset $s$, the median of $s$ is equal to the $\lfloor \frac{|s|+1}{2}\rfloor$-th smallest number in it. For example, the median of $\{1,4,4,6,5\}$ is $4$, and the median of $\{1,7,5,8\}$ is $5$.
Slime wants Orac to make $a_1 = a_2 = \ldots = a_n = k$ using these operations.
Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.
-----Input-----
The first line of the input is a single integer $t$: the number of queries.
The first line of each query contains two integers $n\ (1\le n\le 100\,000)$ and $k\ (1\le k\le 10^9)$, the second line contains $n$ positive integers $a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)$
The total sum of $n$ is at most $100\,000$.
-----Output-----
The output should contain $t$ lines. The $i$-th line should be equal to 'yes' if it is possible to make all integers $k$ in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.
-----Example-----
Input
5
5 3
1 5 2 6 1
1 6
6
3 2
1 2 3
4 3
3 1 2 3
10 3
1 2 3 4 5 6 7 8 9 10
Output
no
yes
yes
no
yes
-----Note-----
In the first query, Orac can't turn all elements into $3$.
In the second query, $a_1=6$ is already satisfied.
In the third query, Orac can select the complete array and turn all elements into $2$.
In the fourth query, Orac can't turn all elements into $3$.
In the fifth query, Orac can select $[1,6]$ at first and then select $[2,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.
Aizu is famous for its buckwheat. There are many people who make buckwheat noodles by themselves.
One day, you went shopping to buy buckwheat flour. You can visit three shops, A, B and C. The amount in a bag and its unit price for each shop is determined by the follows table. Note that it is discounted when you buy buckwheat flour in several bags.
| Shop A | Shop B | Shop C
---|---|---|---
Amount in a bag | 200g| 300g| 500g
Unit price for a bag (nominal cost)| 380 yen | 550 yen | 850 yen
Discounted units | per 5 bags | per 4 bags | per 3 bags
Discount rate| reduced by 20 %| reduced by 15 %| reduced by 12 %
For example, when you buy 12 bags of flour at shop A, the price is reduced by 20 % for 10 bags, but not for other 2 bags. So, the total amount shall be (380 Γ 10) Γ 0.8 + 380 Γ 2 = 3,800 yen.
Write a program which reads the amount of flour, and prints the lowest cost to buy them. Note that you should buy the flour of exactly the same amount as the given input.
Input
The input consists of multiple datasets. For each dataset, an integer a (500 β€ a β€ 5000, a is divisible by 100) which represents the amount of flour is given in a line.
The input ends with a line including a zero. Your program should not process for the terminal symbol. The number of datasets does not exceed 50.
Output
For each dataset, print an integer which represents the lowest cost.
Example
Input
500
2200
0
Output
850
3390
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $ N $ different natural numbers $ a_i $. I decided to make a pair by choosing a different natural number from the given natural numbers. Output one pair that can be created with a value difference that is a multiple of $ N -1 $.
It should be noted that such a pair always exists.
Example
Input
5
1 2 4 7 10
Output
2 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.
There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.
Let A_i be the integer written on the i-th card.
Your objective is to guess A_1, A_2, ..., A_N correctly.
You know the following facts:
- For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.
You are a magician and can use the following magic any number of times:
Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.
What is the minimum cost required to determine all of A_1, A_2, ..., A_N?
It is guaranteed that there is no contradiction in given input.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10^5
- 1 \leq M \leq 10^5
- 1 \leq X_i < Y_i \leq N
- 1 \leq Z_i \leq 100
- The pairs (X_i, Y_i) are distinct.
- There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)
-----Input-----
Input is given from Standard Input in the following format:
N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M
-----Output-----
Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.
-----Sample Input-----
3 1
1 2 1
-----Sample Output-----
2
You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset β a language called HQ...
-----Input-----
The only line of the input is a string between 1 and 10^6 characters long.
-----Output-----
Output "Yes" or "No".
-----Examples-----
Input
HHHH
Output
Yes
Input
HQHQH
Output
No
Input
HHQHHQH
Output
No
Input
HHQQHHQQHH
Output
Yes
-----Note-----
The rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This problem is same as the next one, but has smaller constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the $n$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $i$-th day has a ribbon with color $u_i$. Shiro wants to know the largest number $x$, such that if we consider the streak of the first $x$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $x - 1$ will have the same number of occurrences.
For example, consider the following sequence of $u_i$: $[2, 2, 1, 1, 5, 4, 4, 5]$. Then $x = 7$ makes a streak, since if we remove the leftmost $u_i = 5$, each ribbon color will appear exactly twice in the prefix of $x - 1$ days. Note that $x = 8$ doesn't form a streak, since you must remove exactly one day.
Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$)Β β the total number of days.
The second line contains $n$ integers $u_1, u_2, \ldots, u_n$ ($1 \leq u_i \leq 10$)Β β the colors of the ribbons the cats wear.
-----Output-----
Print a single integer $x$Β β the largest possible streak of days.
-----Examples-----
Input
13
1 1 1 2 2 2 3 3 3 4 4 4 5
Output
13
Input
5
10 2 5 4 1
Output
5
Input
1
10
Output
1
Input
7
3 2 1 1 4 5 1
Output
6
Input
6
1 1 1 2 2 2
Output
5
-----Note-----
In the first example, we can choose the longest streak of $13$ days, since upon removing the last day out of the streak, all of the remaining colors $1$, $2$, $3$, and $4$ will have the same number of occurrences of $3$. Note that the streak can also be $10$ days (by removing the $10$-th day from this streak) but we are interested in the longest streak.
In the fourth example, if we take the streak of the first $6$ days, we can remove the third day from this streak then all of the remaining colors $1$, $2$, $3$, $4$ and $5$ will occur exactly once.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.
Polycarp likes to play computer role-playing game Β«Lizards and BasementsΒ». At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) β they lose b (1 β€ b < a β€ 10) health points each.
As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.
The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?
Polycarp can throw his fire ball into an archer if the latter is already killed.
Input
The first line of the input contains three integers n, a, b (3 β€ n β€ 10; 1 β€ b < a β€ 10). The second line contains a sequence of n integers β h1, h2, ..., hn (1 β€ hi β€ 15), where hi is the amount of health points the i-th archer has.
Output
In the first line print t β the required minimum amount of fire balls.
In the second line print t numbers β indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n - 1. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.
Examples
Input
3 2 1
2 2 2
Output
3
2 2 2
Input
4 3 1
1 4 1 1
Output
4
2 2 3 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem statement
There is an unsigned $ 2 $ decimal integer $ X $ with $ N $ in digits including Leading-zeros. Output the largest non-negative integer that can be expressed in $ 2 $ base in $ N $ digits where the Hamming distance from $ X $ is $ D $.
The Hamming distance between integers expressed in $ 2 $ is the number of digits with different values ββin a number of $ 2 $. For example, the Hamming distance between $ 000 $ and $ 110 $ is $ 2 $.
Constraint
$ 1 \ leq N \ leq 1000 $
$ 0 \ leq D \ leq N $
All inputs are non-negative integers
sample
Sample input 1
Five
00001
3
Sample output 1
11101
Sample input 2
7
0110100
Four
Sample output 2
1111111
Sample input 3
18
110001001110100100
6
Sample output 3
111111111111100100
Sample input 4
3
000
0
Sample output 4
000
input
$ N $
$ X $
$ D $
output
Output the integer of the answer on the $ 1 $ line in unsigned $ 2 $ decimal notation.
Example
Input
5
00001
3
Output
11101
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two strings $s$ and $t$. The string $s$ consists of lowercase Latin letters and at most one wildcard character '*', the string $t$ consists only of lowercase Latin letters. The length of the string $s$ equals $n$, the length of the string $t$ equals $m$.
The wildcard character '*' in the string $s$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $s$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $s$ to obtain a string $t$, then the string $t$ matches the pattern $s$.
For example, if $s=$"aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".
If the given string $t$ matches the given string $s$, print "YES", otherwise print "NO".
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) β the length of the string $s$ and the length of the string $t$, respectively.
The second line contains string $s$ of length $n$, which consists of lowercase Latin letters and at most one wildcard character '*'.
The third line contains string $t$ of length $m$, which consists only of lowercase Latin letters.
-----Output-----
Print "YES" (without quotes), if you can obtain the string $t$ from the string $s$. Otherwise print "NO" (without quotes).
-----Examples-----
Input
6 10
code*s
codeforces
Output
YES
Input
6 5
vk*cup
vkcup
Output
YES
Input
1 1
v
k
Output
NO
Input
9 6
gfgf*gfgf
gfgfgf
Output
NO
-----Note-----
In the first example a wildcard character '*' can be replaced with a string "force". So the string $s$ after this replacement is "codeforces" and the answer is "YES".
In the second example a wildcard character '*' can be replaced with an empty string. So the string $s$ after this replacement is "vkcup" and the answer is "YES".
There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".
In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string $t$ so the answer is "NO".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Example
Input
ACM
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.
Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be a_{i} teams on the i-th day.
There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).
As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.
Sereja wants to order exactly a_{i} pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.
-----Input-----
The first line of input contains a single integer n (1 β€ n β€ 200 000)Β β the number of training sessions.
The second line contains n integers a_1, a_2, ..., a_{n} (0 β€ a_{i} β€ 10 000)Β β the number of teams that will be present on each of the days.
-----Output-----
If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).
-----Examples-----
Input
4
1 2 1 2
Output
YES
Input
3
1 0 1
Output
NO
-----Note-----
In the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.
In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer p_{i} (1 β€ p_{i} β€ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house p_{x}), then he goes to the house whose number is written on the plaque of house p_{x} (that is, to house p_{p}_{x}), and so on.
We know that: When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (10^9 + 7).
-----Input-----
The single line contains two space-separated integers n and k (1 β€ n β€ 1000, 1 β€ k β€ min(8, n)) β the number of the houses and the number k from the statement.
-----Output-----
In a single line print a single integer β the answer to the problem modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
5 2
Output
54
Input
7 4
Output
1728
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Jzzhu has invented a kind of sequences, they meet the following property:$f_{1} = x ; f_{2} = y ; \forall i(i \geq 2), f_{i} = f_{i - 1} + f_{i + 1}$
You are given x and y, please calculate f_{n} modulo 1000000007 (10^9 + 7).
-----Input-----
The first line contains two integers x and y (|x|, |y| β€ 10^9). The second line contains a single integer n (1 β€ n β€ 2Β·10^9).
-----Output-----
Output a single integer representing f_{n} modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
2 3
3
Output
1
Input
0 -1
2
Output
1000000006
-----Note-----
In the first sample, f_2 = f_1 + f_3, 3 = 2 + f_3, f_3 = 1.
In the second sample, f_2 = - 1; - 1 modulo (10^9 + 7) equals (10^9 + 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.
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game Β«Call of Soldiers 3Β».
The game has (m + 1) players and n types of soldiers in total. Players Β«Call of Soldiers 3Β» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer x_{i}. Consider binary representation of x_{i}: if the j-th bit of number x_{i} equal to one, then the army of the i-th player has soldiers of the j-th type.
Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.
-----Input-----
The first line contains three integers n, m, k (1 β€ k β€ n β€ 20;Β 1 β€ m β€ 1000).
The i-th of the next (m + 1) lines contains a single integer x_{i} (1 β€ x_{i} β€ 2^{n} - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.
-----Output-----
Print a single integer β the number of Fedor's potential friends.
-----Examples-----
Input
7 3 1
8
5
111
17
Output
0
Input
3 3 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.
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?
Input
The first line contains integer n (3 β€ n β€ 100) β amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 β€ ai, bi β€ n, ai β bi, 1 β€ ci β€ 100) β road is directed from city ai to city bi, redirecting the traffic costs ci.
Output
Output single integer β the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.
Examples
Input
3
1 3 1
1 2 1
3 2 1
Output
1
Input
3
1 3 1
1 2 5
3 2 1
Output
2
Input
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output
39
Input
4
1 2 9
2 3 8
3 4 7
4 1 5
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one β xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute
$$$ (a_1 + a_2) β (a_1 + a_3) β β¦ β (a_1 + a_n) \\\ β (a_2 + a_3) β β¦ β (a_2 + a_n) \\\ β¦ \\\ β (a_{n-1} + a_n) \\\ $$$
Here x β y is a bitwise XOR operation (i.e. x ^ y in many modern programming languages). You can read about it in Wikipedia: <https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation>.
Input
The first line contains a single integer n (2 β€ n β€ 400 000) β the number of integers in the array.
The second line contains integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^7).
Output
Print a single integer β xor of all pairwise sums of integers in the given array.
Examples
Input
2
1 2
Output
3
Input
3
1 2 3
Output
2
Note
In the first sample case there is only one sum 1 + 2 = 3.
In the second sample case there are three sums: 1 + 2 = 3, 1 + 3 = 4, 2 + 3 = 5. In binary they are represented as 011_2 β 100_2 β 101_2 = 010_2, thus the answer is 2.
β is the bitwise xor operation. To define x β y, consider binary representations of integers x and y. We put the i-th bit of the result to be 1 when exactly one of the i-th bits of x and y is 1. Otherwise, the i-th bit of the result is put to be 0. For example, 0101_2 β 0011_2 = 0110_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.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the `radius` of a circle with the center in point `(0,0)`.
Write a function that calculates the number of points in the circle where `(x,y)` - the cartesian coordinates of the points - are `integers`.
Example: for `radius = 2` the result should be `13`.
`0 <= radius <= 1000`

Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.
The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.
-----Input-----
The input data consists of two lines, one for each square, both containing 4 pairs of integers. Each pair represents coordinates of one vertex of the square. Coordinates within each line are either in clockwise or counterclockwise order.
The first line contains the coordinates of the square with sides parallel to the coordinate axes, the second line contains the coordinates of the square at 45 degrees.
All the values are integer and between $-100$ and $100$.
-----Output-----
Print "Yes" if squares intersect, otherwise print "No".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
0 0 6 0 6 6 0 6
1 3 3 5 5 3 3 1
Output
YES
Input
0 0 6 0 6 6 0 6
7 3 9 5 11 3 9 1
Output
NO
Input
6 0 6 6 0 6 0 0
7 4 4 7 7 10 10 7
Output
YES
-----Note-----
In the first example the second square lies entirely within the first square, so they do intersect.
In the second sample squares do not have any points in common.
Here are images corresponding to the samples: [Image] [Image] [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.
Mr. Chanek gives you a sequence a indexed from 1 to n. Define f(a) as the number of indices where a_i = i.
You can pick an element from the current sequence and remove it, then concatenate the remaining elements together. For example, if you remove the 3-rd element from the sequence [4, 2, 3, 1], the resulting sequence will be [4, 2, 1].
You want to remove some elements from a in order to maximize f(a), using zero or more operations. Find the largest possible f(a).
Input
The first line contains one integer n (1 β€ n β€ 2 β
10^5) β the initial length of the sequence.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 2 β
10^5) β the initial sequence a.
Output
Output an integer denoting the largest f(a) that can be obtained by doing zero or more operations.
Examples
Input
7
2 1 4 2 5 3 7
Output
3
Input
4
4 2 3 1
Output
2
Note
In the first example, f(A) = 3 by doing the following operations.
[2,1,4,2,5,3,7] β [2,1,2,5,3,7] β [1,2,5,3,7] β [1,2,5,3] β [1,2,3]
In the second example, f(A) = 2 and no additional operation is needed.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it β either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in any order you wish. We will then compute the sums of all prefixes in the sequence, and then count how many of these sums are prime numbers. If you want to keep the prize, you will need to maximize the number of primes you get.
Can you win the prize? Hurry up, the bags are waiting!
Input
The first line of the input contains a single integer n (1 β€ n β€ 200 000) β the number of number tiles in the bag. The following line contains n space-separated integers a_1, a_2, ..., a_n (a_i β \{1, 2\}) β the values written on the tiles.
Output
Output a permutation b_1, b_2, ..., b_n of the input sequence (a_1, a_2, ..., a_n) maximizing the number of the prefix sums being prime numbers. If there are multiple optimal permutations, output any.
Examples
Input
5
1 2 1 2 1
Output
1 1 1 2 2
Input
9
1 1 2 1 1 1 2 1 1
Output
1 1 1 2 1 1 1 2 1
Note
The first solution produces the prefix sums 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, \mathbf{\color{blue}{7}} (four primes constructed), while the prefix sums in the second solution are 1, \mathbf{\color{blue}{2}}, \mathbf{\color{blue}{3}}, \mathbf{\color{blue}{5}}, 6, \mathbf{\color{blue}{7}}, 8, 10, \mathbf{\color{blue}{11}} (five primes). Primes are marked bold and blue. In each of these cases, the number of produced primes is maximum possible.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
There is a mysterious device $ M $, and if you put Tanuki and Fox in this device, one animal will come out from the device (hereinafter, Tanuki will be $ T $ and Fox will be $ F $).
$ M (x, y) $ represents an animal that came out by putting animals in the device $ M $ in the order of $ x, y $.
As a result of various trials, the following was found.
$ M (T, T) = T $
$ M (T, F) = F $
$ M (F, T) = T $
$ M (F, F) = T $
You put the animals in a row $ P_1, P_2, ..., P_N $ into the device as follows.
$ M (.... M (M (P_1, P_2), P_3) ...., P_N) $
Answer the last animal that appears.
output
Output the last animal character $ T $ or $ F $, and also a newline at the end.
Example
Input
3
F T T
Output
T
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer $x$ and an array of integers $a_1, a_2, \ldots, a_n$. You have to determine if the number $a_1! + a_2! + \ldots + a_n!$ is divisible by $x!$.
Here $k!$ is a factorial of $k$ β the product of all positive integers less than or equal to $k$. For example, $3! = 1 \cdot 2 \cdot 3 = 6$, and $5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$.
-----Input-----
The first line contains two integers $n$ and $x$ ($1 \le n \le 500000$, $1 \le x \le 500000$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le x$) β elements of given array.
-----Output-----
In the only line print "Yes" (without quotes) if $a_1! + a_2! + \ldots + a_n!$ is divisible by $x!$, and "No" (without quotes) otherwise.
-----Examples-----
Input
6 4
3 2 2 2 3 3
Output
Yes
Input
8 3
3 2 2 2 2 2 1 1
Output
Yes
Input
7 8
7 7 7 7 7 7 7
Output
No
Input
10 5
4 3 2 1 4 3 2 4 3 4
Output
No
Input
2 500000
499999 499999
Output
No
-----Note-----
In the first example $3! + 2! + 2! + 2! + 3! + 3! = 6 + 2 + 2 + 2 + 6 + 6 = 24$. Number $24$ is divisible by $4! = 24$.
In the second example $3! + 2! + 2! + 2! + 2! + 2! + 1! + 1! = 18$, is divisible by $3! = 6$.
In the third example $7! + 7! + 7! + 7! + 7! + 7! + 7! = 7 \cdot 7!$. It is easy to prove that this number is not divisible by $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.
You have array a_1, a_2, ..., a_{n}. Segment [l, r] (1 β€ l β€ r β€ n) is good if a_{i} = a_{i} - 1 + a_{i} - 2, for all i (l + 2 β€ i β€ r).
Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l_1, r_1], is longer than segment [l_2, r_2], if len([l_1, r_1]) > len([l_2, r_2]).
Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.
-----Input-----
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of elements in the array. The second line contains integers: a_1, a_2, ..., a_{n} (0 β€ a_{i} β€ 10^9).
-----Output-----
Print the length of the longest good segment in array a.
-----Examples-----
Input
10
1 2 3 5 8 13 21 34 55 89
Output
10
Input
5
1 1 1 1 1
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Chef is very fond of horses. He enjoys watching them race. As expected, he has a stable full of horses. He, along with his friends, goes to his stable during the weekends to watch a few of these horses race. Chef wants his friends to enjoy the race and so he wants the race to be close. This can happen only if the horses are comparable on their skill i.e. the difference in their skills is less.
There are N horses in the stable. The skill of the horse i is represented by an integer S[i]. The Chef needs to pick 2 horses for the race such that the difference in their skills is minimum. This way, he would be able to host a very interesting race. Your task is to help him do this and report the minimum difference that is possible between 2 horses in the race.
------ Input: ------
First line of the input file contains a single integer T, the number of test cases.
Every test case starts with a line containing the integer N.
The next line contains N space separated integers where the i-th integer is S[i].
------ Output: ------
For each test case, output a single line containing the minimum difference that is possible.
------ Constraints: ------
1 β€ T β€ 10
2 β€ N β€ 5000
1 β€ S[i] β€ 1000000000
----- Sample Input 1 ------
1
5
4 9 1 32 13
----- Sample Output 1 ------
3
----- explanation 1 ------
The minimum difference can be achieved if we pick horses with skills 1 and 4 for the race.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a permutation p_1, p_2, ... , p_n (an array where each integer from 1 to n appears exactly once). The weight of the i-th element of this permutation is a_i.
At first, you separate your permutation into two non-empty sets β prefix and suffix. More formally, the first set contains elements p_1, p_2, ... , p_k, the second β p_{k+1}, p_{k+2}, ... , p_n, where 1 β€ k < n.
After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay a_i dollars to move the element p_i.
Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.
For example, if p = [3, 1, 2] and a = [7, 1, 4], then the optimal strategy is: separate p into two parts [3, 1] and [2] and then move the 2-element into first set (it costs 4). And if p = [3, 5, 1, 6, 2, 4], a = [9, 1, 9, 9, 1, 9], then the optimal strategy is: separate p into two parts [3, 5, 1] and [6, 2, 4], and then move the 2-element into first set (it costs 1), and 5-element into second set (it also costs 1).
Calculate the minimum number of dollars you have to spend.
Input
The first line contains one integer n (2 β€ n β€ 2 β
10^5) β the length of permutation.
The second line contains n integers p_1, p_2, ... , p_n (1 β€ p_i β€ n). It's guaranteed that this sequence contains each element from 1 to n exactly once.
The third line contains n integers a_1, a_2, ... , a_n (1 β€ a_i β€ 10^9).
Output
Print one integer β the minimum number of dollars you have to spend.
Examples
Input
3
3 1 2
7 1 4
Output
4
Input
4
2 4 1 3
5 9 8 3
Output
3
Input
6
3 5 1 6 2 4
9 1 9 9 1 9
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.
George decided to prepare a Codesecrof round, so he has prepared m problems for the round. Let's number the problems with integers 1 through m. George estimates the i-th problem's complexity by integer b_{i}.
To make the round good, he needs to put at least n problems there. Besides, he needs to have at least one problem with complexity exactly a_1, at least one with complexity exactly a_2, ..., and at least one with complexity exactly a_{n}. Of course, the round can also have problems with other complexities.
George has a poor imagination. It's easier for him to make some already prepared problem simpler than to come up with a new one and prepare it. George is magnificent at simplifying problems. He can simplify any already prepared problem with complexity c to any positive integer complexity d (c β₯ d), by changing limits on the input data.
However, nothing is so simple. George understood that even if he simplifies some problems, he can run out of problems for a good round. That's why he decided to find out the minimum number of problems he needs to come up with in addition to the m he's prepared in order to make a good round. Note that George can come up with a new problem of any complexity.
-----Input-----
The first line contains two integers n and m (1 β€ n, m β€ 3000) β the minimal number of problems in a good round and the number of problems George's prepared. The second line contains space-separated integers a_1, a_2, ..., a_{n} (1 β€ a_1 < a_2 < ... < a_{n} β€ 10^6) β the requirements for the complexity of the problems in a good round. The third line contains space-separated integers b_1, b_2, ..., b_{m} (1 β€ b_1 β€ b_2... β€ b_{m} β€ 10^6) β the complexities of the problems prepared by George.
-----Output-----
Print a single integer β the answer to the problem.
-----Examples-----
Input
3 5
1 2 3
1 2 2 3 3
Output
0
Input
3 5
1 2 3
1 1 1 1 1
Output
2
Input
3 1
2 3 4
1
Output
3
-----Note-----
In the first sample the set of the prepared problems meets the requirements for a good round.
In the second sample, it is enough to come up with and prepare two problems with complexities 2 and 3 to get a good round.
In the third sample it is very easy to get a good round if come up with and prepare extra problems with complexities: 2, 3, 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1.
Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p β€ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ i. If the answer is positive, find one way to rearrange the characters.
Input
The only line contains the initial string s, consisting of small Latin letters (1 β€ |s| β€ 1000).
Output
If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".
Examples
Input
abc
Output
YES
abc
Input
abcd
Output
NO
Input
xxxyxxx
Output
YES
xxxxxxy
Note
In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".
In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).
In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Today is Chef's birthday. His mom decided to surprise him with a truly fantastic gift: his favourite binary string B. But, unfortunately, all the stocks of binary string B have been sold out, and only a binary string A (A β B) is available in the market.
She purchases the string A and tries to convert it to string B by applying any of following three operations zero or more times.
AND Operation:
She will choose a pair of indices i and j such that i != j and perform following sequence of operations.
- result = Ai & Aj
- Ai = result & Ai
- Aj = result & Aj
OR Operation:
She will choose a pair of indices i and j such that i != j and perform following sequence of operations.
- result = Ai | Aj
- Ai = result | Ai
- Aj = result | Aj
XOR Operation:
She will choose a pair of indices i and j such that i != j and perform following sequence of operations.
- result = Ai ^ Aj
- Ai = result ^ Ai
- Aj = result ^ Aj
Chef's mom is eagerly waiting to surprise him with his favourite gift and therefore, she wants to convert string A to string B as fast as possible. Can you please help her by telling her the minimum number of operations she will require? If it is impossible to do so, then let Chef's mom know about it.
-----Input-----
First line of input contains a single integer T denoting the number of test cases. T test cases follow.
First line of each test case, will contain binary string A.
Second line of each test case, will contain binary string B.
-----Output-----
For each test case, Print "Lucky Chef" (without quotes) in first line and minimum number of operations required to convert string A to sting B in second line if conversion is possible. Print "Unlucky Chef" (without quotes) in a new line otherwise.
-----Constraints-----
- 1 β€ T β€ 105
- 1 β€ |A| β€ 106
- 1 β€ |B| β€ 106
- A != B
- |A| = |B|
- sum of |A| over all test cases does not exceed 106
- sum of |B| over all test cases does not exceed 106
-----Subtasks-----
- Subtask #1 (40 points) : Sum of |A| & |B| over all test cases does not exceed 103
- Subtask #2 (60 points) : Sum of |A| & |B| over all test cases does not exceed 106
-----Example-----
Input
2
101
010
1111
1010
Output
Lucky Chef
2
Unlucky Chef
-----Explanation-----
Example case 1.
- Applying XOR operation with indices i = 1 and j = 2. Resulting string will be 011.
- Then, Applying AND operation with indices i = 1 and j = 3. Resulting string will be 010.
Example case 2.
- It is impossible to convert string A to string 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.
I have a plan to go on a school trip at a school. I conducted a questionnaire survey for that purpose. Students have student numbers from 1 to n, and the locations of travel candidates are represented by numbers from 1 to m, and where they want to go β , Mark the places you don't want to go with a cross and submit.
At this time, create a program that outputs the place numbers in descending order of the number of people you want to go to. If the number of people is the same, the place numbers are used.
In the first line of the input data, the number of students n and the number of travel candidate locations m are separated by a blank, and the questionnaire result of student i is represented by 1 in β and 0 in Γ in i + 1 line, separated by a blank. There are m numbers in a row. 1 β€ n β€ 1000, 1 β€ m β€ 100.
Input example 1
---
4 6
1 0 1 0 1 1
1 1 0 1 0 0
1 1 1 0 0 0
1 0 1 0 1 0
Output example 1
1 3 2 5 4 6
input
The input consists of multiple datasets. Input ends when both n and m are 0. The number of datasets does not exceed 5.
output
Output the location number on one line for each dataset.
Example
Input
4 6
1 0 1 0 1 1
1 1 0 1 0 0
1 1 1 0 0 0
1 0 1 0 1 0
4 6
1 0 1 0 1 1
1 1 0 1 0 0
1 1 1 0 0 0
1 0 1 0 1 0
0 0
Output
1 3 2 5 4 6
1 3 2 5 4 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.
Takahashi has a string S of length N consisting of lowercase English letters. On this string, he will perform the following operation K times:
* Let T be the string obtained by reversing S, and U be the string obtained by concatenating S and T in this order.
* Let S' be some contiguous substring of U with length N, and replace S with S'.
Among the strings that can be the string S after the K operations, find the lexicographically smallest possible one.
Constraints
* 1 \leq N \leq 5000
* 1 \leq K \leq 10^9
* |S|=N
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N K
S
Output
Print the lexicographically smallest possible string that can be the string S after the K operations.
Examples
Input
5 1
bacba
Output
aabca
Input
10 2
bbaabbbaab
Output
aaaabbaabb
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat s_{i} slices of pizza, and gain a_{i} happiness for each slice of type 1 pizza they eat, and b_{i} happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?
-----Input-----
The first line of input will contain integers N and S (1 β€ N β€ 10^5, 1 β€ S β€ 10^5), the number of contestants and the number of slices per pizza, respectively. N lines follow.
The i-th such line contains integers s_{i}, a_{i}, and b_{i} (1 β€ s_{i} β€ 10^5, 1 β€ a_{i} β€ 10^5, 1 β€ b_{i} β€ 10^5), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.
-----Output-----
Print the maximum total happiness that can be achieved.
-----Examples-----
Input
3 12
3 5 7
4 6 7
5 9 5
Output
84
Input
6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6
Output
314
-----Note-----
In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3Β·5 + 4Β·6 + 5Β·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3Β·7 + 4Β·7 + 5Β·5 = 74.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last n minutes and in the i-th minute friends will send a_{i} requests.
Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load.
Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable.
For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp.
Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to n.
-----Input-----
The first line contains a single integer n (1 β€ n β€ 100 000) β the duration of the load testing.
The second line contains n integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 10^9), where a_{i} is the number of requests from friends in the i-th minute of the load testing.
-----Output-----
Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards.
-----Examples-----
Input
5
1 4 3 2 5
Output
6
Input
5
1 2 2 2 1
Output
1
Input
7
10 20 40 50 70 90 30
Output
0
-----Note-----
In the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests.
In the second example it is enough to make one additional request in the third minute, so the answer is 1.
In the third example the load already satisfies all conditions described in the statement, 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.
Suppose you are living with two cats: A and B. There are $n$ napping spots where both cats usually sleep.
Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:
Cat A changes its napping place in order: $n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$ In other words, at the first hour it's on the spot $n$ and then goes in decreasing order cyclically;
Cat B changes its napping place in order: $1, 2, 3, \dots, n - 1, n, 1, 2, \dots$ In other words, at the first hour it's on the spot $1$ and then goes in increasing order cyclically.
The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $x$ then the A takes this place and B moves to the next place in its order (if $x < n$ then to $x + 1$, but if $x = n$ then to $1$). Cat B follows his order, so it won't return to the skipped spot $x$ after A frees it, but will move to the spot $x + 2$ and so on.
Calculate, where cat B will be at hour $k$?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) β the number of test cases.
The first and only line of each test case contains two integers $n$ and $k$ ($2 \le n \le 10^9$; $1 \le k \le 10^9$) β the number of spots and hour $k$.
-----Output-----
For each test case, print one integer β the index of the spot where cat B will sleep at hour $k$.
-----Examples-----
Input
7
2 1
2 2
3 1
3 2
3 3
5 5
69 1337
Output
1
2
1
3
2
2
65
-----Note-----
In the first and second test cases $n = 2$, so:
at the $1$-st hour, A is on spot $2$ and B is on $1$;
at the $2$-nd hour, A moves to spot $1$ and B β to $2$.
If $n = 3$ then:
at the $1$-st hour, A is on spot $3$ and B is on $1$;
at the $2$-nd hour, A moves to spot $2$; B'd like to move from $1$ to $2$, but this spot is occupied, so it moves to $3$;
at the $3$-rd hour, A moves to spot $1$; B also would like to move from $3$ to $1$, but this spot is occupied, so it moves to $2$.
In the sixth test case:
A's spots at each hour are $[5, 4, 3, 2, 1]$;
B's spots at each hour are $[1, 2, 4, 5, 2]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Mr. Takahashi picked up a dictionary containing all of the N! permutations of integers 1 through N. The dictionary has N! pages, and page i (1 β€ i β€ N!) contains the i-th permutation in the lexicographical order.
Mr. Takahashi wanted to look up a certain permutation of length N in this dictionary, but he forgot some part of it.
His memory of the permutation is described by a sequence P_1, P_2, ..., P_N. If P_i = 0, it means that he forgot the i-th element of the permutation; otherwise, it means that he remembered the i-th element of the permutation and it is P_i.
He decided to look up all the possible permutations in the dictionary. Compute the sum of the page numbers of the pages he has to check, modulo 10^9 + 7.
Constraints
* 1 β€ N β€ 500000
* 0 β€ P_i β€ N
* P_i β P_j if i β j (1 β€ i, j β€ N), P_i β 0 and P_j β 0.
Input
The input is given from Standard Input in the following format:
N
P_1 P_2 ... P_N
Output
Print the sum of the page numbers of the pages he has to check, as modulo 10^9 + 7.
Examples
Input
4
0 2 3 0
Output
23
Input
3
0 0 0
Output
21
Input
5
1 2 3 5 4
Output
2
Input
1
0
Output
1
Input
10
0 3 0 0 1 0 4 0 0 0
Output
953330050
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 10^5
- 1 \leq H_i \leq 10^9
-----Input-----
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
-----Output-----
Print the maximum number of times you can move.
-----Sample Input-----
5
10 4 8 7 3
-----Sample Output-----
2
By landing on the third square from the left, you can move to the right twice.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two sequences $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$. Each element of both sequences is either $0$, $1$ or $2$. The number of elements $0$, $1$, $2$ in the sequence $a$ is $x_1$, $y_1$, $z_1$ respectively, and the number of elements $0$, $1$, $2$ in the sequence $b$ is $x_2$, $y_2$, $z_2$ respectively.
You can rearrange the elements in both sequences $a$ and $b$ however you like. After that, let's define a sequence $c$ as follows:
$c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}$
You'd like to make $\sum_{i=1}^n c_i$ (the sum of all elements of the sequence $c$) as large as possible. What is the maximum possible sum?
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$)Β β the number of test cases.
Each test case consists of two lines. The first line of each test case contains three integers $x_1$, $y_1$, $z_1$ ($0 \le x_1, y_1, z_1 \le 10^8$)Β β the number of $0$-s, $1$-s and $2$-s in the sequence $a$.
The second line of each test case also contains three integers $x_2$, $y_2$, $z_2$ ($0 \le x_2, y_2, z_2 \le 10^8$; $x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$)Β β the number of $0$-s, $1$-s and $2$-s in the sequence $b$.
-----Output-----
For each test case, print the maximum possible sum of the sequence $c$.
-----Example-----
Input
3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1
Output
4
2
0
-----Note-----
In the first sample, one of the optimal solutions is:
$a = \{2, 0, 1, 1, 0, 2, 1\}$
$b = \{1, 0, 1, 0, 2, 1, 0\}$
$c = \{2, 0, 0, 0, 0, 2, 0\}$
In the second sample, one of the optimal solutions is:
$a = \{0, 2, 0, 0, 0\}$
$b = \{1, 1, 0, 1, 0\}$
$c = \{0, 2, 0, 0, 0\}$
In the third sample, the only possible solution is:
$a = \{2\}$
$b = \{2\}$
$c = \{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.
Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.
........#
........#
........#
........#
Constraints
* 3 β€ H β€ 300
* 3 β€ W β€ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the frame made of '#' and '.'.
Print a blank line after each dataset.
Example
Input
3 4
5 6
3 3
0 0
Output
####
#..#
####
######
#....#
#....#
#....#
######
###
#.#
###
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.
You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).
Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.
For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
-----Input-----
The only line of input contains the string s (1 β€ |s| β€ 10^5). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
-----Output-----
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34).
If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
-----Examples-----
Input
aba,123;1a;0
Output
"123,0"
"aba,1a"
Input
1;;01,a0,
Output
"1"
",01,a0,"
Input
1
Output
"1"
-
Input
a
Output
-
"a"
-----Note-----
In the second example the string s contains five words: "1", "", "01", "a0", "".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a program to find the remainder when an integer A is divided by an integer B.
-----Input-----
The first line contains an integer T, the total number of test cases. Then T lines follow, each line contains two Integers A and B.
-----Output-----
For each test case, find the remainder when A is divided by B, and display it in a new line.
-----Constraints-----
- 1 β€ T β€ 1000
- 1 β€ A,B β€ 10000
-----Example-----
Input
3
1 2
100 200
40 15
Output
1
100
10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer N. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and N, inclusive; there will be $\frac{n(n + 1)}{2}$ of them.
You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis.
Find the minimal number of layers you have to use for the given N.
-----Input-----
The only input line contains a single integer N (1 β€ N β€ 100).
-----Output-----
Output a single integer - the minimal number of layers required to draw the segments for the given N.
-----Examples-----
Input
2
Output
2
Input
3
Output
4
Input
4
Output
6
-----Note-----
As an example, here are the segments and their optimal arrangement into layers for N = 4. [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.