question
large_stringlengths 265
13.2k
|
|---|
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`
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
An online contest will soon be held on ForceCoders, a large competitive programming platform. The authors have prepared $n$ problems; and since the platform is very popular, $998244351$ coder from all over the world is going to solve them.
For each problem, the authors estimated the number of people who would solve it: for the $i$-th problem, the number of accepted solutions will be between $l_i$ and $r_i$, inclusive.
The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems $(x, y)$ such that $x$ is located earlier in the contest ($x < y$), but the number of accepted solutions for $y$ is strictly greater.
Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem $i$, any integral number of accepted solutions for it (between $l_i$ and $r_i$) is equally probable, and all these numbers are independent.
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 50$) β the number of problems in the contest.
Then $n$ lines follow, the $i$-th line contains two integers $l_i$ and $r_i$ ($0 \le l_i \le r_i \le 998244351$) β the minimum and maximum number of accepted solutions for the $i$-th problem, respectively.
-----Output-----
The probability that there will be no inversions in the contest can be expressed as an irreducible fraction $\frac{x}{y}$, where $y$ is coprime with $998244353$. Print one integer β the value of $xy^{-1}$, taken modulo $998244353$, where $y^{-1}$ is an integer such that $yy^{-1} \equiv 1$ $(mod$ $998244353)$.
-----Examples-----
Input
3
1 2
1 2
1 2
Output
499122177
Input
2
42 1337
13 420
Output
578894053
Input
2
1 1
0 0
Output
1
Input
2
1 1
1 1
Output
1
-----Note-----
The real answer in the first test is $\frac{1}{2}$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# 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.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 very important person has a piece of paper in the form of a rectangle a Γ b.
Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size x_{i} Γ y_{i}. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).
A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?
-----Input-----
The first line contains three integer numbers n, a and b (1 β€ n, a, b β€ 100).
Each of the next n lines contain two numbers x_{i}, y_{i} (1 β€ x_{i}, y_{i} β€ 100).
-----Output-----
Print the largest total area that can be occupied by two seals. If you can not select two seals, print 0.
-----Examples-----
Input
2 2 2
1 2
2 1
Output
4
Input
4 10 9
2 3
1 1
5 10
9 11
Output
56
Input
3 10 10
6 6
7 7
20 5
Output
0
-----Note-----
In the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.
In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.
In the third example there is no such pair of seals that they both can fit on a piece of paper.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
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!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.
For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.
That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.
-----Constraints-----
- 2 \leq n,m \leq 10^5
- -10^9 \leq x_1 < ... < x_n \leq 10^9
- -10^9 \leq y_1 < ... < y_m \leq 10^9
- x_i and y_i are integers.
-----Input-----
Input is given from Standard Input in the following format:
n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m
-----Output-----
Print the total area of the rectangles, modulo 10^9+7.
-----Sample Input-----
3 3
1 3 4
1 3 6
-----Sample Output-----
60
The following figure illustrates this input:
The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
The objective is to disambiguate two given names: the original with another
Let's start simple, and just work with plain ascii strings.
The function ```could_be``` is given the original name and another one to test
against.
```python
# should return True if the other name could be the same person
> could_be("Chuck Norris", "Chuck")
True
# should False otherwise (whatever you may personnaly think)
> could_be("Chuck Norris", "superman")
False
```
Let's say your name is *Carlos Ray Norris*, your objective is to return True if
the other given name matches any combinaison of the original fullname:
```python
could_be("Carlos Ray Norris", "Carlos Ray Norris") : True
could_be("Carlos Ray Norris", "Carlos Ray") : True
could_be("Carlos Ray Norris", "Norris") : True
could_be("Carlos Ray Norris", "Norris Carlos") : True
```
For the sake of simplicity:
* the function is case sensitive and accent sensitive for now
* it is also punctuation sensitive
* an empty other name should not match any original
* an empty orginal name should not be matchable
* the function is not symmetrical
The following matches should therefore fail:
```python
could_be("Carlos Ray Norris", " ") : False
could_be("Carlos Ray Norris", "carlos") : False
could_be("Carlos Ray Norris", "Norris!") : False
could_be("Carlos Ray Norris", "Carlos-Ray Norris") : False
could_be("Ray Norris", "Carlos Ray Norris") : False
could_be("Carlos", "Carlos Ray Norris") : False
```
Too easy ? Try the next steps:
* [Author Disambiguation: a name is a Name!](https://www.codewars.com/kata/author-disambiguation-a-name-is-a-name)
* or even harder: [Author Disambiguation: Signatures worth it](https://www.codewars.com/kata/author-disambiguation-signatures-worth-it)
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
We'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.
You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)Β·k to add the number n to the sequence.
You can spend a cost up to w, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.
-----Input-----
The first line contains three integers w (1 β€ w β€ 10^16), m (1 β€ m β€ 10^16), k (1 β€ k β€ 10^9).
Please, do not write the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
The first line should contain a single integer β the answer to the problem.
-----Examples-----
Input
9 1 1
Output
9
Input
77 7 7
Output
7
Input
114 5 14
Output
6
Input
1 1 2
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
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.
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.
B: Twice as own
problem
You will be given Q queries. Since one positive integer N is given for each query, find the number of positive integers M that satisfy the following two conditions.
* 2 Satisfy \ leq M \ leq N
* Of the divisors of M, excluding M, the total product is more than twice that of M
Input format
The input is given in the following format:
Q
N_1_1
N_2
::
N_Q
* The first line gives the number of queries Q.
* Lines 2 through N + 1 are given one positive integer N given for each query.
Constraint
* 1 \ leq Q \ leq 10 ^ 5
* 2 \ leq N_i \ leq 10 ^ 5 (1 \ leq i \ leq Q)
Output format
Output the number of positive integers that satisfy the above two conditions for each N_i, separated by line breaks.
Input example
3
43
9
twenty four
Output example
11
0
Five
* When N = 24, there are five types of M that can be considered as 12, 16, 18, 20, 24.
Example
Input
3
43
9
24
Output
11
0
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.
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: Only segments already presented on the picture can be painted; The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; The numbers of points from the beginning of the tail to the end should strictly increase.
Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.
Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.
-----Input-----
First line of the input contains two integers n and m(2 β€ n β€ 100 000, 1 β€ m β€ 200 000)Β β the number of points and the number segments on the picture respectively.
Then follow m lines, each containing two integers u_{i} and v_{i} (1 β€ u_{i}, v_{i} β€ n, u_{i} β v_{i})Β β the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.
-----Output-----
Print the maximum possible value of the hedgehog's beauty.
-----Examples-----
Input
8 6
4 5
3 5
2 5
1 2
2 8
6 7
Output
9
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
12
-----Note-----
The picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3Β·3 = 9.
[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.
The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:
- 1 β€ i < j < k β€ |T| (|T| is the length of T.)
- T_i = A (T_i is the i-th character of T from the beginning.)
- T_j = B
- T_k = C
For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.
You are given a string S. Each character of S is A, B, C or ?.
Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.
This sum can be extremely large, so print the sum modulo 10^9 + 7.
-----Constraints-----
- 3 β€ |S| β€ 10^5
- Each character of S is A, B, C or ?.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.
-----Sample Input-----
A??C
-----Sample Output-----
8
In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:
- AAAC: 0
- AABC: 2
- AACC: 0
- ABAC: 1
- ABBC: 2
- ABCC: 2
- ACAC: 0
- ACBC: 1
- ACCC: 0
The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 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.
Gerald has n younger brothers and their number happens to be even. One day he bought n^2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n^2 he has exactly one bag with k candies.
Help him give n bags of candies to each brother so that all brothers got the same number of candies.
-----Input-----
The single line contains a single integer n (n is even, 2 β€ n β€ 100) β the number of Gerald's brothers.
-----Output-----
Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers β the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n^2. You can print the numbers in the lines in any order.
It is guaranteed that the solution exists at the given limits.
-----Examples-----
Input
2
Output
1 4
2 3
-----Note-----
The sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 positive integers $n$ and $s$. Find the maximum possible median of an array of $n$ non-negative integers (not necessarily distinct), such that the sum of its elements is equal to $s$.
A median of an array of integers of length $m$ is the number standing on the $\lceil {\frac{m}{2}} \rceil$-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from $1$. For example, a median of the array $[20,40,20,50,50,30]$ is the $\lceil \frac{m}{2} \rceil$-th element of $[20,20,30,40,50,50]$, so it is $30$. There exist other definitions of the median, but in this problem we use the described definition.
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) β the number of test cases. Description of the test cases follows.
Each test case contains a single line with two integers $n$ and $s$ ($1 \le n, s \le 10^9$) β the length of the array and the required sum of the elements.
-----Output-----
For each test case print a single integer β the maximum possible median.
-----Examples-----
Input
8
1 5
2 5
3 5
2 1
7 17
4 14
1 1000000000
1000000000 1
Output
5
2
2
0
4
4
1000000000
0
-----Note-----
Possible arrays for the first three test cases (in each array the median is underlined):
In the first test case $[\underline{5}]$
In the second test case $[\underline{2}, 3]$
In the third test case $[1, \underline{2}, 2]$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An n Γ n square matrix is special, if: it is binary, that is, each cell contains either a 0, or a 1; the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n Γ n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
-----Input-----
The first line of the input contains three integers n, m, mod (2 β€ n β€ 500, 0 β€ m β€ n, 2 β€ mod β€ 10^9). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m Γ n table contains at most two numbers one.
-----Output-----
Print the remainder after dividing the required value by number mod.
-----Examples-----
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
-----Note-----
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, 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.
Two integer sequences existed initially, one of them was strictly increasing, and another one β strictly decreasing.
Strictly increasing sequence is a sequence of integers $[x_1 < x_2 < \dots < x_k]$. And strictly decreasing sequence is a sequence of integers $[y_1 > y_2 > \dots > y_l]$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.
Elements of increasing sequence were inserted between elements of the decreasing one (and, possibly, before its first element and after its last element) without changing the order. For example, sequences $[1, 3, 4]$ and $[10, 4, 2]$ can produce the following resulting sequences: $[10, \textbf{1}, \textbf{3}, 4, 2, \textbf{4}]$, $[\textbf{1}, \textbf{3}, \textbf{4}, 10, 4, 2]$. The following sequence cannot be the result of these insertions: $[\textbf{1}, 10, \textbf{4}, 4, \textbf{3}, 2]$ because the order of elements in the increasing sequence was changed.
Let the obtained sequence be $a$. This sequence $a$ is given in the input. Your task is to find any two suitable initial sequences. One of them should be strictly increasing, and another one β strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.
If there is a contradiction in the input and it is impossible to split the given sequence $a$ into one increasing sequence and one decreasing sequence, print "NO".
-----Input-----
The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of elements in $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the $i$-th element of $a$.
-----Output-----
If there is a contradiction in the input and it is impossible to split the given sequence $a$ into one increasing sequence and one decreasing sequence, print "NO" in the first line.
Otherwise print "YES" in the first line. In the second line, print a sequence of $n$ integers $res_1, res_2, \dots, res_n$, where $res_i$ should be either $0$ or $1$ for each $i$ from $1$ to $n$. The $i$-th element of this sequence should be $0$ if the $i$-th element of $a$ belongs to the increasing sequence, and $1$ otherwise. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.
-----Examples-----
Input
9
5 1 3 6 8 2 9 0 10
Output
YES
1 0 0 0 0 1 0 1 0
Input
5
1 2 4 0 2
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Maxim always goes to the supermarket on Sundays. Today the supermarket has a special offer of discount systems.
There are m types of discounts. We assume that the discounts are indexed from 1 to m. To use the discount number i, the customer takes a special basket, where he puts exactly q_{i} items he buys. Under the terms of the discount system, in addition to the items in the cart the customer can receive at most two items from the supermarket for free. The number of the "free items" (0, 1 or 2) to give is selected by the customer. The only condition imposed on the selected "free items" is as follows: each of them mustn't be more expensive than the cheapest item out of the q_{i} items in the cart.
Maxim now needs to buy n items in the shop. Count the minimum sum of money that Maxim needs to buy them, if he use the discount system optimally well.
Please assume that the supermarket has enough carts for any actions. Maxim can use the same discount multiple times. Of course, Maxim can buy items without any discounts.
-----Input-----
The first line contains integer m (1 β€ m β€ 10^5) β the number of discount types. The second line contains m integers: q_1, q_2, ..., q_{m} (1 β€ q_{i} β€ 10^5).
The third line contains integer n (1 β€ n β€ 10^5) β the number of items Maxim needs. The fourth line contains n integers: a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 10^4) β the items' prices.
The numbers in the lines are separated by single spaces.
-----Output-----
In a single line print a single integer β the answer to the problem.
-----Examples-----
Input
1
2
4
50 50 100 100
Output
200
Input
2
2 3
5
50 50 50 50 50
Output
150
Input
1
1
7
1 1 1 1 1 1 1
Output
3
-----Note-----
In the first sample Maxim needs to buy two items that cost 100 and get a discount for two free items that cost 50. In that case, Maxim is going to pay 200.
In the second sample the best strategy for Maxim is to buy 3 items and get 2 items for free using the discount. In that case, Maxim is going to pay 150.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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're given an integer N. Write a program to calculate the sum of all the digits of N.
-----Input-----
The first line contains an integer T, the total number of testcases. Then follow T lines, each line contains an integer N.
-----Output-----
For each test case, calculate the sum of digits of N, and display it in a new line.
-----Constraints-----
- 1 β€ T β€ 1000
- 1 β€ N β€ 1000000
-----Example-----
Input
3
12345
31203
2123
Output
15
9
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.
There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.
Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.
A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.
On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.
<image>
King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.
Input
The first line contains number n, which is the number of knights at the round table (3 β€ n β€ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.
Output
Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".
Examples
Input
3
1 1 1
Output
YES
Input
6
1 0 1 1 1 0
Output
YES
Input
6
1 0 0 1 0 1
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N Snukes lining up in a row. You are given a string S of length N. The i-th Snuke from the front has two red balls if the i-th character in S is `0`; one red ball and one blue ball if the i-th character in S is `1`; two blue balls if the i-th character in S is `2`.
Takahashi has a sequence that is initially empty. Find the number of the possible sequences he may have after repeating the following procedure 2N times, modulo 998244353:
* Each Snuke who has one or more balls simultaneously chooses one of his balls and hand it to the Snuke in front of him, or hand it to Takahashi if he is the first Snuke in the row.
* Takahashi receives the ball and put it to the end of his sequence.
Constraints
* 1 \leq |S| \leq 2000
* S consists of `0`,`1` and `2`.
Note that the integer N is not directly given in input; it is given indirectly as the length of the string S.
Input
Input is given from Standard Input in the following format:
S
Output
Print the number of the possible sequences Takahashi may have after repeating the procedure 2N times, modulo 998244353.
Examples
Input
02
Output
3
Input
1210
Output
55
Input
12001021211100201020
Output
543589959
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$ of length $n$ consisting of lowercase Latin letters. You may apply some operations to this string: in one operation you can delete some contiguous substring of this string, if all letters in the substring you delete are equal. For example, after deleting substring bbbb from string abbbbaccdd we get the string aaccdd.
Calculate the minimum number of operations to delete the whole string $s$.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 500$) β the length of string $s$.
The second line contains the string $s$ ($|s| = n$) consisting of lowercase Latin letters.
-----Output-----
Output a single integer β the minimal number of operation to delete string $s$.
-----Examples-----
Input
5
abaca
Output
3
Input
8
abcddcba
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.
One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold people with the total weight of at most k kilograms.
Greg immediately took a piece of paper and listed there the weights of all people in his group (including himself). It turned out that each person weights either 50 or 100 kilograms. Now Greg wants to know what minimum number of times the boat needs to cross the river to transport the whole group to the other bank. The boat needs at least one person to navigate it from one bank to the other. As the boat crosses the river, it can have any non-zero number of passengers as long as their total weight doesn't exceed k.
Also Greg is wondering, how many ways there are to transport everybody to the other side in the minimum number of boat rides. Two ways are considered distinct if during some ride they have distinct sets of people on the boat.
Help Greg with this problem.
Input
The first line contains two integers n, k (1 β€ n β€ 50, 1 β€ k β€ 5000) β the number of people, including Greg, and the boat's weight limit. The next line contains n integers β the people's weights. A person's weight is either 50 kilos or 100 kilos.
You can consider Greg and his friends indexed in some way.
Output
In the first line print an integer β the minimum number of rides. If transporting everyone to the other bank is impossible, print an integer -1.
In the second line print the remainder after dividing the number of ways to transport the people in the minimum number of rides by number 1000000007 (109 + 7). If transporting everyone to the other bank is impossible, print integer 0.
Examples
Input
1 50
50
Output
1
1
Input
3 100
50 50 100
Output
5
2
Input
2 50
50 50
Output
-1
0
Note
In the first test Greg walks alone and consequently, he needs only one ride across the river.
In the second test you should follow the plan:
1. transport two 50 kg. people;
2. transport one 50 kg. person back;
3. transport one 100 kg. person;
4. transport one 50 kg. person back;
5. transport two 50 kg. people.
That totals to 5 rides. Depending on which person to choose at step 2, we can get two distinct ways.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Fox Ciel studies number theory.
She thinks a non-empty set S contains non-negative integers is perfect if and only if for any $a, b \in S$ (a can be equal to b), $(a \text{xor} b) \in S$. Where operation xor means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or).
Please calculate the number of perfect sets consisting of integers not greater than k. The answer can be very large, so print it modulo 1000000007 (10^9 + 7).
-----Input-----
The first line contains an integer k (0 β€ k β€ 10^9).
-----Output-----
Print a single integer β the number of required sets modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
1
Output
2
Input
2
Output
3
Input
3
Output
5
Input
4
Output
6
-----Note-----
In example 1, there are 2 such sets: {0} and {0, 1}. Note that {1} is not a perfect set since 1 xor 1 = 0 and {1} doesn't contain zero.
In example 4, there are 6 such sets: {0}, {0, 1}, {0, 2}, {0, 3}, {0, 4} and {0, 1, 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.
You are given a rooted tree of $2^n - 1$ vertices. Every vertex of this tree has either $0$ children, or $2$ children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.
The vertices of the tree are numbered in the following order:
the root has index $1$;
if a vertex has index $x$, then its left child has index $2x$, and its right child has index $2x+1$.
Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex $x$ as $s_x$.
Let the preorder string of some vertex $x$ be defined in the following way:
if the vertex $x$ is a leaf, then the preorder string of $x$ be consisting of only one character $s_x$;
otherwise, the preorder string of $x$ is $s_x + f(l_x) + f(r_x)$, where $+$ operator defines concatenation of strings, $f(l_x)$ is the preorder string of the left child of $x$, and $f(r_x)$ is the preorder string of the right child of $x$.
The preorder string of the tree is the preorder string of its root.
Now, for the problem itself...
You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree:
choose any non-leaf vertex $x$, and swap its children (so, the left child becomes the right one, and vice versa).
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 18$).
The second line contains a sequence of $2^n-1$ characters $s_1, s_2, \dots, s_{2^n-1}$. Each character is either A or B. The characters are not separated by spaces or anything else.
-----Output-----
Print one integer β the number of different strings that can be obtained as the preorder string of the given tree, if you can apply any number of operations described in the statement. Since it can be very large, print it modulo $998244353$.
-----Examples-----
Input
4
BAAAAAAAABBABAB
Output
16
Input
2
BAA
Output
1
Input
2
ABA
Output
2
Input
2
AAB
Output
2
Input
2
AAA
Output
1
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 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.
Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars.
Your task is to write a simple function that takes a number of meters, and outputs it using metric prefixes.
In practice, meters are only measured in "mm" (thousandths of a meter), "cm" (hundredths of a meter), "m" (meters) and "km" (kilometers, or clicks for the US military).
For this exercise we just want units bigger than a meter, from meters up to yottameters, excluding decameters and hectometers.
All values passed in will be positive integers.
e.g.
```python
meters(5);
// returns "5m"
meters(51500);
// returns "51.5km"
meters(5000000);
// returns "5Mm"
```
See http://en.wikipedia.org/wiki/SI_prefix for a full list of prefixes
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya plays Robot Bicorn Attack.
The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string s. Vasya decided to brag about his achievement to the friends. However, he has forgotten how many points he got for each round. The only thing he remembers is the string s.
Help Vasya to find out what is the maximum amount of points he could get. Take into account that Vasya played Robot Bicorn Attack for the first time, so he could not get more than 1000000 (106) points for one round.
Input
The only line of input contains non-empty string s obtained by Vasya. The string consists of digits only. The string length does not exceed 30 characters.
Output
Print the only number β the maximum amount of points Vasya could get. If Vasya is wrong and the string could not be obtained according to the rules then output number -1.
Examples
Input
1234
Output
37
Input
9000
Output
90
Input
0009
Output
-1
Note
In the first example the string must be split into numbers 1, 2 and 34.
In the second example the string must be split into numbers 90, 0 and 0.
In the third example the string is incorrect, because after splitting the string into 3 numbers number 00 or 09 will be obtained, but numbers cannot have leading zeroes.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
|
Solve the programming task below in a Python markdown code block.
A super computer has been built in the Turtle Academy of Sciences. The computer consists of nΒ·mΒ·k CPUs. The architecture was the paralellepiped of size n Γ m Γ k, split into 1 Γ 1 Γ 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k.
In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x, y, z) can send messages to CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) (of course, if they exist), there is no feedback, that is, CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) cannot send messages to CPU (x, y, z).
Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a, b, c) controls CPU (d, e, f) , if there is a chain of CPUs (x_{i}, y_{i}, z_{i}), such that (x_1 = a, y_1 = b, z_1 = c), (x_{p} = d, y_{p} = e, z_{p} = f) (here and below p is the length of the chain) and the CPU in the chain with number i (i < p) can send messages to CPU i + 1.
Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x, y, z) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x, y, z) CPUs: (a, b, c) and (d, e, f), such that (a, b, c) controls (d, e, f) before (x, y, z) is turned off and stopped controlling it after the turning off.
-----Input-----
The first line contains three integers n, m and k (1 β€ n, m, k β€ 100)Β β the dimensions of the Super Computer.
Then n blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to n. Each block consists of m lines, k characters in each β the description of a layer in the format of an m Γ k table. Thus, the state of the CPU (x, y, z) is corresponded to the z-th character of the y-th line of the block number x. Character "1" corresponds to a working CPU and character "0" corresponds to a malfunctioning one. The blocks are separated by exactly one empty line.
-----Output-----
Print a single integer β the number of critical CPUs, that is, such that turning only this CPU off will disrupt some control.
-----Examples-----
Input
2 2 3
000
000
111
111
Output
2
Input
3 3 3
111
111
111
111
111
111
111
111
111
Output
19
Input
1 1 10
0101010101
Output
0
-----Note-----
In the first sample the whole first layer of CPUs is malfunctional. In the second layer when CPU (2, 1, 2) turns off, it disrupts the control by CPU (2, 1, 3) over CPU (2, 1, 1), and when CPU (2, 2, 2) is turned off, it disrupts the control over CPU (2, 2, 3) by CPU (2, 2, 1).
In the second sample all processors except for the corner ones are critical.
In the third sample there is not a single processor controlling another processor, so the answer is 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n Γ m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.
They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.
What is the maximum number of little pigs that may be eaten by the wolves?
Input
The first line contains integers n and m (1 β€ n, m β€ 10) which denotes the number of rows and columns in our two-dimensional grid, respectively. Then follow n lines containing m characters each β that is the grid description. "." means that this cell is empty. "P" means that this cell contains a little pig. "W" means that this cell contains a wolf.
It is guaranteed that there will be at most one wolf adjacent to any little pig.
Output
Print a single number β the maximal number of little pigs that may be eaten by the wolves.
Examples
Input
2 3
PPW
W.P
Output
2
Input
3 3
P.W
.P.
W.P
Output
0
Note
In the first example, one possible scenario in which two little pigs get eaten by the wolves is as follows.
<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.
In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifierΒ β an integer from 1 to 10^9.
At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier.
Your task is to determine the k-th identifier to be pronounced.
-----Input-----
The first line contains two positive integers n and k (1 β€ n β€ 100 000, 1 β€ k β€ min(2Β·10^9, nΒ·(n + 1) / 2).
The second line contains the sequence id_1, id_2, ..., id_{n} (1 β€ id_{i} β€ 10^9)Β β identifiers of roborts. It is guaranteed that all identifiers are different.
-----Output-----
Print the k-th pronounced identifier (assume that the numeration starts from 1).
-----Examples-----
Input
2 2
1 2
Output
1
Input
4 5
10 4 18 3
Output
4
-----Note-----
In the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As k = 2, the answer equals to 1.
In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As k = 5, the answer equals to 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.
Check if given chord is minor or major.
_____________________________________________________________
Rules:
1. Basic minor/major chord have three elements.
2. Chord is minor when interval between first and second element equals 3 and between second and third -> 4.
3. Chord is major when interval between first and second element equals 4 and between second and third -> 3.
4. In minor/major chord interval between first and third element equals... 7.
_______________________________________________________________
There is a preloaded list of the 12 notes of a chromatic scale built on C. This means that there are (almost) all allowed note' s names in music.
notes =
['C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G', ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B']
Note that e. g. 'C#' - 'C' = 1, 'C' - 'C#' = 1, 'Db' - 'C' = 1 and 'B' - 'C' = 1.
Input:
String of notes separated by whitespace, e. g. 'A C# E'
Output:
String message: 'Minor', 'Major' or 'Not a chord'.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp has n dice d_1, d_2, ..., d_{n}. The i-th dice shows numbers from 1 to d_{i}. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d_1, d_2, ..., d_{n}. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).
For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.
-----Input-----
The first line contains two integers n, A (1 β€ n β€ 2Β·10^5, n β€ A β€ s) β the number of dice and the sum of shown values where s = d_1 + d_2 + ... + d_{n}.
The second line contains n integers d_1, d_2, ..., d_{n} (1 β€ d_{i} β€ 10^6), where d_{i} is the maximum value that the i-th dice can show.
-----Output-----
Print n integers b_1, b_2, ..., b_{n}, where b_{i} is the number of values for which it is guaranteed that the i-th dice couldn't show them.
-----Examples-----
Input
2 8
4 4
Output
3 3
Input
1 3
5
Output
4
Input
2 3
2 3
Output
0 1
-----Note-----
In the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.
In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.
In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a factory that inputs the data of the side and diagonal lengths to the machine and cuts out the plastic plate. At this factory, we cut out only parallelogram molds, although they vary in size. You have been ordered by your boss to count the number of rectangles and rhombuses produced among the parallelograms that are cut out.
Create a program that reads "Data to be input to the machine" and outputs the number of rectangles and diamonds manufactured.
<image>
Input
The input is given in the following format:
a1, b1, c1
a2, b2, c2
::
The data to be entered into the machine is given in multiple lines. On line i, the integers ai, bi, which represent the lengths of two adjacent sides of the i-th parallelogram, and the integer ci, which represents the length of the diagonal, are given, separated by commas (1 β€ ai, bi, ci β€ 1000). , ai + bi> ci). The number of data does not exceed 100.
Output
The first line outputs the number of rectangles manufactured, and the second line outputs the number of diamonds manufactured.
Example
Input
3,4,5
5,5,8
4,4,4
5,4,3
Output
1
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:
<image>
A swap operation is the following sequence of actions:
* choose two indexes i, j (i β j);
* perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp.
What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?
Input
The first line contains two integers n and k (1 β€ n β€ 200; 1 β€ k β€ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 β€ a[i] β€ 1000).
Output
In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.
Examples
Input
10 2
10 -1 2 2 2 2 2 2 -1 10
Output
32
Input
5 10
-1 -1 -1 -1 -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 have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.
Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:
- Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.
- Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.
- Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)
At least how much MP is needed to achieve the objective?
-----Constraints-----
- 3 \leq N \leq 8
- 1 \leq C < B < A \leq 1000
- 1 \leq l_i \leq 1000
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N A B C
l_1
l_2
:
l_N
-----Output-----
Print the minimum amount of MP needed to achieve the objective.
-----Sample Input-----
5 100 90 80
98
40
30
21
80
-----Sample Output-----
23
We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.
- Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)
- Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)
- Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)
- Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ayrat has number n, represented as it's prime factorization p_{i} of size m, i.e. n = p_1Β·p_2Β·...Β·p_{m}. Ayrat got secret information that that the product of all divisors of n taken modulo 10^9 + 7 is the password to the secret data base. Now he wants to calculate this value.
-----Input-----
The first line of the input contains a single integer m (1 β€ m β€ 200 000)Β β the number of primes in factorization of n.
The second line contains m primes numbers p_{i} (2 β€ p_{i} β€ 200 000).
-----Output-----
Print one integerΒ β the product of all divisors of n modulo 10^9 + 7.
-----Examples-----
Input
2
2 3
Output
36
Input
3
2 3 2
Output
1728
-----Note-----
In the first sample n = 2Β·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1Β·2Β·3Β·6 = 36.
In the second sample 2Β·3Β·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1Β·2Β·3Β·4Β·6Β·12 = 1728.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.
-----Input-----
The first line of the input contains an integer n (1 β€ n β€ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesnβt exceed 100.
-----Output-----
For each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 canβt recognize whose sentence it is. He canβt recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions.
-----Examples-----
Input
5
I will go to play with you lala.
wow, welcome.
miao.lala.
miao.
miao .
Output
Freda's
OMG>.< I don't know!
OMG>.< I don't know!
Rainbow's
OMG>.< I don't know!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 A and B.
Find the largest value among A+B, A-B and A \times B.
-----Constraints-----
- -1000 \leq A,B \leq 1000
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
Print the largest value among A+B, A-B and A \times B.
-----Sample Input-----
3 1
-----Sample Output-----
4
3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number x to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals x?
If the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket.
Initially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number 0, the second integer takes number 1 and so on.
Misha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him.
-----Input-----
The first line contains number m (1 β€ m β€ 2000), showing how many numbers are scattered around the room.
The next m lines contain the numbers in the order in which the robot puts them in the basket. Each number is a positive integer strictly less than 10^600 that doesn't contain leading zeroes.
-----Output-----
For each number either print a 0 on the corresponding line, if the number cannot be represented as a XOR sum of numbers that are in the basket, or print integer k showing how many numbers are in the representation and the indexes of these numbers. Separate the numbers by spaces. Each number can occur in the representation at most once.
-----Examples-----
Input
7
7
6
5
4
3
2
1
Output
0
0
0
3 0 1 2
2 1 2
2 0 2
2 0 1
Input
2
5
5
Output
0
1 0
-----Note-----
The XOR sum of numbers is the result of bitwise sum of numbers modulo 2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can permute it so that it becomes [20, 40, 10, 30]. Then on the first and the second positions the integers became larger (20>10, 40>20) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals 2. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the length of the array.
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9) β the elements of the array.
Output
Print a single integer β the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
Examples
Input
7
10 1 1 1 5 5 3
Output
4
Input
5
1 1 1 1 1
Output
0
Note
In the first sample, one of the best permutations is [1, 5, 5, 3, 10, 1, 1]. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a program that reads the sales unit price and sales quantity and outputs the total sales amount and the average sales quantity.
Input
The input is given in the following format:
Sales unit price, sales quantity
Sales unit price, sales quantity
::
::
A comma-separated pair of unit price and quantity is given across multiple lines. All values ββentered are greater than or equal to 0 and less than or equal to 1,000, and the number of unit price and quantity pairs does not exceed 100.
Output
Please output the total sales amount (integer) on the first line and the average sales quantity (integer) on the second line. If the average sales volume has a fraction (number after the decimal point), round off to the first decimal place.
Example
Input
100,20
50,10
70,35
Output
4950
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.
Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).
Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)
Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.
Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.
-----Notes-----
When you print a rational number, first write it as a fraction \frac{y}{x}, where x, y are integers, and x is not divisible by 10^9 + 7
(under the constraints of the problem, such representation is always possible).
Then, you need to print the only integer z between 0 and 10^9 + 6, inclusive, that satisfies xz \equiv y \pmod{10^9 + 7}.
-----Constraints-----
- 2 \leq N \leq 2 \times 10^5
- 1 \leq A_i,B_i \leq N
- The given graph is a tree.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 B_1
:
A_{N-1} B_{N-1}
-----Output-----
Print the expected holeyness of S, \bmod 10^9+7.
-----Sample Input-----
3
1 2
2 3
-----Sample Output-----
125000001
If the vertices 1, 2, 3 are painted black, white, black, respectively, the holeyness of S is 1.
Otherwise, the holeyness is 0, so the expected holeyness is 1/8.
Since 8 \times 125000001 \equiv 1 \pmod{10^9+7}, we should print 125000001.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Last summer Peter was at his granny's in the country, when a wolf attacked sheep in the nearby forest. Now he fears to walk through the forest, to walk round the forest, even to get out of the house. He explains this not by the fear of the wolf, but by a strange, in his opinion, pattern of the forest that has n levels, where n is an even number.
In the local council you were given an area map, where the granny's house is marked by point H, parts of dense forest are marked grey (see the picture to understand better).
After a long time at home Peter decided to yield to his granny's persuasions and step out for a breath of fresh air. Being prudent, Peter plans the route beforehand. The route, that Peter considers the most suitable, has the following characteristics:
* it starts and ends in the same place β the granny's house;
* the route goes along the forest paths only (these are the segments marked black in the picture);
* the route has positive length (to step out for a breath of fresh air Peter has to cover some distance anyway);
* the route cannot cross itself;
* there shouldn't be any part of dense forest within the part marked out by this route;
You should find the amount of such suitable oriented routes modulo 1000000009.
<image>
The example of the area map for n = 12 is given in the picture. Since the map has a regular structure, you can construct it for other n by analogy using the example.
Input
The input data contain the only even integer n (2 β€ n β€ 106).
Output
Output the only number β the amount of Peter's routes modulo 1000000009.
Examples
Input
2
Output
10
Input
4
Output
74
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alex is transitioning from website design to coding and wants to sharpen his skills with CodeWars.
He can do ten kata in an hour, but when he makes a mistake, he must do pushups. These pushups really tire poor Alex out, so every time he does them they take twice as long. His first set of redemption pushups takes 5 minutes. Create a function, `alexMistakes`, that takes two arguments: the number of kata he needs to complete, and the time in minutes he has to complete them. Your function should return how many mistakes Alex can afford to make.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 2^0, 2^1 and 2^2 respectively.
Calculate the answer for t values of n.
-----Input-----
The first line of the input contains a single integer t (1 β€ t β€ 100) β the number of values of n to be processed.
Each of next t lines contains a single integer n (1 β€ n β€ 10^9).
-----Output-----
Print the requested sum for each of t integers n given in the input.
-----Examples-----
Input
2
4
1000000000
Output
-4
499999998352516354
-----Note-----
The answer for the first sample is explained in the statement.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didnβt make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.
Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.
Input
The first line contains one integer N (1 β€ N β€ 1000) β the number of words in Old Berland language. The second line contains N space-separated integers β the lengths of these words. All the lengths are natural numbers not exceeding 1000.
Output
If thereβs no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next N lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any.
Examples
Input
3
1 2 3
Output
YES
0
10
110
Input
3
1 1 1
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Introduction and Warm-up (Highly recommended)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
___
# Task
**_Given_** an *array/list [] of integers* , **_Find_** **_The maximum difference_** *between the successive elements in its sorted form*.
___
# Notes
* **_Array/list_** size is *at least 3* .
* **_Array/list's numbers_** Will be **mixture of positives and negatives also zeros_**
* **_Repetition_** of numbers in *the array/list could occur*.
* **_The Maximum Gap_** is *computed Regardless the sign*.
___
# Input >> Output Examples
```
maxGap ({13,10,5,2,9}) ==> return (4)
```
## **_Explanation_**:
* **_The Maximum Gap_** *after sorting the array is* `4` , *The difference between* ``` 9 - 5 = 4 ``` .
___
```
maxGap ({-3,-27,-4,-2}) ==> return (23)
```
## **_Explanation_**:
* **_The Maximum Gap_** *after sorting the array is* `23` , *The difference between* ` |-4- (-27) | = 23` .
* **_Note_** : *Regardless the sign of negativity* .
___
```
maxGap ({-7,-42,-809,-14,-12}) ==> return (767)
```
## **_Explanation_**:
* **_The Maximum Gap_** *after sorting the array is* `767` , *The difference between* ` | -809- (-42) | = 767` .
* **_Note_** : *Regardless the sign of negativity* .
___
```
maxGap ({-54,37,0,64,640,0,-15}) //return (576)
```
## **_Explanation_**:
* **_The Maximum Gap_** *after sorting the array is* `576` , *The difference between* ` | 64 - 640 | = 576` .
* **_Note_** : *Regardless the sign of negativity* .
___
___
___
# [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
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = $2$, b = $3$ changes the value of a to $5$ (the value of b does not change).
In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $n$. What is the smallest number of operations he has to perform?
-----Input-----
The first line contains a single integer $T$ ($1 \leq T \leq 100$)Β β the number of test cases.
Each of the following $T$ lines describes a single test case, and contains three integers $a, b, n$ ($1 \leq a, b \leq n \leq 10^9$)Β β initial values of a and b, and the value one of the variables has to exceed, respectively.
-----Output-----
For each test case print a single integerΒ β the smallest number of operations needed. Separate answers with line breaks.
-----Example-----
Input
2
1 2 3
5 4 100
Output
2
7
-----Note-----
In the first case we cannot make a variable exceed $3$ in one operation. One way of achieving this in two operations is to perform "b += a" twice.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a sorted array $a_1, a_2, \dots, a_n$ (for each index $i > 1$ condition $a_i \ge a_{i-1}$ holds) and an integer $k$.
You are asked to divide this array into $k$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.
Let $max(i)$ be equal to the maximum in the $i$-th subarray, and $min(i)$ be equal to the minimum in the $i$-th subarray. The cost of division is equal to $\sum\limits_{i=1}^{k} (max(i) - min(i))$. For example, if $a = [2, 4, 5, 5, 8, 11, 19]$ and we divide it into $3$ subarrays in the following way: $[2, 4], [5, 5], [8, 11, 19]$, then the cost of division is equal to $(4 - 2) + (5 - 5) + (19 - 8) = 13$.
Calculate the minimum cost you can obtain by dividing the array $a$ into $k$ non-empty consecutive subarrays.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 3 \cdot 10^5$).
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($ 1 \le a_i \le 10^9$, $a_i \ge a_{i-1}$).
-----Output-----
Print the minimum cost you can obtain by dividing the array $a$ into $k$ nonempty consecutive subarrays.
-----Examples-----
Input
6 3
4 8 15 16 23 42
Output
12
Input
4 4
1 3 3 7
Output
0
Input
8 1
1 1 2 3 5 8 13 21
Output
20
-----Note-----
In the first test we can divide array $a$ in the following way: $[4, 8, 15, 16], [23], [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.
Alice is playing a game with her good friend, Marisa.
There are n boxes arranged in a line, numbered with integers from 1 to n from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have m chances to guess where the doll is. If Alice will correctly guess the number of box, where doll is now, she will win the game, otherwise, her friend will win the game.
In order to win, Marisa will use some unfair tricks. After each time Alice guesses a box, she can move the doll to the neighboring box or just keep it at its place. Boxes i and i + 1 are neighboring for all 1 β€ i β€ n - 1. She can also use this trick once before the game starts.
So, the game happens in this order: the game starts, Marisa makes the trick, Alice makes the first guess, Marisa makes the trick, Alice makes the second guess, Marisa makes the trick, β¦, Alice makes m-th guess, Marisa makes the trick, the game ends.
Alice has come up with a sequence a_1, a_2, β¦, a_m. In the i-th guess, she will ask if the doll is in the box a_i. She wants to know the number of scenarios (x, y) (for all 1 β€ x, y β€ n), such that Marisa can win the game if she will put the doll at the x-th box at the beginning and at the end of the game, the doll will be at the y-th box. Help her and calculate this number.
Input
The first line contains two integers n and m, separated by space (1 β€ n, m β€ 10^5) β the number of boxes and the number of guesses, which Alice will make.
The next line contains m integers a_1, a_2, β¦, a_m, separated by spaces (1 β€ a_i β€ n), the number a_i means the number of the box which Alice will guess in the i-th guess.
Output
Print the number of scenarios in a single line, or the number of pairs of boxes (x, y) (1 β€ x, y β€ n), such that if Marisa will put the doll into the box with number x, she can make tricks in such way, that at the end of the game the doll will be in the box with number y and she will win the game.
Examples
Input
3 3
2 2 2
Output
7
Input
5 2
3 1
Output
21
Note
In the first example, the possible scenarios are (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3).
Let's take (2, 2) as an example. The boxes, in which the doll will be during the game can be 2 β 3 β 3 β 3 β 2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Ancient Berland there were n cities and m two-way roads of equal length. The cities are numbered with integers from 1 to n inclusively. According to an ancient superstition, if a traveller visits three cities ai, bi, ci in row, without visiting other cities between them, a great disaster awaits him. Overall there are k such city triplets. Each triplet is ordered, which means that, for example, you are allowed to visit the cities in the following order: ai, ci, bi. Vasya wants to get from the city 1 to the city n and not fulfil the superstition. Find out which minimal number of roads he should take. Also you are required to find one of his possible path routes.
Input
The first line contains three integers n, m, k (2 β€ n β€ 3000, 1 β€ m β€ 20000, 0 β€ k β€ 105) which are the number of cities, the number of roads and the number of the forbidden triplets correspondingly.
Then follow m lines each containing two integers xi, yi (1 β€ xi, yi β€ n) which are the road descriptions. The road is described by the numbers of the cities it joins. No road joins a city with itself, there cannot be more than one road between a pair of cities.
Then follow k lines each containing three integers ai, bi, ci (1 β€ ai, bi, ci β€ n) which are the forbidden triplets. Each ordered triplet is listed mo more than one time. All three cities in each triplet are distinct.
City n can be unreachable from city 1 by roads.
Output
If there are no path from 1 to n print -1. Otherwise on the first line print the number of roads d along the shortest path from the city 1 to the city n. On the second line print d + 1 numbers β any of the possible shortest paths for Vasya. The path should start in the city 1 and end in the city n.
Examples
Input
4 4 1
1 2
2 3
3 4
1 3
1 4 3
Output
2
1 3 4
Input
3 1 0
1 2
Output
-1
Input
4 4 2
1 2
2 3
3 4
1 3
1 2 3
1 3 4
Output
4
1 3 2 3 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.
Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):
- In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.
Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)
-----Constraints-----
- 2 \leq N \leq 5000
- 1 \leq K \leq 10^9
- 1 \leq P_i \leq N
- P_i \neq i
- P_1, P_2, \cdots, P_N are all different.
- -10^9 \leq C_i \leq 10^9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N
-----Output-----
Print the maximum possible score at the end of the game.
-----Sample Input-----
5 2
2 4 5 1 3
3 4 -10 -8 8
-----Sample Output-----
8
When we start at some square of our choice and make at most two moves, we have the following options:
- If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.
- If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.
- If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.
- If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.
- If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.
The maximum score achieved is 8.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have initially a string of N characters, denoted by A1,A2...AN. You have to print the size of the largest subsequence of string A such that all the characters in that subsequence are distinct ie. no two characters in that subsequence should be same.
A subsequence of string A is a sequence that can be derived from A by deleting some elements and without changing the order of the remaining elements.
-----Input-----
First line contains T, number of testcases. Each testcase consists of a single string in one line. Each character of the string will be a small alphabet(ie. 'a' to 'z').
-----Output-----
For each testcase, print the required answer in one line.
-----Constraints-----
- 1 β€ T β€ 10
- Subtask 1 (20 points):1 β€ N β€ 10
- Subtask 2 (80 points):1 β€ N β€ 105
-----Example-----
Input:
2
abc
aba
Output:
3
2
-----Explanation-----
For first testcase, the whole string is a subsequence which has all distinct characters.
In second testcase, the we can delete last or first 'a' to get the required subsequence.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row.
Because of the noise, you only heard part of the answer β some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.
Determine if it is true that the given string $s$ is a substring of YesYesYes... (Yes repeated many times in a row).
-----Input-----
The first line of input data contains the singular $t$ ($1 \le t \le 1000$) β the number of test cases in the test.
Each test case is described by a single string of Latin letters $s$ ($1 \le |s| \le 50$) β the part of Polycarp's answer that you heard, where $|s|$ β is the length of the string $s$.
-----Output-----
Output $t$ lines, each of which is the answer to the corresponding test case. As an answer, output "YES" if the specified string $s$ is a substring of the string YesYesYes...Yes (the number of words Yes is arbitrary), and "NO" otherwise.
You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
-----Examples-----
Input
12
YES
esYes
codeforces
es
se
YesY
esYesYesYesYesYesYe
seY
Yess
sY
o
Yes
Output
NO
YES
NO
YES
NO
YES
YES
NO
NO
YES
NO
YES
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.
You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.
-----Input-----
The first line of input contains integer n denoting the number of psychos, (1 β€ n β€ 10^5). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β ids of the psychos in the line from left to right.
-----Output-----
Print the number of steps, so that the line remains the same afterward.
-----Examples-----
Input
10
10 9 7 8 6 5 3 4 2 1
Output
2
Input
6
1 2 3 4 5 6
Output
0
-----Note-----
In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] β [10 8 4] β [10]. So, there are two steps.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Matsudaira is always careful about eco-friendliness in his life. Last month's water charge was 4280 yen, which exceeded the usual target of 4000 yen, so we have been trying to save water this month. How much have you saved on your water bill compared to last month?
Enter this month's water usage w [m3] and create a program that outputs how much water charges you have saved compared to last month's water charges of 4280 yen.
The water charge is calculated as follows.
(Water charge) = (Basic charge) + (Charge based on water volume)
The charge based on the amount of water is calculated according to the amount used as shown in the table below.
Stage | Water volume | Price
--- | --- | ---
1st stage charge | Up to 10 [m3] | Basic charge 1150 yen
Second stage fee | 10 [m3] Excess up to 20 [m3] | 125 yen per [m3]
Third stage charge | 20 [m3] Excess up to 30 [m3] | 140 yen per [m3]
4th stage charge | 30 [m3] excess | 160 yen per [m3]
For example, if the amount of water used is 40 [m3], the basic charge is 1150 yen (1st stage) + 10 [m3] x 125 yen (2nd stage) + 10 [m3] x 140 yen (3rd stage) + 10 [ m3] x 160 yen (4th stage) = 5400 yen.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of -1.
For each dataset, an integer w (0 β€ w β€ 100) representing the amount of water used this month is given on one line.
The number of datasets does not exceed 200.
Output
For each input dataset, the difference from last month's water charges is output on one line.
Example
Input
29
40
0
-1
Output
620
-1120
3130
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.
Input
The first line contains integers n and k β the number and digit capacity of numbers correspondingly (1 β€ n, k β€ 8). Next n lines contain k-digit positive integers. Leading zeroes are allowed both in the initial integers and the integers resulting from the rearranging of digits.
Output
Print a single number: the minimally possible difference between the largest and the smallest number after the digits are rearranged in all integers by the same rule.
Examples
Input
6 4
5237
2753
7523
5723
5327
2537
Output
2700
Input
3 3
010
909
012
Output
3
Input
7 5
50808
36603
37198
44911
29994
42543
50156
Output
20522
Note
In the first sample, if we rearrange the digits in numbers as (3,1,4,2), then the 2-nd and the 4-th numbers will equal 5237 and 2537 correspondingly (they will be maximum and minimum for such order of digits).
In the second sample, if we swap the second digits and the first ones, we get integers 100, 99 and 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.
Let's consider all integers in the range from $1$ to $n$ (inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $\mathrm{gcd}(a, b)$, where $1 \leq a < b \leq n$.
The greatest common divisor, $\mathrm{gcd}(a, b)$, of two positive integers $a$ and $b$ is the biggest integer that is a divisor of both $a$ and $b$.
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 100$) Β β the number of test cases. The description of the test cases follows.
The only line of each test case contains a single integer $n$ ($2 \leq n \leq 10^6$).
-----Output-----
For each test case, output the maximum value of $\mathrm{gcd}(a, b)$ among all $1 \leq a < b \leq n$.
-----Example-----
Input
2
3
5
Output
1
2
-----Note-----
In the first test case, $\mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1$.
In the second test case, $2$ is the maximum possible value, corresponding to $\mathrm{gcd}(2, 4)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bamboo Blossoms
The bamboos live for decades, and at the end of their lives, they flower to make their seeds. Dr. ACM, a biologist, was fascinated by the bamboos in blossom in his travel to Tsukuba. He liked the flower so much that he was tempted to make a garden where the bamboos bloom annually. Dr. ACM started research of improving breed of the bamboos, and finally, he established a method to develop bamboo breeds with controlled lifetimes. With this method, he can develop bamboo breeds that flower after arbitrarily specified years.
Let us call bamboos that flower k years after sowing "k-year-bamboos." k years after being sowed, k-year-bamboos make their seeds and then die, hence their next generation flowers after another k years. In this way, if he sows seeds of k-year-bamboos, he can see bamboo blossoms every k years. For example, assuming that he sows seeds of 15-year-bamboos, he can see bamboo blossoms every 15 years; 15 years, 30 years, 45 years, and so on, after sowing.
Dr. ACM asked you for designing his garden. His garden is partitioned into blocks, in each of which only a single breed of bamboo can grow. Dr. ACM requested you to decide which breeds of bamboos should he sow in the blocks in order to see bamboo blossoms in at least one block for as many years as possible.
You immediately suggested to sow seeds of one-year-bamboos in all blocks. Dr. ACM, however, said that it was difficult to develop a bamboo breed with short lifetime, and would like a plan using only those breeds with long lifetimes. He also said that, although he could wait for some years until he would see the first bloom, he would like to see it in every following year. Then, you suggested a plan to sow seeds of 10-year-bamboos, for example, in different blocks each year, that is, to sow in a block this year and in another block next year, and so on, for 10 years. Following this plan, he could see bamboo blossoms in one block every year except for the first 10 years. Dr. ACM objected again saying he had determined to sow in all blocks this year.
After all, you made up your mind to make a sowing plan where the bamboos bloom in at least one block for as many consecutive years as possible after the first m years (including this year) under the following conditions:
* the plan should use only those bamboo breeds whose lifetimes are m years or longer, and
* Dr. ACM should sow the seeds in all the blocks only this year.
Input
The input consists of at most 50 datasets, each in the following format.
m n
An integer m (2 β€ m β€ 100) represents the lifetime (in years) of the bamboos with the shortest lifetime that Dr. ACM can use for gardening. An integer n (1 β€ n β€ 500,000) represents the number of blocks.
The end of the input is indicated by a line containing two zeros.
Output
No matter how good your plan is, a "dull-year" would eventually come, in which the bamboos do not flower in any block. For each dataset, output in a line an integer meaning how many years from now the first dull-year comes after the first m years.
Note that the input of m = 2 and n = 500,000 (the last dataset of the Sample Input) gives the largest answer.
Sample Input
3 1
3 4
10 20
100 50
2 500000
0 0
Output for the Sample Input
4
11
47
150
7368791
Example
Input
3 1
3 4
10 20
100 50
2 500000
0 0
Output
4
11
47
150
7368791
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.
When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).
In how many ways can the knight reach the square (X, Y)?
Find the number of ways modulo 10^9 + 7.
-----Constraints-----
- 1 \leq X \leq 10^6
- 1 \leq Y \leq 10^6
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
X Y
-----Output-----
Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.
-----Sample Input-----
3 3
-----Sample Output-----
2
There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy.
The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is 12345. After that one should write her favorite digit from 0 to 9 under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is 9. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to (2 + 9) / 2 = 5.5. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit 5. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is (5 + 3) / 2 = 4. In this case the answer is unique. Thus, every i-th digit is determined as an arithmetic average of the i-th digit of Masha's number and the i - 1-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get:
12345 95444 Unfortunately, when Masha tried dialing the number, she got disappointed: as it turned out, the number was unavailable or outside the coverage area. But Masha won't give up. Perhaps, she rounded to a wrong digit or chose the first digit badly. That's why she keeps finding more and more new numbers and calling them. Count the number of numbers Masha calls. Masha calls all the possible numbers that can be found by the described means of arithmancy, except for, perhaps, her own one.
Input
The first line contains nonempty sequence consisting of digits from 0 to 9 β Masha's phone number. The sequence length does not exceed 50.
Output
Output the single number β the number of phone numbers Masha will dial.
Examples
Input
12345
Output
48
Input
09
Output
15
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
I am a craftsman specialized in interior works. A customer asked me to perform wiring work on a wall whose entire rectangular surface is tightly pasted with pieces of panels. The panels are all of the same size (2 m in width, 1 m in height) and the wall is filled with an x (horizontal) by y (vertical) array of the panels. The customer asked me to stretch a wire from the left top corner of the wall to the right bottom corner whereby the wire is tied up at the crossing points with the panel boundaries (edges and vertexes) as shown in the figure. There are nine tied-up points in the illustrative figure shown below.
<image>
Fig: The wire is tied up at the edges and vertexes of the panels (X: 4 panels, Y: 6 panels)
Write a program to provide the number of points where the wire intersects with the panel boundaries. Assume that the wire and boundary lines have no thickness.
Input
The input is given in the following format.
x y
A line of data is given that contains the integer number of panels in the horizontal direction x (1 β€ x β€ 1000) and those in the vertical direction y (1 β€ y β€ 1000).
Output
Output the number of points where the wire intersects with the panel boundaries.
Examples
Input
4 4
Output
5
Input
4 6
Output
9
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A rabbit who came to the fair found that the prize for a game at a store was a carrot cake. The rules for this game are as follows.
There is a grid-like field of vertical h squares x horizontal w squares, and each block has at most one block. Each block is a color represented by one of the uppercase letters ('A'-'Z'). When n or more blocks of the same color are lined up in a straight line vertically or horizontally, those blocks disappear.
Participants can select two adjacent cells next to each other and switch their states to each other. When blocks are exchanged, disappeared, or dropped and there are no blocks in the cell below the cell with the block, this block At this time, it disappears when n or more blocks of the same color are lined up again. However, the disappearance of the blocks does not occur while the falling blocks exist, and occurs at the same time when all the blocks have finished falling.
If you eliminate all the blocks on the field with one operation, this game will be successful and you will get a free gift cake. Rabbit wants to get the cake with one entry fee, can not do it If you don't want to participate. From the state of the field at the beginning of the game, answer if the rabbit should participate in this game.
Input
The first line of input is given h, w, n separated by spaces.
2 β€ h, w, n β€ 30
In the following h lines, the state of the field is given in order from the top. Uppercase letters represent blocks, and'.' Represents an empty space. The state of the given field is n or more consecutive blocks of the same color in the vertical or horizontal direction. No, no blocks are in a falling state. There is one or more blocks.
Output
Output "YES" if the rabbit should participate in this game, otherwise output "NO" on one line.
Examples
Input
4 6 3
......
...Y..
...Y..
RRYRYY
Output
YES
Input
4 6 3
......
...Y..
...Y..
RRYRY.
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.
Given an array, return the difference between the count of even numbers and the count of odd numbers. `0` will be considered an even number.
```
For example:
solve([0,1,2,3]) = 0 because there are two even numbers and two odd numbers. Even - Odd = 2 - 2 = 0.
```
Let's now add two letters to the last example:
```
solve([0,1,2,3,'a','b']) = 0. Again, Even - Odd = 2 - 2 = 0. Ignore letters.
```
The input will be an array of lowercase letters and numbers only.
In some languages (Haskell, C++, and others), input will be an array of strings:
```
solve ["0","1","2","3","a","b"] = 0
```
Good luck!
If you like this Kata, please try:
[Longest vowel chain](https://www.codewars.com/kata/59c5f4e9d751df43cf000035)
[Word values](https://www.codewars.com/kata/598d91785d4ce3ec4f000018)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:
- Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.
For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?
-----Constraints-----
- S is a string of length between 1 and 100 (inclusive).
- K is an integer between 1 and 10^{18} (inclusive).
- The length of the string after 5 \times 10^{15} days is at least K.
-----Input-----
Input is given from Standard Input in the following format:
S
K
-----Output-----
Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.
-----Sample Input-----
1214
4
-----Sample Output-----
2
The string S changes as follows:
- Now: 1214
- After one day: 12214444
- After two days: 1222214444444444444444
- After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444
The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
_This kata is based on [Project Euler Problem 546](https://projecteuler.net/problem=546)_
# Objective
Given the recursive sequence
fk(n) =
β
i
=
0
n
fk(floor(i / k)) where fk(0) = 1
Define a function `f` that takes arguments `k` and `n` and returns the nth term in the sequence fk
## Examples
`f(2, 3)` = f2(3) = 6
`f(2, 200)` = f2(200) = 7389572
`f(7, 500)` = f7(500) = 74845
`f(1000, 0)` = f1000(0) = 1
**Note:**
No error checking is needed, `k` ranges from 2 to 100 and `n` ranges between 0 and 500000 (mostly small and medium values with a few large ones)
As always any feedback would be much appreciated
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.
Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j].
There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.
If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.
-----Input-----
The first line of the input contains two integers n and m (3 β€ n, m β€ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 β€ a[i][j] β€ 10^5).
-----Output-----
The output contains a single number β the maximum total gain possible.
-----Examples-----
Input
3 3
100 100 100
100 1 100
100 100 100
Output
800
-----Note-----
Iahub will choose exercises a[1][1] β a[1][2] β a[2][2] β a[3][2] β a[3][3]. Iahubina will choose exercises a[3][1] β a[2][1] β a[2][2] β a[2][3] β a[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.
Write a simple regex to validate a username. Allowed characters are:
- lowercase letters,
- numbers,
- underscore
Length should be between 4 and 16 characters (both included).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.
Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race.
-----Input-----
The first line contains two integer numbers $N$ ($1 \leq N \leq 200000$) representing number of F1 astronauts, and current position of astronaut $D$ ($1 \leq D \leq N$) you want to calculate best ranking for (no other competitor will have the same number of points before the race).
The second line contains $N$ integer numbers $S_k$ ($0 \leq S_k \leq 10^8$, $k=1...N$), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order.
The third line contains $N$ integer numbers $P_k$ ($0 \leq P_k \leq 10^8$, $k=1...N$), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points.
-----Output-----
Output contains one integer number β the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking.
-----Example-----
Input
4 3
50 30 20 10
15 10 7 3
Output
2
-----Note-----
If the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Oranges on Cans
square1001 You put a $ N $ can of aluminum on the table.
E869120 You put $ M $ of oranges on each aluminum can on the table.
How many oranges are on the aluminum can?
input
Input is given from standard input in the following format.
$ N $ $ M $
output
Output the number of oranges on the aluminum can in one line.
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 9 $
* $ 1 \ leq M \ leq 9 $
* All inputs are integers.
Input example 1
3 4
Output example 1
12
Input example 2
7 7
Output example 2
49
Example
Input
3 4
Output
12
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i. Here, h_1 < h_2 < \cdots < h_N holds.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, N. Here, a cost of (h_j - h_i)^2 + C is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N.
Constraints
* All values in input are integers.
* 2 \leq N \leq 2 \times 10^5
* 1 \leq C \leq 10^{12}
* 1 \leq h_1 < h_2 < \cdots < h_N \leq 10^6
Input
Input is given from Standard Input in the following format:
N C
h_1 h_2 \ldots h_N
Output
Print the minimum possible total cost incurred.
Examples
Input
5 6
1 2 3 4 5
Output
20
Input
2 1000000000000
500000 1000000
Output
1250000000000
Input
8 5
1 3 4 5 10 11 12 13
Output
62
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Goal
Given a list of elements [a1, a2, ..., an], with each ai being a string, write a function **majority** that returns the value that appears the most in the list.
If there's no winner, the function should return None, NULL, nil, etc, based on the programming language.
Example
majority(["A", "B", "A"]) returns "A"
majority(["A", "B", "B", "A"]) returns None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.
Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.
The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them β those with biggest ti.
Your task is to handle queries of two types:
* "1 id" β Friend id becomes online. It's guaranteed that he wasn't online before.
* "2 id" β Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line.
Are you able to help Limak and answer all queries of the second type?
Input
The first line contains three integers n, k and q (1 β€ n, q β€ 150 000, 1 β€ k β€ min(6, n)) β the number of friends, the maximum number of displayed online friends and the number of queries, respectively.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ 109) where ti describes how good is Limak's relation with the i-th friend.
The i-th of the following q lines contains two integers typei and idi (1 β€ typei β€ 2, 1 β€ idi β€ n) β the i-th query. If typei = 1 then a friend idi becomes online. If typei = 2 then you should check whether a friend idi is displayed.
It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei = 2) so the output won't be empty.
Output
For each query of the second type print one line with the answer β "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise.
Examples
Input
4 2 8
300 950 500 200
1 3
2 4
2 3
1 1
1 2
2 1
2 2
2 3
Output
NO
YES
NO
YES
YES
Input
6 3 9
50 20 51 17 99 24
1 3
1 4
1 5
1 2
2 4
2 2
1 1
2 4
2 3
Output
NO
YES
NO
YES
Note
In the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries:
1. "1 3" β Friend 3 becomes online.
2. "2 4" β We should check if friend 4 is displayed. He isn't even online and thus we print "NO".
3. "2 3" β We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES".
4. "1 1" β Friend 1 becomes online. The system now displays both friend 1 and friend 3.
5. "1 2" β Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1 < t2, t3) so friend 1 won't be displayed
6. "2 1" β Print "NO".
7. "2 2" β Print "YES".
8. "2 3" β Print "YES".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μλ
, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.
There are two sequences of $n$ strings $s_1, s_2, s_3, \ldots, s_{n}$ and $m$ strings $t_1, t_2, t_3, \ldots, t_{m}$. These strings contain only lowercase letters. There might be duplicates among these strings.
Let's call a concatenation of strings $x$ and $y$ as the string that is obtained by writing down strings $x$ and $y$ one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".
The year 1 has a name which is the concatenation of the two strings $s_1$ and $t_1$. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.
For example, if $n = 3, m = 4, s = ${"a", "b", "c"}, $t =$ {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. [Image]
You are given two sequences of strings of size $n$ and $m$ and also $q$ queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?
-----Input-----
The first line contains two integers $n, m$ ($1 \le n, m \le 20$).
The next line contains $n$ strings $s_1, s_2, \ldots, s_{n}$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $1$ and at most $10$.
The next line contains $m$ strings $t_1, t_2, \ldots, t_{m}$. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least $1$ and at most $10$.
Among the given $n + m$ strings may be duplicates (that is, they are not necessarily all different).
The next line contains a single integer $q$ ($1 \le q \le 2\,020$).
In the next $q$ lines, an integer $y$ ($1 \le y \le 10^9$) is given, denoting the year we want to know the name for.
-----Output-----
Print $q$ lines. For each line, print the name of the year as per the rule described above.
-----Example-----
Input
10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
Output
sinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
-----Note-----
The first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from 1 to 3n, and all the teams possess numbers from 1 to n. The splitting of students into teams is performed in the following manner: while there are people who are not part of a team, a person with the best total score is chosen among them (the captain of a new team), this person chooses for himself two teammates from those who is left according to his list of priorities. The list of every person's priorities is represented as a permutation from the rest of 3n - 1 students who attend the centre, besides himself.
You are given the results of personal training sessions which are a permutation of numbers from 1 to 3n, where the i-th number is the number of student who has won the i-th place. No two students share a place. You are also given the arrangement of the already formed teams in the order in which they has been created. Your task is to determine the list of priorities for the student number k. If there are several priority lists, choose the lexicographically minimal one.
Input
The first line contains an integer n (1 β€ n β€ 105) which is the number of resulting teams. The second line contains 3n space-separated integers from 1 to 3n which are the results of personal training sessions. It is guaranteed that every student appears in the results exactly once.
Then follow n lines each containing three integers from 1 to 3n β each line describes the members of a given team. The members of one team can be listed in any order, but the teams themselves are listed in the order in which they were created. It is guaranteed that the arrangement is correct, that is that every student is a member of exactly one team and those teams could really be created from the given results using the method described above.
The last line contains number k (1 β€ k β€ 3n) which is the number of a student for who the list of priorities should be found.
Output
Print 3n - 1 numbers β the lexicographically smallest list of priorities for the student number k.
The lexicographical comparison is performed by the standard < operator in modern programming languages. The list a is lexicographically less that the list b if exists such an i (1 β€ i β€ 3n), that ai < bi, and for any j (1 β€ j < i) aj = bj. Note, that the list 1 9 10 is lexicographically less than the list 1 10 9. That is, the comparison of lists is different from the comparison of lines.
Examples
Input
3
5 4 1 2 6 3 7 8 9
5 6 2
9 3 4
1 7 8
4
Output
2 3 5 6 9 1 7 8
Input
3
5 4 1 2 6 3 7 8 9
5 6 2
9 3 4
1 7 8
8
Output
1 2 3 4 5 6 7 9
Input
2
4 1 3 2 5 6
4 6 5
1 2 3
4
Output
5 6 1 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.
According to ISO 8601, the first calendar week (1) starts with the week containing the first thursday in january.
Every year contains of 52 (53 for leap years) calendar weeks.
**Your task is** to calculate the calendar week (1-53) from a given date.
For example, the calendar week for the date `2019-01-01` (string) should be 1 (int).
Good luck π
See also [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date) and [Week Number](https://en.wikipedia.org/wiki/Week#Week_numbering) on Wikipedia for further information about calendar weeks.
On [whatweekisit.org](http://whatweekisit.org/) you may click through the calender and study calendar weeks in more depth.
*heads-up:* `require(xxx)` has been disabled
Thanks to @ZED.CWT, @Unnamed and @proxya for their feedback.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a_1, a_2, \dots, a_n$ where all $a_i$ are integers and greater than $0$.
In one operation, you can choose two different indices $i$ and $j$ ($1 \le i, j \le n$). If $gcd(a_i, a_j)$ is equal to the minimum element of the whole array $a$, you can swap $a_i$ and $a_j$. $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
Now you'd like to make $a$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this.
An array $a$ is non-decreasing if and only if $a_1 \le a_2 \le \ldots \le a_n$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$)Β β the number of test cases.
The first line of each test case contains one integer $n$ ($1 \le n \le 10^5$)Β β the length of array $a$.
The second line of each test case contains $n$ positive integers $a_1, a_2, \ldots a_n$ ($1 \le a_i \le 10^9$)Β β the array itself.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, output "YES" if it is possible to make the array $a$ non-decreasing using the described operation, or "NO" if it is impossible to do so.
-----Example-----
Input
4
1
8
6
4 3 6 6 2 9
4
4 5 6 7
5
7 5 2 2 4
Output
YES
YES
YES
NO
-----Note-----
In the first and third sample, the array is already non-decreasing.
In the second sample, we can swap $a_1$ and $a_3$ first, and swap $a_1$ and $a_5$ second to make the array non-decreasing.
In the forth sample, we cannot the array non-decreasing using the 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.
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:
d_1 is the distance between the 1-st and the 2-nd station;
d_2 is the distance between the 2-nd and the 3-rd station;
...
d_{n} - 1 is the distance between the n - 1-th and the n-th station;
d_{n} is the distance between the n-th and the 1-st station.
The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.
-----Input-----
The first line contains integer n (3 β€ n β€ 100) β the number of stations on the circle line. The second line contains n integers d_1, d_2, ..., d_{n} (1 β€ d_{i} β€ 100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1 β€ s, t β€ n) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same.
The numbers in the lines are separated by single spaces.
-----Output-----
Print a single number β the length of the shortest path between stations number s and t.
-----Examples-----
Input
4
2 3 4 9
1 3
Output
5
Input
4
5 8 2 100
4 1
Output
15
Input
3
1 1 1
3 1
Output
1
Input
3
31 41 59
1 1
Output
0
-----Note-----
In the first sample the length of path 1 β 2 β 3 equals 5, the length of path 1 β 4 β 3 equals 13.
In the second sample the length of path 4 β 1 is 100, the length of path 4 β 3 β 2 β 1 is 15.
In the third sample the length of path 3 β 1 is 1, the length of path 3 β 2 β 1 is 2.
In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a sequence of $n$ integers $a_1, \, a_2, \, \dots, \, a_n$.
Does there exist a sequence of $n$ integers $b_1, \, b_2, \, \dots, \, b_n$ such that the following property holds?
For each $1 \le i \le n$, there exist two (not necessarily distinct) indices $j$ and $k$ ($1 \le j, \, k \le n$) such that $a_i = b_j - b_k$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 20$) β the number of test cases. Then $t$ test cases follow.
The first line of each test case contains one integer $n$ ($1 \le n \le 10$).
The second line of each test case contains the $n$ integers $a_1, \, \dots, \, a_n$ ($-10^5 \le a_i \le 10^5$).
-----Output-----
For each test case, output a line containing YES if a sequence $b_1, \, \dots, \, b_n$ satisfying the required property exists, and NO otherwise.
-----Examples-----
Input
5
5
4 -7 -1 5 10
1
0
3
1 10 100
4
-3 2 10 2
9
25 -171 250 174 152 242 100 -205 -258
Output
YES
YES
NO
YES
YES
-----Note-----
In the first test case, the sequence $b = [-9, \, 2, \, 1, \, 3, \, -2]$ satisfies the property. Indeed, the following holds:
$a_1 = 4 = 2 - (-2) = b_2 - b_5$;
$a_2 = -7 = -9 - (-2) = b_1 - b_5$;
$a_3 = -1 = 1 - 2 = b_3 - b_2$;
$a_4 = 5 = 3 - (-2) = b_4 - b_5$;
$a_5 = 10 = 1 - (-9) = b_3 - b_1$.
In the second test case, it is sufficient to choose $b = [0]$, since $a_1 = 0 = 0 - 0 = b_1 - b_1$.
In the third test case, it is possible to show that no sequence $b$ of length $3$ satisfies the property.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment t_{i} and needs to be processed for d_{i} units of time. All t_{i} are guaranteed to be distinct.
When a query appears server may react in three possible ways: If server is free and query queue is empty, then server immediately starts to process this query. If server is busy and there are less than b queries in the queue, then new query is added to the end of the queue. If server is busy and there are already b queries pending in the queue, then new query is just rejected and will never be processed.
As soon as server finished to process some query, it picks new one from the queue (if it's not empty, of course). If a new query comes at some moment x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.
For each query find the moment when the server will finish to process it or print -1 if this query will be rejected.
-----Input-----
The first line of the input contains two integers n and b (1 β€ n, b β€ 200 000)Β β the number of queries and the maximum possible size of the query queue.
Then follow n lines with queries descriptions (in chronological order). Each description consists of two integers t_{i} and d_{i} (1 β€ t_{i}, d_{i} β€ 10^9), where t_{i} is the moment of time when the i-th query appears and d_{i} is the time server needs to process it. It is guaranteed that t_{i} - 1 < t_{i} for all i > 1.
-----Output-----
Print the sequence of n integers e_1, e_2, ..., e_{n}, where e_{i} is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or - 1 if the corresponding query will be rejected.
-----Examples-----
Input
5 1
2 9
4 8
10 9
15 2
19 1
Output
11 19 -1 21 22
Input
4 1
2 8
4 8
10 9
15 2
Output
10 18 27 -1
-----Note-----
Consider the first sample. The server will start to process first query at the moment 2 and will finish to process it at the moment 11. At the moment 4 second query appears and proceeds to the queue. At the moment 10 third query appears. However, the server is still busy with query 1, b = 1 and there is already query 2 pending in the queue, so third query is just rejected. At the moment 11 server will finish to process first query and will take the second query from the queue. At the moment 15 fourth query appears. As the server is currently busy it proceeds to the queue. At the moment 19 two events occur simultaneously: server finishes to proceed the second query and the fifth query appears. As was said in the statement above, first server will finish to process the second query, then it will pick the fourth query from the queue and only then will the fifth query appear. As the queue is empty fifth query is proceed there. Server finishes to process query number 4 at the moment 21. Query number 5 is picked from the queue. Server finishes to process query number 5 at the moment 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.
You play a strategic video game (yeah, we ran out of good problem legends). In this game you control a large army, and your goal is to conquer $n$ castles of your opponent.
Let's describe the game process in detail. Initially you control an army of $k$ warriors. Your enemy controls $n$ castles; to conquer the $i$-th castle, you need at least $a_i$ warriors (you are so good at this game that you don't lose any warriors while taking over a castle, so your army stays the same after the fight). After you take control over a castle, you recruit new warriors into your army β formally, after you capture the $i$-th castle, $b_i$ warriors join your army. Furthermore, after capturing a castle (or later) you can defend it: if you leave at least one warrior in a castle, this castle is considered defended. Each castle has an importance parameter $c_i$, and your total score is the sum of importance values over all defended castles. There are two ways to defend a castle:
if you are currently in the castle $i$, you may leave one warrior to defend castle $i$; there are $m$ one-way portals connecting the castles. Each portal is characterised by two numbers of castles $u$ and $v$ (for each portal holds $u > v$). A portal can be used as follows: if you are currently in the castle $u$, you may send one warrior to defend castle $v$.
Obviously, when you order your warrior to defend some castle, he leaves your army.
You capture the castles in fixed order: you have to capture the first one, then the second one, and so on. After you capture the castle $i$ (but only before capturing castle $i + 1$) you may recruit new warriors from castle $i$, leave a warrior to defend castle $i$, and use any number of portals leading from castle $i$ to other castles having smaller numbers. As soon as you capture the next castle, these actions for castle $i$ won't be available to you.
If, during some moment in the game, you don't have enough warriors to capture the next castle, you lose. Your goal is to maximize the sum of importance values over all defended castles (note that you may hire new warriors in the last castle, defend it and use portals leading from it even after you capture it β your score will be calculated afterwards).
Can you determine an optimal strategy of capturing and defending the castles?
-----Input-----
The first line contains three integers $n$, $m$ and $k$ ($1 \le n \le 5000$, $0 \le m \le \min(\frac{n(n - 1)}{2}, 3 \cdot 10^5)$, $0 \le k \le 5000$) β the number of castles, the number of portals and initial size of your army, respectively.
Then $n$ lines follow. The $i$-th line describes the $i$-th castle with three integers $a_i$, $b_i$ and $c_i$ ($0 \le a_i, b_i, c_i \le 5000$) β the number of warriors required to capture the $i$-th castle, the number of warriors available for hire in this castle and its importance value.
Then $m$ lines follow. The $i$-th line describes the $i$-th portal with two integers $u_i$ and $v_i$ ($1 \le v_i < u_i \le n$), meaning that the portal leads from the castle $u_i$ to the castle $v_i$. There are no two same portals listed.
It is guaranteed that the size of your army won't exceed $5000$ under any circumstances (i. e. $k + \sum\limits_{i = 1}^{n} b_i \le 5000$).
-----Output-----
If it's impossible to capture all the castles, print one integer $-1$.
Otherwise, print one integer equal to the maximum sum of importance values of defended castles.
-----Examples-----
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 3
Output
5
Input
4 3 7
7 4 17
3 0 8
11 2 0
13 3 5
3 1
2 1
4 1
Output
22
Input
4 3 7
7 4 17
3 0 8
11 2 0
14 3 5
3 1
2 1
4 3
Output
-1
-----Note-----
The best course of action in the first example is as follows:
capture the first castle; hire warriors from the first castle, your army has $11$ warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has $13$ warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has $12$ warriors now.
This course of action (and several other ones) gives $5$ as your total score.
The best course of action in the second example is as follows:
capture the first castle; hire warriors from the first castle, your army has $11$ warriors now; capture the second castle; capture the third castle; hire warriors from the third castle, your army has $13$ warriors now; capture the fourth castle; leave one warrior to protect the fourth castle, your army has $12$ warriors now; send one warrior to protect the first castle through the third portal, your army has $11$ warriors now.
This course of action (and several other ones) gives $22$ as your total score.
In the third example it's impossible to capture the last castle: you need $14$ warriors to do so, but you can accumulate no more than $13$ without capturing it.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 three boxes A, B, and C, each of which contains an integer.
Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.
We will now do the operations below in order. Find the content of each box afterward.
- Swap the contents of the boxes A and B
- Swap the contents of the boxes A and C
-----Constraints-----
- 1 \leq X,Y,Z \leq 100
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
X Y Z
-----Output-----
Print the integers contained in the boxes A, B, and C, in this order, with space in between.
-----Sample Input-----
1 2 3
-----Sample Output-----
3 1 2
After the contents of the boxes A and B are swapped, A, B, and C contain 2, 1, and 3, respectively.
Then, after the contents of A and C are swapped, A, B, and C contain 3, 1, and 2, respectively.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.
How many kinds of items did you get?
-----Constraints-----
- 1 \leq N \leq 2\times 10^5
- S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
N
S_1
:
S_N
-----Output-----
Print the number of kinds of items you got.
-----Sample Input-----
3
apple
orange
apple
-----Sample Output-----
2
You got two kinds of items: apple and orange.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.
-----Input-----
The first line of the input contains one integer, n (1 β€ n β€ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 10^9, inclusive.
-----Output-----
Print the maximum possible even sum that can be obtained if we use some of the given integers.
-----Examples-----
Input
3
1 2 3
Output
6
Input
5
999999999 999999999 999999999 999999999 999999999
Output
3999999996
-----Note-----
In the first sample, we can simply take all three integers for a total sum of 6.
In the second sample Wet Shark should take any four out of five integers 999 999 999.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious.
Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters.
Input
The first input data line contains a string whose length is equal to n (1 β€ n β€ 105). The string consists of lowercase Latin letters. The second line contains the number k (0 β€ k β€ 105).
Output
Print on the first line the only number m β the least possible number of different characters that could remain in the given string after it loses no more than k characters.
Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them.
Examples
Input
aaaaa
4
Output
1
aaaaa
Input
abacaba
4
Output
1
aaaa
Input
abcdefgh
10
Output
0
Note
In the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length.
In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string.
In the third sample you are given a line whose length is equal to 8, and k = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string.
Read the inputs from 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.