question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won $x$ rounds in a row. For example, if Bob won five rounds in a row and $x = 2$, then two sets ends.
You know that Alice and Bob have already played $n$ rounds, and you know the results of some rounds. For each $x$ from $1$ to $n$, calculate the maximum possible number of sets that could have already finished if each set lasts until one of the players wins $x$ rounds in a row. It is possible that the last set is still not finished β in that case, you should not count it in the answer.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 10^6$)Β β the number of rounds.
The second line contains one string $s$ of length $n$ β the descriptions of rounds. If the $i$-th element of the string is 0, then Alice won the $i$-th round; if it is 1, then Bob won the $i$-th round, and if it is ?, then you don't know who won the $i$-th round.
-----Output-----
In the only line print $n$ integers. The $i$-th integer should be equal to the maximum possible number of sets that could have already finished if each set lasts until one of the players wins $i$ rounds in a row.
-----Examples-----
Input
6
11?000
Output
6 3 2 1 0 0
Input
5
01?01
Output
5 1 0 0 0
Input
12
???1??????1?
Output
12 6 4 3 2 2 1 1 1 1 1 1
-----Note-----
Let's consider the first test case:
if $x = 1$ and $s = 110000$ or $s = 111000$ then there are six finished sets; if $x = 2$ and $s = 110000$ then there are three finished sets; if $x = 3$ and $s = 111000$ then there are two finished sets; if $x = 4$ and $s = 110000$ then there is one finished set; if $x = 5$ then there are no finished sets; if $x = 6$ then there are no finished sets.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
Input
The first line contains a non-empty string s, consisting of lowercase Latin letters β that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.
The next line contains integer k (0 β€ k β€ 13) β the number of forbidden pairs of letters.
Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.
Output
Print the single number β the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.
Examples
Input
ababa
1
ab
Output
2
Input
codeforces
2
do
cs
Output
1
Note
In the first sample you should remove two letters b.
In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a string s of length 3 or greater. No two neighboring characters in s are equal.
Takahashi and Aoki will play a game against each other. The two players alternately performs the following operation, Takahashi going first:
* Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.
The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.
Constraints
* 3 β€ |s| β€ 10^5
* s consists of lowercase English letters.
* No two neighboring characters in s are equal.
Input
The input is given from Standard Input in the following format:
s
Output
If Takahashi will win, print `First`. If Aoki will win, print `Second`.
Examples
Input
aba
Output
Second
Input
abc
Output
First
Input
abcab
Output
First
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya and Vasya are competing with each other in a new interesting game as they always do.
At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 β€ K β€ S.
In order to win, Vasya has to find a non-empty subarray in Petya's array such that the sum of all selected elements equals to either K or S - K. Otherwise Vasya loses.
You are given integers N and S. You should determine if Petya can win, considering Vasya plays optimally. If Petya can win, help him to do that.
Input
The first line contains two integers N and S (1 β€ N β€ S β€ 10^{6}) β the required length of the array and the required sum of its elements.
Output
If Petya can win, print "YES" (without quotes) in the first line. Then print Petya's array in the second line. The array should contain N positive integers with sum equal to S. In the third line print K. If there are many correct answers, you can print any of them.
If Petya can't win, print "NO" (without quotes).
You can print each letter in any register (lowercase or uppercase).
Examples
Input
1 4
Output
YES
4
2
Input
3 4
Output
NO
Input
3 8
Output
YES
2 1 5
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.
Snuke received a positive integer N from Takahashi. A positive integer m is called a favorite number when the following condition is satisfied:
* The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.
Find all favorite numbers and print the sum of those.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^{12}
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Examples
Input
8
Output
10
Input
1000000000000
Output
2499686339916
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)
Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.
-----Constraints-----
- 1 \leq K \leq N \leq 1000
- 1 \leq p_i \leq 1000
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N K
p_1 p_2 \ldots p_N
-----Output-----
Print an integer representing the minimum possible total price of fruits.
-----Sample Input-----
5 3
50 100 80 120 80
-----Sample Output-----
210
This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.
The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!
### input
```if-not:c
* customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* n: a positive integer, the number of checkout tills.
```
```if:c
* customers: a pointer to an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
* customers_length: the length of the array that `customers` points to.
* n: a positive integer, the number of checkout tills.
```
### output
The function should return an integer, the total time required.
-------------------------------------------
## Important
**Please look at the examples and clarifications below, to ensure you understand the task correctly :)**
-------
### Examples
```python
queue_time([5,3,4], 1)
# should return 12
# because when n=1, the total time is just the sum of the times
queue_time([10,2,3,3], 2)
# should return 10
# because here n=2 and the 2nd, 3rd, and 4th people in the
# queue finish before the 1st person has finished.
queue_time([2,3,10], 2)
# should return 12
```
### Clarifications
* There is only ONE queue serving many tills, and
* The order of the queue NEVER changes, and
* The front person in the queue (i.e. the first element in the array/list) proceeds to a till as soon as it becomes free.
N.B. You should assume that all the test input will be valid, as specified above.
P.S. The situation in this kata can be likened to the more-computer-science-related idea of a thread pool, with relation to running multiple processes at the same time: https://en.wikipedia.org/wiki/Thread_pool
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 likes cooking. But more than that, he likes to give gifts. And now he wants to give his girlfriend an unforgettable gift. But unfortunately he forgot the password to the safe where the money he saved for the gift is kept.
But he knows how to hack the safe. To do this, you need to correctly answer questions asked by the embedded computer. The computer is very strange, and asks special questions, sometimes it can ask about 10000 question (really weird). Because of this, Chef wants you to write a program that will help him to crack the safe.
The questions are different, but there is only one type of question. Several numbers are given and between them one of three characters: *, +, - can be inserted. Note that in this case there is no priority for the operators, that is, if + is the before multiplication, you must first execute the operation of addition, and then multiplication (1 - 2 * 3 must be interpreted as (1 - 2) * 3 = -3 and not -5). The computer asks the minimum possible value of any valid expression.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The first line of each test case contains a positive integer N. The second line contains N space separated integers A_{1}, A_{2}, ..., A_{N} denoting the expression without the operators.
Β
------ Output ------
For each test case, output a single line containing the minimal value of given expression.
------ Constraints ------
$1 β€ T β€ 10^{5}$
$1 β€ N β€ 10$
$-9 β€ A_{i} β€ 9 .
$Β
------ Scoring ------
Subtask 1 (15 points): 1 β€ T β€ 10
Subtask 2 (10 points): 1 β€ N β€ 3
Subtask 3 (20 points): 1 β€ A_{i} β€ 5.
Subtask 4 (35 points): 1 β€ T β€ 10^{4}
Subtask 5 (20 points): Look at constraints.
----- Sample Input 1 ------
2
3
1 2 3
1
9
----- Sample Output 1 ------
-4
9
----- explanation 1 ------
Example case 1: 1-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.
Given few numbers, you need to print out the digits that are not being used.
Example:
```python
unused_digits(12, 34, 56, 78) # "09"
unused_digits(2015, 8, 26) # "3479"
```
Note:
- Result string should be sorted
- The test case won't pass Integer with leading zero
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.
Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.
After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.
Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.
Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.
The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
Input
The first input line contains four integer numbers n, t1, t2, k (1 β€ n, t1, t2 β€ 1000; 1 β€ k β€ 100) β the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.
Each of the following n lines contains two integers. The i-th (1 β€ i β€ n) line contains space-separated integers ai, bi (1 β€ ai, bi β€ 1000) β the speeds which the participant number i chose.
Output
Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
Examples
Input
2 3 3 50
2 4
4 2
Output
1 15.00
2 15.00
Input
4 1 1 1
544 397
280 101
280 101
693 970
Output
4 1656.07
1 937.03
2 379.99
3 379.99
Note
* First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 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.
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.
As you woke up, you found Mom's coins and read her note. "But why split the money equally?" β you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.
Input
The first line contains integer n (1 β€ n β€ 100) β the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 β€ ai β€ 100) β the coins' values. All numbers are separated with spaces.
Output
In the single line print the single number β the minimum needed number of coins.
Examples
Input
2
3 3
Output
2
Input
3
2 1 2
Output
2
Note
In the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.
In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 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.
This kata is blatantly copied from inspired by This Kata
Welcome
this is the second in the series of the string iterations kata!
Here we go!
---------------------------------------------------------------------------------
We have a string s
Let's say you start with this: "String"
The first thing you do is reverse it: "gnirtS"
Then you will take the string from the 1st position and reverse it again: "gStrin"
Then you will take the string from the 2nd position and reverse it again: "gSnirt"
Then you will take the string from the 3rd position and reverse it again: "gSntri"
Continue this pattern until you have done every single position, and then you will return the string you have created. For this particular string, you would return:
"gSntir"
now,
The Task:
In this kata, we also have a number x
take that reversal function, and apply it to the string x times.
return the result of the string after applying the reversal function to it x times.
example where s = "String" and x = 3:
after 0 iteration s = "String"
after 1 iteration s = "gSntir"
after 2 iterations s = "rgiStn"
after 3 iterations s = "nrtgSi"
so you would return "nrtgSi".
Note
String lengths may exceed 2 million
x exceeds a billion
be read to optimize
if this is too hard, go here https://www.codewars.com/kata/string-%3E-n-iterations-%3E-string/java
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in the middle of a lesson. And only a loud ringing of a school bell could interrupt his sweet dream.
Of course, the valuable material and the teacher's explanations were lost. However, Valera will one way or another have to do the homework. As he does not know the new material absolutely, he cannot do the job himself. That's why he asked you to help. You're his best friend after all, you just cannot refuse to help.
Valera's home task has only one problem, which, though formulated in a very simple way, has not a trivial solution. Its statement looks as follows: if we consider all positive integers in the interval [a;b] then it is required to count the amount of such numbers in this interval that their smallest divisor will be a certain integer k (you do not have to consider divisor equal to one). In other words, you should count the amount of such numbers from the interval [a;b], that are not divisible by any number between 2 and k - 1 and yet are divisible by k.
Input
The first and only line contains three positive integers a, b, k (1 β€ a β€ b β€ 2Β·109, 2 β€ k β€ 2Β·109).
Output
Print on a single line the answer to the given problem.
Examples
Input
1 10 2
Output
5
Input
12 23 3
Output
2
Input
6 19 5
Output
0
Note
Comments to the samples from the statement:
In the first sample the answer is numbers 2, 4, 6, 8, 10.
In the second one β 15, 21
In the third one there are no such numbers.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Serval is fighting with a monster.
The health of the monster is H.
In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.
Serval wins when the monster's health becomes 0 or below.
Find the number of attacks Serval needs to make before winning.
-----Constraints-----
- 1 \leq H \leq 10^4
- 1 \leq A \leq 10^4
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
H A
-----Output-----
Print the number of attacks Serval needs to make before winning.
-----Sample Input-----
10 4
-----Sample Output-----
3
- After one attack, the monster's health will be 6.
- After two attacks, the monster's health will be 2.
- After three attacks, the monster's health will be -2.
Thus, Serval needs to make three attacks to win.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Monocarp has arranged $n$ colored marbles in a row. The color of the $i$-th marble is $a_i$. Monocarp likes ordered things, so he wants to rearrange marbles in such a way that all marbles of the same color form a contiguos segment (and there is only one such segment for each color).
In other words, Monocarp wants to rearrange marbles so that, for every color $j$, if the leftmost marble of color $j$ is $l$-th in the row, and the rightmost marble of this color has position $r$ in the row, then every marble from $l$ to $r$ has color $j$.
To achieve his goal, Monocarp can do the following operation any number of times: choose two neighbouring marbles, and swap them.
You have to calculate the minimum number of operations Monocarp has to perform to rearrange the marbles. Note that the order of segments of marbles having equal color does not matter, it is only required that, for every color, all the marbles of this color form exactly one contiguous segment.
-----Input-----
The first line contains one integer $n$ $(2 \le n \le 4 \cdot 10^5)$ β the number of marbles.
The second line contains an integer sequence $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 20)$, where $a_i$ is the color of the $i$-th marble.
-----Output-----
Print the minimum number of operations Monocarp has to perform to achieve his goal.
-----Examples-----
Input
7
3 4 2 3 4 2 2
Output
3
Input
5
20 1 14 10 2
Output
0
Input
13
5 5 4 4 3 5 7 6 5 4 4 6 5
Output
21
-----Note-----
In the first example three operations are enough. Firstly, Monocarp should swap the third and the fourth marbles, so the sequence of colors is $[3, 4, 3, 2, 4, 2, 2]$. Then Monocarp should swap the second and the third marbles, so the sequence is $[3, 3, 4, 2, 4, 2, 2]$. And finally, Monocarp should swap the fourth and the fifth marbles, so the sequence is $[3, 3, 4, 4, 2, 2, 2]$.
In the second example there's no need to perform any operations.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array of n integer numbers a_0, a_1, ..., a_{n} - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
-----Input-----
The first line contains positive integer n (2 β€ n β€ 10^5) β size of the given array. The second line contains n integers a_0, a_1, ..., a_{n} - 1 (1 β€ a_{i} β€ 10^9) β elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
-----Output-----
Print the only number β distance between two nearest minimums in the array.
-----Examples-----
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob play ping-pong with simplified rules.
During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.
The one who doesn't make a return loses this play. The winner of the play commences the next play. Alice starts the first play.
Alice has $x$ stamina and Bob has $y$. To hit the ball (while serving or returning) each player spends $1$ stamina, so if they don't have any stamina, they can't return the ball (and lose the play) or can't serve the ball (in this case, the other player serves the ball instead). If both players run out of stamina, the game is over.
Sometimes, it's strategically optimal not to return the ball, lose the current play, but save the stamina. On the contrary, when the server commences a play, they have to hit the ball, if they have some stamina left.
Both Alice and Bob play optimally and want to, firstly, maximize their number of wins and, secondly, minimize the number of wins of their opponent.
Calculate the resulting number of Alice's and Bob's wins.
-----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 $x$ and $y$ ($1 \le x, y \le 10^6$) β Alice's and Bob's initial stamina.
-----Output-----
For each test case, print two integers β the resulting number of Alice's and Bob's wins, if both of them play optimally.
-----Examples-----
Input
3
1 1
2 1
1 7
Output
0 1
1 1
0 7
-----Note-----
In the first test case, Alice serves the ball and spends $1$ stamina. Then Bob returns the ball and also spends $1$ stamina. Alice can't return the ball since she has no stamina left and loses the play. Both of them ran out of stamina, so the game is over with $0$ Alice's wins and $1$ Bob's wins.
In the second test case, Alice serves the ball and spends $1$ stamina. Bob decides not to return the ball β he loses the play but saves stamina. Alice, as the winner of the last play, serves the ball in the next play and spends $1$ more stamina. This time, Bob returns the ball and spends $1$ stamina. Alice doesn't have any stamina left, so she can't return the ball and loses the play. Both of them ran out of stamina, so the game is over with $1$ Alice's and $1$ Bob's win.
In the third test case, Alice serves the ball and spends $1$ stamina. Bob returns the ball and spends $1$ stamina. Alice ran out of stamina, so she can't return the ball and loses the play. Bob, as a winner, serves the ball in the next $6$ plays. Each time Alice can't return the ball and loses each play. The game is over with $0$ Alice's and $7$ Bob's wins.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.
The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.
Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move.
Help Anton and write the program that for the given position determines whether the white king is in check.
Remainder, on how do chess pieces move: Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells. Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells. Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap".
-----Input-----
The first line of the input contains a single integer n (1 β€ n β€ 500 000)Β β the number of black pieces.
The second line contains two integers x_0 and y_0 ( - 10^9 β€ x_0, y_0 β€ 10^9)Β β coordinates of the white king.
Then follow n lines, each of them contains a character and two integers x_{i} and y_{i} ( - 10^9 β€ x_{i}, y_{i} β€ 10^9)Β β type of the i-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position.
-----Output-----
The only line of the output should contains "YES" (without quotes) if the white king is in check and "NO" (without quotes) otherwise.
-----Examples-----
Input
2
4 2
R 1 1
B 1 5
Output
YES
Input
2
4 2
R 3 3
B 1 5
Output
NO
-----Note-----
Picture for the first sample: [Image] White king is in check, because the black bishop can reach the cell with the white king in one move. The answer is "YES".
Picture for the second sample: [Image] Here bishop can't reach the cell with the white king, because his path is blocked by the rook, and the bishop cant "leap" over it. Rook can't reach the white king, because it can't move diagonally. Hence, the king is not in check and 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.
There are N stores called Store 1, Store 2, \cdots, Store N. Takahashi, who is at his house at time 0, is planning to visit some of these stores.
It takes Takahashi one unit of time to travel from his house to one of the stores, or between any two stores.
If Takahashi reaches Store i at time t, he can do shopping there after standing in a queue for a_i \times t + b_i units of time. (We assume that it takes no time other than waiting.)
All the stores close at time T + 0.5. If Takahashi is standing in a queue for some store then, he cannot do shopping there.
Takahashi does not do shopping more than once in the same store.
Find the maximum number of times he can do shopping before time T + 0.5.
Constraints
* All values in input are integers.
* 1 \leq N \leq 2 \times 10^5
* 0 \leq a_i \leq 10^9
* 0 \leq b_i \leq 10^9
* 0 \leq T \leq 10^9
Input
Input is given from Standard Input in the following format:
N T
a_1 b_1
a_2 b_2
\vdots
a_N b_N
Output
Print the answer.
Examples
Input
3 7
2 0
3 2
0 3
Output
2
Input
1 3
0 3
Output
0
Input
5 21600
2 14
3 22
1 3
1 10
1 9
Output
5
Input
7 57
0 25
3 10
2 4
5 15
3 22
2 14
1 15
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.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* β you can add an asterisk to the right of the existing type X β that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite β to any type of X, which is a pointer, you can add an ampersand β that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types β void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator β the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and Ρ β to void**.
The next query typedef redefines b β it is now equal to &b = &void* = void. At that, the Ρ type doesn't change.
After that the Ρ type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 cats. We number them from 1 through N.
Each of the cats wears a hat. Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me."
Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats.
Constraints
* 2 β€ N β€ 10^5
* 1 β€ a_i β€ N-1
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print `Yes` if there exists a sequence of colors of the hats that is consistent with the remarks of the cats; print `No` otherwise.
Examples
Input
3
1 2 2
Output
Yes
Input
3
1 1 2
Output
No
Input
5
4 3 4 3 4
Output
No
Input
3
2 2 2
Output
Yes
Input
4
2 2 2 2
Output
Yes
Input
5
3 3 3 3 3
Output
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
Consider a `bishop`, a `knight` and a `rook` on an `n Γ m` chessboard. They are said to form a `triangle` if each piece attacks exactly one other piece and is attacked by exactly one piece.
Calculate the number of ways to choose positions of the pieces to form a triangle.
Note that the bishop attacks pieces sharing the common diagonal with it; the rook attacks in horizontal and vertical directions; and, finally, the knight attacks squares which are two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from its position.

