question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
# Definition
A **number** is called **_Automorphic number_** if and only if *its square ends in the same digits as the number itself*.
___
# Task
**_Given_** a **number** *determine if it Automorphic or not* .
___
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* The **_number_** passed to the function is **_positive_**
* **_Single-digit_** numbers are considered **_Automorphic number_**.
___
# Input >> Output Examples
```
autoMorphic (25) -->> return "Automorphic"
```
## **_Explanation_**:
* `25` squared is `625` , **_Ends with the same number's digits which are 25_** .
___
```
autoMorphic (13) -->> return "Not!!"
```
## **_Explanation_**:
* `13` squared is `169` , **_Not ending with the same number's digits which are 69_** .
___
```
autoMorphic (76) -->> return "Automorphic"
```
## **_Explanation_**:
* `76` squared is `5776` , **_Ends with the same number's digits which are 76_** .
___
```
autoMorphic (225) -->> return "Not!!"
```
## **_Explanation_**:
* `225` squared is `50625` , **_Not ending with the same number's digits which are 225_** .
___
```
autoMorphic (625) -->> return "Automorphic"
```
## **_Explanation_**:
* `625` squared is `390625` , **_Ends with the same number's digits which are 625_** .
___
```
autoMorphic (1) -->> return "Automorphic"
```
## **_Explanation_**:
* `1` squared is `1` , **_Ends with the same number's digits which are 1_** .
___
```
autoMorphic (6) -->> return "Automorphic"
```
## **_Explanation_**:
* `6` squared is `36` , **_Ends with the same number's digits which are 6_**
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Write your solution by modifying this code:
```python
def automorphic(n):
```
Your solution should implemented in the function "automorphic". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 pizza store wants to know how long each order will take. They know:
- Prepping a pizza takes 3 mins
- Cook a pizza takes 10 mins
- Every salad takes 3 mins to make
- Every appetizer takes 5 mins to make
- There are 2 pizza ovens
- 5 pizzas can fit in a oven
- Prepping for a pizza must be done before it can be put in the oven
- There are two pizza chefs and one chef for appitizers and salads combined
- The two pizza chefs can work on the same pizza
Write a function, order, which will tell the company how much time the order will take.
See example tests for details.
Write your solution by modifying this code:
```python
def order(pizzas, salads, appetizers):
```
Your solution should implemented in the function "order". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) и 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "ВSCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again.
Polycarpus has n_{b} pieces of bread, n_{s} pieces of sausage and n_{c} pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are p_{b} rubles for a piece of bread, p_{s} for a piece of sausage and p_{c} for a piece of cheese.
Polycarpus has r rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.
-----Input-----
The first line of the input contains a non-empty string that describes the recipe of "Le Hamburger de Polycarpus". The length of the string doesn't exceed 100, the string contains only letters 'B' (uppercase English B), 'S' (uppercase English S) and 'C' (uppercase English C).
The second line contains three integers n_{b}, n_{s}, n_{c} (1 ≤ n_{b}, n_{s}, n_{c} ≤ 100) — the number of the pieces of bread, sausage and cheese on Polycarpus' kitchen. The third line contains three integers p_{b}, p_{s}, p_{c} (1 ≤ p_{b}, p_{s}, p_{c} ≤ 100) — the price of one piece of bread, sausage and cheese in the shop. Finally, the fourth line contains integer r (1 ≤ r ≤ 10^12) — the number of rubles Polycarpus has.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print the maximum number of hamburgers Polycarpus can make. If he can't make any hamburger, print 0.
-----Examples-----
Input
BBBSSC
6 4 1
1 2 3
4
Output
2
Input
BBC
1 10 1
1 10 1
21
Output
7
Input
BSC
1 1 1
1 1 3
1000000000000
Output
200000000001
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$. Each character is either 0 or 1.
You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.
You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.
Then $t$ lines follow, each representing a test case. Each line contains one string $s$ ($1 \le |s| \le 100$); each character of $s$ is either 0 or 1.
-----Output-----
Print $t$ integers, where the $i$-th integer is the answer to the $i$-th testcase (the minimum number of 0's that you have to erase from $s$).
-----Example-----
Input
3
010011
0
1111000
Output
2
0
0
-----Note-----
In the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Complete the function that calculates the derivative of a polynomial. A polynomial is an expression like: 3x^(4) - 2x^(2) + x - 10
### How to calculate the derivative:
* Take the exponent and multiply it with the coefficient
* Reduce the exponent by 1
For example: 3x^(4) --> (4*3)x^((4-1)) = 12x^(3)
### Good to know:
* The derivative of a constant is 0 (e.g. 100 --> 0)
* Anything to the 0th exponent equals 1 (e.g. x^(0) = 1)
* The derivative of the sum of two function is the sum of the derivatives
Notes:
* The exponentiation is marked with "^"
* Exponents are always integers and >= 0
* Exponents are written only if > 1
* There are no spaces around the operators
* Leading "+" signs are omitted
See the examples below.
## Examples
```python
derivative("-100") = "0"
derivative("4x+1") = "4" # = 4x^0 + 0
derivative("-x^2+3x+4") = "-2x+3" # = -2x^1 + 3x^0 + 0
```
Write your solution by modifying this code:
```python
def derivative(eq):
```
Your solution should implemented in the function "derivative". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 telephone number is a sequence of exactly $11$ digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string $s$ of length $n$ ($n$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $s$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.
You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).
-----Input-----
The first line contains one integer $n$ ($13 \le n < 10^5$, $n$ is odd) — the length of string $s$.
The second line contains the string $s$ ($|s| = n$) consisting only of decimal digits.
-----Output-----
If Vasya has a strategy that guarantees him victory, print YES.
Otherwise print NO.
-----Examples-----
Input
13
8380011223344
Output
YES
Input
15
807345619350641
Output
NO
-----Note-----
In the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.
In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is data that records the customer number of the business partner and the trading date on a monthly basis. Please create a program that reads this month's data and last month's data and outputs the customer number of the company with which you have transactions and the number of transactions for two consecutive months from last month. However, the number of monthly business partners is 1,000 or less.
Input
This month's data and last month's data are given separated by one blank line. Each data is given in the following format.
c1, d1
c2, d2
...
...
ci (1 ≤ ci ≤ 1,000) is an integer representing the customer number, and di (1 ≤ di ≤ 31) is an integer representing the trading day.
Output
For companies that have transactions for two consecutive months, the customer number and the total number of transactions are output separated by a blank in ascending order of customer number.
Example
Input
123,10
56,12
34,14
123,3
56,4
123,5
Output
56 2
123 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.
Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S zero or more times:
* Remove the two characters at the beginning of S, erase one of them, and reinsert the other somewhere in S. This operation can be applied only when S has two or more characters.
Constraints
* 1 \leq |S| \leq 300
* S consists of `0` and `1`.
Input
Input is given from Standard Input in the following format:
S
Output
Print the number of strings, modulo 998244353, that can result from applying the operation on S zero or more times.
Examples
Input
0001
Output
8
Input
110001
Output
24
Input
11101111011111000000000110000001111100011111000000001111111110000000111111111
Output
697354558
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.
A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.
When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.
At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.
In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10^5
- 1 \leq K \leq 10^9
- 1 \leq Q \leq 10^5
- 1 \leq A_i \leq N\ (1 \leq i \leq Q)
-----Input-----
Input is given from Standard Input in the following format:
N K Q
A_1
A_2
.
.
.
A_Q
-----Output-----
Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.
-----Sample Input-----
6 3 4
3
1
3
2
-----Sample Output-----
No
No
Yes
No
No
No
In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).
- Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).
- Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).
- Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).
- Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).
Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 small town the population is `p0 = 1000` at the beginning of a year. The population
regularly increases by `2 percent` per year and moreover `50` new inhabitants per year
come to live in the town.
How many years does the town need to see its population
greater or equal to `p = 1200` inhabitants?
```
At the end of the first year there will be:
1000 + 1000 * 0.02 + 50 => 1070 inhabitants
At the end of the 2nd year there will be:
1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)
At the end of the 3rd year there will be:
1141 + 1141 * 0.02 + 50 => 1213
It will need 3 entire years.
```
More generally given parameters:
`p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass)`
the function `nb_year` should return `n` number of entire years needed to
get a population greater or equal to `p`.
aug is an integer, percent a positive or null number, p0 and p are positive integers (> 0)
```
Examples:
nb_year(1500, 5, 100, 5000) -> 15
nb_year(1500000, 2.5, 10000, 2000000) -> 10
```
Note: Don't forget to convert the percent parameter as a percentage in the body of your function: if the parameter percent is 2 you have to convert it to 0.02.
Write your solution by modifying this code:
```python
def nb_year(p0, percent, aug, p):
```
Your solution should implemented in the function "nb_year". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Salve, mi amice.
Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus.
Rp:
I Aqua Fortis
I Aqua Regia
II Amalgama
VII Minium
IV Vitriol
Misce in vitro et æstus, et nil admirari. Festina lente, et nulla tenaci invia est via.
Fac et spera,
Vale,
Nicolas Flamel
-----Input-----
The first line of input contains several space-separated integers a_{i} (0 ≤ a_{i} ≤ 100).
-----Output-----
Print a single integer.
-----Examples-----
Input
2 4 6 8 10
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.
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that
1. 1 ≤ i, j ≤ N
2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
Input
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
Output
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
Examples
Input
great10
Output
7
Input
aaaaaaaaaa
Output
100
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a binary string $s$.
Find the number of distinct cyclical binary strings of length $n$ which contain $s$ as a substring.
The cyclical string $t$ contains $s$ as a substring if there is some cyclical shift of string $t$, such that $s$ is a substring of this cyclical shift of $t$.
For example, the cyclical string "000111" contains substrings "001", "01110" and "10", but doesn't contain "0110" and "10110".
Two cyclical strings are called different if they differ from each other as strings. For example, two different strings, which differ from each other by a cyclical shift, are still considered different cyclical strings.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 40$) — the length of the target string $t$.
The next line contains the string $s$ ($1 \le |s| \le n$) — the string which must be a substring of cyclical string $t$. String $s$ contains only characters '0' and '1'.
-----Output-----
Print the only integer — the number of distinct cyclical binary strings $t$, which contain $s$ as a substring.
-----Examples-----
Input
2
0
Output
3
Input
4
1010
Output
2
Input
20
10101010101010
Output
962
-----Note-----
In the first example, there are three cyclical strings, which contain "0" — "00", "01" and "10".
In the second example, there are only two such strings — "1010", "0101".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 University of Aizu has a park covered with grass, and there are no trees or buildings that block the sunlight. On sunny summer days, sprinklers installed in the park operate to sprinkle water on the lawn. The frog Pyonkichi lives in this park. Pyonkichi is not good at hot weather, and on summer days when the sun is strong, he will dry out and die if he is not exposed to the water of the sprinkler. The sprinklers installed in the park are supposed to sprinkle only one sprinkler at a time to save water, so Pyonkichi must move according to the operation of the sprinklers.
<image>
---
(a) Map of the park
<image> | <image>
--- | ---
(b) Pyonkichi's jump range | (c) Sprinkler watering range
The park is as shown in (a) of the above figure, the location in the park is represented by the coordinates 0 to 9 in each of the vertical and horizontal directions, and the black ● is the sprinkler, which indicates the order in which the numbers operate. This is just an example, and the location and order of operation of each sprinkler changes daily.
Pyonkichi is clumsy, so he can only jump a certain distance to move. Pyonkichi's jumpable range is as shown in (b) above, and he cannot move to any other location. Moreover, one jump consumes a lot of physical strength, so you have to rest in the water for a while.
The range in which the sprinkler can sprinkle water is as shown in the above figure (c), including the coordinates of the sprinkler itself. Each sprinkler will stop after a period of watering, and the next sprinkler will start working immediately. Pyonkichi shall jump only once at this time, and shall not jump until the next watering stops. Also, since the park is surrounded on all sides by scorching asphalt, it is assumed that you will not jump in a direction that would cause you to go out of the park.
This summer was extremely hot. Was Pyonkichi able to survive? One day, read the initial position of Pyonkichi, the position of the sprinkler and the operation order, and if there is a movement path that Pyonkichi can survive, "OK", how? If you die even if you do your best, create a program that outputs "NA". However, the maximum number of sprinklers is 10, and Pyonkichi will jump from the initial position at the same time as the first sprinkler is activated.
Input
Given multiple datasets. Each dataset is given in the following format:
px py
n
x1 y1 x2 y2 ... xn yn
The first line gives the abscissa px and ordinate py of the initial position of Pyonkichi. The second line gives the number of sprinklers n. The third line gives the abscissa xi and the ordinate yi of the sprinkler that operates third.
The input ends with two zero lines. The number of datasets does not exceed 20.
Output
For each dataset, print OK if it is alive, or NA on one line otherwise.
Example
Input
6 1
10
6 4 3 3 1 2 0 5 4 6 1 8 5 9 7 7 8 6 8 3
6 1
10
6 4 3 3 1 2 0 5 4 6 1 8 5 9 7 7 8 6 9 0
0 0
Output
OK
NA
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An array is defined to be `odd-heavy` if it contains at least one odd element and every element whose value is `odd` is greater than
every even-valued element.
eg.
```
Array [11,4,9,2,8] is odd-heavy
because:- its odd elements [11,9] are greater than all the even elements [4,2,8]
Array [11,4,9,2,3,10] is not odd-heavy
because:- one of it's even element 10 from [4,2,10] is greater than two of its odd elements [9,3] from [ 11,9,3]
```
write a function called `isOddHeavy` or `is_odd_heavy` that accepts an integer array and returns `true` if the array is `odd-heavy` else return `false`.
Write your solution by modifying this code:
```python
def is_odd_heavy(arr):
```
Your solution should implemented in the function "is_odd_heavy". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $a$ and $b$. It is known that $|b| \leq |a|$, that is, the length of $b$ is at most the length of $a$.
The Cossack considers every substring of length $|b|$ in string $a$. Let's call this substring $c$. He matches the corresponding characters in $b$ and $c$, after which he counts the number of positions where the two strings are different. We call this function $f(b, c)$.
For example, let $b = 00110$, and $c = 11000$. In these strings, the first, second, third and fourth positions are different.
Vus the Cossack counts the number of such substrings $c$ such that $f(b, c)$ is even.
For example, let $a = 01100010$ and $b = 00110$. $a$ has four substrings of the length $|b|$: $01100$, $11000$, $10001$, $00010$. $f(00110, 01100) = 2$; $f(00110, 11000) = 4$; $f(00110, 10001) = 4$; $f(00110, 00010) = 1$.
Since in three substrings, $f(b, c)$ is even, the answer is $3$.
Vus can not find the answer for big strings. That is why he is asking you to help him.
-----Input-----
The first line contains a binary string $a$ ($1 \leq |a| \leq 10^6$) — the first string.
The second line contains a binary string $b$ ($1 \leq |b| \leq |a|$) — the second string.
-----Output-----
Print one number — the answer.
-----Examples-----
Input
01100010
00110
Output
3
Input
1010111110
0110
Output
4
-----Note-----
The first example is explained in the legend.
In the second example, there are five substrings that satisfy us: $1010$, $0101$, $1111$, $1111$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are a total of A + B cats and dogs.
Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs.
Determine if it is possible that there are exactly X cats among these A + B animals.
-----Constraints-----
- 1 \leq A \leq 100
- 1 \leq B \leq 100
- 1 \leq X \leq 200
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
A B X
-----Output-----
If it is possible that there are exactly X cats, print YES; if it is impossible, print NO.
-----Sample Input-----
3 5 4
-----Sample Output-----
YES
If there are one cat and four dogs among the B = 5 animals, there are X = 4 cats in total.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin.
For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors.
Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.
-----Input-----
First line of input consists of one integer n (1 ≤ n ≤ 3000).
Next line consists of n integers a_{i} (1 ≤ a_{i} ≤ n), which stand for coolness factor of each badge.
-----Output-----
Output single integer — minimum amount of coins the colonel has to pay.
-----Examples-----
Input
4
1 3 1 4
Output
1
Input
5
1 2 3 2 5
Output
2
-----Note-----
In first sample test we can increase factor of first badge by 1.
In second sample test we can increase factors of the second and the third badge by 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.
Water Country Water Deven has n cities. Each city is surrounded by water and looks like an island country. Water Deven has m bridges, and transportation between cities is carried out by these bridges, which allows you to travel to and from all cities.
Recently, it was decided to reduce the maintenance cost of the bridge by reviewing the road specific financial resources. I couldn't maintain all the bridges and had to demolish some of them. Therefore, the challenge for Water Deven was to minimize the cost of maintaining the bridge while leaving the bridge so that it could reach any city.
Create a program that inputs the number of cities, the number of bridges, and the maintenance cost of each bridge, so that you can go to any city using the bridge, and outputs the minimum value of the maintenance cost when the bridge is demolished. Please give me. There is no cost to demolish the bridge. However, each city shall be numbered sequentially from 0 to n-1.
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:
n m
a1 b1 cost1
a2 b2 cost2
::
am bm costm
The first line gives the number of cities n (2 ≤ n ≤ 100) and the number of bridges m (1 ≤ m ≤ 500). The following m lines give information about the i-th bridge. ai and bi are the numbers of the cities to which the bridge is connected, and costi (1 ≤ costi ≤ 1000) is the maintenance cost of the bridge.
Output
The total bridge maintenance cost is output to one line for each data set.
Example
Input
5 6
0 2 1
2 1 3
2 3 8
1 3 2
3 4 5
1 4 4
3 3
1 2 3
2 0 3
0 1 3
0 0
Output
10
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.
The problem set at CODE FESTIVAL 20XX Finals consists of N problems.
The score allocated to the i-th (1≦i≦N) problem is i points.
Takahashi, a contestant, is trying to score exactly N points. For that, he is deciding which problems to solve.
As problems with higher scores are harder, he wants to minimize the highest score of a problem among the ones solved by him.
Determine the set of problems that should be solved.
Constraints
* 1≦N≦10^7
Input
The input is given from Standard Input in the following format:
N
Output
Among the sets of problems with the total score of N, find a set in which the highest score of a problem is minimum, then print the indices of the problems in the set in any order, one per line.
If there exists more than one such set, any of them will be accepted.
Examples
Input
4
Output
1
3
Input
7
Output
1
2
4
Input
1
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You've made it through the moat and up the steps of knowledge. You've won the temples games and now you're hunting for treasure in the final temple run. There's good news and bad news. You've found the treasure but you've triggered a nasty trap. You'll surely perish in the temple chamber.
With your last movements, you've decided to draw an "X" marks the spot for the next archeologist.
Given an odd number, n, draw an X for the next crew. Follow the example below.
`
`
If n = 1 return 'X\n' and if you're given an even number or invalid input, return '?'.
The output should be a string with no spaces after the final X on each line, but a \n to indicate a new line.
Check out my other 80's Kids Katas:
80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5: You Can't Do That on Television
80's Kids #6: Rock 'Em, Sock 'Em Robots
80's Kids #7: She's a Small Wonder
80's Kids #8: The Secret World of Alex Mack
80's Kids #9: Down in Fraggle Rock
80's Kids #10: Captain Planet
Write your solution by modifying this code:
```python
def mark_spot(n):
```
Your solution should implemented in the function "mark_spot". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata, you have to define a function named **func** that will take a list as input.
You must try and guess the pattern how we get the output number and return list - **[output number,binary representation,octal representation,hexadecimal representation]**, but **you must convert that specific number without built-in : bin,oct and hex functions.**
Examples :
```python
func([12,13,6,3,6,45,123]) returns - [29,'11101','35','1d']
func([1,9,23,43,65,31,63,99]) returns - [41,'101001','51','29']
func([2,4,6,8,10,12,14,16,18,19]) returns - [10,'1010','12','a']
```
Write your solution by modifying this code:
```python
def func(l):
```
Your solution should implemented in the function "func". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to x_{i} coins.
Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent m_{i} coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of shops in the city that sell Vasiliy's favourite drink.
The second line contains n integers x_{i} (1 ≤ x_{i} ≤ 100 000) — prices of the bottles of the drink in the i-th shop.
The third line contains a single integer q (1 ≤ q ≤ 100 000) — the number of days Vasiliy plans to buy the drink.
Then follow q lines each containing one integer m_{i} (1 ≤ m_{i} ≤ 10^9) — the number of coins Vasiliy can spent on the i-th day.
-----Output-----
Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.
-----Example-----
Input
5
3 10 8 6 11
4
1
10
3
11
Output
0
4
1
5
-----Note-----
On the first day, Vasiliy won't be able to buy a drink in any of the shops.
On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.
On the third day, Vasiliy can buy a drink only in the shop number 1.
Finally, on the last day Vasiliy can buy a drink in any shop.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 JOI Railways is the only railway company in the Kingdom of JOI. There are $N$ stations numbered from $1$ to $N$ along a railway. Currently, two kinds of trains are operated; one is express and the other one is local.
A local train stops at every station. For each $i$ ($1 \leq i < N$), by a local train, it takes $A$ minutes from the station $i$ to the station ($i + 1$).
An express train stops only at the stations $S_1, S_2, ..., S_M$ ($1 = S_1 < S_2 < ... < S_M = N$). For each $i$ ($1 \leq i < N$), by an express train, it takes $B$ minutes from the station $i$ to the station ($i + 1$).
The JOI Railways plans to operate another kind of trains called "semiexpress." For each $i$ ($1 \leq i < N$), by a semiexpress train, it takes $C$ minutes from the station $i$ to the station ($i + 1$). The stops of semiexpress trains are not yet determined. But they must satisfy the following conditions:
* Semiexpress trains must stop at every station where express trains stop.
* Semiexpress trains must stop at $K$ stations exactly.
The JOI Railways wants to maximize the number of stations (except for the station 1) to which we can travel from the station 1 within $T$ minutes. The JOI Railways plans to determine the stops of semiexpress trains so that this number is maximized. We do not count the standing time of trains.
When we travel from the station 1 to another station, we can take trains only to the direction where the numbers of stations increase. If several kinds of trains stop at the station $i$ ($2 \leq i \leq N - 1$), you can transfer between any trains which stop at that station.
When the stops of semiexpress trains are determined appropriately, what is the maximum number of stations (except for the station 1) to which we can travel from the station 1 within $T$ minutes?
Task
Given the number of stations of the JOI Railways, the stops of express trains, the speeds of the trains, and maximum travel time, write a program which calculates the maximum number of stations which satisfy the condition on the travel time.
Input
Read the following data from the standard input.
* The first line of input contains three space separated integers $N$, $M$, $K$. This means there are $N$ stations of the JOI Railways, an express train stops at $M$ stations, and a semiexpress train stops at $K$ stations,
* The second line of input contains three space separated integers $A$, $B$, $C$. This means it takes $A$, $B$, $C$ minutes by a local, express, semiexpress train to travel from a station to the next station, respectively.
>li> The third line of input contains an integer $T$. This means the JOI Railways wants to maximize the number of stations (except for the station 1) to which we can travel from the station 1 within $T$ minutes.
* The $i$-th line ($1 \leq i \leq M$) of the following $M$ lines contains an integer $S_i$. This means an express train stops at the station $S_i$.
Output
Write one line to the standard output. The output contains the maximum number of stations satisfying the condition on the travel time.
Constraints
All input data satisfy the following conditions.
* $2 \leq N \leq 1 000 000 000.$
* $2 \leq M \leq K \leq 3 000.$
* $K \leq N.$
* $1 \leq B < C < A \leq 1 000 000 000.$
* $1 \leq T \leq 10^{18}$
* $1 = S_1 < S_2 < ... < S_M = N$
Sample Input and Output
Sample Input 1
10 3 5
10 3 5
30
1
6
10
Sample Output 1
8
In this sample input, there are 10 stations of the JOI Railways. An express train stops at three stations 1, 6, 10. Assume that the stops of an semiexpress train are 1, 5, 6, 8, 10. Then, among the stations 2, 3, ...10, we can travel from the station 1 to every station except for the station 9 within 30 minutes.
For some $i$, the travel time and the route from the station 1 to the station $i$ are as follows:
* From the station 1 to the station 3, we can travel using a local train only. The travel time is 20 minutes.
* From the station 1 to the station 7, we travel from the station 1 to the station 6 by an express train, and transfer to a local train. The travel time is 25 minutes.
* From the station 1 to the station 8, we travel from the station 1 to the station 6 by an express train, and transfer to a semiexpress train. The travel time is 25 minutes.
* From the station 1 to the station 9, we travel from the station 1 to the station 6 by an express train, from the station 6 to the station 8 by a semiexpress train, and from the station 8 to the station 9 by a local train. In total, the travel time is 35 minutes.
Sample Input 2
10 3 5
10 3 5
25
1
6
10
Sample Output 2
7
Sample Input 3
90 10 12
100000 1000 10000
10000
1
10
20
30
40
50
60
70
80
90
Sample Output 2
2
Sample Input 4
12 3 4
10 1 2
30
1
11
12
Sample Output 4
8
Sample Input 5
300 8 16
345678901 123456789 234567890
12345678901
1
10
77
82
137
210
297
300
Sample Output 5
72
Sample Input 6
1000000000 2 3000
1000000000 1 2
1000000000
1
1000000000
Sample Output 6
3000
Creative Commonse License
The 16th Japanese Olympiad in Informatics (JOI 2016/2017) Final Round
Example
Input
10 3 5
10 3 5
30
1
6
10
Output
8
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Nikolay got a string $s$ of even length $n$, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from $1$ to $n$.
He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.
The prefix of string $s$ of length $l$ ($1 \le l \le n$) is a string $s[1..l]$.
For example, for the string $s=$"abba" there are two prefixes of the even length. The first is $s[1\dots2]=$"ab" and the second $s[1\dots4]=$"abba". Both of them have the same number of 'a' and 'b'.
Your task is to calculate the minimum number of operations Nikolay has to perform with the string $s$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.
-----Input-----
The first line of the input contains one even integer $n$ $(2 \le n \le 2\cdot10^{5})$ — the length of string $s$.
The second line of the input contains the string $s$ of length $n$, which consists only of lowercase Latin letters 'a' and 'b'.
-----Output-----
In the first line print the minimum number of operations Nikolay has to perform with the string $s$ to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.
In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them.
-----Examples-----
Input
4
bbbb
Output
2
abba
Input
6
ababab
Output
0
ababab
Input
2
aa
Output
1
ba
-----Note-----
In the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'.
In the second example Nikolay doesn't need to do anything because each prefix of an even length of the initial string already contains an equal amount of letters 'a' and 'b'.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ students and $m$ clubs in a college. The clubs are numbered from $1$ to $m$. Each student has a potential $p_i$ and is a member of the club with index $c_i$. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next $d$ days. There is a coding competition every day in the technical fest.
Every day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming $d$ days. Thus, every day the director chooses such team, that the team strength is maximized.
The mex of the multiset $S$ is the smallest non-negative integer that is not present in $S$. For example, the mex of the $\{0, 1, 1, 2, 4, 5, 9\}$ is $3$, the mex of $\{1, 2, 3\}$ is $0$ and the mex of $\varnothing$ (empty set) is $0$.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \leq m \leq n \leq 5000$), the number of students and the number of clubs in college.
The second line contains $n$ integers $p_1, p_2, \ldots, p_n$ ($0 \leq p_i < 5000$), where $p_i$ is the potential of the $i$-th student.
The third line contains $n$ integers $c_1, c_2, \ldots, c_n$ ($1 \leq c_i \leq m$), which means that $i$-th student is initially a member of the club with index $c_i$.
The fourth line contains an integer $d$ ($1 \leq d \leq n$), number of days for which the director wants to know the maximum possible strength of the team.
Each of the next $d$ lines contains an integer $k_i$ ($1 \leq k_i \leq n$), which means that $k_i$-th student lefts their club on the $i$-th day. It is guaranteed, that the $k_i$-th student has not left their club earlier.
-----Output-----
For each of the $d$ days, print the maximum possible strength of the team on that day.
-----Examples-----
Input
5 3
0 1 2 2 0
1 2 2 3 2
5
3
2
4
5
1
Output
3
1
1
1
0
Input
5 3
0 1 2 2 1
1 3 2 3 2
5
4
2
3
5
1
Output
3
2
2
1
0
Input
5 5
0 1 2 4 5
1 2 3 4 5
4
2
3
5
4
Output
1
1
1
1
-----Note-----
Consider the first example:
On the first day, student $3$ leaves their club. Now, the remaining students are $1$, $2$, $4$ and $5$. We can select students $1$, $2$ and $4$ to get maximum possible strength, which is $3$. Note, that we can't select students $1$, $2$ and $5$, as students $2$ and $5$ belong to the same club. Also, we can't select students $1$, $3$ and $4$, since student $3$ has left their club.
On the second day, student $2$ leaves their club. Now, the remaining students are $1$, $4$ and $5$. We can select students $1$, $4$ and $5$ to get maximum possible strength, which is $1$.
On the third day, the remaining students are $1$ and $5$. We can select students $1$ and $5$ to get maximum possible strength, which is $1$.
On the fourth day, the remaining student is $1$. We can select student $1$ to get maximum possible strength, which is $1$.
On the fifth day, no club has students and so the maximum possible strength 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.
# Task
You know the slogan `p`, which the agitators have been chanting for quite a while now. Roka has heard this slogan a few times, but he missed almost all of them and grasped only their endings. You know the string `r` that Roka has heard.
You need to determine what is the `minimal number` of times agitators repeated the slogan `p`, such that Roka could hear `r`.
It is guaranteed the Roka heard nothing but the endings of the slogan P repeated several times.
# Example
For `p = "glorytoukraine", r = "ukraineaineaine"`, the output should be `3`.
The slogan was `"glorytoukraine"`, and Roka heard `"ukraineaineaine"`.
He could hear it as follows: `"ukraine"` + `"aine"` + `"aine"` = `"ukraineaineaine"`.
# Input/Output
- `[input]` string `p`
The slogan the agitators chanted, a string of lowecase Latin letters.
- `[input]` string `r`
The string of lowercase Latin letters Roka has heard.
- `[output]` an integer
The `minimum number` of times the agitators chanted.
Write your solution by modifying this code:
```python
def slogans(p,r):
```
Your solution should implemented in the function "slogans". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.
## Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (`*`) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (`\n`).
Return `null/nil/None/...` if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.
## Examples
A size 3 diamond:
```
*
***
*
```
...which would appear as a string of `" *\n***\n *\n"`
A size 5 diamond:
```
*
***
*****
***
*
```
...that is: `" *\n ***\n*****\n ***\n *\n"`
Write your solution by modifying this code:
```python
def diamond(n):
```
Your solution should implemented in the function "diamond". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 [Ones' Complement](https://en.wikipedia.org/wiki/Ones%27_complement) of a binary number is the number obtained by swapping all the 0s for 1s and all the 1s for 0s. For example:
```
onesComplement(1001) = 0110
onesComplement(1001) = 0110
```
For any given binary number,formatted as a string, return the Ones' Complement of that number.
Write your solution by modifying this code:
```python
def ones_complement(binary_number):
```
Your solution should implemented in the function "ones_complement". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ann and Borya have n piles with candies and n is even number. There are a_{i} candies in pile with number i.
Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile).
Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.
-----Input-----
First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies.
Second line contains sequence of integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — amounts of candies in each pile.
-----Output-----
Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.
-----Examples-----
Input
4
12 14 30 4
Output
2
Input
6
0 0 0 0 0 0
Output
6
Input
6
120 110 23 34 25 45
Output
3
Input
10
121 56 78 81 45 100 1 0 54 78
Output
0
-----Note-----
In first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).
In second example you should add two candies to any three piles.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 system is transmitting messages in binary, however it is not a perfect transmission, and sometimes errors will occur which result in a single bit flipping from 0 to 1, or from 1 to 0.
To resolve this, A 2-dimensional Parity Bit Code is used: https://en.wikipedia.org/wiki/Multidimensional_parity-check_code
In this system, a message is arrayed out on a M x N grid. A 24-bit message could be put on a 4x6 grid like so:
>1 0 1 0 0 1
>1 0 0 1 0 0
>0 1 1 1 0 1
>1 0 0 0 0 1
Then, Parity bits are computed for each row and for each column, equal to 1 if there is an odd number of 1s in the row of column, and 0 if it is an even number. The result for the above message looks like:
>1 0 1 0 0 1 1
>1 0 0 1 0 0 0
>0 1 1 1 0 1 0
>1 0 0 0 0 1 0
>1 1 0 0 0 1
Since the 1st row, and 1st, 2nd and 6th column each have an odd number of 1s in them, and the others all do not.
Then the whole message is sent, including the parity bits. This is arranged as:
> message + row_parities + column_parities
> 101001100100011101100001 + 1000 + 110001
> 1010011001000111011000011000110001
If an error occurs in transmission, the parity bit for a column and row will be incorrect, which can be used to identify and correct the error. If a row parity bit is incorrect, but all column bits are correct, then we can assume the row parity bit was the one flipped, and likewise if a column is wrong but all rows are correct.
Your Task:
Create a function correct, which takes in integers M and N, and a string of bits where the first M\*N represent the content of the message, the next M represent the parity bits for the rows, and the final N represent the parity bits for the columns. A single-bit error may or may not have appeared in the bit array.
The function should check to see if there is a single-bit error in the coded message, correct it if it exists, and return the corrected string of bits.
Write your solution by modifying this code:
```python
def correct(m, n, bits):
```
Your solution should implemented in the function "correct". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two non-empty strings $s$ and $t$, consisting of Latin letters.
In one move, you can choose an occurrence of the string $t$ in the string $s$ and replace it with dots.
Your task is to remove all occurrences of the string $t$ in the string $s$ in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.
Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string $t$ in $s$ begin differ. For example, the sets $\{1, 2, 3\}$ and $\{1, 2, 4\}$ are considered different, the sets $\{2, 4, 6\}$ and $\{2, 6\}$ — too, but sets $\{3, 5\}$ and $\{5, 3\}$ — not.
For example, let the string $s =$ "abababacababa" and the string $t =$ "aba". We can remove all occurrences of the string $t$ in $2$ moves by cutting out the occurrences of the string $t$ at the $3$th and $9$th positions. In this case, the string $s$ is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string $t$ at the $3$th and $11$th positions. There are two different sequences of minimum length moves.
Since the answer can be large, output it modulo $10^9 + 7$.
-----Input-----
The first line of the input contains a single integer $q$ ($1 \le q \le 50$) — the number of test cases. The descriptions of the sets follow.
The first line of each set contains a non-empty string $s$ ($1 \le |s| \le 500$) consisting of lowercase Latin letters.
The second line of each set contains a non-empty string $t$ ($1 \le |t| \le 500$) consisting of lowercase Latin letters.
It is guaranteed that the sum of string lengths $s$ over all test cases does not exceed $500$. Similarly, it is guaranteed that the sum of string lengths $t$ over all test cases does not exceed $500$.
-----Output-----
For each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo $10^9 + 7$.
-----Examples-----
Input
8
abababacababa
aba
ddddddd
dddd
xyzxyz
xyz
abc
abcd
abacaba
abaca
abc
def
aaaaaaaa
a
aaaaaaaa
aa
Output
2 2
1 4
2 1
0 1
1 1
0 1
8 1
3 6
-----Note-----
The first test case is explained in the statement.
In the second case, it is enough to cut any of the four occurrences.
In the third case, string $s$ is the concatenation of two strings $t =$ "xyz", so there is a unique optimal sequence of $2$ moves.
In the fourth and sixth cases, the string $s$ initially contains no occurrences of the string $t$.
In the fifth case, the string $s$ contains exactly one occurrence of the string $t$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have had record hot temperatures this summer. To avoid heat stroke, you decided to buy a quantity of drinking water at the nearby supermarket. Two types of bottled water, 1 and 0.5 liter, are on sale at respective prices there. You have a definite quantity in your mind, but are willing to buy a quantity larger than that if: no combination of these bottles meets the quantity, or, the total price becomes lower.
Given the prices for each bottle of water and the total quantity needed, make a program to seek the lowest price to buy greater than or equal to the quantity required.
Input
The input is given in the following format.
$A$ $B$ $X$
The first line provides the prices for a 1-liter bottle $A$ ($1\leq A \leq 1000$), 500-milliliter bottle $B$ ($1 \leq B \leq 1000$), and the total water quantity needed $X$ ($1 \leq X \leq 20000$). All these values are given as integers, and the quantity of water in milliliters.
Output
Output the total price.
Examples
Input
180 100 2400
Output
460
Input
200 90 2018
Output
450
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term):
* expression ::= summand | expression + summand | expression - summand
* summand ::= increment | coefficient*increment
* increment ::= a++ | ++a
* coefficient ::= 0|1|2|...|1000
For example, "5*a++-3*++a+a++" is a valid expression in C*++.
Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.
The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then — multiplied by the coefficient.
The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
Input
The first input line contains an integer a ( - 1000 ≤ a ≤ 1000) — the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output
Output a single number — the maximal possible value of the expression.
Examples
Input
1
5*a++-3*++a+a++
Output
11
Input
3
a+++++a
Output
8
Note
Consider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, 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.
There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct.
You have two types of spells which you may cast: Fireball: you spend $x$ mana and destroy exactly $k$ consecutive warriors; Berserk: you spend $y$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power.
For example, let the powers of warriors be $[2, 3, 7, 8, 11, 5, 4]$, and $k = 3$. If you cast Berserk on warriors with powers $8$ and $11$, the resulting sequence of powers becomes $[2, 3, 7, 11, 5, 4]$. Then, for example, if you cast Fireball on consecutive warriors with powers $[7, 11, 5]$, the resulting sequence of powers becomes $[2, 3, 4]$.
You want to turn the current sequence of warriors powers $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$. Calculate the minimum amount of mana you need to spend on it.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of sequence $a$ and the length of sequence $b$ respectively.
The second line contains three integers $x, k, y$ ($1 \le x, y, \le 10^9; 1 \le k \le n$) — the cost of fireball, the range of fireball and the cost of berserk respectively.
The third line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$). It is guaranteed that all integers $a_i$ are pairwise distinct.
The fourth line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \le b_i \le n$). It is guaranteed that all integers $b_i$ are pairwise distinct.
-----Output-----
Print the minimum amount of mana for turning the sequnce $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$, or $-1$ if it is impossible.
-----Examples-----
Input
5 2
5 2 3
3 1 4 5 2
3 5
Output
8
Input
4 4
5 1 4
4 3 1 2
2 4 3 1
Output
-1
Input
4 4
2 1 11
1 3 2 4
1 3 2 4
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob are studying for their class test together. The topic of the test is Prime Numbers. The preparation is getting too boring for their liking. To make it interesting, they turn it into a game. The winner will get an ice-cream treat from the other.
The game is called Count K-Primes. A number is a $K$-prime if it has exactly $K$ distinct prime factors. The game is quite simple. Alice will give three numbers $A$, $B$ & $K$ to Bob. Bob needs to tell Alice the number of $K$-prime numbers between $A$ & $B$ (both inclusive). If Bob gives the correct answer, he gets a point. If not, Alice gets a point. They play this game $T$ times.
Bob hasn't prepared so well. But he really wants to win the game. He wants you to tell him the correct answer.
------ Input ------
First line of input contains a single integer $T$, the number of times they play.
Each game is described in a single line containing the three numbers $A$,$B$ & $K$.
------ Output ------
For each game, output on a separate line the number of $K$-primes between $A$ & $B$.
------ Constraints: ------
$1 ≤ T ≤ 10000$
$2 ≤ A ≤ B ≤ 100000$
$1 ≤ K ≤ 5$
----- Sample Input 1 ------
4
2 5 1
4 10 2
14 15 2
2 20 3
----- Sample Output 1 ------
4
2
2
0
----- explanation 1 ------
Test case $1$: The range includes $4$ integers $\{2, 3, 4,5 \}$. We need to find the number of integers in this range having only $1$ distinct prime factor.
- For $2$, since it is prime, it has $1$ distinct prime factor.
- For $3$, since it is prime, it has $1$ distinct prime factor.
- For $4$, we can write it as $2\times 2$. Thus, it has $1$ distinct prime factor which is $2$.
- For $5$, since it is prime, it has $1$ distinct prime factor.
Thus, all $4$ integers in the given range are $1$-primes.
Test case $2$: The only *K-primes* in the given range are $6$ and $10$. This is because $6 = 2\times 3$ and $10 = 2\times 5$. Thus both these integers have $2$ distinct prime factors.
Test case $3$: The only *K-primes* in the given range are $14$ and $15$. This is because $14 = 2\times 7$ and $15 = 3\times 5$. Thus both these integers have $2$ distinct prime factors.
Test case $4$: There are no *K-primes* in the given range.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 drop a ball from a given height. After each bounce, the ball returns to some fixed proportion of its previous height. If the ball bounces to height 1 or less, we consider it to have stopped bouncing. Return the number of bounces it takes for the ball to stop moving.
```
bouncingBall(initialHeight, bouncingProportion)
boucingBall(4, 0.5)
After first bounce, ball bounces to height 2
After second bounce, ball bounces to height 1
Therefore answer is 2 bounces
boucingBall(30, 0.3)
After first bounce, ball bounces to height 9
After second bounce, ball bounces to height 2.7
After third bounce, ball bounces to height 0.81
Therefore answer is 3 bounces
```
Initial height is an integer in range [2,1000]
Bouncing Proportion is a decimal in range [0, 1)
Write your solution by modifying this code:
```python
def bouncing_ball(initial, proportion):
```
Your solution should implemented in the function "bouncing_ball". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function that returns the average of an array of numbers ("scores"), rounded to the nearest whole number. You are not allowed to use any loops (including for, for/in, while, and do/while loops).
Write your solution by modifying this code:
```python
def average(array):
```
Your solution should implemented in the function "average". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Æsir - CHAOS Æsir - V.
"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.
The time right now...... 00:01:12......
It's time."
The emotion samples are now sufficient. After almost 3 years, it's time for Ivy to awake her bonded sister, Vanessa.
The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers ($1, 2, 3, \ldots$). The node with a number $x$ ($x > 1$), is directly connected with a node with number $\frac{x}{f(x)}$, with $f(x)$ being the lowest prime divisor of $x$.
Vanessa's mind is divided into $n$ fragments. Due to more than 500 years of coma, the fragments have been scattered: the $i$-th fragment is now located at the node with a number $k_i!$ (a factorial of $k_i$).
To maximize the chance of successful awakening, Ivy decides to place the samples in a node $P$, so that the total length of paths from each fragment to $P$ is smallest possible. If there are multiple fragments located at the same node, the path from that node to $P$ needs to be counted multiple times.
In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.
But for a mere human like you, is this still possible?
For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node $P$.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^6$) — number of fragments of Vanessa's mind.
The second line contains $n$ integers: $k_1, k_2, \ldots, k_n$ ($0 \le k_i \le 5000$), denoting the nodes where fragments of Vanessa's mind are located: the $i$-th fragment is at the node with a number $k_i!$.
-----Output-----
Print a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node $P$).
As a reminder, if there are multiple fragments at the same node, the distance from that node to $P$ needs to be counted multiple times as well.
-----Examples-----
Input
3
2 1 4
Output
5
Input
4
3 1 4 4
Output
6
Input
4
3 1 4 1
Output
6
Input
5
3 1 4 1 5
Output
11
-----Note-----
Considering the first $24$ nodes of the system, the node network will look as follows (the nodes $1!$, $2!$, $3!$, $4!$ are drawn bold):
[Image]
For the first example, Ivy will place the emotion samples at the node $1$. From here:
The distance from Vanessa's first fragment to the node $1$ is $1$. The distance from Vanessa's second fragment to the node $1$ is $0$. The distance from Vanessa's third fragment to the node $1$ is $4$.
The total length is $5$.
For the second example, the assembly node will be $6$. From here:
The distance from Vanessa's first fragment to the node $6$ is $0$. The distance from Vanessa's second fragment to the node $6$ is $2$. The distance from Vanessa's third fragment to the node $6$ is $2$. The distance from Vanessa's fourth fragment to the node $6$ is again $2$.
The total path length is $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.
There are N integers written on a blackboard. The i-th integer is A_i.
Takahashi and Aoki will arrange these integers in a row, as follows:
* First, Takahashi will arrange the integers as he wishes.
* Then, Aoki will repeatedly swap two adjacent integers that are coprime, as many times as he wishes.
We will assume that Takahashi acts optimally so that the eventual sequence will be lexicographically as small as possible, and we will also assume that Aoki acts optimally so that the eventual sequence will be lexicographically as large as possible. Find the eventual sequence that will be produced.
Constraints
* 1 ≦ N ≦ 2000
* 1 ≦ A_i ≦ 10^8
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
Output
Print the eventual sequence that will be produced, in a line.
Examples
Input
5
1 2 3 4 5
Output
5 3 2 4 1
Input
4
2 3 4 6
Output
2 4 6 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n positive integers a_1, …, a_n, and an integer k ≥ 2. Count the number of pairs i, j such that 1 ≤ i < j ≤ n, and there exists an integer x such that a_i ⋅ a_j = x^k.
Input
The first line contains two integers n and k (2 ≤ n ≤ 10^5, 2 ≤ k ≤ 100).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^5).
Output
Print a single integer — the number of suitable pairs.
Example
Input
6 3
1 3 9 8 24 1
Output
5
Note
In the sample case, the suitable pairs are:
* a_1 ⋅ a_4 = 8 = 2^3;
* a_1 ⋅ a_6 = 1 = 1^3;
* a_2 ⋅ a_3 = 27 = 3^3;
* a_3 ⋅ a_5 = 216 = 6^3;
* a_4 ⋅ a_6 = 8 = 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.
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege.
Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: **they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act)**.
Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea.
You are now to create a function that returns a Josephus permutation, taking as parameters the initial *array/list of items* to be permuted as if they were in a circle and counted out every *k* places until none remained.
**Tips and notes:** it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1.
For example, with n=7 and k=3 `josephus(7,3)` should act this way.
```
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out and goes into the result [3]
[1,2,4,5,7] => 6 is counted out and goes into the result [3,6]
[1,4,5,7] => 2 is counted out and goes into the result [3,6,2]
[1,4,5] => 7 is counted out and goes into the result [3,6,2,7]
[1,4] => 5 is counted out and goes into the result [3,6,2,7,5]
[4] => 1 is counted out and goes into the result [3,6,2,7,5,1]
[] => 4 is counted out and goes into the result [3,6,2,7,5,1,4]
```
So our final result is:
```
josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4]
```
For more info, browse the Josephus Permutation page on wikipedia; related kata: Josephus Survivor.
Also, [live game demo](https://iguacel.github.io/josephus/) by [OmniZoetrope](https://www.codewars.com/users/OmniZoetrope).
Write your solution by modifying this code:
```python
def josephus(items,k):
```
Your solution should implemented in the function "josephus". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two strings $s$ and $t$ both of length $n$ and both consisting of lowercase Latin letters.
In one move, you can choose any length $len$ from $1$ to $n$ and perform the following operation: Choose any contiguous substring of the string $s$ of length $len$ and reverse it; at the same time choose any contiguous substring of the string $t$ of length $len$ and reverse it as well.
Note that during one move you reverse exactly one substring of the string $s$ and exactly one substring of the string $t$.
Also note that borders of substrings you reverse in $s$ and in $t$ can be different, the only restriction is that you reverse the substrings of equal length. For example, if $len=3$ and $n=5$, you can reverse $s[1 \dots 3]$ and $t[3 \dots 5]$, $s[2 \dots 4]$ and $t[2 \dots 4]$, but not $s[1 \dots 3]$ and $t[1 \dots 2]$.
Your task is to say if it is possible to make strings $s$ and $t$ equal after some (possibly, empty) sequence of moves.
You have to answer $q$ independent test cases.
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 10^4$) — the number of test cases. Then $q$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$ and $t$.
The second line of the test case contains one string $s$ consisting of $n$ lowercase Latin letters.
The third line of the test case contains one string $t$ consisting of $n$ lowercase Latin letters.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer on it — "YES" (without quotes) if it is possible to make strings $s$ and $t$ equal after some (possibly, empty) sequence of moves and "NO" otherwise.
-----Example-----
Input
4
4
abcd
abdc
5
ababa
baaba
4
asdf
asdg
4
abcd
badc
Output
NO
YES
NO
YES
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Once Vasya played bricks. All the bricks in the set had regular cubical shape. Vasya vas a talented architect, however the tower he built kept falling apart.
Let us consider the building process. Vasya takes a brick and puts it on top of the already built tower so that the sides of the brick are parallel to the sides of the bricks he has already used. Let's introduce a Cartesian coordinate system on the horizontal plane, where Vasya puts the first brick. Then the projection of brick number i on the plane is a square with sides parallel to the axes of coordinates with opposite corners in points (xi, 1, yi, 1) and (xi, 2, yi, 2). The bricks are cast from homogeneous plastic and the weight of a brick a × a × a is a3 grams.
It is guaranteed that Vasya puts any brick except the first one on the previous one, that is the area of intersection of the upper side of the previous brick and the lower side of the next brick is always positive.
We (Vasya included) live in a normal world where the laws of physical statics work. And that is why, perhaps, if we put yet another brick, the tower will collapse under its own weight. Vasya puts the cubes consecutively one on top of the other until at least one cube loses the balance and falls down. If it happens, Vasya gets upset and stops the construction. Print the number of bricks in the maximal stable tower, that is the maximal number m satisfying the condition that all the towers consisting of bricks 1, 2, ..., k for every integer k from 1 to m remain stable.
Input
The first input file contains an integer n (1 ≤ n ≤ 100) which is the number of bricks. Each of the next n lines contains four numbers xi, 1, yi, 1, xi, 2, yi, 2 (xi, 1 ≠ xi, 2, |xi, 1 - xi, 2| = |yi, 1 - yi, 2|) which are the coordinates of the opposite angles of the base of the brick number i. The coordinates are integers and their absolute value does not exceed 50.
The cubes are given in the order Vasya puts them. It is guaranteed that the area of intersection of the upper side of the brick number i - 1 and the lower side of the brick number i is strictly strictly greater than zero for all i ≥ 2.
Output
Print the number of bricks in the maximal stable tower.
Examples
Input
2
0 0 3 3
1 0 4 3
Output
2
Input
2
0 0 3 3
2 0 5 3
Output
1
Input
3
0 0 3 3
1 0 4 3
2 0 5 3
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
At the annual family gathering, the family likes to find the oldest living family member’s age and the youngest family member’s age and calculate the difference between them.
You will be given an array of all the family members' ages, in any order. The ages will be given in whole numbers, so a baby of 5 months, will have an ascribed ‘age’ of 0. Return a new array (a tuple in Python) with [youngest age, oldest age, difference between the youngest and oldest age].
Write your solution by modifying this code:
```python
def difference_in_ages(ages):
```
Your solution should implemented in the function "difference_in_ages". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)^{n}n
Your task is to calculate f(n) for a given integer n.
-----Input-----
The single line contains the positive integer n (1 ≤ n ≤ 10^15).
-----Output-----
Print f(n) in a single line.
-----Examples-----
Input
4
Output
2
Input
5
Output
-3
-----Note-----
f(4) = - 1 + 2 - 3 + 4 = 2
f(5) = - 1 + 2 - 3 + 4 - 5 = - 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.
Your friend who lives in undisclosed country is involved in debt. He is borrowing 100,000-yen from a loan shark. The loan shark adds 5% interest of the debt and rounds it to the nearest 1,000 above week by week.
Write a program which computes the amount of the debt in n weeks.
Input
An integer n (0 ≤ n ≤ 100) is given in a line.
Output
Print the amout of the debt in a line.
Example
Input
5
Output
130000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!
This contest consists of n problems, and Pasha solves ith problem in a_{i} time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.
Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment l_{j} and ending moment r_{j}. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that l_{x} ≤ T ≤ r_{x}.
Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 1000) — the number of problems. The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^5) — the time Pasha needs to solve ith problem.
The third line contains one integer m (0 ≤ m ≤ 1000) — the number of periods of time when the website is working. Next m lines represent these periods. jth line contains two numbers l_{j} and r_{j} (1 ≤ l_{j} < r_{j} ≤ 10^5) — the starting and the ending moment of jth period.
It is guaranteed that the periods are not intersecting and are given in chronological order, so for every j > 1 the condition l_{j} > r_{j} - 1 is met.
-----Output-----
If Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted.
Otherwise print "-1" (without brackets).
-----Examples-----
Input
2
3 4
2
1 4
7 9
Output
7
Input
1
5
1
1 4
Output
-1
Input
1
5
1
1 5
Output
5
-----Note-----
In the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.
In the second example Pasha invents the solution only after the website stops working for the last time.
In the third example Pasha sends the solution exactly at the end of the first period.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Karen has just arrived at school, and she has a math test today! [Image]
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.
Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.
The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.
Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?
Since this number can be quite large, output only the non-negative remainder after dividing it by 10^9 + 7.
-----Input-----
The first line of input contains a single integer n (1 ≤ n ≤ 200000), the number of numbers written on the first row.
The next line contains n integers. Specifically, the i-th one among these is a_{i} (1 ≤ a_{i} ≤ 10^9), the i-th number on the first row.
-----Output-----
Output a single integer on a line by itself, the number on the final row after performing the process above.
Since this number can be quite large, print only the non-negative remainder after dividing it by 10^9 + 7.
-----Examples-----
Input
5
3 6 9 12 15
Output
36
Input
4
3 7 5 2
Output
1000000006
-----Note-----
In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.
Karen performs the operations as follows: [Image]
The non-negative remainder after dividing the final number by 10^9 + 7 is still 36, so this is the correct output.
In the second test case, the numbers written on the first row are 3, 7, 5 and 2.
Karen performs the operations as follows: [Image]
The non-negative remainder after dividing the final number by 10^9 + 7 is 10^9 + 6, so this is the correct 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.
There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to x.
You want to determine two positive integer values:
1. how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop?
2. how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop?
If any of these values doesn't exist then that value should be equal to -1. If there are multiple possible answers, then print any of them.
The printed values should be less or equal to 10^9. It can be shown that under the given constraints such values always exist if any values exist at all.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases.
Each of the next t lines contains three integers a, b and c (1 ≤ a ≤ 10^9, 2 ≤ b ≤ 10^9, 1 ≤ c ≤ 10^9).
Output
For each testcase print two positive integers. For both shops print such x that buying x donuts in this shop is strictly cheaper than buying x donuts in the other shop. x should be greater than 0 and less or equal to 10^9.
If there is no such x, then print -1. If there are multiple answers, then print any of them.
Example
Input
4
5 10 4
4 5 20
2 2 3
1000000000 1000000000 1000000000
Output
-1 20
8 -1
1 2
-1 1000000000
Note
In the first testcase buying any number of donuts will be cheaper in the second shop. For example, for 3 or 5 donuts you'll have to buy a box of 10 donuts for 4 dollars. 3 or 5 donuts in the first shop would cost you 15 or 25 dollars, respectively, however. For 20 donuts you'll have to buy two boxes for 8 dollars total. Note that 3 and 5 are also valid answers for the second shop, along with many other answers.
In the second testcase buying any number of donuts will be either cheaper in the first shop or the same price. 8 donuts cost 32 dollars in the first shop and 40 dollars in the second shop (because you have to buy two boxes). 10 donuts will cost 40 dollars in both shops, so 10 is not a valid answer for any of the shops.
In the third testcase 1 donut costs 2 and 3 dollars, respectively. 2 donuts cost 4 and 3 dollars. Thus, 1 is a valid answer for the first shop and 2 is a valid answer for the second shop.
In the fourth testcase 10^9 donuts cost 10^{18} dollars in the first shop and 10^9 dollars in the second shop.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exactly <image> rows above it and the same number of rows below it.
* Elements of the "middle" column — the column that has exactly <image> columns to the left of it and the same number of columns to the right of it.
<image> The figure shows a 5 × 5 matrix. The good elements are marked with green.
Help the Smart Beaver count the sum of good elements of the given matrix.
Input
The first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≤ aij ≤ 100) separated by single spaces — the elements of the given matrix.
The input limitations for getting 30 points are:
* 1 ≤ n ≤ 5
The input limitations for getting 100 points are:
* 1 ≤ n ≤ 101
Output
Print a single integer — the sum of good matrix elements.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
45
Input
5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Output
17
Note
In the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555.
Given a number X, compute <image> modulo 109 + 7.
Input
The first line of input will contain the integer X (1 ≤ X ≤ 10700).
Output
Print a single integer, the answer to the question.
Examples
Input
21
Output
195
Input
345342
Output
390548434
Note
The first few values of S are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 12. The sum of these values is 195.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is a_{i}. If some free time remains, she can spend it on reading.
Help Luba to determine the minimum number of day when she finishes reading.
It is guaranteed that the answer doesn't exceed n.
Remember that there are 86400 seconds in a day.
-----Input-----
The first line contains two integers n and t (1 ≤ n ≤ 100, 1 ≤ t ≤ 10^6) — the number of days and the time required to read the book.
The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 86400) — the time Luba has to spend on her work during i-th day.
-----Output-----
Print the minimum day Luba can finish reading the book.
It is guaranteed that answer doesn't exceed n.
-----Examples-----
Input
2 2
86400 86398
Output
2
Input
2 86400
0 86400
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.
## Welcome to my (amazing) kata!
You are given a gigantic number to decode. Each number is a code that alternates in a pattern between encoded text and a smaller, encoded number. The pattern's length varies with every test, but the alternation between encoded text and an encoded number will always be there. Following this rule, each number tested begins with encoded text and ends with an encoded number.
## How the encoding works
Now, we should probably review how the string of numbers is formed - considering you have to unform it. So, first, some text is taken, and encoded. The system of encoding is taking each letter's position in the alphabet and adding 100 to it. For example, `m` in the real text would be `113` in the code-number.
After the text, there is a binary number. You should convert this number to a normal, base 10 decimal (all of them can be converted into whole, non-negative numbers).
Separating encoded text and encoded numbers, there is a `98`. Because the numbers are in binary, the only digits they use are '0' and '1', and each letter of the alphabet, encoded, is between 101-127, all instances of `98` are to indicate a separation between encoded text and encoded numbers. There may also be a `98` at the very end of the number.
When you return your final answer, the text and numbers should always be separated by a comma (`,`)
## Example
```python
decode(103115104105123101118119981001098113113113981000) = "codewars, 18, mmm, 8"
```
The part of the code until the first `98` can be decoded to `"codewars"`. `10010` is binary for `18`. `113113113` translates to `"mmm"`. And `1000` is binary for `8`.
Here is a visualisation of the example:
Good luck!
Write your solution by modifying this code:
```python
def decode(number):
```
Your solution should implemented in the function "decode". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: [Image] By the pieces lay a large square wooden board. The board is divided into $n^2$ cells arranged into $n$ rows and $n$ columns. Some of the cells are already occupied by single tiles stuck to it. The remaining cells are free.
Alice started wondering whether she could fill the board completely using the pieces she had found. Of course, each piece has to cover exactly five distinct cells of the board, no two pieces can overlap and every piece should fit in the board entirely, without some parts laying outside the board borders. The board however was too large for Alice to do the tiling by hand. Can you help determine if it's possible to fully tile the board?
-----Input-----
The first line of the input contains a single integer $n$ ($3 \leq n \leq 50$) — the size of the board.
The following $n$ lines describe the board. The $i$-th line ($1 \leq i \leq n$) contains a single string of length $n$. Its $j$-th character ($1 \leq j \leq n$) is equal to "." if the cell in the $i$-th row and the $j$-th column is free; it is equal to "#" if it's occupied.
You can assume that the board contains at least one free cell.
-----Output-----
Output YES if the board can be tiled by Alice's pieces, or NO otherwise. You can print each letter in any case (upper or lower).
-----Examples-----
Input
3
#.#
...
#.#
Output
YES
Input
4
##.#
#...
####
##.#
Output
NO
Input
5
#.###
....#
#....
###.#
#####
Output
YES
Input
5
#.###
....#
#....
....#
#..##
Output
NO
-----Note-----
The following sketches show the example boards and their tilings if such tilings exist: [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.
RJ Freight, a Japanese railroad company for freight operations has recently constructed exchange lines at Hazawa, Yokohama. The layout of the lines is shown in Figure B-1.
<image>
Figure B-1: Layout of the exchange lines
A freight train consists of 2 to 72 freight cars. There are 26 types of freight cars, which are denoted by 26 lowercase letters from "a" to "z". The cars of the same type are indistinguishable from each other, and each car's direction doesn't matter either. Thus, a string of lowercase letters of length 2 to 72 is sufficient to completely express the configuration of a train.
Upon arrival at the exchange lines, a train is divided into two sub-trains at an arbitrary position (prior to entering the storage lines). Each of the sub-trains may have its direction reversed (using the reversal line). Finally, the two sub-trains are connected in either order to form the final configuration. Note that the reversal operation is optional for each of the sub-trains.
For example, if the arrival configuration is "abcd", the train is split into two sub-trains of either 3:1, 2:2 or 1:3 cars. For each of the splitting, possible final configurations are as follows ("+" indicates final concatenation position):
[3:1]
abc+d cba+d d+abc d+cba
[2:2]
ab+cd ab+dc ba+cd ba+dc cd+ab cd+ba dc+ab dc+ba
[1:3]
a+bcd a+dcb bcd+a dcb+a
Excluding duplicates, 12 distinct configurations are possible.
Given an arrival configuration, answer the number of distinct configurations which can be constructed using the exchange lines described above.
Input
The entire input looks like the following.
> the number of datasets = m
> 1st dataset
> 2nd dataset
> ...
> m-th dataset
>
Each dataset represents an arriving train, and is a string of 2 to 72 lowercase letters in an input line.
Output
For each dataset, output the number of possible train configurations in a line. No other characters should appear in the output.
Example
Input
4
aa
abba
abcd
abcde
Output
1
6
12
18
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.
Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if: on both diagonals of the square paper all letters are the same; all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals.
Help Valera, write the program that completes the described task for him.
-----Input-----
The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.
-----Output-----
Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.
-----Examples-----
Input
5
xooox
oxoxo
soxoo
oxoxo
xooox
Output
NO
Input
3
wsw
sws
wsw
Output
YES
Input
3
xpx
pxp
xpe
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.
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.
Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability.
Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.
Input
The only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only.
Output
Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>
Examples
Input
technocup
Output
1.000000000000000
Input
tictictactac
Output
0.333333333333333
Input
bbaabaabbb
Output
0.100000000000000
Note
In the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.
In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider the following experiment. You have a deck of m cards, and exactly one card is a joker. n times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck.
Let x be the number of times you have taken the joker out of the deck during this experiment. Assuming that every time you shuffle the deck, all m! possible permutations of cards are equiprobable, what is the expected value of x^k? Print the answer modulo 998244353.
Input
The only line contains three integers n, m and k (1 ≤ n, m < 998244353, 1 ≤ k ≤ 5000).
Output
Print one integer — the expected value of x^k, taken modulo 998244353 (the answer can always be represented as an irreducible fraction a/b, where b mod 998244353 ≠ 0; you have to print a ⋅ b^{-1} mod 998244353).
Examples
Input
1 1 1
Output
1
Input
1 1 5000
Output
1
Input
2 2 2
Output
499122178
Input
998244352 1337 5000
Output
326459680
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has recently learnt some new facts about the famous number π. For example, he was surprised that ordinary fractions are sometimes used to represent this number approximately. For example, 22/7, 355/113 or even 103993/33102.
Soon, by calculating the value of 22/7 and 355/113 on paper Chef became quite disappointed because these values are not precise enough. For example, 22/7 differs in the third digit after the decimal point. So, these values are definitely should not be used for serious calculations.
However, Chef doesn't know anything about 103993/33102. This fraction is quite inconvenient to calculate on paper. Chef is curious how precise this value is. So he asks you to help him and to calculate the first K digits after the decimal point of such an approximation of π. He consider this ordinary fraction as infinite decimal fraction so formally he asks you to calculate this approximation truncated to the first K digits after the decimal point.
------ 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 a single integer K.
------ Output ------
For each test case output a single line containing the value of 103993/33102 truncated to the first K digits after the decimal point. Note that for K = 0 you should output just "3" without decimal point (quotes are for clarity).
------ Constraints ------
$0 ≤ K ≤ 10^{6}$
$1 ≤ T ≤ 2000$
$The sum of K over the input does not exceed 10^{6}$
----- Sample Input 1 ------
3
0
6
20
----- Sample Output 1 ------
3
3.141592
3.14159265301190260407
----- explanation 1 ------
Example case 1. Here K = 0 so we don't need to output any digits after the decimal point. The decimal point itself also should not be output.
Example case 2. Note that here we truncate (not round) the actual value of 103993/33102 to 6 digits after the decimal point. As you see from example case 3 rounded value here differs from truncated one.
Example case 3. This example is only to show that this approximation of ? is also far from perfect :)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. [Image]
There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength a_{i}.
Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.
When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.
To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer.
Determine the minimum strength of the computer Inzane needs to hack all the banks.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 3·10^5) — the total number of banks.
The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the strengths of the banks.
Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — meaning that there is a wire directly connecting banks u_{i} and v_{i}.
It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.
-----Output-----
Print one integer — the minimum strength of the computer Inzane needs to accomplish the goal.
-----Examples-----
Input
5
1 2 3 4 5
1 2
2 3
3 4
4 5
Output
5
Input
7
38 -29 87 93 39 28 -55
1 2
2 5
3 2
2 4
1 7
7 6
Output
93
Input
5
1 2 7 6 7
1 5
5 3
3 4
2 4
Output
8
-----Note-----
In the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1, 2, 3, 4, 5]. He hacks bank 5, then strengths of the banks become [1, 2, 4, 5, - ]. He hacks bank 4, then strengths of the banks become [1, 3, 5, - , - ]. He hacks bank 3, then strengths of the banks become [2, 4, - , - , - ]. He hacks bank 2, then strengths of the banks become [3, - , - , - , - ]. He completes his goal by hacking bank 1.
In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata you must take an input string, reverse the order of the words, and reverse the order of the letters within the words.
But, as a bonus, every test input will end with a punctuation mark (! ? .) and the output should be returned with the mark at the end.
A few examples should help clarify:
```python
esrever("hello world.") == "dlrow olleh."
esrever("Much l33t?") == "t33l hcuM?"
esrever("tacocat!") == "tacocat!"
```
Quick Note: A string will always be passed in (though it may be empty) so no need for error-checking other types.
Write your solution by modifying this code:
```python
def esrever(string):
```
Your solution should implemented in the function "esrever". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.
He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 2·10^5) — the length of the string.
-----Output-----
Print the string that satisfies all the constraints.
If there are multiple answers, print any of them.
-----Examples-----
Input
2
Output
aa
Input
3
Output
bba
-----Note-----
A palindrome is a sequence of characters which reads the same backward and forward.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 some perfect squares with a particular property.
For example the number ```n = 256``` is a perfect square, its square root is ```16```. If we change the position of the digits of n, we may obtain another perfect square``` 625``` (square root = 25).
With these three digits ```2```,```5``` and ```6``` we can get two perfect squares: ```[256,625]```
The number ```1354896``` may generate another ```4``` perfect squares, having with the number itself, a total of five perfect squares: ```[1354896, 3594816, 3481956, 5391684, 6395841]```, being the last one in the list, ```6395841```, the highest value of the set.
Your task is to find the first perfect square above the given lower_limit, that can generate the given k number of perfect squares, and it doesn't contain the digit 0. Then return the maximum perfect square that can be obtained from its digits.
Example with the cases seen above:
```
lower_limit = 200
k = 2 (amount of perfect squares)
result = 625
lower_limit = 3550000
k = 5 (amount of perfect squares)
result = 6395841
```
Features of the random tests:
```
100 <= lower_limit <= 1e6
2 <= k <= 5
number of tests = 45
```
Have a good time!
Write your solution by modifying this code:
```python
def next_perfectsq_perm(lower_limit, k):
```
Your solution should implemented in the function "next_perfectsq_perm". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.
For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.
In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.
How many days from 2018-1-1 through 2018-a-b are Takahashi?
-----Constraints-----
- a is an integer between 1 and 12 (inclusive).
- b is an integer between 1 and 31 (inclusive).
- 2018-a-b is a valid date in Gregorian calendar.
-----Input-----
Input is given from Standard Input in the following format:
a b
-----Output-----
Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.
-----Sample Input-----
5 5
-----Sample Output-----
5
There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a set of strings S. Each string consists of lowercase Latin letters.
For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions:
* if the current string is t, choose some lowercase Latin letter c and append it to the back of t, so the current string becomes t + c. This action takes 1 second;
* use autocompletion. When you try to autocomplete the current string t, a list of all strings s ∈ S such that t is a prefix of s is shown to you. This list includes t itself, if t is a string from S, and the strings are ordered lexicographically. You can transform t into the i-th string from this list in i seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type.
What is the minimum number of seconds that you have to spend to type each string from S?
Note that the strings from S are given in an unusual way.
Input
The first line contains one integer n (1 ≤ n ≤ 10^6).
Then n lines follow, the i-th line contains one integer p_i (0 ≤ p_i < i) and one lowercase Latin character c_i. These lines form some set of strings such that S is its subset as follows: there are n + 1 strings, numbered from 0 to n; the 0-th string is an empty string, and the i-th string (i ≥ 1) is the result of appending the character c_i to the string p_i. It is guaranteed that all these strings are distinct.
The next line contains one integer k (1 ≤ k ≤ n) — the number of strings in S.
The last line contains k integers a_1, a_2, ..., a_k (1 ≤ a_i ≤ n, all a_i are pairwise distinct) denoting the indices of the strings generated by above-mentioned process that form the set S — formally, if we denote the i-th generated string as s_i, then S = {s_{a_1}, s_{a_2}, ..., s_{a_k}}.
Output
Print k integers, the i-th of them should be equal to the minimum number of seconds required to type the string s_{a_i}.
Examples
Input
10
0 i
1 q
2 g
0 k
1 e
5 r
4 m
5 h
3 p
3 e
5
8 9 1 10 6
Output
2 4 1 3 3
Input
8
0 a
1 b
2 a
2 b
4 a
4 b
5 c
6 d
5
2 3 4 7 8
Output
1 2 2 4 4
Note
In the first example, S consists of the following strings: ieh, iqgp, i, iqge, ier.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.
There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car: - 1: if this pair of cars never collided. - 1 occurs only on the main diagonal of the matrix. 0: if no car turned over during the collision. 1: if only the i-th car turned over during the collision. 2: if only the j-th car turned over during the collision. 3: if both cars turned over during the collision.
Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of cars.
Each of the next n lines contains n space-separated integers that determine matrix A.
It is guaranteed that on the main diagonal there are - 1, and - 1 doesn't appear anywhere else in the matrix.
It is guaranteed that the input is correct, that is, if A_{ij} = 1, then A_{ji} = 2, if A_{ij} = 3, then A_{ji} = 3, and if A_{ij} = 0, then A_{ji} = 0.
-----Output-----
Print the number of good cars and in the next line print their space-separated indices in the increasing order.
-----Examples-----
Input
3
-1 0 0
0 -1 1
0 2 -1
Output
2
1 3
Input
4
-1 3 3 3
3 -1 3 3
3 3 -1 3
3 3 3 -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.
You are given a string and a number k. You are suggested to generate new strings by swapping any adjacent pair of characters in the string up to k times. Write a program to report the lexicographically smallest string among them.
Input
The input is given in the following format.
s
k
The first line provides a string s. The second line provides the maximum number of swapping operations k (0 ≤ k ≤ 109). The string consists solely of lower-case alphabetical letters and has a length between 1 and 2 × 105.
Output
Output the lexicographically smallest string.
Examples
Input
pckoshien
3
Output
ckopshien
Input
pckoshien
10
Output
cekophsin
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 having drifted about in a small boat for a couple of days, Akira Crusoe Maeda was finally cast ashore on a foggy island. Though he was exhausted and despaired, he was still fortunate to remember a legend of the foggy island, which he had heard from patriarchs in his childhood. This must be the island in the legend.
In the legend, two tribes have inhabited the island, one is divine and the other is devilish; once members of the divine tribe bless you, your future is bright and promising, and your soul will eventually go to Heaven; in contrast, once members of the devilish tribe curse you, your future is bleak and hopeless, and your soul will eventually fall down to Hell.
In order to prevent the worst-case scenario, Akira should distinguish the devilish from the divine. But how? They looked exactly alike and he could not distinguish one from the other solely by their appearances. He still had his last hope, however. The members of the divine tribe are truth-tellers, that is, they always tell the truth and those of the devilish tribe are liars, that is, they always tell a lie.
He asked some of the whether or not some are divine. They knew one another very much and always responded to him "faithfully" according to their individual natures (i.e., they always tell the truth or always a lie). He did not dare to ask any other forms of questions, since the legend says that a devilish member would curse a person forever when he did not like the question. He had another piece of useful information: the legend tells the populations of both tribes. These numbers in the legend are trustworthy since everyone living on this island is immortal and none have ever been born at least these millennia.
You are a good computer programmer and so requested to help Akira by writing a program that classifies the inhabitants according to their answers to his inquiries.
Input
The input consists of multiple data sets, each in the following format:
n p1 p2
x1 y1 a1
x2 y2 a2
...
xi yi ai
...
xn yn an
The first line has three non-negative integers n, p1, and p2. n is the number of questions Akira asked. p1 and p2 are the populations of the divine and devilish tribes, respectively, in the legend. Each of the following n lines has two integers xi, yi and one word ai. xi and yi are the identification numbers of inhabitants, each of which is between 1 and p1 + p2, inclusive. ai is either "yes", if the inhabitant xi said that the inhabitant yi was a member of the divine tribe, or "no", otherwise. Note that xi and yi can be the same number since "are you a member of the divine tribe?" is a valid question. Note also that two lines may have the same x's and y's since Akira was very upset and might have asked the same question to the same one more than once.
You may assume that n is less than 1000 and that p1 and p2 are less than 300. A line with three zeros, i.e., "0 0 0", represents the end of the input. You can assume that each data set is consistent and no contradictory answers are included.
Output
For each data set, if it includes sufficient information to classify all the inhabitants, print the identification numbers of all the divine ones in ascending order, one in a line. In addition, following the output numbers, print "end" in a line. Otherwise, i.e., if a given data set does not include sufficient information to identify all the divine members, print "no" in a line.
Example
Input
2 1 1
1 2 no
2 1 no
3 2 1
1 1 yes
2 2 yes
3 3 yes
2 2 1
1 2 yes
2 3 no
5 4 3
1 2 yes
1 3 no
4 5 yes
5 6 yes
6 7 no
0 0 0
Output
no
no
1
2
end
3
4
5
6
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.
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.
After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 5·10^5) — the number of elements in the array. The next line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^6) — the values of the array elements.
-----Output-----
In a single line print a single integer — the maximum number of points Artem can get.
-----Examples-----
Input
5
3 1 5 2 6
Output
11
Input
5
1 2 3 4 5
Output
6
Input
5
1 100 101 100 1
Output
102
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata you will create a function to check a non-negative input to see if it is a prime number.
The function will take in a number and will return True if it is a prime number and False if it is not.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
### Examples
Write your solution by modifying this code:
```python
def is_prime(n):
```
Your solution should implemented in the function "is_prime". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 statement of this problem shares a lot with problem A. The differences are that in this problem, the probability is introduced, and the constraint is different.
A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of n rows and m columns. The rows of the floor are numbered from 1 to n from top to bottom, and columns of the floor are numbered from 1 to m from left to right. The cell on the intersection of the r-th row and the c-th column is denoted as (r,c). The initial position of the robot is (r_b, c_b).
In one second, the robot moves by dr rows and dc columns, that is, after one second, the robot moves from the cell (r, c) to (r + dr, c + dc). Initially dr = 1, dc = 1. If there is a vertical wall (the left or the right walls) in the movement direction, dc is reflected before the movement, so the new value of dc is -dc. And if there is a horizontal wall (the upper or lower walls), dr is reflected before the movement, so the new value of dr is -dr.
Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at (r_d, c_d). The job of the robot is to clean that dirty cell.
After a lot of testings in problem A, the robot is now broken. It cleans the floor as described above, but at each second the cleaning operation is performed with probability \frac p {100} only, and not performed with probability 1 - \frac p {100}. The cleaning or not cleaning outcomes are independent each second.
Given the floor size n and m, the robot's initial position (r_b, c_b) and the dirty cell's position (r_d, c_d), find the expected time for the robot to do its job.
It can be shown that the answer can be expressed as an irreducible fraction \frac x y, where x and y are integers and y not ≡ 0 \pmod{10^9 + 7} . Output the integer equal to x ⋅ y^{-1} mod (10^9 + 7). In other words, output such an integer a that 0 ≤ a < 10^9 + 7 and a ⋅ y ≡ x \pmod {10^9 + 7}.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10). Description of the test cases follows.
A test case consists of only one line, containing n, m, r_b, c_b, r_d, c_d, and p (4 ≤ n ⋅ m ≤ 10^5, n, m ≥ 2, 1 ≤ r_b, r_d ≤ n, 1 ≤ c_b, c_d ≤ m, 1 ≤ p ≤ 99) — the sizes of the room, the initial position of the robot, the position of the dirt cell and the probability of cleaning in percentage.
Output
For each test case, print a single integer — the expected time for the robot to clean the dirty cell, modulo 10^9 + 7.
Example
Input
6
2 2 1 1 2 1 25
3 3 1 2 2 2 25
10 10 1 1 10 10 75
10 10 10 10 1 1 75
5 5 1 3 2 2 10
97 98 3 5 41 43 50
Output
3
3
15
15
332103349
99224487
Note
In the first test case, the robot has the opportunity to clean the dirty cell every second. Using the [geometric distribution](https://en.wikipedia.org/wiki/Geometric_distribution), we can find out that with the success rate of 25\%, the expected number of tries to clear the dirty cell is \frac 1 {0.25} = 4. But because the first moment the robot has the opportunity to clean the cell is before the robot starts moving, the answer is 3.
<image> Illustration for the first example. The blue arc is the robot. The red star is the target dirt cell. The purple square is the initial position of the robot. Each second the robot has an opportunity to clean a row and a column, denoted by yellow stripes.
In the second test case, the board size and the position are different, but the robot still has the opportunity to clean the dirty cell every second, and it has the same probability of cleaning. Therefore the answer is the same as in the first example.
<image> Illustration for the second example.
The third and the fourth case are almost the same. The only difference is that the position of the dirty cell and the robot are swapped. But the movements in both cases are identical, hence the same result.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
a is an array of n positive integers, all of which are not greater than n.
You have to process q queries to this array. Each query is represented by two numbers p and k. Several operations are performed in each query; each operation changes p to p + ap + k. There operations are applied until p becomes greater than n. The answer to the query is the number of performed operations.
Input
The first line contains one integer n (1 ≤ n ≤ 100000).
The second line contains n integers — elements of a (1 ≤ ai ≤ n for each i from 1 to n).
The third line containts one integer q (1 ≤ q ≤ 100000).
Then q lines follow. Each line contains the values of p and k for corresponding query (1 ≤ p, k ≤ n).
Output
Print q integers, ith integer must be equal to the answer to ith query.
Example
Input
3
1 1 1
3
1 1
2 1
3 1
Output
2
1
1
Note
Consider first example:
In first query after first operation p = 3, after second operation p = 5.
In next two queries p is greater than n after the first operation.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
JOI has a stove in your room. JOI himself is resistant to the cold, so he doesn't need to put on the stove when he is alone in the room, but he needs to put on the stove when there are visitors.
On this day, there are N guests under JOI. The ith (1 \ leq i \ leq N) visitor arrives at time T_i and leaves at time T_i + 1. There can never be more than one visitor at the same time.
JOI can turn the stove on and off at any time. However, each time you turn on the stove, you will consume one match. JOI has only K matches, so he can only stove up to K times. The stove is gone at the beginning of the day.
When the stove is on, fuel is consumed by that amount, so I want to set the time when the stove is on and off and minimize the total time when the stove is on.
Example
Input
3 2
1
3
6
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.
Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.
Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.
There are $n$ lamps with Spirit Tree's light. Sein knows the time of turning on and off for the $i$-th lamp — $l_i$ and $r_i$ respectively. To open the door you have to choose $k$ lamps in such a way that there will be a moment of time when they all will be turned on.
While Sein decides which of the $k$ lamps to pick, Ori is interested: how many ways there are to pick such $k$ lamps that the door will open? It may happen that Sein may be wrong and there are no such $k$ lamps. The answer might be large, so print it modulo $998\,244\,353$.
-----Input-----
First line contains two integers $n$ and $k$ ($1 \le n \le 3 \cdot 10^5$, $1 \le k \le n$) — total number of lamps and the number of lamps that must be turned on simultaneously.
Next $n$ lines contain two integers $l_i$ ans $r_i$ ($1 \le l_i \le r_i \le 10^9$) — period of time when $i$-th lamp is turned on.
-----Output-----
Print one integer — the answer to the task modulo $998\,244\,353$.
-----Examples-----
Input
7 3
1 7
3 8
4 5
6 7
1 3
5 10
8 9
Output
9
Input
3 1
1 1
2 2
3 3
Output
3
Input
3 2
1 1
2 2
3 3
Output
0
Input
3 3
1 3
2 3
3 3
Output
1
Input
5 2
1 3
2 4
3 5
4 6
5 7
Output
7
-----Note-----
In first test case there are nine sets of $k$ lamps: $(1, 2, 3)$, $(1, 2, 4)$, $(1, 2, 5)$, $(1, 2, 6)$, $(1, 3, 6)$, $(1, 4, 6)$, $(2, 3, 6)$, $(2, 4, 6)$, $(2, 6, 7)$.
In second test case $k=1$, so the answer is 3.
In third test case there are no such pairs of lamps.
In forth test case all lamps are turned on in a time $3$, so the answer is 1.
In fifth test case there are seven sets of $k$ lamps: $(1, 2)$, $(1, 3)$, $(2, 3)$, $(2, 4)$, $(3, 4)$, $(3, 5)$, $(4, 5)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It is the easy version of the problem. The difference is that in this version, there are no nodes with already chosen colors.
Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?
You have a perfect binary tree of $2^k - 1$ nodes — a binary tree where all vertices $i$ from $1$ to $2^{k - 1} - 1$ have exactly two children: vertices $2i$ and $2i + 1$. Vertices from $2^{k - 1}$ to $2^k - 1$ don't have any children. You want to color its vertices with the $6$ Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).
Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube.
A picture of Rubik's cube and its 2D map.
More formally:
a white node can not be neighboring with white and yellow nodes;
a yellow node can not be neighboring with white and yellow nodes;
a green node can not be neighboring with green and blue nodes;
a blue node can not be neighboring with green and blue nodes;
a red node can not be neighboring with red and orange nodes;
an orange node can not be neighboring with red and orange nodes;
You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.
The answer may be too large, so output the answer modulo $10^9+7$.
-----Input-----
The first and only line contains the integers $k$ ($1 \le k \le 60$) — the number of levels in the perfect binary tree you need to color.
-----Output-----
Print one integer — the number of the different colorings modulo $10^9+7$.
-----Examples-----
Input
3
Output
24576
Input
14
Output
934234
-----Note-----
In the picture below, you can see one of the correct colorings of the first example.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
What are you doing at the end of the world? Are you busy? Will you save us?
[Image]
Nephren is playing a game with little leprechauns.
She gives them an infinite array of strings, f_{0... ∞}.
f_0 is "What are you doing at the end of the world? Are you busy? Will you save us?".
She wants to let more people know about it, so she defines f_{i} = "What are you doing while sending "f_{i} - 1"? Are you busy? Will you send "f_{i} - 1"?" for all i ≥ 1.
For example, f_1 is
"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f_1.
It can be seen that the characters in f_{i} are letters, question marks, (possibly) quotation marks and spaces.
Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of f_{n}. The characters are indexed starting from 1. If f_{n} consists of less than k characters, output '.' (without quotes).
Can you answer her queries?
-----Input-----
The first line contains one integer q (1 ≤ q ≤ 10) — the number of Nephren's questions.
Each of the next q lines describes Nephren's question and contains two integers n and k (0 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^18).
-----Output-----
One line containing q characters. The i-th character in it should be the answer for the i-th query.
-----Examples-----
Input
3
1 1
1 2
1 111111111111
Output
Wh.
Input
5
0 69
1 194
1 139
0 47
1 66
Output
abdef
Input
10
4 1825
3 75
3 530
4 1829
4 1651
3 187
4 584
4 255
4 774
2 474
Output
Areyoubusy
-----Note-----
For the first two examples, refer to f_0 and f_1 given in the legend.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 interactive problem.
Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him:
* "x", if (x mod a) ≥ (y mod a).
* "y", if (x mod a) < (y mod a).
We define (x mod a) as a remainder of division x by a.
Vasya should guess the number a using no more, than 60 questions.
It's guaranteed that Petya has a number, that satisfies the inequality 1 ≤ a ≤ 10^9.
Help Vasya playing this game and write a program, that will guess the number a.
Interaction
Your program should play several games.
Before the start of any game your program should read the string:
* "start" (without quotes) — the start of the new game.
* "mistake" (without quotes) — in the previous game, you found the wrong answer. Your program should terminate after reading this string and it will get verdict "Wrong answer".
* "end" (without quotes) — all games finished. Your program should terminate after reading this string.
After reading the string "start" (without quotes) the new game starts.
At the beginning, your program should ask several questions about pairs of non-negative integer numbers (x, y). You can only ask the numbers, that satisfy the inequalities 0 ≤ x, y ≤ 2 ⋅ 10^9. To ask a question print "? x y" (without quotes). As the answer, you should read one symbol:
* "x" (without quotes), if (x mod a) ≥ (y mod a).
* "y" (without quotes), if (x mod a) < (y mod a).
* "e" (without quotes) — you asked more than 60 questions. Your program should terminate after reading this string and it will get verdict "Wrong answer".
After your program asked several questions your program should print the answer in form "! a" (without quotes). You should print the number a satisfying the inequalities 1 ≤ a ≤ 10^9. It's guaranteed that Petya's number a satisfied this condition. After that, the current game will finish.
We recall that your program can't ask more than 60 questions during one game.
If your program doesn't terminate after reading "mistake" (without quotes), "end" (without quotes) or "e" (without quotes), it can get any verdict, because it will continue reading from closed input. Also, if your program prints answer or question in the incorrect format it can get any verdict, too. Be careful.
Don't forget to flush the output after printing questions and answers.
To flush the output, you can use:
* fflush(stdout) in C++.
* System.out.flush() in Java.
* stdout.flush() in Python.
* flush(output) in Pascal.
* See the documentation for other languages.
It's guaranteed that you should play at least 1 and no more than 100 games.
Hacks:
In hacks, you can use only one game. To hack a solution with Petya's number a (1 ≤ a ≤ 10^9) in the first line you should write a single number 1 and in the second line you should write a single number a.
Example
Input
start
x
x
start
x
x
y
start
x
x
y
y
end
Output
? 0 0
? 10 1
! 1
? 0 0
? 3 4
? 2 5
! 2
? 2 4
? 2 5
? 3 10
? 9 1
! 3
Note
In the first test, you should play 3 games with Petya's numbers 1, 2 and 3.
In the first game, Petya will answer "x" (without quotes) to any question, because (x mod 1) = 0 for any integer x.
In the second game, if you will ask pair (0, 0), the answer will be "x" (without quotes), because (0 mod 2) ≥ (0 mod 2). But if you will ask pair (2, 5), the answer will be "y" (without quotes), because (2 mod 2) < (5 mod 2), because (2 mod 2) = 0 and (5 mod 2) = 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
[Generala](https://en.wikipedia.org/wiki/Generala) is a dice game popular in South America. It's very similar to [Yahtzee](https://en.wikipedia.org/wiki/Yahtzee) but with a different scoring approach. It is played with 5 dice, and the possible results are:
| Result | Points | Rules | Samples |
|---------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------|
| GENERALA | 50 | When all rolled dice are of the same value. | 66666, 55555, 44444, 11111, 22222, 33333. |
| POKER | 40 | Four rolled dice are of the same value. | 44441, 33233, 22262. |
| FULLHOUSE | 30 | Three rolled dice are of the same value, the remaining two are of a different value, but equal among themselves. | 12121, 44455, 66116. |
| STRAIGHT | 20 | Rolled dice are in sequential order. Dice with value `1` is a wildcard that can be used at the beginning of the straight, or at the end of it. | 12345, 23456, 34561, 13654, 62534. |
| Anything else | 0 | Anything else will return `0` points. | 44421, 61623, 12346. |
Please note that dice are not in order; for example `12543` qualifies as a `STRAIGHT`. Also, No matter what string value you get for the dice, you can always reorder them any order you need to make them qualify as a `STRAIGHT`. I.E. `12453`, `16543`, `15364`, `62345` all qualify as valid `STRAIGHT`s.
Complete the function that is given the rolled dice as a string of length `5` and return the points scored in that roll. You can safely assume that provided parameters will be valid:
* String of length 5,
* Each character will be a number between `1` and `6`
Write your solution by modifying this code:
```python
def points(dice):
```
Your solution should implemented in the function "points". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.
After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.
Input
The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers ai (1 ≤ ai ≤ 106) — the values of the array elements.
Output
In a single line print a single integer — the maximum number of points Artem can get.
Examples
Input
5
3 1 5 2 6
Output
11
Input
5
1 2 3 4 5
Output
6
Input
5
1 100 101 100 1
Output
102
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Brown are brothers in a family and each receives pocket money in celebration of the coming year. They are very close and share the total amount of the money fifty-fifty. The pocket money each receives is a multiple of 1,000 yen.
Write a program to calculate each one’s share given the amount of money Alice and Brown received.
Input
The input is given in the following format.
a b
A line of data is given that contains two values of money: a (1000 ≤ a ≤ 50000) for Alice and b (1000 ≤ b ≤ 50000) for Brown.
Output
Output the amount of money each of Alice and Brown receive in a line.
Examples
Input
1000 3000
Output
2000
Input
5000 5000
Output
5000
Input
1000 2000
Output
1500
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
You are given a car odometer which displays the miles traveled as an integer.
The odometer has a defect, however: it proceeds from digit `3` to digit `5` always skipping the digit `4`. This defect shows up in all positions (ones, tens, hundreds, etc).
For example, if the odometer displays `15339` and the car travels another mile, the odometer changes to `15350` (instead of `15340`).
Your task is to calculate the real distance, according The number the odometer shows.
# Example
For `n = 13` the output should be `12`(4 skiped).
For `n = 15` the output should be `13`(4 and 14 skiped).
For `n = 2003` the output should be `1461`.
# Input/Output
- `[input]` integer `n`
The number the odometer shows.
`1 <= n <= 999999999`
- `[output]` an integer
The real distance.
Write your solution by modifying this code:
```python
def faulty_odometer(n):
```
Your solution should implemented in the function "faulty_odometer". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
-----Input-----
The first line contains two integers n and k (1 ≤ n, k ≤ 10^18, k ≤ n) — the number of sticks drawn by Sasha and the number k — the number of sticks to be crossed out on each turn.
-----Output-----
If Sasha wins, print "YES" (without quotes), otherwise print "NO" (without quotes).
You can print each letter in arbitrary case (upper of lower).
-----Examples-----
Input
1 1
Output
YES
Input
10 4
Output
NO
-----Note-----
In the first example Sasha crosses out 1 stick, and then there are no sticks. So Lena can't make a move, and Sasha wins.
In the second example Sasha crosses out 4 sticks, then Lena crosses out 4 sticks, and after that there are only 2 sticks left. Sasha can't make a move. The players make equal number of moves, so Sasha doesn't 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.
Grigory has $n$ magic stones, conveniently numbered from $1$ to $n$. The charge of the $i$-th stone is equal to $c_i$.
Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index $i$, where $2 \le i \le n - 1$), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its own charge, but acquires the charges from neighboring stones. In other words, its charge $c_i$ changes to $c_i' = c_{i + 1} + c_{i - 1} - c_i$.
Andrew, Grigory's friend, also has $n$ stones with charges $t_i$. Grigory is curious, whether there exists a sequence of zero or more synchronization operations, which transforms charges of Grigory's stones into charges of corresponding Andrew's stones, that is, changes $c_i$ into $t_i$ for all $i$?
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 10^5$) — the number of magic stones.
The second line contains integers $c_1, c_2, \ldots, c_n$ ($0 \le c_i \le 2 \cdot 10^9$) — the charges of Grigory's stones.
The second line contains integers $t_1, t_2, \ldots, t_n$ ($0 \le t_i \le 2 \cdot 10^9$) — the charges of Andrew's stones.
-----Output-----
If there exists a (possibly empty) sequence of synchronization operations, which changes all charges to the required ones, print "Yes".
Otherwise, print "No".
-----Examples-----
Input
4
7 2 4 12
7 15 10 12
Output
Yes
Input
3
4 4 4
1 2 3
Output
No
-----Note-----
In the first example, we can perform the following synchronizations ($1$-indexed): First, synchronize the third stone $[7, 2, \mathbf{4}, 12] \rightarrow [7, 2, \mathbf{10}, 12]$. Then synchronize the second stone: $[7, \mathbf{2}, 10, 12] \rightarrow [7, \mathbf{15}, 10, 12]$.
In the second example, any operation with the second stone will not change its charge.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this Kata, you will be given a string and your task is to return the most valuable character. The value of a character is the difference between the index of its last occurrence and the index of its first occurrence. Return the character that has the highest value. If there is a tie, return the alphabetically lowest character. `[For Golang return rune]`
All inputs will be lower case.
```
For example:
solve('a') = 'a'
solve('ab') = 'a'. Last occurrence is equal to first occurrence of each character. Return lexicographically lowest.
solve("axyzxyz") = 'x'
```
More examples in test cases. Good luck!
Write your solution by modifying this code:
```python
def solve(st):
```
Your solution should implemented in the function "solve". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a_1 × b_1 segments large and the second one is a_2 × b_2 segments large.
Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares.
To make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following: he either breaks one bar exactly in half (vertically or horizontally) and eats exactly a half of the bar, or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar.
In the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar.
Both variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is 16 × 23, then Polycarpus can chip off a half, but not a third. If the bar is 20 × 18, then Polycarpus can chip off both a half and a third. If the bar is 5 × 7, then Polycarpus cannot chip off a half nor a third.
What is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process.
-----Input-----
The first line of the input contains integers a_1, b_1 (1 ≤ a_1, b_1 ≤ 10^9) — the initial sizes of the first chocolate bar. The second line of the input contains integers a_2, b_2 (1 ≤ a_2, b_2 ≤ 10^9) — the initial sizes of the second bar.
You can use the data of type int64 (in Pascal), long long (in С++), long (in Java) to process large integers (exceeding 2^31 - 1).
-----Output-----
In the first line print m — the sought minimum number of minutes. In the second and third line print the possible sizes of the bars after they are leveled in m minutes. Print the sizes using the format identical to the input format. Print the sizes (the numbers in the printed pairs) in any order. The second line must correspond to the first bar and the third line must correspond to the second bar. If there are multiple solutions, print any of them.
If there is no solution, print a single line with integer -1.
-----Examples-----
Input
2 6
2 3
Output
1
1 6
2 3
Input
36 5
10 16
Output
3
16 5
5 16
Input
3 5
2 1
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December?
-----Constraints-----
- 1≤M≤23
- M is an integer.
-----Input-----
Input is given from Standard Input in the following format:
M
-----Output-----
If we have x hours until New Year at M o'clock on 30th, December, print x.
-----Sample Input-----
21
-----Sample Output-----
27
We have 27 hours until New Year at 21 o'clock on 30th, December.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it?
-----Input-----
The input contains a single integer n (0 ≤ n ≤ 2000000000).
-----Output-----
Output a single integer.
-----Examples-----
Input
11
Output
2
Input
14
Output
0
Input
61441
Output
2
Input
571576
Output
10
Input
2128506
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 given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph. [Image] Example of a tree.
You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.
You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $(x, y, z)$ such that $x \neq y, y \neq z, x \neq z$, $x$ is connected by an edge with $y$, and $y$ is connected by an edge with $z$. The colours of $x$, $y$ and $z$ should be pairwise distinct. Let's call a painting which meets this condition good.
You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.
-----Input-----
The first line contains one integer $n$ $(3 \le n \le 100\,000)$ — the number of vertices.
The second line contains a sequence of integers $c_{1, 1}, c_{1, 2}, \dots, c_{1, n}$ $(1 \le c_{1, i} \le 10^{9})$, where $c_{1, i}$ is the cost of painting the $i$-th vertex into the first color.
The third line contains a sequence of integers $c_{2, 1}, c_{2, 2}, \dots, c_{2, n}$ $(1 \le c_{2, i} \le 10^{9})$, where $c_{2, i}$ is the cost of painting the $i$-th vertex into the second color.
The fourth line contains a sequence of integers $c_{3, 1}, c_{3, 2}, \dots, c_{3, n}$ $(1 \le c_{3, i} \le 10^{9})$, where $c_{3, i}$ is the cost of painting the $i$-th vertex into the third color.
Then $(n - 1)$ lines follow, each containing two integers $u_j$ and $v_j$ $(1 \le u_j, v_j \le n, u_j \neq v_j)$ — the numbers of vertices connected by the $j$-th undirected edge. It is guaranteed that these edges denote a tree.
-----Output-----
If there is no good painting, print $-1$.
Otherwise, print the minimum cost of a good painting in the first line. In the second line print $n$ integers $b_1, b_2, \dots, b_n$ $(1 \le b_i \le 3)$, where the $i$-th integer should denote the color of the $i$-th vertex. If there are multiple good paintings with minimum cost, print any of them.
-----Examples-----
Input
3
3 2 3
4 3 2
3 1 3
1 2
2 3
Output
6
1 3 2
Input
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 3
Output
-1
Input
5
3 4 2 1 2
4 2 1 5 4
5 3 2 1 1
1 2
3 2
4 3
5 4
Output
9
1 3 2 1 3
-----Note-----
All vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color $1$, the second vertex — into color $3$, and the third vertex — into color $2$. The cost of this painting is $3 + 2 + 1 = 6$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi and Aoki will play a game using a grid with H rows and W columns of square cells. There are N obstacles on this grid; the i-th obstacle is at (X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there is a piece placed there at (1,1).
Starting from Takahashi, he and Aoki alternately perform one of the following actions:
* Move the piece to an adjacent cell. Here, let the position of the piece be (x,y). Then Takahashi can only move the piece to (x+1,y), and Aoki can only move the piece to (x,y+1). If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.
* Do not move the piece, and end his turn without affecting the grid.
The game ends when the piece does not move twice in a row.
Takahashi would like to perform as many actions (including not moving the piece) as possible before the game ends, while Aoki would like to perform as few actions as possible before the game ends. How many actions will Takahashi end up performing?
Constraints
* 1 \leq H,W \leq 2\times 10^5
* 0 \leq N \leq 2\times 10^5
* 1 \leq X_i \leq H
* 1 \leq Y_i \leq W
* If i \neq j, (X_i,Y_i) \neq (X_j,Y_j)
* (X_i,Y_i) \neq (1,1)
* X_i and Y_i are integers.
Input
Input is given from Standard Input in the following format:
H W N
X_1 Y_1
:
X_N Y_N
Output
Print the number of actions Takahashi will end up performing.
Examples
Input
3 3 1
3 2
Output
2
Input
10 10 14
4 3
2 2
7 3
9 10
7 7
8 1
10 10
5 4
3 4
2 8
6 4
4 4
5 8
9 2
Output
6
Input
100000 100000 0
Output
100000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way: [Image]
Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253": [Image] [Image]
Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?
-----Input-----
The first line of the input contains the only integer n (1 ≤ n ≤ 9) — the number of digits in the phone number that Mike put in.
The second line contains the string consisting of n digits (characters from '0' to '9') representing the number that Mike put in.
-----Output-----
If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.
Otherwise print "NO" (without quotes) in the first line.
-----Examples-----
Input
3
586
Output
NO
Input
2
09
Output
NO
Input
9
123456789
Output
YES
Input
3
911
Output
YES
-----Note-----
You can find the picture clarifying the first sample case in the statement above.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.
Input
The first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 ≤ ai ≤ 1000) — the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.
Output
Print a single integer — the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.
Examples
Input
1 1 1 1 1 1
Output
6
Input
1 2 1 2 1 2
Output
13
Note
This is what Gerald's hexagon looks like in the first sample:
<image>
And that's what it looks like in the second sample:
<image>
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a^3. A tower consisting of blocks with sides a_1, a_2, ..., a_{k} has the total volume a_1^3 + a_2^3 + ... + a_{k}^3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
-----Input-----
The only line of the input contains one integer m (1 ≤ m ≤ 10^15), meaning that Limak wants you to choose X between 1 and m, inclusive.
-----Output-----
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
-----Examples-----
Input
48
Output
9 42
Input
6
Output
6 6
-----Note-----
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is: Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15. The second added block has side 2, so the remaining volume is 15 - 8 = 7. Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 3^3 + 2^3 + 7·1^3 = 27 + 8 + 7 = 42.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The only difference between easy and hard versions is constraints.
You are given a sequence $a$ consisting of $n$ positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are three block palindromes but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.
Your task is to choose the maximum by length subsequence of $a$ that is a three blocks palindrome.
You have to answer $t$ independent test cases.
Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 2000$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 26$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $26$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$ ($\sum n \le 2000$).
-----Output-----
For each test case, print the answer — the maximum possible length of some subsequence of $a$ that is a three blocks palindrome.
-----Example-----
Input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
Output
7
2
4
1
1
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
3:33
It's possible for all the digits displayed on a digital clock in the hours:minutes format to be identical. The time shown above (3:33) is an example of such a situation. Other examples are 2:2 and 1:11. Note that the digits of 33:33 are identical, but it is not a valid time on a usual digital clock.
The above example was for a usual 24-hour format digital clock. Let's consider a more general clock, where an hour lasts M minutes and a day lasts H hours (therefore, the clock can show any number of hours between 0 and H-1, inclusive, and any number of minutes between 0 and M-1, inclusive). Both the hours and the minutes are shown without leading zeroes in decimal notation and their separator (e.g., ':') doesn't matter.
Can you tell how many minutes during a day will the digital clock have identical digits displayed on it?
------ Input ------
The first line of the input contains an integer T - the number of test cases.
Each of the next T lines contains two space-separated integers H and M for one test case.
------ Output ------
For each test case, output a single line corresponding to the answer of the problem.
------ Constraints ------
$1 ≤ T ≤ 50$
$1 ≤ H, M ≤ 100$
----- Sample Input 1 ------
6
24 60
34 50
10 11
10 12
11 11
1 1
----- Sample Output 1 ------
19
20
10
11
10
1
----- explanation 1 ------
Example case 1. A clock shows two identical digits at times 0:0, 1:1, .., 9:9, three identical digits at times 11:1, 22:2, 1:11, 2:22, 3:33, 4:44, 5:55, and four identical digits at times 11:11 and 22:22. So, there are 19 minutes during which the time displayed by the clock will have identical digits.
Example case 2. Compared to the previous case, the clock doesn't show 5:55, but can show 33:3 and 33:33.
Example case 6. In this example, our day consists of one hour and one hour consists of one minute. Hence, the entire day is just 1 minute - the only time the digital clock will display is 0:0 during the entire day, (i.e. the entire hour, i.e. entire minute). And 0:0 has all digits identical, so the answer is 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array A of N numbers, find the number of distinct pairs (i, j) such that j ≥i and A[i] = A[j].
First line of the input contains number of test cases T. Each test case has two lines, first line is the number N, followed by a line consisting of N integers which are the elements of array A.
For each test case print the number of distinct pairs.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 10^6
-10^6 ≤ A[i] ≤ 10^6 for 0 ≤ i < N
SAMPLE INPUT
2
4
1 2 3 4
3
1 2 1
SAMPLE OUTPUT
4
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Elephant likes lemonade.
When Little Elephant visits any room, he finds the bottle of the lemonade in that room that contains the greatest number of litres of lemonade and drinks it all.
There are n rooms (numbered from 0 to n-1), each contains C_{i} bottles. Each bottle has a volume (in litres). The first room visited by Little Elephant was P_{0}-th, the second - P_{1}-th, ..., the m-th - P_{m-1}-th room. Note that Little Elephant may visit a room more than once.
Find for Little Elephant the total volume of lemonade he has drunk.
------ Input ------
First line of the input contains single integer T - the number of test cases. T test cases follow. First line of each test case contains pair of integers n and m. Second line contains m integers separated by a single space - array P. Next n lines describe bottles in each room in such format: C_{i} V_{0} V_{1} ... VC_{i}-1, where V is the list of volumes (in liters) of all bottles in i-th room.
------ Output ------
In T lines print T integers - the answers for the corresponding test cases.
------ Constraints ------
1 ≤ T ≤ 10
1 ≤ n, C_{i} ≤ 100
1 ≤ m ≤ 10^{4}
0 ≤ P_{i} < n
1 ≤ V_{i} ≤ 10^{5}
----- Sample Input 1 ------
2
3 3
0 2 1
3 1 2 3
1 7
2 4 7
4 7
0 1 3 0 1 0 0
1 7
3 9 4 5
7 1 2 3 4 5 6 7
1 1
----- Sample Output 1 ------
17
22
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Professor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.
There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line.
<image>
Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".
Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.
Input
The first line contains n (1 ≤ n ≤ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≤ xi ≤ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≤ yi ≤ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n.
Output
Output contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.
Examples
Input
5
1 4 5 2 3
3 4 2 1 5
Output
3
Input
3
3 1 2
2 3 1
Output
2
Note
For the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two integers $n$ and $m$. Calculate the number of pairs of arrays $(a, b)$ such that:
the length of both arrays is equal to $m$; each element of each array is an integer between $1$ and $n$ (inclusive); $a_i \le b_i$ for any index $i$ from $1$ to $m$; array $a$ is sorted in non-descending order; array $b$ is sorted in non-ascending order.
As the result can be very large, you should print it modulo $10^9+7$.
-----Input-----
The only line contains two integers $n$ and $m$ ($1 \le n \le 1000$, $1 \le m \le 10$).
-----Output-----
Print one integer – the number of arrays $a$ and $b$ satisfying the conditions described above modulo $10^9+7$.
-----Examples-----
Input
2 2
Output
5
Input
10 1
Output
55
Input
723 9
Output
157557417
-----Note-----
In the first test there are $5$ suitable arrays: $a = [1, 1], b = [2, 2]$; $a = [1, 2], b = [2, 2]$; $a = [2, 2], b = [2, 2]$; $a = [1, 1], b = [2, 1]$; $a = [1, 1], b = [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.
There are $n$ points on the plane, $(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$.
You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
-----Input-----
First line contains one integer $n$ ($1 \leq n \leq 10^5$).
Each of the next $n$ lines contains two integers $x_i$ and $y_i$ ($1 \leq x_i,y_i \leq 10^9$).
-----Output-----
Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.
-----Examples-----
Input
3
1 1
1 2
2 1
Output
3
Input
4
1 1
1 2
2 1
2 2
Output
4
-----Note-----
Illustration for the first example: [Image]
Illustration for the second example: [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.