# Example
For `n = 2 and m = 3`, the output should be `8`.

# Input/Output
- `[input]` integer `n`
Constraints: `1 β€ n β€ 40.`
- `[input]` integer `m`
Constraints: `1 β€ m β€ 40, 3 β€ n x m`.
- `[output]` 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.
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.
You are given an array [a_1, a_2, ..., a_n].
Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.
An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
Input
The first line contains a single integer n (1 β€ n β€ 200 000) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ min(n, 100)) β elements of the array.
Output
You should output exactly one integer β the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.
Examples
Input
7
1 1 2 2 3 3 3
Output
6
Input
10
1 1 1 5 4 1 3 1 2 2
Output
7
Input
1
1
Output
0
Note
In the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is lexicographically greater or equal to string s. If such a string does not exist, output -1.
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a β b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains a single integer T (1 β€ T β€ 10 000) β the number of test cases.
The next 2 β
T lines contain the description of test cases. The description of each test case consists of two lines.
The first line of the description contains two integers n and k (1 β€ k β€ n β€ 10^5) β the length of string s and number k respectively.
The second line contains string s consisting of lowercase English letters.
It is guaranteed that the sum of n over all test cases does not exceed 10^5.
Output
For each test case output in a separate line lexicographically smallest beautiful string of length n, which is greater or equal to string s, or -1 if such a string does not exist.
Example
Input
4
4 2
abcd
3 1
abc
4 3
aaaa
9 3
abaabaaaa
Output
acac
abc
-1
abaabaaab
Note
In the first test case "acac" is greater than or equal to s, and each letter appears 2 or 0 times in it, so it is beautiful.
In the second test case each letter appears 0 or 1 times in s, so s itself is the answer.
We can show that there is no suitable string in the third test case.
In the fourth test case each letter appears 0, 3, or 6 times in "abaabaaab". All these integers are divisible by 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.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -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.
Polycarp must pay exactly $n$ burles at the checkout. He has coins of two nominal values: $1$ burle and $2$ burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other.
Thus, Polycarp wants to minimize the difference between the count of coins of $1$ burle and $2$ burles being used. Help him by determining two non-negative integer values $c_1$ and $c_2$ which are the number of coins of $1$ burle and $2$ burles, respectively, so that the total value of that number of coins is exactly $n$ (i. e. $c_1 + 2 \cdot c_2 = n$), and the absolute value of the difference between $c_1$ and $c_2$ is as little as possible (i. e. you must minimize $|c_1-c_2|$).
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$) β the number of test cases. Then $t$ test cases follow.
Each test case consists of one line. This line contains one integer $n$ ($1 \le n \le 10^9$) β the number of burles to be paid by Polycarp.
-----Output-----
For each test case, output a separate line containing two integers $c_1$ and $c_2$ ($c_1, c_2 \ge 0$) separated by a space where $c_1$ is the number of coins of $1$ burle and $c_2$ is the number of coins of $2$ burles. If there are multiple optimal solutions, print any one.
-----Examples-----
Input
6
1000
30
1
32
1000000000
5
Output
334 333
10 10
1 0
10 11
333333334 333333333
1 2
-----Note-----
The answer for the first test case is "334 333". The sum of the nominal values of all coins is $334 \cdot 1 + 333 \cdot 2 = 1000$, whereas $|334 - 333| = 1$. One can't get the better value because if $|c_1 - c_2| = 0$, then $c_1 = c_2$ and $c_1 \cdot 1 + c_1 \cdot 2 = 1000$, but then the value of $c_1$ isn't an integer.
The answer for the second test case is "10 10". The sum of the nominal values is $10 \cdot 1 + 10 \cdot 2 = 30$ and $|10 - 10| = 0$, whereas there's no number having an absolute value less than $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.
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen standing successively one after another. Find the number of beautiful arrangements of the soldiers.
Note that all n1 + n2 warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.
Input
The only line contains four space-separated integers n1, n2, k1, k2 (1 β€ n1, n2 β€ 100, 1 β€ k1, k2 β€ 10) which represent how many footmen and horsemen there are and the largest acceptable number of footmen and horsemen standing in succession, correspondingly.
Output
Print the number of beautiful arrangements of the army modulo 100000000 (108). That is, print the number of such ways to line up the soldiers, that no more than k1 footmen stand successively, and no more than k2 horsemen stand successively.
Examples
Input
2 1 1 10
Output
1
Input
2 3 1 2
Output
5
Input
2 4 1 1
Output
0
Note
Let's mark a footman as 1, and a horseman as 2.
In the first sample the only beautiful line-up is: 121
In the second sample 5 beautiful line-ups exist: 12122, 12212, 21212, 21221, 22121
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider integer coordinates x, y in the Cartesian plan and three functions f, g, h
defined by:
```
f: 1 <= x <= n, 1 <= y <= n --> f(x, y) = min(x, y)
g: 1 <= x <= n, 1 <= y <= n --> g(x, y) = max(x, y)
h: 1 <= x <= n, 1 <= y <= n --> h(x, y) = x + y
```
where n is a given integer (n >= 1, guaranteed) and x, y are integers.
In the table below you can see the value of the function f with n = 6.
---|*0* |*1*|*2*|*3*|*4*|*5*|*6*|
-- |--|--|--|--|--|--|--|
*6*|- |1 |2 |3 |4 |5 |6 |
*5*|- |1 |2 |3 |4 |5 |5 |
*4*|- |1 |2 |3 |4 |4 |4 |
*3*|- |1 |2 |3 |3 |3 |3 |
*2*|- |1 |2 |2 |2 |2 |2 |
*1*|- |1 |1 |1 |1 |1 |1 |
*0*|- |- |- |- |- |- |- |
The task is to calculate the sum of f(x, y), g(x, y) and h(x, y) for all integers x and y such that (1 <= x <= n, 1 <= y <= n).
The function sumin (sum of f) will take n as a parameter and return the sum of min(x, y) in the domain 1 <= x <= n, 1 <= y <= n.
The function sumax (sum of g) will take n as a parameter and return the sum of max(x, y) in the same domain.
The function sumsum (sum of h) will take n as a parameter and return the sum of x + y in the same domain.
#Examples:
```
sumin(6) --> 91
sumin(45) --> 31395
sumin(999) --> 332833500
sumin(5000) --> 41679167500
sumax(6) --> 161
sumax(45) --> 61755
sumax(999) --> 665167500
sumax(5000) --> 83345832500
sumsum(6) --> 252
sumsum(45) --> 93150
sumsum(999) --> 998001000
sumsum(5000) --> 125025000000
```
#Hint:
1. Try to avoid nested loops
2. Note that h = f + g
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!
An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 β€ x,y,z β€ n), a_{x}+a_{y} β a_{z} (not necessarily distinct).
You are given one integer n. Please find any complete array of length n. It is guaranteed that under given constraints such array exists.
Input
Each test contains multiple test cases. The first line contains t (1 β€ t β€ 1000) β the number of test cases. Description of the test cases follows.
The only line of each test case contains one integer n (1 β€ n β€ 1000).
It is guaranteed that the sum of n over all test cases does not exceed 1000.
Output
For each test case, print a complete array on a single line. All elements have to be integers between 1 and 1000 and for all indices x,y,z (1 β€ x,y,z β€ n) (not necessarily distinct), a_{x}+a_{y} β a_{z} must hold.
If multiple solutions exist, you may print any.
Example
Input
2
5
4
Output
1 5 3 77 12
384 384 44 44
Note
It can be shown that the outputs above are valid for each test case. For example, 44+44 β 384.
Below are some examples of arrays that are NOT complete for the 1st test case:
[1,2,3,4,5]
Notice that a_{1}+a_{2} = a_{3}.
[1,3000,1,300,1]
Notice that a_{2} = 3000 > 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.
Vova decided to clean his room. The room can be represented as the coordinate axis $OX$. There are $n$ piles of trash in the room, coordinate of the $i$-th pile is the integer $p_i$. All piles have different coordinates.
Let's define a total cleanup as the following process. The goal of this process is to collect all the piles in no more than two different $x$ coordinates. To achieve this goal, Vova can do several (possibly, zero) moves. During one move, he can choose some $x$ and move all piles from $x$ to $x+1$ or $x-1$ using his broom. Note that he can't choose how many piles he will move.
Also, there are two types of queries:
$0$ $x$ β remove a pile of trash from the coordinate $x$. It is guaranteed that there is a pile in the coordinate $x$ at this moment. $1$ $x$ β add a pile of trash to the coordinate $x$. It is guaranteed that there is no pile in the coordinate $x$ at this moment.
Note that it is possible that there are zero piles of trash in the room at some moment.
Vova wants to know the minimum number of moves he can spend if he wants to do a total cleanup before any queries. He also wants to know this number of moves after applying each query. Queries are applied in the given order. Note that the total cleanup doesn't actually happen and doesn't change the state of piles. It is only used to calculate the number of moves.
For better understanding, please read the Notes section below to see an explanation for the first example.
-----Input-----
The first line of the input contains two integers $n$ and $q$ ($1 \le n, q \le 10^5$) β the number of piles in the room before all queries and the number of queries, respectively.
The second line of the input contains $n$ distinct integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le 10^9$), where $p_i$ is the coordinate of the $i$-th pile.
The next $q$ lines describe queries. The $i$-th query is described with two integers $t_i$ and $x_i$ ($0 \le t_i \le 1; 1 \le x_i \le 10^9$), where $t_i$ is $0$ if you need to remove a pile from the coordinate $x_i$ and is $1$ if you need to add a pile to the coordinate $x_i$. It is guaranteed that for $t_i = 0$ there is such pile in the current set of piles and for $t_i = 1$ there is no such pile in the current set of piles.
-----Output-----
Print $q+1$ integers: the minimum number of moves Vova needs to do a total cleanup before the first query and after each of $q$ queries.
-----Examples-----
Input
5 6
1 2 6 8 10
1 4
1 9
0 6
0 10
1 100
1 50
Output
5
7
7
5
4
8
49
Input
5 8
5 1 2 4 3
0 1
0 2
0 3
0 4
0 5
1 1000000000
1 1
1 500000000
Output
3
2
1
0
0
0
0
0
499999999
-----Note-----
Consider the first example.
Initially, the set of piles is $[1, 2, 6, 8, 10]$. The answer before the first query is $5$ because you can move all piles from $1$ to $2$ with one move, all piles from $10$ to $8$ with $2$ moves and all piles from $6$ to $8$ with $2$ moves.
After the first query, the set becomes $[1, 2, 4, 6, 8, 10]$. Then the answer is $7$ because you can move all piles from $6$ to $4$ with $2$ moves, all piles from $4$ to $2$ with $2$ moves, all piles from $2$ to $1$ with $1$ move and all piles from $10$ to $8$ with $2$ moves.
After the second query, the set of piles becomes $[1, 2, 4, 6, 8, 9, 10]$ and the answer is the same (and the previous sequence of moves can be applied to the current set of piles).
After the third query, the set of piles becomes $[1, 2, 4, 8, 9, 10]$ and the answer is $5$ because you can move all piles from $1$ to $2$ with $1$ move, all piles from $2$ to $4$ with $2$ moves, all piles from $10$ to $9$ with $1$ move and all piles from $9$ to $8$ with $1$ move.
After the fourth query, the set becomes $[1, 2, 4, 8, 9]$ and the answer is almost the same (the previous sequence of moves can be applied without moving piles from $10$).
After the fifth query, the set becomes $[1, 2, 4, 8, 9, 100]$. You can move all piles from $1$ and further to $9$ and keep $100$ at its place. So the answer is $8$.
After the sixth query, the set becomes $[1, 2, 4, 8, 9, 50, 100]$. The answer is $49$ and can be obtained with almost the same sequence of moves as after the previous query. The only difference is that you need to move all piles from $50$ to $9$ too.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 a coach of a group consisting of $n$ students. The $i$-th student has programming skill $a_i$. All students have distinct programming skills. You want to divide them into teams in such a way that: No two students $i$ and $j$ such that $|a_i - a_j| = 1$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $1$); the number of teams is the minimum possible.
You have to answer $q$ independent queries.
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 100$) β the number of queries. Then $q$ queries follow.
The first line of the query contains one integer $n$ ($1 \le n \le 100$) β the number of students in the query. The second line of the query contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$, all $a_i$ are distinct), where $a_i$ is the programming skill of the $i$-th student.
-----Output-----
For each query, print the answer on it β the minimum number of teams you can form if no two students $i$ and $j$ such that $|a_i - a_j| = 1$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $1$)
-----Example-----
Input
4
4
2 10 1 20
2
3 6
5
2 3 4 99 100
1
42
Output
2
1
2
1
-----Note-----
In the first query of the example, there are $n=4$ students with the skills $a=[2, 10, 1, 20]$. There is only one restriction here: the $1$-st and the $3$-th students can't be in the same team (because of $|a_1 - a_3|=|2-1|=1$). It is possible to divide them into $2$ teams: for example, students $1$, $2$ and $4$ are in the first team and the student $3$ in the second team.
In the second query of the example, there are $n=2$ students with the skills $a=[3, 6]$. It is possible to compose just a single team containing both students.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an easier version of the next problem. In this version, $q = 0$.
A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal.
Let's define difficulty of a sequence as a minimum possible number of elements to change to get a nice sequence. However, if you change at least one element of value $x$ to value $y$, you must also change all other elements of value $x$ into $y$ as well. For example, for $[3, 3, 1, 3, 2, 1, 2]$ it isn't allowed to change first $1$ to $3$ and second $1$ to $2$. You need to leave $1$'s untouched or change them to the same value.
You are given a sequence of integers $a_1, a_2, \ldots, a_n$ and $q$ updates.
Each update is of form "$i$ $x$"Β β change $a_i$ to $x$. Updates are not independent (the change stays for the future).
Print the difficulty of the initial sequence and of the sequence after every update.
-----Input-----
The first line contains integers $n$ and $q$ ($1 \le n \le 200\,000$, $q = 0$), the length of the sequence and the number of the updates.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 200\,000$), the initial sequence.
Each of the following $q$ lines contains integers $i_t$ and $x_t$ ($1 \le i_t \le n$, $1 \le x_t \le 200\,000$), the position and the new value for this position.
-----Output-----
Print $q+1$ integers, the answer for the initial sequence and the answer after every update.
-----Examples-----
Input
5 0
3 7 3 7 3
Output
2
Input
10 0
1 2 1 2 3 1 1 1 50 1
Output
4
Input
6 0
6 6 3 3 4 4
Output
0
Input
7 0
3 3 1 3 2 1 2
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.
Vasya likes taking part in Codeforces contests. When a round is over, Vasya follows all submissions in the system testing tab.
There are $n$ solutions, the $i$-th of them should be tested on $a_i$ tests, testing one solution on one test takes $1$ second. The solutions are judged in the order from $1$ to $n$. There are $k$ testing processes which test solutions simultaneously. Each of them can test at most one solution at a time.
At any time moment $t$ when some testing process is not judging any solution, it takes the first solution from the queue and tests it on each test in increasing order of the test ids. Let this solution have id $i$, then it is being tested on the first test from time moment $t$ till time moment $t + 1$, then on the second test till time moment $t + 2$ and so on. This solution is fully tested at time moment $t + a_i$, and after that the testing process immediately starts testing another solution.
Consider some time moment, let there be exactly $m$ fully tested solutions by this moment. There is a caption "System testing: $d$%" on the page with solutions, where $d$ is calculated as
$$d = round\left(100\cdot\frac{m}{n}\right),$$
where $round(x) = \lfloor{x + 0.5}\rfloor$ is a function which maps every real to the nearest integer.
Vasya calls a submission interesting if there is a time moment (possibly, non-integer) when the solution is being tested on some test $q$, and the caption says "System testing: $q$%". Find the number of interesting solutions.
Please note that in case when multiple processes attempt to take the first submission from the queue at the same moment (for instance, at the initial moment), the order they take the solutions does not matter.
-----Input-----
The first line contains two positive integers $n$ and $k$ ($1 \le n \le 1000$, $1 \le k \le 100$) standing for the number of submissions and the number of testing processes respectively.
The second line contains $n$ positive integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 150$), where $a_i$ is equal to the number of tests the $i$-th submission is to be run on.
-----Output-----
Output the only integerΒ β the number of interesting submissions.
-----Examples-----
Input
2 2
49 100
Output
1
Input
4 2
32 100 33 1
Output
2
Input
14 5
48 19 6 9 50 20 3 42 38 43 36 21 44 6
Output
5
-----Note-----
Consider the first example. At time moment $0$ both solutions start testing. At time moment $49$ the first solution is fully tested, so at time moment $49.5$ the second solution is being tested on the test $50$, and the caption says "System testing: $50$%" (because there is one fully tested solution out of two). So, the second solution is interesting.
Consider the second example. At time moment $0$ the first and the second solutions start testing. At time moment $32$ the first solution is fully tested, the third solution starts testing, the caption says "System testing: $25$%". At time moment $32 + 24.5 = 56.5$ the third solutions is being tested on test $25$, the caption is still the same, thus this solution is interesting. After that the third solution is fully tested at time moment $32 + 33 = 65$, the fourth solution is fully tested at time moment $65 + 1 = 66$. The captions becomes "System testing: $75$%", and at time moment $74.5$ the second solution is being tested on test $75$. So, this solution is also interesting. Overall, there are two interesting solutions.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 game of Berland poker is played with a deck of $n$ cards, $m$ of which are jokers. $k$ players play this game ($n$ is divisible by $k$).
At the beginning of the game, each player takes $\frac{n}{k}$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $x - y$, where $x$ is the number of jokers in the winner's hand, and $y$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $0$ points.
Here are some examples: $n = 8$, $m = 3$, $k = 2$. If one player gets $3$ jokers and $1$ plain card, and another player gets $0$ jokers and $4$ plain cards, then the first player is the winner and gets $3 - 0 = 3$ points; $n = 4$, $m = 2$, $k = 4$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $0$ points; $n = 9$, $m = 6$, $k = 3$. If the first player gets $3$ jokers, the second player gets $1$ joker and $2$ plain cards, and the third player gets $2$ jokers and $1$ plain card, then the first player is the winner, and he gets $3 - 2 = 1$ point; $n = 42$, $m = 0$, $k = 7$. Since there are no jokers, everyone gets $0$ jokers, everyone is a winner, and everyone gets $0$ points.
Given $n$, $m$ and $k$, calculate the maximum number of points a player can get for winning the game.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 500$) β the number of test cases.
Then the test cases follow. Each test case contains three integers $n$, $m$ and $k$ ($2 \le n \le 50$, $0 \le m \le n$, $2 \le k \le n$, $k$ is a divisors of $n$).
-----Output-----
For each test case, print one integer β the maximum number of points a player can get for winning the game.
-----Example-----
Input
4
8 3 2
4 2 4
9 6 3
42 0 7
Output
3
0
1
0
-----Note-----
Test cases of the example are described in the statement.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Jou and Yae are a good couple. Jou is collecting prizes for capsule toy vending machines (Gachapon), and even when they go out together, when they find Gachapon, they seem to get so hot that they try it several times. Yae was just looking at Jou, who looked happy, but decided to give him a Gachapon prize for his upcoming birthday present. Yae wasn't very interested in Gachapon itself, but hopefully he would like a match with Jou.
For Gachapon that Yae wants to try, one prize will be given in one challenge. You can see how many types of prizes there are, including those that are out of stock, and how many of each prize remains. However, I don't know which prize will be given in one challenge. Therefore, regardless of the order in which the prizes are given, create a program that outputs the minimum number of challenges required for Yae to get two of the same prizes.
input
The input consists of multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
N
k1 k2 ... kN
Each dataset has two lines, and the first line is given the integer N (1 β€ N β€ 10000), which indicates how many types of prizes there are. The next line is given the integer ki (0 β€ ki β€ 10000), which indicates how many prizes are left.
The number of datasets does not exceed 100.
output
For each dataset, the minimum number of challenges required to get two identical prizes is output. However, if it is not possible, NA is output.
Example
Input
2
3 2
3
0 1 1
1
1000
0
Output
3
NA
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.
There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (10^9 + 7). Two ways are different, if the set of deleted positions in s differs.
Look at the input part of the statement, s is given in a special form.
-----Input-----
In the first line you're given a string a (1 β€ |a| β€ 10^5), containing digits only. In the second line you're given an integer k (1 β€ k β€ 10^9). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.
-----Output-----
Print a single integer β the required number of ways modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
1256
1
Output
4
Input
13990
2
Output
528
Input
555
2
Output
63
-----Note-----
In the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.
In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.
In the third case, except deleting all digits, any choice will do. Therefore there are 2^6 - 1 = 63 possible ways to delete digits.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day, Chef prepared D brand new dishes. He named the i-th dish by a string Si. After the cooking, he decided to categorize each of these D dishes as special or not.
A dish Si is called special if it's name (i.e. the string Si) can be represented in the form of a double string by removing at most one (possibly zero) character from it's name from any position.
A string is called a double string if it can be represented as a concatenation of two identical, non-empty strings.
e.g. "abab" is a double string as it can be represented as "ab" + "ab" where + operation denotes concatenation.
Similarly, "aa", "abcabc" are double strings whereas "a", "abba", "abc" are not.
-----Input-----
- First line of the input contains an integer D denoting the number of dishes prepared by Chef on that day.
- Each of the next D lines will contain description of a dish.
- The i-th line contains the name of i-th dish Si.
-----Output-----
For each of the D dishes, print a single line containing "YES" or "NO" (without quotes) denoting whether the dish can be called as a special or not.
-----Constraints-----
- 1 β€ D β€ 106
- 1 β€ |Si| β€ 106.
- Each character of string Si will be lower case English alphabet (i.e. from 'a' to 'z').
-----Subtasks-----
Subtask #1 : (20 points)
- Sum of |Si| in an input file doesn't exceed 2 * 103
Subtask 2 : (80 points)
- Sum of |Si| in an input file doesn't exceed 2 * 106
-----Example-----
Input:
3
aba
abac
abcd
Output:
YES
NO
NO
-----Explanation-----
Example case 1.
We can remove the character at position 1 (0-based index) to get "aa" which is a double string. Hence, it is a special dish.
Example case 2.
It is not possible to remove the character at any of the position to get the double string. Hence, it is not a special dish.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" β are regular, at the same time "][", "[[]" and "[[]]][" β are irregular.
Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height β use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as:
+- -++- -+
|+- -++- -+|| |
|| || ||| |
|+- -++- -+|| |
+- -++- -+
Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.
Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height.
The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.
Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.
-----Input-----
The first line contains an even integer n (2 β€ n β€ 100) β the length of the sequence of brackets.
The second line contains the sequence of brackets β these are n symbols "[" and "]". It is guaranteed that the given sequence of brackets is regular.
-----Output-----
Print the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces.
-----Examples-----
Input
8
[[][]][]
Output
+- -++- -+
|+- -++- -+|| |
|| || ||| |
|+- -++- -+|| |
+- -++- -+
Input
6
[[[]]]
Output
+- -+
|+- -+|
||+- -+||
||| |||
||+- -+||
|+- -+|
+- -+
Input
6
[[][]]
Output
+- -+
|+- -++- -+|
|| || ||
|+- -++- -+|
+- -+
Input
2
[]
Output
+- -+
| |
+- -+
Input
4
[][]
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.
Given is a string S consisting of L and R.
Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.
The character written on the leftmost square is always R, and the character written on the rightmost square is always L.
Initially, one child is standing on each square.
Each child will perform the move below 10^{100} times:
- Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.
Find the number of children standing on each square after the children performed the moves.
-----Constraints-----
- S is a string of length between 2 and 10^5 (inclusive).
- Each character of S is L or R.
- The first and last characters of S are R and L, respectively.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the number of children standing on each square after the children performed the moves, in order from left to right.
-----Sample Input-----
RRLRL
-----Sample Output-----
0 1 2 1 1
- After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.
- After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.
- After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to 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.
In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.
Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.
Given this information, is it possible to restore the exact floor for flat n?
-----Input-----
The first line contains two integers n and m (1 β€ n β€ 100, 0 β€ m β€ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory.
m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers k_{i}, f_{i} (1 β€ k_{i} β€ 100, 1 β€ f_{i} β€ 100), which means that the flat k_{i} is on the f_{i}-th floor. All values k_{i} are distinct.
It is guaranteed that the given information is not self-contradictory.
-----Output-----
Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.
-----Examples-----
Input
10 3
6 2
2 1
7 3
Output
4
Input
8 4
3 1
6 2
5 2
2 1
Output
-1
-----Note-----
In the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.
In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Kata is intended as a small challenge for my students**
Create a function, called ``removeVowels`` (or ``remove_vowels``), that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u").
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
```python
is_isogram("Dermatoglyphics" ) == true
is_isogram("aba" ) == false
is_isogram("moOse" ) == false # -- ignore letter case
```
```C
is_isogram("Dermatoglyphics" ) == true;
is_isogram("aba" ) == false;
is_isogram("moOse" ) == false; // -- ignore letter case
```
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
Yesterday Chef had a great party and doesn't remember the way he celebreated it. But he found a strange paper in his kitchen containing n digits (lets give them indices from 1 to n and name them a_{1}, a_{2} ... a_{N}).
Chef remembers that he played such game:
On each step he choose an index x from 1 to n.
For all indices y (y < x) he calculated the difference b_{y} = a_{x} - a_{y}.
Then he calculated B1 - sum of all b_{y} which are greater than 0 and B2 - sum of all b_{y} which are less than 0.
The answer for this step is B1 - B2.
Chef remembers the game, but forgot the answer. Please, help him!
------ Input ------
The first line contains two integers n, m denoting the number of digits and number of steps. The second line contains n digits (without spaces) a_{1}, a_{2}, ..., a_{n}.
Each of next m lines contains single integer x denoting the index for current step.
Β
------ Output ------
For each of m steps print single number in a line - answer of the step.
Β
------ Constraints ------
$1 β€ n, m β€ 10^{5}$
$0 β€ a_{i} β€ 9$
$1 β€ x β€ n$
Β
----- Sample Input 1 ------
10 3
0324152397
1
4
7
----- Sample Output 1 ------
0
7
9
----- explanation 1 ------
For index 1 there are no indexes which are less, so B1 = B2 = 0 and the answer is 0.
For index 4 we have
b1 = 4-0=4,
b2 = 4-3=1,
b3 = 4-2=2,
so B1 = 4+1+2 = 7, B2 = 0
and the answer is 7.
For index 7 we have
b1 = 2-0=2,
b2 = 2-3=-1,
b3 = 2-2=0,
b4 = 2-4=-2,
b5 = 2-1=1,
b6 = 2-5=-3,
so B1 = 2 + 1 = 3,
B2 = -1 -2 -3 = -6
and the answer is 9.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n cities situated along the main road of Berland. Cities are represented by their coordinates β integer numbers a_1, a_2, ..., a_{n}. All coordinates are pairwise distinct.
It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money β he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.
It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs.
Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
-----Input-----
The first line contains one integer number n (2 β€ n β€ 2Β·10^5).
The second line contains n integer numbers a_1, a_2, ..., a_{n} ( - 10^9 β€ a_{i} β€ 10^9). All numbers a_{i} are pairwise distinct.
-----Output-----
Print two integer numbers β the minimal distance and the quantity of pairs with this distance.
-----Examples-----
Input
4
6 -3 0 4
Output
2 1
Input
3
-2 0 2
Output
2 2
-----Note-----
In the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that: character'+' is placed on the left of character '=', characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle partΒ β b and the right partΒ β c), all the three parts a, b and c do not contain leading zeros, it is true that a+b=c.
It is guaranteed that in given tests answer always exists.
-----Input-----
The first line contains a non-empty string consisting of digits. The length of the string does not exceed 10^6.
-----Output-----
Output the restored expression. If there are several solutions, you can print any of them.
Note that the answer at first should contain two terms (divided with symbol '+'), and then the result of their addition, before which symbol'=' should be.
Do not separate numbers and operation signs with spaces. Strictly follow the output format given in the examples.
If you remove symbol '+' and symbol '=' from answer string you should get a string, same as string from the input data.
-----Examples-----
Input
12345168
Output
123+45=168
Input
099
Output
0+9=9
Input
199100
Output
1+99=100
Input
123123123456456456579579579
Output
123123123+456456456=579579579
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 lives on a coordinate line at the point $x = 0$. He goes to his friend that lives at the point $x = a$. Polycarp can move only from left to right, he can pass one unit of length each second.
Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $n$ non-intersecting segments, the $i$-th segment which is in the rain is represented as $[l_i, r_i]$ ($0 \le l_i < r_i \le a$).
There are $m$ umbrellas lying on the line, the $i$-th umbrella is located at point $x_i$ ($0 \le x_i \le a$) and has weight $p_i$. When Polycarp begins his journey, he doesn't have any umbrellas.
During his journey from $x = 0$ to $x = a$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $x$ to $x + 1$ if a segment $[x, x + 1]$ is in the rain (i.e. if there exists some $i$ such that $l_i \le x$ and $x + 1 \le r_i$).
The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.
Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.
Can Polycarp make his way from point $x = 0$ to point $x = a$? If yes, find the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.
-----Input-----
The first line contains three integers $a$, $n$ and $m$ ($1 \le a, m \le 2000, 1 \le n \le \lceil\frac{a}{2}\rceil$) β the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.
Each of the next $n$ lines contains two integers $l_i$ and $r_i$ ($0 \le l_i < r_i \le a$) β the borders of the $i$-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments $i$ and $j$ either $r_i < l_j$ or $r_j < l_i$.
Each of the next $m$ lines contains two integers $x_i$ and $p_i$ ($0 \le x_i \le a$, $1 \le p_i \le 10^5$) β the location and the weight of the $i$-th umbrella.
-----Output-----
Print "-1" (without quotes) if Polycarp can't make his way from point $x = 0$ to point $x = a$. Otherwise print one integer β the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.
-----Examples-----
Input
10 2 4
3 7
8 10
0 10
3 4
8 1
1 2
Output
14
Input
10 1 1
0 9
0 5
Output
45
Input
10 1 1
0 9
1 5
Output
-1
-----Note-----
In the first example the only possible strategy is to take the fourth umbrella at the point $x = 1$, keep it till the point $x = 7$ (the total fatigue at $x = 7$ will be equal to $12$), throw it away, move on from $x = 7$ to $x = 8$ without an umbrella, take the third umbrella at $x = 8$ and keep it till the end (the total fatigue at $x = 10$ will be equal to $14$).
In the second example the only possible strategy is to take the first umbrella, move with it till the point $x = 9$, throw it away and proceed without an umbrella till the end.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Daruma Otoshi
You are playing a variant of a game called "Daruma Otoshi (Dharma Block Striking)".
At the start of a game, several wooden blocks of the same size but with varying weights are stacked on top of each other, forming a tower. Another block symbolizing Dharma is placed atop. You have a wooden hammer with its head thicker than the height of a block, but not twice that.
You can choose any two adjacent blocks, except Dharma on the top, differing at most 1 in their weight, and push both of them out of the stack with a single blow of your hammer. The blocks above the removed ones then fall straight down, without collapsing the tower. You cannot hit a block pair with weight difference of 2 or more, for that makes too hard to push out blocks while keeping the balance of the tower. There is no chance in hitting three blocks out at a time, for that would require superhuman accuracy.
The goal of the game is to remove as many blocks as you can. Your task is to decide the number of blocks that can be removed by repeating the blows in an optimal order.
<image>
Figure D1. Striking out two blocks at a time
In the above figure, with a stack of four blocks weighing 1, 2, 3, and 1, in this order from the bottom, you can hit middle two blocks, weighing 2 and 3, out from the stack. The blocks above will then fall down, and two blocks weighing 1 and the Dharma block will remain. You can then push out the remaining pair of weight-1 blocks after that.
Input
The input consists of multiple datasets. The number of datasets is at most 50. Each dataset is in the following format.
n
w1 w2 β¦ wn
n is the number of blocks, except Dharma on the top. n is a positive integer not exceeding 300. wi gives the weight of the i-th block counted from the bottom. wi is an integer between 1 and 1000, inclusive.
The end of the input is indicated by a line containing a zero.
Output
For each dataset, output in a line the maximum number of blocks you can remove.
Sample Input
4
1 2 3 4
4
1 2 3 1
5
5 1 2 3 6
14
8 7 1 4 3 5 4 1 6 8 10 4 6 5
5
1 3 5 1 3
0
Output for the Sample Input
4
4
2
12
0
Example
Input
4
1 2 3 4
4
1 2 3 1
5
5 1 2 3 6
14
8 7 1 4 3 5 4 1 6 8 10 4 6 5
5
1 3 5 1 3
0
Output
4
4
2
12
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.
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".
Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.
For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.
You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
-----Input-----
The first line of the input contains one integer $n$ ($1 \le n \le 10^5$) β the number of pairs to check. Further input contains $n$ descriptions of pairs.
The first line of each description contains a single non-empty word $s$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $t$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $10^6$.
It is guaranteed that the total length of all words $s$ in the input is not greater than $10^6$. Also, it is guaranteed that the total length of all words $t$ in the input is not greater than $10^6$.
-----Output-----
Output $n$ lines. In the $i$-th line for the $i$-th pair of words $s$ and $t$ print YES if the word $t$ could be printed by typing the word $s$. Otherwise, print NO.
-----Examples-----
Input
4
hello
hello
hello
helloo
hello
hlllloo
hello
helo
Output
YES
YES
NO
NO
Input
5
aa
bb
codeforces
codeforce
polycarp
poolycarpp
aaaa
aaaab
abcdefghijklmnopqrstuvwxyz
zabcdefghijklmnopqrstuvwxyz
Output
NO
NO
YES
NO
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.
Sunuke received a d-dimensional hypercube with a side length of l1 Γ ... Γ ld as a birthday present. Sunuke placed this rectangular parallelepiped so that the range of the i-th coordinate was 0 or more and li or less, and ate the part that satisfied x1 + ... + xd β€ s. However, xi represents the i-th coordinate. If the volume of the part eaten by Sunuke is V, it can be proved that d! V (V multiplied by the factorial of d) is an integer. Find the remainder of d! V divided by 1,000,000,007.
Constraints
* 2 β€ d β€ 300
* 1 β€ li β€ 300
* 0 β€ s β€ $ \ sum l_ {i} $
* All inputs are integers
Input
d
l1
.. ..
ld
s
Output
Output d! V divided by 1,000,000,007.
Examples
Input
2
6
3
4
Output
15
Input
5
12
34
56
78
90
123
Output
433127538
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As you have noticed, there are lovely girls in Arpaβs land.
People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crush_{i}. [Image]
Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.
The game consists of rounds. Assume person x wants to start a round, he calls crush_{x} and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crush_{x} calls crush_{crush}_{x} and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.
Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.
Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crush_{i} = i).
-----Input-----
The first line of input contains integer n (1 β€ n β€ 100)Β β the number of people in Arpa's land.
The second line contains n integers, i-th of them is crush_{i} (1 β€ crush_{i} β€ n)Β β the number of i-th person's crush.
-----Output-----
If there is no t satisfying the condition, print -1. Otherwise print such smallest t.
-----Examples-----
Input
4
2 3 1 4
Output
3
Input
4
4 4 4 4
Output
-1
Input
4
2 1 4 3
Output
1
-----Note-----
In the first sample suppose t = 3.
If the first person starts some round:
The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1.
The process is similar for the second and the third person.
If the fourth person starts some round:
The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4.
In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Yuki made a sugoroku so that everyone can play at the children's association event. In this sugoroku, squares are lined up in a ring, and each square has an integer of 1 or more written on it.
The player chooses a square as a starting point and places his piece. Advance the pieces clockwise by the number written on the square. Advance the pieces clockwise again by the number written on the stopped square. Repeat this, and when the piece stops on the square selected as the starting point, it is "Agari".
In reality, depending on how you choose the squares, it may never be "finished". Yuki is trying to count the number of squares that can reach the "Agari" in this sugoroku.
Create a program that inputs sugoroku information and reports the number of squares that can reach "Agari".
Input
The input is given in the following format.
N
a1 a2 ... aN
The number N (1 β€ N β€ 100000) of all the cells contained in the sugoroku is given in the first line. On the second line, the number ai (1 β€ ai β€ 109) written in each cell is given in turn clockwise.
Output
The number of squares that can reach "Agari" is output in one line.
Examples
Input
3
1 1 1
Output
3
Input
3
1 1 2
Output
2
Input
8
2 3 7 3 3 3 4 4
Output
6
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
-----Input-----
The first line of the input contains a single integer n (1 β€ n β€ 100 000)Β β the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
-----Output-----
Print one integerΒ β the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
-----Examples-----
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
-----Note-----
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus 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.
We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 β€ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 β€ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v.
It is expected that one of the vertices will be invaded by aliens from outer space. Snuke wants to immediately identify that vertex when the invasion happens. To do so, he has decided to install an antenna on some vertices.
First, he decides the number of antennas, K (1 β€ K β€ N). Then, he chooses K different vertices, x_0, x_1, ..., x_{K - 1}, on which he installs Antenna 0, 1, ..., K - 1, respectively. If Vertex v is invaded by aliens, Antenna k (0 β€ k < K) will output the distance d(x_k, v). Based on these K outputs, Snuke will identify the vertex that is invaded. Thus, in order to identify the invaded vertex no matter which one is invaded, the following condition must hold:
* For each vertex u (0 β€ u < N), consider the vector (d(x_0, u), ..., d(x_{K - 1}, u)). These N vectors are distinct.
Find the minumum value of K, the number of antennas, when the condition is satisfied.
Constraints
* 2 β€ N β€ 10^5
* 0 β€ a_i, b_i < N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_0 b_0
a_1 b_1
:
a_{N - 2} b_{N - 2}
Output
Print the minumum value of K, the number of antennas, when the condition is satisfied.
Examples
Input
5
0 1
0 2
0 3
3 4
Output
2
Input
2
0 1
Output
1
Input
10
2 8
6 0
4 1
7 6
2 3
8 6
6 9
2 4
5 8
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.
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations: Write parity(a) to the end of a. For example, $1010 \rightarrow 10100$. Remove the first character of a. For example, $1001 \rightarrow 001$. You cannot perform this operation if a is empty.
You can use as many operations as you want. The problem is, is it possible to turn a into b?
The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
-----Input-----
The first line contains the string a and the second line contains the string b (1 β€ |a|, |b| β€ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.
-----Output-----
Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.
-----Examples-----
Input
01011
0110
Output
YES
Input
0011
1110
Output
NO
-----Note-----
In the first sample, the steps are as follows: 01011 β 1011 β 011 β 0110
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You can print your name on a billboard ad. Find out how much it will cost you. Each letter has a default price of Β£30, but that can be different if you are given 2 parameters instead of 1.
You can not use multiplier "*" operator.
If your name would be Jeong-Ho Aristotelis, ad would cost Β£600.
20 leters * 30 = 600 (Space counts as a letter).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
John is new to spreadsheets. He is well aware of rows and columns, but he is not comfortable with spreadsheets numbering system.
```
Spreadsheet Row Column
A1 R1C1
D5 R5C4
AA48 R48C27
BK12 R12C63```
Since John has a lot of work to do both in row-column and spreadsheet systems, he needs a program that converts cell numbers from one system to another.
# Example
For `s = "A1"`, the result should be `"R1C1"`.
For `s = "R48C27"`, the result should be `"AA48"`.
- Input/Output
- `[input]` string `s`
The position (in spreadsheet or row-column numbering system).
`Spreadsheet : A1 to CRXO65535`
`Row-Column: R1C1 to R65535C65535`
- `[output]` a string
The position (in the opposite format; if input was in spreadsheet system, the output should be int row-column system, and vise versa).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 north country is conquered by the great shogun-sama (which means king). Recently many beautiful dice which were made by order of the great shogun-sama were given to all citizens of the country. All citizens received the beautiful dice with a tear of delight. Now they are enthusiastically playing a game with the dice.
The game is played on grid of h * w cells that each of which has a number, which is designed by the great shogun-sama's noble philosophy. A player put his die on a starting cell and move it to a destination cell with rolling the die. After rolling the die once, he takes a penalty which is multiple of the number written on current cell and the number printed on a bottom face of the die, because of malicious conspiracy of an enemy country. Since the great shogun-sama strongly wishes, it is decided that the beautiful dice are initially put so that 1 faces top, 2 faces south, and 3 faces east. You will find that the number initially faces north is 5, as sum of numbers on opposite faces of a die is always 7. Needless to say, idiots those who move his die outside the grid are punished immediately.
The great shogun-sama is pleased if some citizens can move the beautiful dice with the least penalty when a grid and a starting cell and a destination cell is given. Other citizens should be sent to coal mine (which may imply labor as slaves). Write a program so that citizens can deal with the great shogun-sama's expectations.
Constraints
* 1 β€ h, w β€ 10
* 0 β€ number assinged to a cell β€ 9
* the start point and the goal point are different.
Input
The first line of each data set has two numbers h and w, which stands for the number of rows and columns of the grid.
Next h line has w integers, which stands for the number printed on the grid. Top-left corner corresponds to northwest corner.
Row number and column number of the starting cell are given in the following line, and those of the destination cell are given in the next line. Rows and columns are numbered 0 to h-1, 0 to w-1, respectively.
Input terminates when h = w = 0.
Output
For each dataset, output the least penalty.
Example
Input
1 2
8 8
0 0
0 1
3 3
1 2 5
2 8 3
0 1 2
0 0
2 2
3 3
1 2 5
2 8 3
0 1 2
0 0
1 2
2 2
1 2
3 4
0 0
0 1
2 3
1 2 3
4 5 6
0 0
1 2
0 0
Output
24
19
17
6
21
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya is having a party soon, and he has decided to invite his $n$ friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with $k$ sheets. That is, each notebook contains $k$ sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all $n$ of his friends.
-----Input-----
The first line contains two integers $n$ and $k$ ($1\leq n, k\leq 10^8$)Β β the number of Petya's friends and the number of sheets in each notebook respectively.
-----Output-----
Print one numberΒ β the minimum number of notebooks that Petya needs to buy.
-----Examples-----
Input
3 5
Output
10
Input
15 6
Output
38
-----Note-----
In the first example, we need $2$ red notebooks, $3$ green notebooks, and $5$ blue notebooks.
In the second example, we need $5$ red notebooks, $13$ green notebooks, and $20$ blue notebooks.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Your program fails again. This time it gets "Wrong answer on test 233".
This is the harder version of the problem. In this version, $1 \le n \le 2\cdot10^5$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
The problem is to finish $n$ one-choice-questions. Each of the questions contains $k$ options, and only one of them is correct. The answer to the $i$-th question is $h_{i}$, and if your answer of the question $i$ is $h_{i}$, you earn $1$ point, otherwise, you earn $0$ points for this question. The values $h_1, h_2, \dots, h_n$ are known to you in this problem.
However, you have a mistake in your program. It moves the answer clockwise! Consider all the $n$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.
Formally, the mistake moves the answer for the question $i$ to the question $i \bmod n + 1$. So it moves the answer for the question $1$ to question $2$, the answer for the question $2$ to the question $3$, ..., the answer for the question $n$ to the question $1$.
We call all the $n$ answers together an answer suit. There are $k^n$ possible answer suits in total.
You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $1$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $998\,244\,353$.
For example, if $n = 5$, and your answer suit is $a=[1,2,3,4,5]$, it will submitted as $a'=[5,1,2,3,4]$ because of a mistake. If the correct answer suit is $h=[5,2,2,3,4]$, the answer suit $a$ earns $1$ point and the answer suite $a'$ earns $4$ points. Since $4 > 1$, the answer suit $a=[1,2,3,4,5]$ should be counted.
-----Input-----
The first line contains two integers $n$, $k$ ($1 \le n \le 2\cdot10^5$, $1 \le k \le 10^9$)Β β the number of questions and the number of possible answers to each question.
The following line contains $n$ integers $h_1, h_2, \dots, h_n$, ($1 \le h_{i} \le k)$Β β answers to the questions.
-----Output-----
Output one integer: the number of answers suits satisfying the given condition, modulo $998\,244\,353$.
-----Examples-----
Input
3 3
1 3 1
Output
9
Input
5 5
1 1 4 2 2
Output
1000
Input
6 2
1 1 2 2 1 1
Output
16
-----Note-----
For the first example, valid answer suits are $[2,1,1], [2,1,2], [2,1,3], [3,1,1], [3,1,2], [3,1,3], [3,2,1], [3,2,2], [3,2,3]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bad news came to Mike's village, some thieves stole a bunch of chocolates from the local factory! Horrible!
Aside from loving sweet things, thieves from this area are known to be very greedy. So after a thief takes his number of chocolates for himself, the next thief will take exactly k times more than the previous one. The value of k (k > 1) is a secret integer known only to them. It is also known that each thief's bag can carry at most n chocolates (if they intend to take more, the deal is cancelled) and that there were exactly four thieves involved.
Sadly, only the thieves know the value of n, but rumours say that the numbers of ways they could have taken the chocolates (for a fixed n, but not fixed k) is m. Two ways are considered different if one of the thieves (they should be numbered in the order they take chocolates) took different number of chocolates in them.
Mike want to track the thieves down, so he wants to know what their bags are and value of n will help him in that. Please find the smallest possible value of n or tell him that the rumors are false and there is no such n.
-----Input-----
The single line of input contains the integer m (1 β€ m β€ 10^15)Β β the number of ways the thieves might steal the chocolates, as rumours say.
-----Output-----
Print the only integer nΒ β the maximum amount of chocolates that thieves' bags can carry. If there are more than one n satisfying the rumors, print the smallest one.
If there is no such n for a false-rumoured m, print - 1.
-----Examples-----
Input
1
Output
8
Input
8
Output
54
Input
10
Output
-1
-----Note-----
In the first sample case the smallest n that leads to exactly one way of stealing chocolates is n = 8, whereas the amounts of stealed chocolates are (1, 2, 4, 8) (the number of chocolates stolen by each of the thieves).
In the second sample case the smallest n that leads to exactly 8 ways is n = 54 with the possibilities: (1, 2, 4, 8), β(1, 3, 9, 27), β(2, 4, 8, 16), β(2, 6, 18, 54), β(3, 6, 12, 24), β(4, 8, 16, 32), β(5, 10, 20, 40), β(6, 12, 24, 48).
There is no n leading to exactly 10 ways of stealing chocolates in the third sample case.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ of length $n$. The array is called 3SUM-closed if for all distinct indices $i$, $j$, $k$, the sum $a_i + a_j + a_k$ is an element of the array. More formally, $a$ is 3SUM-closed if for all integers $1 \leq i < j < k \leq n$, there exists some integer $1 \leq l \leq n$ such that $a_i + a_j + a_k = a_l$.
Determine if $a$ is 3SUM-closed.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 1000$) β the number of test cases.
The first line of each test case contains an integer $n$ ($3 \leq n \leq 2 \cdot 10^5$) β the length of the array.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \leq a_i \leq 10^9$) β the elements of the array.
It is guaranteed that the sum of $n$ across all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output "YES" (without quotes) if $a$ is 3SUM-closed and "NO" (without quotes) otherwise.
You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).
-----Examples-----
Input
4
3
-1 0 1
5
1 -2 -2 1 -3
6
0 0 0 0 0 0
4
-1 2 -3 4
Output
YES
NO
YES
NO
-----Note-----
In the first test case, there is only one triple where $i=1$, $j=2$, $k=3$. In this case, $a_1 + a_2 + a_3 = 0$, which is an element of the array ($a_2 = 0$), so the array is 3SUM-closed.
In the second test case, $a_1 + a_4 + a_5 = -1$, which is not an element of the array. Therefore, the array is not 3SUM-closed.
In the third test case, $a_i + a_j + a_k = 0$ for all distinct $i$, $j$, $k$, and $0$ is an element of the array, so the array is 3SUM-closed.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 throw a ball vertically upwards with an initial speed `v (in km per hour)`. The height `h` of the ball at each time `t`
is given by `h = v*t - 0.5*g*t*t` where `g` is Earth's gravity `(g ~ 9.81 m/s**2)`. A device is recording at every **tenth
of second** the height of the ball.
For example with `v = 15 km/h` the device gets something of the following form:
`(0, 0.0), (1, 0.367...), (2, 0.637...), (3, 0.808...), (4, 0.881..) ...`
where the first number is the time in tenth of second and the second number the height in meter.
# Task
Write a function `max_ball` with parameter `v (in km per hour)` that returns the `time in tenth of second`
of the maximum height recorded by the device.
# Examples:
`max_ball(15) should return 4`
`max_ball(25) should return 7`
# Notes
- Remember to convert the velocity from km/h to m/s or from m/s in km/h when necessary.
- The maximum height recorded by the device is not necessarily the maximum height reached by the ball.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Nauuo is a girl who loves playing cards.
One day she was playing cards but found that the cards were mixed with some empty ones.
There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n cards in the pile are also given in the order from top to bottom.
In one operation she can choose a card in her hands and play it β put it at the bottom of the pile, then draw the top card from the pile.
Nauuo wants to make the n numbered cards piled up in increasing order (the i-th card in the pile from top to bottom is the card i) as quickly as possible. Can you tell her the minimum number of operations?
Input
The first line contains a single integer n (1β€ nβ€ 2β
10^5) β the number of numbered cards.
The second line contains n integers a_1,a_2,β¦,a_n (0β€ a_iβ€ n) β the initial cards in Nauuo's hands. 0 represents an empty card.
The third line contains n integers b_1,b_2,β¦,b_n (0β€ b_iβ€ n) β the initial cards in the pile, given in order from top to bottom. 0 represents an empty card.
It is guaranteed that each number from 1 to n appears exactly once, either in a_{1..n} or b_{1..n}.
Output
The output contains a single integer β the minimum number of operations to make the n numbered cards piled up in increasing order.
Examples
Input
3
0 2 0
3 0 1
Output
2
Input
3
0 2 0
1 0 3
Output
4
Input
11
0 0 0 5 0 0 0 4 0 0 11
9 2 6 0 8 1 7 0 3 0 10
Output
18
Note
Example 1
We can play the card 2 and draw the card 3 in the first operation. After that, we have [0,3,0] in hands and the cards in the pile are [0,1,2] from top to bottom.
Then, we play the card 3 in the second operation. The cards in the pile are [1,2,3], in which the cards are piled up in increasing order.
Example 2
Play an empty card and draw the card 1, then play 1, 2, 3 in order.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has N integers. Among them, the smallest is A, and the largest is B. We are interested in the sum of those N integers. How many different possible sums there are?
Constraints
* 1 β€ N,A,B β€ 10^9
* A and B are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the number of the different possible sums.
Examples
Input
4 4 6
Output
5
Input
5 4 3
Output
0
Input
1 7 10
Output
0
Input
1 3 3
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As we know, DZY loves playing games. One day DZY decided to play with a n Γ m matrix. To be more precise, he decided to modify the matrix with exactly k operations.
Each modification is one of the following:
1. Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing.
2. Pick some column of the matrix and decrease each element of the column by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing.
DZY wants to know: what is the largest total value of pleasure he could get after performing exactly k modifications? Please, help him to calculate this value.
Input
The first line contains four space-separated integers n, m, k and p (1 β€ n, m β€ 103; 1 β€ k β€ 106; 1 β€ p β€ 100).
Then n lines follow. Each of them contains m integers representing aij (1 β€ aij β€ 103) β the elements of the current row of the matrix.
Output
Output a single integer β the maximum possible total pleasure value DZY could get.
Examples
Input
2 2 2 2
1 3
2 4
Output
11
Input
2 2 5 2
1 3
2 4
Output
11
Note
For the first sample test, we can modify: column 2, row 2. After that the matrix becomes:
1 1
0 0
For the second sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:
-3 -3
-2 -2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polo, the Penguin, likes numbers. He says that the goodness of a number is itself multiplied by the number of digits in it's decimal representation. For example, the goodness of the integer 474 is 474*3 = 1422.
Help him to count the sum of goodness of all integers from L to R, inclusive. Since the answer can be too large, output it modulo 1,000,000,007 (10^9+7).
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains the pair of integers L and R, separated by a single space.
-----Output-----
For each test case, output a single line containing the answer to the corresponding test case.
-----Constraints-----
- 1 β€ T β€ 1,000
- 1 β€ L β€ R β€ 1,000,000,000 (10^9)
-----Example-----
Input:
1
9 12
Output:
75
-----Explanation-----
Example case 1. The answer is 9*1 + 10*2 + 11*2 + 12*2 = 75.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ people sitting in a circle, numbered from $1$ to $n$ in the order in which they are seated. That is, for all $i$ from $1$ to $n-1$, the people with id $i$ and $i+1$ are adjacent. People with id $n$ and $1$ are adjacent as well.
The person with id $1$ initially has a ball. He picks a positive integer $k$ at most $n$, and passes the ball to his $k$-th neighbour in the direction of increasing ids, that person passes the ball to his $k$-th neighbour in the same direction, and so on until the person with the id $1$ gets the ball back. When he gets it back, people do not pass the ball any more.
For instance, if $n = 6$ and $k = 4$, the ball is passed in order $[1, 5, 3, 1]$.
Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $1 + 5 + 3 = 9$.
Find and report the set of possible fun values for all choices of positive integer $k$. It can be shown that under the constraints of the problem, the ball always gets back to the $1$-st player after finitely many steps, and there are no more than $10^5$ possible fun values for given $n$.
-----Input-----
The only line consists of a single integer $n$Β ($2 \leq n \leq 10^9$)Β β the number of people playing with the ball.
-----Output-----
Suppose the set of all fun values is $f_1, f_2, \dots, f_m$.
Output a single line containing $m$ space separated integers $f_1$ through $f_m$ in increasing order.
-----Examples-----
Input
6
Output
1 5 9 21
Input
16
Output
1 10 28 64 136
-----Note-----
In the first sample, we've already shown that picking $k = 4$ yields fun value $9$, as does $k = 2$. Picking $k = 6$ results in fun value of $1$. For $k = 3$ we get fun value $5$ and with $k = 1$ or $k = 5$ we get $21$. [Image]
In the second sample, the values $1$, $10$, $28$, $64$ and $136$ are achieved for instance for $k = 16$, $8$, $4$, $10$ and $11$, respectively.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Tanya decided to present her dad a postcard on his Birthday. She has already created a message β string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
-----Input-----
The first line contains line s (1 β€ |s| β€ 2Β·10^5), consisting of uppercase and lowercase English letters β the text of Tanya's message.
The second line contains line t (|s| β€ |t| β€ 2Β·10^5), consisting of uppercase and lowercase English letters β the text written in the newspaper.
Here |a| means the length of the string a.
-----Output-----
Print two integers separated by a space: the first number is the number of times Tanya shouts "YAY!" while making the message, the second number is the number of times Tanya says "WHOOPS" while making the message.
-----Examples-----
Input
AbC
DCbA
Output
3 0
Input
ABC
abc
Output
0 3
Input
abacaba
AbaCaBA
Output
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.
This is related to my other Kata about cats and dogs.
# Kata Task
I have a cat and a dog which I got as kitten / puppy.
I forget when that was, but I do know their current ages as `catYears` and `dogYears`.
Find how long I have owned each of my pets and return as a list [`ownedCat`, `ownedDog`]
NOTES:
* Results are truncated whole numbers of "human" years
## Cat Years
* `15` cat years for first year
* `+9` cat years for second year
* `+4` cat years for each year after that
## Dog Years
* `15` dog years for first year
* `+9` dog years for second year
* `+5` dog years for each year after that
**References**
* http://www.catster.com/cats-101/calculate-cat-age-in-cat-years
* http://www.slate.com/articles/news_and_politics/explainer/2009/05/a_dogs_life.html
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is Borya's eleventh birthday, and he has got a great present: n cards with numbers. The i-th card has the number a_{i} written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112.
He is only 11, but he already knows that there are n! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112 = 1192 Γ 11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there.
Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways.
Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.
-----Input-----
Input data contains multiple test cases. The first line of the input data contains an integer tΒ β the number of test cases (1 β€ t β€ 100). The descriptions of test cases follow.
Each test is described by two lines.
The first line contains an integer n (1 β€ n β€ 2000)Β β the number of cards in Borya's present.
The second line contains n integers a_{i} (1 β€ a_{i} β€ 10^9)Β β numbers written on the cards.
It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.
-----Output-----
For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.
-----Example-----
Input
4
2
1 1
3
1 31 12
3
12345 67 84
9
1 2 3 4 5 6 7 8 9
Output
2
2
2
31680
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.
The operation of changing a number's sign is the operation of multiplying this number by -1.
Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.
-----Input-----
The first line contains two integers n and k (1 β€ n, k β€ 10^5), showing, how many numbers are in the sequence and how many swaps are to be made.
The second line contains a non-decreasing sequence, consisting of n integers a_{i} (|a_{i}| β€ 10^4).
The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.
-----Output-----
In the single line print the answer to the problem β the maximum total income that we can obtain after exactly k changes.
-----Examples-----
Input
3 2
-1 -1 1
Output
3
Input
3 1
-1 -1 1
Output
1
-----Note-----
In the first sample we can get sequence [1, 1, 1], thus the total income equals 3.
In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 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.
-----Problem Statement-----
Chef studies combinatorics. He tries to group objects by their rang (a positive integer associated with each object). He also gives the formula for calculating the number of different objects with rang N as following:
the number of different objects with rang N = F(N) = A0 + A1 * N + A2 * N2 + A3 * N3.
Now Chef wants to know how many different multisets of these objects exist such that sum of rangs of the objects in the multiset equals to S. You are given the coefficients in F(N) and the target sum S. Please, find the number of different multisets modulo 1,000,000,007.
You should consider a multiset as an unordered sequence of integers. Two multisets are different if and only if there at least exists one element which occurs X times in the first multiset but Y times in the second one, where (X β Y).
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains four integers A0, A1, A2, A3. The second line contains an integer S.
-----Output-----
For each test case, output a single line containing a single integer - the answer to the test case modulo 1,000,000,007.
-----Constraints-----
- 1 β€ T β€ 500
- 1 β€ S β€ 100
- 0 β€ Ai β€ 1000
- Sum of all S for all test cases is not greater than 500. It's guaranteed that at least one Ai is non-zero.
-----Example-----
Input:
4
1 0 0 0
1
1 0 0 0
3
0 1 0 0
2
2 3 1 4
10
Output:
1
3
3
213986343
-----Explanation-----
Example case 2.
In the second example function looks as follows F(N) = 1. So for each rang there is a single object of the rang. To get multiset with sum of rangs equal to 3, you can pick: three objects of rang 1, or one object of rang 1 and one of rang 2, or only one object of rang 3.
Example case 3.
In the third example function looks as follows F(N) = N. So, you have one distinct object of rang 1, two distinct objects of rang 2, three distinct objects of rang 3 and so on. To get
multiset with sum of rangs equal to 2, you can pick: two objects of rang 1, one of objects of rang 2 (two ways).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?
-----Constraints-----
- 1 \leq a \leq 9
- 1 \leq b \leq 9
- a and b are integers.
-----Input-----
Input is given from Standard Input in the following format:
a b
-----Output-----
Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)
-----Sample Input-----
4 3
-----Sample Output-----
3333
We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 TV program called "Saizo" is popular in a certain country. In this program, participants challenge field athletics and get a prize if they successfully capture it.
Field athletics are made by arranging blocks of different heights in a row, and how to climb up and down the steps is important for capture (Fig. 1). Your friend who will be attending this show wants you to write a program that calculates the maximum steps you have to climb and the maximum steps you have to descend given a field athletic structure. I asked you, a great programmer.
Example of athletic structure (first dataset of input example).
---
Figure 1: Example of athletic structure (first dataset of input example).
Input
The number of datasets t (0 <t β€ 100) is given on the first line of the input. This line is followed by t datasets.
The first line of the dataset is the number of blocks that make up the field athletics n (2 β€ n β€ 100). In the second line, n integers indicating the height of the block from the start to the goal are given in order. The first corresponds to the start and the nth corresponds to the goal. These integers are separated by a single space character. The height h of each block satisfies 0 <h β€ 1000.
Output
For each dataset, output the maximum step size you must climb and the maximum step size you must descend on a single line, separated by a single space character. If there is no step to climb or step to descend, the maximum corresponding step size shall be 0.
Example
Input
5
5
10 70 30 50 90
2
20 100
2
100 30
3
50 50 50
7
123 45 678 901 234 567 890
Output
60 40
80 0
0 70
0 0
633 667
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 now 260 AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran.
Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captured by Shapur and Shapur is now going to capture Valerian, the Roman emperor.
Being defeated, the cowardly Valerian hid in a room at the top of one of his castles. To capture him, Shapur has to open many doors. Fortunately Valerian was too scared to make impenetrable locks for the doors.
Each door has 4 parts. The first part is an integer number a. The second part is either an integer number b or some really odd sign which looks like R. The third one is an integer c and the fourth part is empty! As if it was laid for writing something. Being extremely gifted, after opening the first few doors, Shapur found out the secret behind the locks.
c is an integer written in base a, to open the door we should write it in base b. The only bad news is that this R is some sort of special numbering system that is used only in Roman empire, so opening the doors is not just a piece of cake!
Here's an explanation of this really weird number system that even doesn't have zero:
Roman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc.:
* I=1
* V=5
* X=10
* L=50
* C=100
* D=500
* M=1000
Symbols are iterated to produce multiples of the decimal (1, 10, 100, 1, 000) values, with V, L, D substituted for a multiple of five, and the iteration continuing: I 1, II 2, III 3, V 5, VI 6, VII 7, etc., and the same for other bases: X 10, XX 20, XXX 30, L 50, LXXX 80; CC 200, DCC 700, etc. At the fourth and ninth iteration, a subtractive principle must be employed, with the base placed before the higher base: IV 4, IX 9, XL 40, XC 90, CD 400, CM 900.
Also in bases greater than 10 we use A for 10, B for 11, etc.
Help Shapur capture Valerian and bring peace back to Persia, especially Armenia.
Input
The first line contains two integers a and b (2 β€ a, b β€ 25). Only b may be replaced by an R which indicates Roman numbering system.
The next line contains a single non-negative integer c in base a which may contain leading zeros but its length doesn't exceed 103.
It is guaranteed that if we have Roman numerals included the number would be less than or equal to 300010 and it won't be 0. In any other case the number won't be greater than 101510.
Output
Write a single line that contains integer c in base b. You must omit leading zeros.
Examples
Input
10 2
1
Output
1
Input
16 R
5
Output
V
Input
5 R
4
Output
IV
Input
2 2
1111001
Output
1111001
Input
12 13
A
Output
A
Note
You can find more information about roman numerals here: http://en.wikipedia.org/wiki/Roman_numerals
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a board with H horizontal rows and W vertical columns of squares. There is a bishop at the top-left square on this board. How many squares can this bishop reach by zero or more movements?
Here the bishop can only move diagonally. More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:
* r_1 + c_1 = r_2 + c_2
* r_1 - c_1 = r_2 - c_2
For example, in the following figure, the bishop can move to any of the red squares in one move:
<image>
Constraints
* 1 \leq H, W \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
H \ W
Output
Print the number of squares the bishop can reach.
Examples
Input
4 5
Output
10
Input
7 3
Output
11
Input
1000000000 1000000000
Output
500000000000000000
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure.
<image>
For a given chess board where $k$ queens are already placed, find the solution of the 8 queens problem.
Constraints
* There is exactly one solution
Input
In the first line, an integer $k$ is given. In the following $k$ lines, each square where a queen is already placed is given by two integers $r$ and $c$. $r$ and $c$ respectively denotes the row number and the column number. The row/column numbers start with 0.
Output
Print a $8 \times 8$ chess board by strings where a square with a queen is represented by 'Q' and an empty square is represented by '.'.
Example
Input
2
2 2
5 3
Output
......Q.
Q.......
..Q.....
.......Q
.....Q..
...Q....
.Q......
....Q...
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Task
Find the sum of the first `n` elements in the RecamΓ‘n Sequence.
Input range:
```python
1000 tests
0 <= n <= 2,500,000
```
___
## Sequence
The sequence is formed using the next formula:
* We start with `0`
* At each step `i`, we subtract `i` from the previous number
* If the result is not negative, and not yet present in the sequence, it becomes the `i`th element of the sequence
* Otherwise the `i`th element of the sequence will be previous number plus `i`
The beginning of the sequence is `[0, 1, 3, 6, 2, ...]` because:
0) `0` <- we start with `0`
1) `1` <- `0 - 1` is negative, hence we choose `0 + 1`
2) `3` <- `1 - 2` is negative, hence we choose `1 + 2`
3) `6` <-`3 - 3` is not negative, but we already have a `0` in the sequence, hence we choose `3 + 3`
4) `2` <- `6 - 4` is positive, and is not present in the sequence yet, so we go for it
___
## Examples
```
rec(0) == 0
rec(1) == 0
rec(2) == 1
rec(3) == 4
rec(4) == 10
rec(5) == 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.
Snuke has N integers: 1,2,\ldots,N. He will choose K of them and give those to Takahashi.
How many ways are there to choose K consecutive integers?
Constraints
* All values in input are integers.
* 1 \leq K \leq N \leq 50
Input
Input is given from Standard Input in the following format:
N K
Output
Print the answer.
Examples
Input
3 2
Output
2
Input
13 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.
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $M$ with $n$ rows and $n$ columns such that $M_{ij}=a_i \cdot a_j$ where $a_1, \dots, a_n$ is some sequence of positive integers.
Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $a_1, \dots, a_n$. Help Sasha restore the array!
-----Input-----
The first line contains a single integer $n$ ($3 \leqslant n \leqslant 10^3$), the size of the table.
The next $n$ lines contain $n$ integers each. The $j$-th number of the $i$-th line contains the number $M_{ij}$ ($1 \leq M_{ij} \leq 10^9$). The table has zeroes on the main diagonal, that is, $M_{ii}=0$.
-----Output-----
In a single line print $n$ integers, the original array $a_1, \dots, a_n$ ($1 \leq a_i \leq 10^9$). It is guaranteed that an answer exists. If there are multiple answers, print any.
-----Examples-----
Input
5
0 4 6 2 4
4 0 6 2 4
6 6 0 3 6
2 2 3 0 2
4 4 6 2 0
Output
2 2 3 1 2
Input
3
0 99990000 99970002
99990000 0 99980000
99970002 99980000 0
Output
9999 10000 9998
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 program that consists of $n$ instructions. Initially a single variable $x$ is assigned to $0$. Afterwards, the instructions are of two types:
increase $x$ by $1$;
decrease $x$ by $1$.
You are given $m$ queries of the following format:
query $l$ $r$ β how many distinct values is $x$ assigned to if all the instructions between the $l$-th one and the $r$-th one inclusive are ignored and the rest are executed without changing the order?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) β the number of testcases.
Then the description of $t$ testcases follows.
The first line of each testcase contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) β the number of instructions in the program and the number of queries.
The second line of each testcase contains a program β a string of $n$ characters: each character is either '+' or '-' β increment and decrement instruction, respectively.
Each of the next $m$ lines contains two integers $l$ and $r$ ($1 \le l \le r \le n$) β the description of the query.
The sum of $n$ over all testcases doesn't exceed $2 \cdot 10^5$. The sum of $m$ over all testcases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each testcase print $m$ integers β for each query $l$, $r$ print the number of distinct values variable $x$ is assigned to if all the instructions between the $l$-th one and the $r$-th one inclusive are ignored and the rest are executed without changing the order.
-----Examples-----
Input
2
8 4
-+--+--+
1 8
2 8
2 5
1 1
4 10
+-++
1 1
1 2
2 2
1 3
2 3
3 3
1 4
2 4
3 4
4 4
Output
1
2
4
4
3
3
4
2
3
2
1
2
2
2
-----Note-----
The instructions that remain for each query of the first testcase are:
empty program β $x$ was only equal to $0$;
"-" β $x$ had values $0$ and $-1$;
"---+" β $x$ had values $0$, $-1$, $-2$, $-3$, $-2$ β there are $4$ distinct values among them;
"+--+--+" β the distinct values are $1$, $0$, $-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.
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.
In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.
Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?
Input
The first line contains a single integer n (1 β€ n β€ 105) β the number of patterns. Next n lines contain the patterns.
It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.
Output
In a single line print the answer to the problem β the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.
Examples
Input
2
?ab
??b
Output
xab
Input
2
a
b
Output
?
Input
1
?a?b
Output
cacb
Note
Consider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1^{n} + 2^{n} + 3^{n} + 4^{n})Β modΒ 5
for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).
-----Input-----
The single line contains a single integer n (0 β€ n β€ 10^10^5). The number doesn't contain any leading zeroes.
-----Output-----
Print the value of the expression without leading zeros.
-----Examples-----
Input
4
Output
4
Input
124356983594583453458888889
Output
0
-----Note-----
Operation xΒ modΒ y means taking remainder after division x by y.
Note to the first 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.
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:
You have an array $a$ consisting of $n$ positive integers. An operation consists of choosing an element and either adding $1$ to it or subtracting $1$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $1$. Find the minimum number of operations needed to make the array good.
Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!
-----Input-----
The first line contains an integer $n$ ($2 \le n \le 2 \cdot 10^5$) Β β the number of elements in the array.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$. ($1 \le a_i \le 10^{12}$) Β β the elements of the array.
-----Output-----
Print a single integer Β β the minimum number of operations required to make the array good.
-----Examples-----
Input
3
6 2 4
Output
0
Input
5
9 8 7 3 1
Output
4
-----Note-----
In the first example, the first array is already good, since the greatest common divisor of all the elements is $2$.
In the second example, we may apply the following operations:
Add $1$ to the second element, making it equal to $9$. Subtract $1$ from the third element, making it equal to $6$. Add $1$ to the fifth element, making it equal to $2$. Add $1$ to the fifth element again, making it equal to $3$.
The greatest common divisor of all elements will then be equal to $3$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i.
For example, a multiset of strings {"abc", "aba", "adc", "ada"} are not easy to remember. And multiset {"abc", "ada", "ssa"} is easy to remember because: the first string is the only string that has character c in position 3; the second string is the only string that has character d in position 2; the third string is the only string that has character s in position 2.
You want to change your multiset a little so that it is easy to remember. For a_{ij} coins, you can change character in the j-th position of the i-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember.
-----Input-----
The first line contains two integers n, m (1 β€ n, m β€ 20)Β β the number of strings in the multiset and the length of the strings respectively. Next n lines contain the strings of the multiset, consisting only of lowercase English letters, each string's length is m.
Next n lines contain m integers each, the i-th of them contains integers a_{i}1, a_{i}2, ..., a_{im} (0 β€ a_{ij} β€ 10^6).
-----Output-----
Print a single number β the answer to the problem.
-----Examples-----
Input
4 5
abcde
abcde
abcde
abcde
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
3
Input
4 3
abc
aba
adc
ada
10 10 10
10 1 10
10 10 10
10 1 10
Output
2
Input
3 3
abc
ada
ssa
1 1 1
1 1 1
1 1 1
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.
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.
There are $n$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $i$-th position. Thus each of $n$ positions should contain exactly one flower: a rose or a lily.
She knows that exactly $m$ people will visit this exhibition. The $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.
Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.
-----Input-----
The first line contains two integers $n$ and $m$ ($1\leq n, m\leq 10^3$)Β β the number of flowers and visitors respectively.
Each of the next $m$ lines contains two integers $l_i$ and $r_i$ ($1\leq l_i\leq r_i\leq n$), meaning that $i$-th visitor will visit all flowers from $l_i$ to $r_i$ inclusive.
-----Output-----
Print the string of $n$ characters. The $i$-th symbol should be Β«0Β» if you want to put a rose in the $i$-th position, otherwise Β«1Β» if you want to put a lily.
If there are multiple answers, print any.
-----Examples-----
Input
5 3
1 3
2 4
2 5
Output
01100
Input
6 3
5 6
1 4
4 6
Output
110010
-----Note-----
In the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions;
in the segment $[1\ldots3]$, there are one rose and two lilies, so the beauty is equal to $1\cdot 2=2$; in the segment $[2\ldots4]$, there are one rose and two lilies, so the beauty is equal to $1\cdot 2=2$; in the segment $[2\ldots5]$, there are two roses and two lilies, so the beauty is equal to $2\cdot 2=4$.
The total beauty is equal to $2+2+4=8$.
In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions;
in the segment $[5\ldots6]$, there are one rose and one lily, so the beauty is equal to $1\cdot 1=1$; in the segment $[1\ldots4]$, there are two roses and two lilies, so the beauty is equal to $2\cdot 2=4$; in the segment $[4\ldots6]$, there are two roses and one lily, so the beauty is equal to $2\cdot 1=2$.
The total beauty is equal to $1+4+2=7$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!
Input
The input file consists of three lines. The first line contains string t. The second and the third lines contain the sbegin and send identificators, correspondingly. All three lines are non-empty strings consisting of lowercase Latin letters. The length of each string doesn't exceed 2000 characters.
Output
Output the only number β the amount of different substrings of t that start with sbegin and end with send.
Examples
Input
round
ro
ou
Output
1
Input
codeforces
code
forca
Output
0
Input
abababab
a
b
Output
4
Input
aba
ab
ba
Output
1
Note
In the third sample there are four appropriate different substrings. They are: ab, abab, ababab, abababab.
In the fourth sample identificators intersect.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m Γ m of this matrix contains at least one zero.
Consider the following problem:
You are given two integers n and m. You have to construct an m-free square matrix of size n Γ n such that the number of 1's in this matrix is maximum possible. Print the maximum possible number of 1's in such matrix.
You don't have to solve this problem. Instead, you have to construct a few tests for it.
You will be given t numbers x_1, x_2, ..., x_{t}. For every $i \in [ 1, t ]$, find two integers n_{i} and m_{i} (n_{i} β₯ m_{i}) such that the answer for the aforementioned problem is exactly x_{i} if we set n = n_{i} and m = m_{i}.
-----Input-----
The first line contains one integer t (1 β€ t β€ 100) β the number of tests you have to construct.
Then t lines follow, i-th line containing one integer x_{i} (0 β€ x_{i} β€ 10^9).
Note that in hacks you have to set t = 1.
-----Output-----
For each test you have to construct, output two positive numbers n_{i} and m_{i} (1 β€ m_{i} β€ n_{i} β€ 10^9) such that the maximum number of 1's in a m_{i}-free n_{i} Γ n_{i} matrix is exactly x_{i}. If there are multiple solutions, you may output any of them; and if this is impossible to construct a test, output a single integer - 1.
-----Example-----
Input
3
21
0
1
Output
5 2
1 1
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Aizuwakamatsu City, there is a first city called "Tokaichi" on January 10th every year. This Tokaichi has a history of about 600 years and is the largest first city in the Aizu region. It is also well known that Okiagari-koboshi, a familiar lucky charm, is sold in the Aizu region. Okiagari-koboshi is a papier-mΓ’chΓ© with a center of gravity of about 3 cm in size, and it got up immediately after rolling, so it got its name. At each household, be sure to buy one more than your family and offer it to the Kamidana. This one has the meaning of "to increase the number of families" and "to carry troubles".
| <image>
--- | ---
The Tokaichi Executive Committee has decided to investigate the stores that have the highest number of Okiagari-koboshi sold for the next Tokaichi. The number of stores opened this year is 5 (A, B, C, D, E: half-width alphabetic characters), and the number of units sold is reported to the Tokaichi Executive Committee in the morning and afternoon.
Enter the information of each store and create a program that outputs the name of the store with the highest number of units sold per day and the number of stores.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
s1A s2A
s1B s2B
s1C s2C
s1D s2D
s1E s2E
Line i is given the morning sales quantity s1i and the afternoon sales quantity s2i (1 β€ s1i, s2i β€ 10000) for A, B, C, D, and E, respectively. However, it is assumed that no store has the same number of units sold per day.
The number of datasets does not exceed 100.
Output
For each dataset, the name of the store with the highest sales volume per day and the number of stores are output on one line.
Example
Input
1593 4311
4321 2155
1256 6421
5310 1455
2152 5421
1549 3386
4528 3719
1234 4321
3330 3109
2739 2199
0 0
Output
C 7677
B 8247
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya wants to climb up a stair of certain amount of steps (Input parameter 1). There are 2 simple rules that he has to stick to.
1. Vasya can climb 1 or 2 steps at each move.
2. Vasya wants the number of moves to be a multiple of a certain integer. (Input parameter 2).
### Task:
What is the `MINIMAL` number of moves making him climb to the top of the stairs that satisfies his conditions?
### Input
1. Number of stairs: `0 < N β€ 10000` ;
2. Integer to be multiplied : `1 < M β€ 10 `;
### Output
1. Return a single integer - the minimal number of moves being a multiple of M;
2. If there is no way he can climb satisfying condition returnβ-β1 instead. (`Nothing` in Haskell)
### Examples
```python
numberOfSteps(10, 2) => 6 # Sequence of steps : {2, 2, 2, 2, 1, 1}
numberOfSteps(3, 5) => -1 # !Possible sequences of steps : {2, 1}, {1, 2}, {1, 1, 1}
```
``` haskell
numberOfSteps 10 2 == Just 6 -- Sequence of steps : {2, 2, 2, 2, 1, 1}
numberOfSteps 3 5 == Nothing -- Not possible, since the sequences of steps would be {2, 1}, {1, 2} or {1, 1, 1}
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.
Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then β zero or more lowercase letters.
To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.
Input
The only line of the input contains a non-empty string consisting of uppercase and lowercase letters. The string's length does not exceed 105.
Output
Print a single number β the least number of actions needed to make the message fancy.
Examples
Input
PRuvetSTAaYA
Output
5
Input
OYPROSTIYAOPECHATALSYAPRIVETSTASYA
Output
0
Input
helloworld
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N people (with different names) and K clubs. For each club you know the list of members (so you have K unordered lists). Each person can be a member of many clubs (and also 0 clubs) and two different clubs might have exactly the same members. The value of the number K is the minimum possible such that the following property can be true for at least one configuration of clubs. If every person changes her name (maintaining the property that all names are different) and you know the new K lists of members of the clubs (but you don't know which list corresponds to which club), you are sure that you would be able to match the old names with the new ones.
Count the number of such configurations of clubs (or say that there are more than 1000). Two configurations of clubs that can be obtained one from the other if the N people change their names are considered equal.
Formal statement: A club is a (possibly empty) subset of \\{1,\dots, N\\} (the subset identifies the members, assuming that the people are indexed by the numbers 1, 2,\dots, N). A configuration of clubs is an unordered collection of K clubs (not necessarily distinct). Given a permutation \sigma(1), \dots, \sigma(N) of \\{1,\dots, N\\} and a configuration of clubs L=\\{C_1, C_2, \dots, C_K\\}, we denote with \sigma(L) the configuration of clubs \\{\sigma(C_1), \sigma(C_2), \dots, \sigma(C_K)\\} (if C is a club, \sigma(C)=\\{\sigma(x):\, x\in C\\}). A configuration of clubs L is name-preserving if for any pair of distinct permutations \sigma\not=\tau, it holds \sigma(L)\not=\tau(L).
You have to count the number of name-preserving configurations of clubs with the minimum possible number of clubs (so K is minimum). Two configurations L_1, L_2 such that L_2=\sigma(L_1) (for some permutation \sigma) are considered equal. If there are more than 1000 such configurations, print -1.
Constraints
* 2 \le N \le 2\cdot10^{18}
Input
The input is given from Standard Input in the format
N
Output
If ans is the number of configurations with the properties described in the statement, you should print on Standard Output
ans
If there are more than 1000 such configurations, print -1.
Examples
Input
2
Output
1
Input
3
Output
1
Input
4
Output
7
Input
13
Output
6
Input
26
Output
-1
Input
123456789123456789
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.
Mike received an array $a$ of length $n$ as a birthday present and decided to test how pretty it is.
An array would pass the $i$-th prettiness test if there is a way to get an array with a sum of elements totaling $s_i$, using some number (possibly zero) of slicing operations.
An array slicing operation is conducted in the following way:
assume $mid = \lfloor\frac{max(array) + min(array)}{2}\rfloor$, where $max$ and $min$ β are functions that find the maximum and the minimum array elements. In other words, $mid$ is the sum of the maximum and the minimum element of $array$ divided by $2$ rounded down.
Then the array is split into two parts $\mathit{left}$ and $right$. The $\mathit{left}$ array contains all elements which are less than or equal $mid$, and the $right$ array contains all elements which are greater than $mid$. Elements in $\mathit{left}$ and $right$ keep their relative order from $array$.
During the third step we choose which of the $\mathit{left}$ and $right$ arrays we want to keep. The chosen array replaces the current one and the other is permanently discarded.
You need to help Mike find out the results of $q$ prettiness tests.
Note that you test the prettiness of the array $a$, so you start each prettiness test with the primordial (initial) array $a$. Thus, the first slice (if required) is always performed on the array $a$.
-----Input-----
Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$).
The first line of each test case contains two integers $n$ and $q$ $(1 \le n, q \le 10^5)$ β the length of the array $a$ and the total number of prettiness tests.
The second line of each test case contains $n$ integers $a_1, a_2, ..., a_n$ $(1 \le a_i \le 10^6)$ β the contents of the array $a$.
Next $q$ lines of each test case contain a single integer $s_i$ $(1 \le s_i \le 10^9)$ β the sum of elements which Mike wants to get in the $i$-th test.
It is guaranteed that the sum of $n$ and the sum of $q$ does not exceed $10^5$ ($\sum n, \sum q \le 10^5$).
-----Output-----
Print $q$ lines, each containing either a "Yes" if the corresponding prettiness test is passed and "No" in the opposite case.
-----Examples-----
Input
2
5 5
1 2 3 4 5
1
8
9
12
6
5 5
3 1 3 1 3
1
2
3
9
11
Output
Yes
No
Yes
No
Yes
No
Yes
No
Yes
Yes
-----Note-----
Explanation of the first test case:
We can get an array with the sum $s_1 = 1$ in the following way:
1.1 $a = [1, 2, 3, 4, 5]$, $mid = \frac{1+5}{2} = 3$, $\mathit{left} = [1, 2, 3]$, $right = [4, 5]$. We choose to keep the $\mathit{left}$ array.
1.2 $a = [1, 2, 3]$, $mid = \frac{1+3}{2} = 2$, $\mathit{left} = [1, 2]$, $right = [3]$. We choose to keep the $\mathit{left}$ array.
1.3 $a = [1, 2]$, $mid = \frac{1+2}{2} = 1$, $\mathit{left} = [1]$, $right = [2]$. We choose to keep the $\mathit{left}$ array with the sum equalling $1$.
It can be demonstrated that an array with the sum $s_2 = 8$ is impossible to generate.
An array with the sum $s_3 = 9$ can be generated in the following way:
3.1 $a = [1, 2, 3, 4, 5]$, $mid = \frac{1+5}{2} = 3$, $\mathit{left} = [1, 2, 3]$, $right = [4, 5]$. We choose to keep the $right$ array with the sum equalling $9$.
It can be demonstrated that an array with the sum $s_4 = 12$ is impossible to generate.
We can get an array with the sum $s_5 = 6$ in the following way:
5.1 $a = [1, 2, 3, 4, 5]$, $mid = \frac{1+5}{2} = 3$, $\mathit{left} = [1, 2, 3]$, $right = [4, 5]$. We choose to keep the $\mathit{left}$ with the sum equalling $6$.
Explanation of the second test case:
It can be demonstrated that an array with the sum $s_1 = 1$ is imposssible to generate.
We can get an array with the sum $s_2 = 2$ in the following way:
2.1 $a = [3, 1, 3, 1, 3]$, $mid = \frac{1+3}{2} = 2$, $\mathit{left} = [1, 1]$, $right = [3, 3, 3]$. We choose to keep the $\mathit{left}$ array with the sum equalling $2$.
It can be demonstrated that an array with the sum $s_3 = 3$ is imposssible to generate.
We can get an array with the sum $s_4 = 9$ in the following way:
4.1 $a = [3, 1, 3, 1, 3]$, $mid = \frac{1+3}{2} = 2$, $\mathit{left} = [1, 1]$, $right = [3, 3, 3]$. We choose to keep the $right$ array with the sum equalling $9$.
We can get an array with the sum $s_5 = 11$ with zero slicing operations, because array sum is equal to $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.
Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge.
Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division.
* Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds.
Constraints
* 2 \leq N \leq 200
* S_{i,j} is `0` or `1`.
* S_{i,i} is `0`.
* S_{i,j}=S_{j,i}
* The given graph is connected.
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
S_{1,1}...S_{1,N}
:
S_{N,1}...S_{N,N}
Output
If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition.
Examples
Input
2
01
10
Output
2
Input
3
011
101
110
Output
-1
Input
6
010110
101001
010100
101000
100000
010000
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.
You like playing chess tournaments online.
In your last tournament you played $n$ games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get $0$ points. When you win you get $1$ or $2$ points: if you have won also the previous game you get $2$ points, otherwise you get $1$ point. If you win the very first game of the tournament you get $1$ point (since there is not a "previous game").
The outcomes of the $n$ games are represented by a string $s$ of length $n$: the $i$-th character of $s$ is W if you have won the $i$-th game, while it is L if you have lost the $i$-th game.
After the tournament, you notice a bug on the website that allows you to change the outcome of at most $k$ of your games (meaning that at most $k$ times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.
Compute the maximum score you can get by cheating in the optimal way.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1\le t \le 20,000$) β the number of test cases. The description of the test cases follows.
The first line of each testcase contains two integers $n, k$ ($1\le n\le 100,000$, $0\le k\le n$) β the number of games played and the number of outcomes that you can change.
The second line contains a string $s$ of length $n$ containing only the characters W and L. If you have won the $i$-th game then $s_i=\,$W, if you have lost the $i$-th game then $s_i=\,$L.
It is guaranteed that the sum of $n$ over all testcases does not exceed $200,000$.
-----Output-----
For each testcase, print a single integer β the maximum score you can get by cheating in the optimal way.
-----Example-----
Input
8
5 2
WLWLL
6 5
LLLWWL
7 1
LWLWLWL
15 5
WWWLLLWWWLLLWWW
40 7
LLWLWLWWWLWLLWLWWWLWLLWLLWLLLLWLLWWWLWWL
1 0
L
1 1
L
6 1
WLLWLW
Output
7
11
6
26
46
0
1
6
-----Note-----
Explanation of the first testcase. Before changing any outcome, the score is $2$. Indeed, you won the first game, so you got $1$ point, and you won also the third, so you got another $1$ point (and not $2$ because you lost the second game).
An optimal way to cheat is to change the outcomes of the second and fourth game. Doing so, you end up winning the first four games (the string of the outcomes becomes WWWWL). Hence, the new score is $7=1+2+2+2$: $1$ point for the first game and $2$ points for the second, third and fourth game.
Explanation of the second testcase. Before changing any outcome, the score is $3$. Indeed, you won the fourth game, so you got $1$ point, and you won also the fifth game, so you got $2$ more points (since you won also the previous game).
An optimal way to cheat is to change the outcomes of the first, second, third and sixth game. Doing so, you end up winning all games (the string of the outcomes becomes WWWWWW). Hence, the new score is $11 = 1+2+2+2+2+2$: $1$ point for the first game and $2$ points for all the other games.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to a_{i} inclusive. No tickets are sold at the last station.
Let Ο_{i}, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values Ο_{i}, j among all pairs 1 β€ i < j β€ n.
-----Input-----
The first line of the input contains a single integer n (2 β€ n β€ 100 000)Β β the number of stations.
The second line contains n - 1 integer a_{i} (i + 1 β€ a_{i} β€ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to a_{i} inclusive.
-----Output-----
Print the sum of Ο_{i}, j among all pairs of 1 β€ i < j β€ n.
-----Examples-----
Input
4
4 4 4
Output
6
Input
5
2 3 5 5
Output
17
-----Note-----
In the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.
Consider the second sample: Ο_{1, 2} = 1 Ο_{1, 3} = 2 Ο_{1, 4} = 3 Ο_{1, 5} = 3 Ο_{2, 3} = 1 Ο_{2, 4} = 2 Ο_{2, 5} = 2 Ο_{3, 4} = 1 Ο_{3, 5} = 1 Ο_{4, 5} = 1
Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 many years of research, Ikta has acquired the ability to predict the future! The time and money he spent on this research was enormous, but it's finally time to be rewarded. To get the money back, Ikta decided to start investing in stocks.
Ikta does not currently own any shares, but owns x yen. He has invested in n stocks, and has succeeded in predicting the stock price for d days from today. As a result, it was surprisingly found that there was no intraday stock price fluctuation for d days from today. In other words, we know the stock price pi, j yen of the stock j (1 β€ j β€ n) on the i (1 β€ i β€ d) day when today is the first day. Ikta is free to buy and sell stocks each day. That is, the following operations (purchase / sale) can be performed at any time in any order and any number of times. However, the amount of money held and the number of units held of shares before and after each operation must be non-negative integers.
* Purchase: On day i, select one stock type j (1 β€ j β€ n) and pay pi, j yen in possession to obtain 1 unit of stock j.
* Sale: On day i, select one stock type j (1 β€ j β€ n) and pay 1 unit of stock j to get pi, j yen.
(While he was absorbed in his research, the securities trading system made great progress and there were no transaction fees.)
Ikta had studied information science at university, but had forgotten everything he had learned at university before he could devote himself to future prediction research. Instead of him, write a program that maximizes your money on the final day.
Input
The input is given in the following format.
n d x
p1,1 ... p1, n
...
pd, 1 ... pd, n
* n: Number of stock types
* d: days
* x: Money on the first day
* pi, j: Stock price of stock j on day i (today is the first day)
Constraints
Each variable being input is an integer that satisfies the following constraints.
* 1 β€ n β€ 10
* 1 β€ d β€ 10
* 1 β€ x, pi, j β€ 105
* It is guaranteed that the amount of money you have on the last day will be 105 or less.
Output
Output the last day's money in one line when you invest optimally.
Examples
Input
2 2 5
3 2
5 4
Output
9
Input
1 2 5
6
10000
Output
5
Input
2 3 5
4 5
6 3
8 5
Output
11
Input
3 3 10
10 9 6
8 7 3
7 5 1
Output
10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.
There is a very powerful system of pointers on &K* β you can add an asterisk to the right of the existing type X β that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite β to any type of X, which is a pointer, you can add an ampersand β that will result in a type &X, to which refers X. That is called a dereference operation.
The &K* language has only two basic data types β void and errtype. Also, the language has operators typedef and typeof.
* The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
* The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.
An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.
Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.
Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T * is always equal to T.
Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).
Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.
All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.
Output
For every typeof operator print on the single line the answer to that operator β the type that the given operator returned.
Examples
Input
5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv
Output
void*
errtype
void
Input
17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c
Output
void*
void**
void
void**
errtype
void
errtype
errtype
errtype
Note
Let's look at the second sample.
After the first two queries typedef the b type is equivalent to void*, and Ρ β to void**.
The next query typedef redefines b β it is now equal to &b = &void* = void. At that, the Ρ type doesn't change.
After that the Ρ type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.
Then the b type is again redefined as &void = errtype.
Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:
AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.
-----Constraints-----
- All input values are integers.
- 1β€Wβ€10^5
- 1β€a,bβ€10^5
-----Input-----
The input is given from Standard Input in the following format:
W a b
-----Output-----
Print the minimum distance the second rectangle needs to be moved.
-----Sample Input-----
3 2 6
-----Sample Output-----
1
This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 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.
Adam Ivan is working as a system administrator at Soy Group, Inc. He is now facing at a big trouble: a number of computers under his management have been infected by a computer virus. Unfortunately, anti-virus system in his company failed to detect this virus because it was very new.
Adam has identified the first computer infected by the virus and collected the records of all data packets sent within his network. He is now trying to identify which computers have been infected. A computer is infected when receiving any data packet from any infected computer. The computer is not infected, on the other hand, just by sending data packets to infected computers.
It seems almost impossible for him to list all infected computers by hand, because the size of the packet records is fairly large. So he asked you for help: write a program that can identify infected computers.
Input
The input consists of multiple datasets. Each dataset has the following format:
N M
t1 s1 d1
t2 s2 d2
...
tM sM dM
N is the number of computers; M is the number of data packets; ti (1 β€ i β€ M) is the time when the i-th data packet is sent; si and di (1 β€ i β€ M) are the source and destination computers of the i-th data packet respectively. The first infected computer is indicated by the number 1; the other computers are indicated by unique numbers between 2 and N.
The input meets the following constraints: 0 < N β€ 20000, 0 β€ M β€ 20000, and 0 β€ ti β€ 109 for 1 β€ i β€ N; all ti 's are different; and the source and destination of each packet are always different.
The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed.
Output
For each dataset, print the number of computers infected by the computer virus.
Example
Input
3 2
1 1 2
2 2 3
3 2
2 3 2
1 2 1
0 0
Output
3
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.