question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!
There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad.
Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.
-----Input-----
The first line contains integers $n$ and $k$ ($2 \le n \le 10^5$, $1 \le k \le 10^5$), the number of snacks and the number of guests.
The $i$-th of the following $k$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), favorite snack flavors of the $i$-th guest.
-----Output-----
Output one integer, the smallest possible number of sad guests.
-----Examples-----
Input
5 4
1 2
4 3
1 4
3 4
Output
1
Input
6 5
2 3
2 1
3 4
6 5
4 5
Output
0
-----Note-----
In the first example, Bessie can order the guests like this: $3, 1, 2, 4$. Guest $3$ goes first and eats snacks $1$ and $4$. Then the guest $1$ goes and eats the snack $2$ only, because the snack $1$ has already been eaten. Similarly, the guest $2$ goes up and eats the snack $3$ only. All the snacks are gone, so the guest $4$ will be sad.
In the second example, one optimal ordering is $2, 1, 3, 5, 4$. All the guests will be satisfied.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider some positive integer $x$. Its prime factorization will be of form $x = 2^{k_1} \cdot 3^{k_2} \cdot 5^{k_3} \cdot \dots$
Let's call $x$ elegant if the greatest common divisor of the sequence $k_1, k_2, \dots$ is equal to $1$. For example, numbers $5 = 5^1$, $12 = 2^2 \cdot 3$, $72 = 2^3 \cdot 3^2$ are elegant and numbers $8 = 2^3$ ($GCD = 3$), $2500 = 2^2 \cdot 5^4$ ($GCD = 2$) are not.
Count the number of elegant integers from $2$ to $n$.
Each testcase contains several values of $n$, for each of them you are required to solve the problem separately.
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 10^5$) — the number of values of $n$ in the testcase.
Each of the next $T$ lines contains a single integer $n_i$ ($2 \le n_i \le 10^{18}$).
-----Output-----
Print $T$ lines — the $i$-th line should contain the number of elegant numbers from $2$ to $n_i$.
-----Example-----
Input
4
4
2
72
10
Output
2
1
61
6
-----Note-----
Here is the list of non-elegant numbers up to $10$:
$4 = 2^2, GCD = 2$; $8 = 2^3, GCD = 3$; $9 = 3^2, GCD = 2$.
The rest have $GCD = 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.
A fraction whose numerator is 1 and whose denominator is a positive integer is called a unit fraction. A representation of a positive rational number p/q as the sum of finitely many unit fractions is called a partition of p/q into unit fractions. For example, 1/2 + 1/6 is a partition of 2/3 into unit fractions. The difference in the order of addition is disregarded. For example, we do not distinguish 1/6 + 1/2 from 1/2 + 1/6.
For given four positive integers p, q, a, and n, count the number of partitions of p/q into unit fractions satisfying the following two conditions.
* The partition is the sum of at most n many unit fractions.
* The product of the denominators of the unit fractions in the partition is less than or equal to a.
For example, if (p,q,a,n) = (2,3,120,3), you should report 4 since
2/3 = 1/3 + 1/3 = 1/2 + 1/6 = 1/4 + 1/4 + 1/6 = 1/3 + 1/6 + 1/6
enumerates all of the valid partitions.
Input
The input is a sequence of at most 1000 data sets followed by a terminator.
A data set is a line containing four positive integers p, q, a, and n satisfying p,q <= 800, a <= 12000 and n <= 7. The integers are separated by a space.
The terminator is composed of just one line which contains four zeros separated by a space. It is not a part of the input data but a mark for the end of the input.
Output
The output should be composed of lines each of which contains a single integer. No other characters should appear in the output.
The output integer corresponding to a data set p, q, a, n should be the number of all partitions of p/q into at most n many unit fractions such that the product of the denominators of the unit fractions is less than or equal to a.
Example
Input
2 3 120 3
2 3 300 3
2 3 299 3
2 3 12 3
2 3 12000 7
54 795 12000 7
2 3 300 1
2 1 200 5
2 4 54 2
0 0 0 0
Output
4
7
6
2
42
1
0
9
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 are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).
Alice makes the first move. During the first move, she will eat $1$ candy (its size is $a_1$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.
On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.
For example, if $n=11$ and $a=[3,1,4,1,5,9,2,6,5,3,5]$, then: move 1: Alice eats one candy of size $3$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3,5]$. move 2: Alice ate $3$ on the previous move, which means Bob must eat $4$ or more. Bob eats one candy of size $5$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3]$. move 3: Bob ate $5$ on the previous move, which means Alice must eat $6$ or more. Alice eats three candies with the total size of $1+4+1=6$ and the sequence of candies becomes $[5,9,2,6,5,3]$. move 4: Alice ate $6$ on the previous move, which means Bob must eat $7$ or more. Bob eats two candies with the total size of $3+5=8$ and the sequence of candies becomes $[5,9,2,6]$. move 5: Bob ate $8$ on the previous move, which means Alice must eat $9$ or more. Alice eats two candies with the total size of $5+9=14$ and the sequence of candies becomes $[2,6]$. move 6 (the last): Alice ate $14$ on the previous move, which means Bob must eat $15$ or more. It is impossible, so Bob eats the two remaining candies and the game ends.
Print the number of moves in the game and two numbers: $a$ — the total size of all sweets eaten by Alice during the game; $b$ — the total size of all sweets eaten by Bob during the game.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 5000$) — the number of test cases in the input. The following are descriptions of the $t$ test cases.
Each test case consists of two lines. The first line contains an integer $n$ ($1 \le n \le 1000$) — the number of candies. The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) — the sizes of candies in the order they are arranged from left to right.
It is guaranteed that the sum of the values of $n$ for all sets of input data in a test does not exceed $2\cdot10^5$.
-----Output-----
For each set of input data print three integers — the number of moves in the game and the required values $a$ and $b$.
-----Example-----
Input
7
11
3 1 4 1 5 9 2 6 5 3 5
1
1000
3
1 1 1
13
1 2 3 4 5 6 7 8 9 10 11 12 13
2
2 1
6
1 1 1 1 1 1
7
1 1 1 1 1 1 1
Output
6 23 21
1 1000 0
2 1 2
6 45 46
2 2 1
3 4 2
4 4 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.
One day Alice visited Byteland to purchase jewels for her upcoming wedding anniversary.
In Byteland, every Jewelry shop has their own discount methods to attract the customers. One discount method called Buy1-Get1 caught Alice's attention. That is, Alice buys one jewel, then she can get one additional jewel with the same color without charge by Buy1-Get1.
Alice lists the needed jewels as a string S, each letter denotes one jewel, and the same letters denote the same colors of jewels, and the different letters denote the different colors of jewels. The cost of each jewel is 1. Your task is to calculate the minimum cost for getting all the jewels Alice listed.
------ Input ------
The first line of input contains a single line T, which represents the number of test cases. Then T lines will follow, and each contains a string S, which represents the jewels Alice needed.
------ Output ------
Output the minimum cost for each test case.
------ Constraints ------
1 ≤ T ≤ 100
1 ≤ |S| ≤ 200, where |S| represents the length of the string S.
The string S is case sensitive, and will contain only English characters in the range [a-z], [A-Z].
----- Sample Input 1 ------
4
ssss
ssas
sa
s
----- Sample Output 1 ------
2
3
2
1
----- explanation 1 ------
In the first sample case, Alice needs 4 jewel of color s. One of the optimal way is the following: Buy the first s with cost 1, and she can get the second s without charge. Then buy the third s with cost 1, and she can get the last s without charge. In this case, she get 4 jewels with only cost 2.
In the second sample case, Alice needs 3 jewels of color s and 1 jewel of color a. One of the optimal way is the following: Buy the second s with cost 1, and she can get the last s without charge. Then buy the a and the first s with cost 2. In this case, she get 4 jewels with only cost 3.
In the third and fourth sample cases, she cannot save her money by using Buy1-Get1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ivan has got an array of n non-negative integers a_1, a_2, ..., a_{n}. Ivan knows that the array is sorted in the non-decreasing order.
Ivan wrote out integers 2^{a}_1, 2^{a}_2, ..., 2^{a}_{n} on a piece of paper. Now he wonders, what minimum number of integers of form 2^{b} (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2^{v} - 1 for some integer v (v ≥ 0).
Help Ivan, find the required quantity of numbers.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5). The second input line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 2·10^9). It is guaranteed that a_1 ≤ a_2 ≤ ... ≤ a_{n}.
-----Output-----
Print a single integer — the answer to the problem.
-----Examples-----
Input
4
0 1 1 1
Output
0
Input
1
3
Output
3
-----Note-----
In the first sample you do not need to add anything, the sum of numbers already equals 2^3 - 1 = 7.
In the second sample you need to add numbers 2^0, 2^1, 2^2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two integers K and S.
Three variable X, Y and Z takes integer values satisfying 0≤X,Y,Z≤K.
How many different assignments of values to X, Y and Z are there such that X + Y + Z = S?
Constraints
* 2≤K≤2500
* 0≤S≤3K
* K and S are integers.
Input
The input is given from Standard Input in the following format:
K S
Output
Print the number of the triples of X, Y and Z that satisfy the condition.
Examples
Input
2 2
Output
6
Input
5 15
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.
Hierarchical Democracy
The presidential election in Republic of Democratia is carried out through multiple stages as follows.
1. There are exactly two presidential candidates.
2. At the first stage, eligible voters go to the polls of his/her electoral district. The winner of the district is the candidate who takes a majority of the votes. Voters cast their ballots only at this first stage.
3. A district of the k-th stage (k > 1) consists of multiple districts of the (k − 1)-th stage. In contrast, a district of the (k − 1)-th stage is a sub-district of one and only one district of the k-th stage. The winner of a district of the k-th stage is the candidate who wins in a majority of its sub-districts of the (k − 1)-th stage.
4. The final stage has just one nation-wide district. The winner of the final stage is chosen as the president.
You can assume the following about the presidential election of this country.
* Every eligible voter casts a vote.
* The number of the eligible voters of each electoral district of the first stage is odd.
* The number of the sub-districts of the (k − 1)-th stage that constitute a district of the k-th stage (k > 1) is also odd.
This means that each district of every stage has its winner (there is no tie).
Your mission is to write a program that finds a way to win the presidential election with the minimum number of votes. Suppose, for instance, that the district of the final stage has three sub-districts of the first stage and that the numbers of the eligible voters of the sub-districts are 123, 4567, and 89, respectively. The minimum number of votes required to be the winner is 107, that is, 62 from the first district and 45 from the third. In this case, even if the other candidate were given all the 4567 votes in the second district, s/he would inevitably be the loser. Although you might consider this election system unfair, you should accept it as a reality.
Input
The entire input looks like:
> the number of datasets (=n)
> 1st dataset
> 2nd dataset
> …
> n-th dataset
>
The number of datasets, n, is no more than 100.
The number of the eligible voters of each district and the part-whole relations among districts are denoted as follows.
* An electoral district of the first stage is denoted as [c], where c is the number of the eligible voters of the district.
* A district of the k-th stage (k > 1) is denoted as [d1d2…dm], where d1, d2, …, dm denote its sub-districts of the (k − 1)-th stage in this notation.
For instance, an electoral district of the first stage that has 123 eligible voters is denoted as [123]. A district of the second stage consisting of three sub-districts of the first stage that have 123, 4567, and 89 eligible voters, respectively, is denoted as [[123][4567][89]].
Each dataset is a line that contains the character string denoting the district of the final stage in the aforementioned notation. You can assume the following.
* The character string in each dataset does not include any characters except digits ('0', '1', …, '9') and square brackets ('[', ']'), and its length is between 11 and 10000, inclusive.
* The number of the eligible voters of each electoral district of the first stage is between 3 and 9999, inclusive.
The number of stages is a nation-wide constant. So, for instance, [[[9][9][9]][9][9]] never appears in the input. [[[[9]]]] may not appear either since each district of the second or later stage must have multiple sub-districts of the previous stage.
Output
For each dataset, print the minimum number of votes required to be the winner of the presidential election in a line. No output line may include any characters except the digits with which the number is written.
Sample Input
6
[[123][4567][89]]
[[5][3][7][3][9]]
[[[99][59][63][85][51]][[1539][7995][467]][[51][57][79][99][3][91][59]]]
[[[37][95][31][77][15]][[43][5][5][5][85]][[71][3][51][89][29]][[57][95][5][69][31]][[99][59][65][73][31]]]
[[[[9][7][3]][[3][5][7]][[7][9][5]]][[[9][9][3]][[5][9][9]][[7][7][3]]][[[5][9][7]][[3][9][3]][[9][5][5]]]]
[[8231][3721][203][3271][8843]]
Output for the Sample Input
107
7
175
95
21
3599
Example
Input
6
[[123][4567][89]]
[[5][3][7][3][9]]
[[[99][59][63][85][51]][[1539][7995][467]][[51][57][79][99][3][91][59]]]
[[[37][95][31][77][15]][[43][5][5][5][85]][[71][3][51][89][29]][[57][95][5][69][31]][[99][59][65][73][31]]]
[[[[9][7][3]][[3][5][7]][[7][9][5]]][[[9][9][3]][[5][9][9]][[7][7][3]]][[[5][9][7]][[3][9][3]][[9][5][5]]]]
[[8231][3721][203][3271][8843]]
Output
107
7
175
95
21
3599
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 important contest will take place on the most famous programming platform (Topforces) very soon!
The authors have a pool of $n$ problems and should choose at most three of them into this contest. The prettiness of the $i$-th problem is $a_i$. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be maximum possible).
But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are $x, y, z$, then $x$ should be divisible by neither $y$, nor $z$, $y$ should be divisible by neither $x$, nor $z$ and $z$ should be divisible by neither $x$, nor $y$. If the prettinesses of chosen problems are $x$ and $y$ then neither $x$ should be divisible by $y$ nor $y$ should be divisible by $x$. Any contest composed from one problem is considered good.
Your task is to find out the maximum possible total prettiness of the contest composed of at most three problems from the given pool.
You have to answer $q$ independent queries.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries.
The first line of the query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of problems.
The second line of the query contains $n$ integers $a_1, a_2, \dots, a_n$ ($2 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the prettiness of the $i$-th problem.
It is guaranteed that the sum of $n$ over all queries does not exceed $2 \cdot 10^5$.
-----Output-----
For each query print one integer — the maximum possible cumulative prettiness of the contest composed of at most three problems from the given pool of problems in the query.
-----Example-----
Input
3
4
5 6 15 30
4
10 6 30 15
3
3 4 6
Output
30
31
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.
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to $120^{\circ}$. 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 a_1, a_2, a_3, a_4, a_5 and a_6 (1 ≤ a_{i} ≤ 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:
$\theta$
And that's what it looks like in the second sample:
$A$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
There are n islands in JOI, and each island is numbered from 1 to n. Currently, the JOI country is developing a route network connecting each island.
You work at a ticket center that handles ship tickets. There are many people in JOI who want to travel between islands by boat, as cheaply as possible, and they fill out the order form with their origin and destination, and they are at your place. Will be sent to.
Your job is to transfer several vessels as soon as you receive the order form from the customer, calculate the cheapest fare on the route connecting the departure point and the destination, and tell the customer. However, depending on the itinerary, it may not be possible to travel by ship. At that time, it is necessary to tell the customer that "I cannot travel by ship". Also, in JOI, new vessels connecting the islands are starting to operate one after another, and you will be informed of this information from time to time. When replying to customers, you must keep in mind the latest information.
Create a program that asks for a reply to the customer when the customer's order form or operation information of the newly started vessel is given as input.
The execution status of Input Example 1 and Output Example 1 is shown in Fig. 1.
input
The input consists of multiple datasets. Each dataset is given in the following format.
Two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ 5000) are written on the first line of the input. This means that the number of islands is n and the input consists of k + 1 lines. On the first line of i + (1 ≤ i ≤ k), three or four integers are written separated by blanks.
* When the first number is 0, this line represents the customer's order form.
Three integers 0, a, b (1 ≤ a ≤ n, 1 ≤ b ≤ n, a ≠ b) are written on this line, separated by blanks. This means that the customer has sent an order form with island a as the starting point and island b as the destination.
* When the first number is 1, this line represents the operation information of the newly started vessel.
This line contains four integers 1, c, d, e (1 ≤ c ≤ n, 1 ≤ d ≤ n, c ≠ d, 1 ≤ e ≤ 1000000).
This means that a vessel that goes back and forth between island c and island d has newly started operation, and the fare from island c to island d and the fare from island d to island c are both e.
The order form after this line must be answered in consideration of this vessel.
At the first stage, it is assumed that no vessel is in operation. Of the inputs, the number of lines representing ship operation information is 1000 or less. Also note that multiple vessels may operate between islands.
When both n and k are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output in the following format for each data set.
Let m be the number of lines representing the order form in the input. The output of each dataset consists of m lines, and on the i-th line (1 ≤ i ≤ m), an integer representing the reply to the i-th order form is written. That is, if it is possible to travel between the departure point and the destination of the i-th order form by connecting several vessels, write the minimum value of the total fare. If it is impossible to travel, output -1.
Examples
Input
3 8
1 3 1 10
0 2 3
1 2 3 20
1 1 2 5
0 3 2
1 1 3 7
1 2 1 9
0 2 3
5 16
1 1 2 343750
1 1 3 3343
1 1 4 347392
1 1 5 5497
1 2 3 123394
1 2 4 545492
1 2 5 458
1 3 4 343983
1 3 5 843468
1 4 5 15934
0 2 1
0 4 1
0 3 2
0 4 2
0 4 3
0 5 3
0 0
Output
-1
15
12
5955
21431
9298
16392
24774
8840
Input
None
Output
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 stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
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 Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| 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 10^5
* 1 \leq h_i \leq 10^4
Input
Input is given from Standard Input in the following format:
N
h_1 h_2 \ldots h_N
Output
Print the minimum possible total cost incurred.
Examples
Input
4
10 30 40 20
Output
30
Input
2
10 10
Output
0
Input
6
30 10 60 10 60 50
Output
40
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.
He has a special interest to create difficult problems for others to solve. This time, with many $1 \times 1 \times 1$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $n \times m$ matrix, such that in each cell $(i,j)$, there are $h_{i,j}$ bricks standing on the top of each other.
However, Serval doesn't give you any $h_{i,j}$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $m$ columns, and in the $i$-th of them, the height is the maximum of $h_{1,i},h_{2,i},\dots,h_{n,i}$. It is similar for the left view, where there are $n$ columns. And in the top view, there is an $n \times m$ matrix $t_{i,j}$, where $t_{i,j}$ is $0$ or $1$. If $t_{i,j}$ equals $1$, that means $h_{i,j}>0$, otherwise, $h_{i,j}=0$.
However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?
-----Input-----
The first line contains three positive space-separated integers $n, m, h$ ($1\leq n, m, h \leq 100$) — the length, width and height.
The second line contains $m$ non-negative space-separated integers $a_1,a_2,\dots,a_m$, where $a_i$ is the height in the $i$-th column from left to right of the front view ($0\leq a_i \leq h$).
The third line contains $n$ non-negative space-separated integers $b_1,b_2,\dots,b_n$ ($0\leq b_j \leq h$), where $b_j$ is the height in the $j$-th column from left to right of the left view.
Each of the following $n$ lines contains $m$ numbers, each is $0$ or $1$, representing the top view, where $j$-th number of $i$-th row is $1$ if $h_{i, j}>0$, and $0$ otherwise.
It is guaranteed that there is at least one structure satisfying the input.
-----Output-----
Output $n$ lines, each of them contains $m$ integers, the $j$-th number in the $i$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.
-----Examples-----
Input
3 7 3
2 3 0 0 2 0 1
2 1 3
1 0 0 0 1 0 0
0 0 0 0 0 0 1
1 1 0 0 0 0 0
Output
1 0 0 0 2 0 0
0 0 0 0 0 0 1
2 3 0 0 0 0 0
Input
4 5 5
3 5 2 0 4
4 2 5 4
0 0 0 0 1
1 0 1 0 0
0 1 0 0 0
1 1 1 0 0
Output
0 0 0 0 4
1 0 2 0 0
0 5 0 0 0
3 4 1 0 0
-----Note-----
[Image]
The graph above illustrates the object in the first example.
[Image]
[Image]
The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of 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.
###Task:
You have to write a function `pattern` which creates the following pattern (see examples) up to the desired number of rows.
* If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
* If any even number is passed as argument then the pattern should last upto the largest odd number which is smaller than the passed even number.
###Examples:
pattern(9):
1
333
55555
7777777
999999999
pattern(6):
1
333
55555
```Note: There are no spaces in the pattern```
```Hint: Use \n in string to jump to next line```
Write your solution by modifying this code:
```python
def pattern(n):
```
Your solution should implemented in the function "pattern". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have stumbled across the divine pleasure that is owning a dog and a garden. Now time to pick up all the cr@p! :D
Given a 2D array to represent your garden, you must find and collect all of the dog cr@p - represented by '@'.
You will also be given the number of bags you have access to (bags), and the capactity of a bag (cap). If there are no bags then you can't pick anything up, so you can ignore cap.
You need to find out if you have enough capacity to collect all the cr@p and make your garden clean again.
If you do, return 'Clean', else return 'Cr@p'.
Watch out though - if your dog is out there ('D'), he gets very touchy about being watched. If he is there you need to return 'Dog!!'.
For example:
x=
[[\_,\_,\_,\_,\_,\_]
[\_,\_,\_,\_,@,\_]
[@,\_,\_,\_,\_,\_]]
bags = 2, cap = 2
return --> 'Clean'
Write your solution by modifying this code:
```python
def crap(garden, bags, cap):
```
Your solution should implemented in the function "crap". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
Find the integer from `a` to `b` (included) with the greatest number of divisors. For example:
```
divNum(15, 30) ==> 24
divNum(1, 2) ==> 2
divNum(0, 0) ==> 0
divNum(52, 156) ==> 120
```
If there are several numbers that have the same (maximum) number of divisors, the smallest among them should be returned. Return the string `"Error"` if `a > b`.
Write your solution by modifying this code:
```python
def div_num(a, b):
```
Your solution should implemented in the function "div_num". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Johnny needs to make a rectangular box for his physics class project. He has bought P cm of wire and S cm^{2} of special paper. He would like to use all the wire (for the 12 edges) and paper (for the 6 sides) to make the box.
What is the largest volume of the box that Johnny can make?
------ Input ------
The first line contains t, the number of test cases (about 10). Then t test cases follow.
Each test case contains two integers P and S in a line (1 ≤ P ≤ 40000, 1 ≤ S ≤ 20000). You may assume that there always exists an optimal solution for the given input cases.
------ Output ------
For each test case, print a real number that is the largest volume of the box that Johnny can make, rounded to two decimal places.
----- Sample Input 1 ------
2
20 14
20 16
----- Sample Output 1 ------
3.00
4.15
----- explanation 1 ------
First case: the dimensions of the largest box may be 3, 1 and 1.
Second case: the dimensions of the largest box may be 7/3, 4/3 and 4/3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is an easier version of the problem with smaller constraints.
Korney Korneevich dag up an array $a$ of length $n$. Korney Korneevich has recently read about the operation bitwise XOR , so he wished to experiment with it. For this purpose, he decided to find all integers $x \ge 0$ such that there exists an increasing subsequence of the array $a$, in which the bitwise XOR of numbers is equal to $x$.
It didn't take a long time for Korney Korneevich to find all such $x$, and he wants to check his result. That's why he asked you to solve this problem!
A sequence $s$ is a subsequence of a sequence $b$ if $s$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.
A sequence $s_1, s_2, \ldots , s_m$ is called increasing if $s_1 < s_2 < \ldots < s_m$.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 500$) — the elements of the array $a$.
-----Output-----
In the first line print a single integer $k$ — the number of found $x$ values.
In the second line print $k$ integers in increasing order $x_1, x_2, \ldots x_k$ ($0 \le x_1 < \ldots < x_k$) — found $x$ values.
-----Examples-----
Input
4
4 2 2 4
Output
4
0 2 4 6
Input
8
1 0 1 7 12 5 3 2
Output
12
0 1 2 3 4 5 6 7 10 11 12 13
-----Note-----
In the first test case:
To get value $x = 0$ it is possible to choose and empty subsequence
To get value $x = 2$ it is possible to choose a subsequence $[2]$
To get value $x = 4$ it is possible to choose a subsequence $[4]$
To get value $x = 6$ it is possible to choose a subsequence $[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.
Alice became interested in periods of integer numbers. We say positive $X$ integer number is periodic with length $L$ if there exists positive integer number $P$ with $L$ digits such that $X$ can be written as $PPPP…P$. For example:
$X = 123123123$ is periodic number with length $L = 3$ and $L = 9$
$X = 42424242$ is periodic number with length $L = 2,L = 4$ and $L = 8$
$X = 12345$ is periodic number with length $L = 5$
For given positive period length $L$ and positive integer number $A$, Alice wants to find smallest integer number $X$ strictly greater than $A$ that is periodic with length L.
-----Input-----
First line contains one positive integer number $L \ (1 \leq L \leq 10^5)$ representing length of the period. Second line contains one positive integer number $A \ (1 \leq A \leq 10^{100 000})$.
-----Output-----
One positive integer number representing smallest positive number that is periodic with length $L$ and is greater than $A$.
-----Examples-----
Input
3
123456
Output
124124
Input
3
12345
Output
100100
-----Note-----
In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).
In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.
Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.
You are to determine the total number of times Vasily takes the top card from the deck.
Input
The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck.
The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), where ai is the number written on the i-th from top card in the deck.
Output
Print the total number of times Vasily takes the top card from the deck.
Examples
Input
4
6 3 1 2
Output
7
Input
1
1000
Output
1
Input
7
3 3 3 3 3 3 3
Output
7
Note
In the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Introduction
The first century spans from the **year 1** *up to* and **including the year 100**, **The second** - *from the year 101 up to and including the year 200*, etc.
# Task :
Given a year, return the century it is in.
Write your solution by modifying this code:
```python
def century(year):
```
Your solution should implemented in the function "century". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given some positive integers, I wish to print the integers such that all take up the same width by adding a minimum number of leading zeroes. No leading zeroes shall be added to the largest integer.
For example, given `1, 23, 2, 17, 102`, I wish to print out these numbers as follows:
```python
001
023
002
017
102
```
Write a function `print_nums(n1, n2, n3, ...)` that takes a variable number of arguments and returns the string to be printed out.
Write your solution by modifying this code:
```python
def print_nums(*args):
```
Your solution should implemented in the function "print_nums". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many participants will advance to the next round.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 50) separated by a single space.
The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the score earned by the participant who got the i-th place. The given sequence is non-increasing (that is, for all i from 1 to n - 1 the following condition is fulfilled: ai ≥ ai + 1).
Output
Output the number of participants who advance to the next round.
Examples
Input
8 5
10 9 8 7 7 7 5 5
Output
6
Input
4 2
0 0 0 0
Output
0
Note
In the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.
In the second example nobody got a positive score.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.
Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.
On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.
The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct:
* n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"),
* p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ min(n, m)), here characters in strings are numbered starting from 1.
Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum.
Input
The first line contains a non-empty string s (1 ≤ |s| ≤ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≤ |t| ≤ 5000), where |t| is its length. Both strings consist of lowercase Latin letters.
Output
Print the sought name or -1 if it doesn't exist.
Examples
Input
aad
aac
Output
aad
Input
abad
bob
Output
daab
Input
abc
defg
Output
-1
Input
czaaab
abcdef
Output
abczaa
Note
In the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<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.
Ievan Ritola is a researcher of behavioral ecology. Her group visited a forest to analyze an ecological system of some kinds of foxes.
The forest can be expressed as a two-dimensional plane. With her previous research, foxes in the forest are known to live at lattice points. Here, lattice points are the points whose x and y coordinates are both integers. Two or more foxes might live at the same point.
To observe the biology of these foxes, they decided to put a pair of sensors in the forest. The sensors can be put at lattice points. Then, they will be able to observe all foxes inside the bounding rectangle (including the boundary) where the sensors are catty-corner to each other. The sensors cannot be placed at the points that have the same x or y coordinate; in other words the rectangle must have non-zero area.
The more foxes can be observed, the more data can be collected; on the other hand, monitoring a large area consumes a large amount of energy. So they want to maximize the value given by N' / (|x_1 − x_2| × |y_1 − y_2|), where N' is the number of foxes observed and (x_1, y_1) and (x_2, y_2) are the positions of the two sensors.
Let's help her observe cute foxes!
Input
The input is formatted as follows.
N
x_1 y_1 w_1
x_2 y_2 w_2
:
:
x_N y_N w_N
The first line contains a single integer N (1 ≤ N ≤ 10^5) indicating the number of the fox lairs in the forest. Each of the next N lines contains three integers x_i, y_i (|x_i|,\, |y_i| ≤ 10^9) and w_i (1 ≤ w_i ≤ 10^4), which represent there are w_i foxes at the point (x_i, y_i). It is guaranteed that all points are mutually different.
Output
Output the maximized value as a fraction:
a / b
where a and b are integers representing the numerator and the denominato respectively. There should be exactly one space before and after the slash. The fraction should be written in the simplest form, that is, a and b must not have a common integer divisor greater than one.
If the value becomes an integer, print a fraction with the denominator of one (e.g. `5 / 1` to represent 5). This implies zero should be printed as `0 / 1` (without quotes).
Sample Input 1
2
1 1 2
2 2 3
Output for the Sample Input 1
5 / 1
Example
Input
2
1 1 2
2 2 3
Output
5 / 1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In mathematics, a [Diophantine equation](https://en.wikipedia.org/wiki/Diophantine_equation) is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied.
In this kata we want to find all integers `x, y` (`x >= 0, y >= 0`) solutions of a diophantine equation of the form:
#### x^(2) - 4 \* y^(2) = n
(where the unknowns are `x` and `y`, and `n` is a given positive number)
in decreasing order of the positive xi.
If there is no solution return `[]` or `"[]" or ""`. (See "RUN SAMPLE TESTS" for examples of returns).
## Examples:
```
solEquaStr(90005) --> "[[45003, 22501], [9003, 4499], [981, 467], [309, 37]]"
solEquaStr(90002) --> "[]"
```
## Hint:
x^(2) - 4 \* y^(2) = (x - 2\*y) \* (x + 2\*y)
Write your solution by modifying this code:
```python
def sol_equa(n):
```
Your solution should implemented in the function "sol_equa". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.
-----Constraints-----
- 1 \leq N \leq 10^9
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the largest square number not exceeding N.
-----Sample Input-----
10
-----Sample Output-----
9
10 is not square, but 9 = 3 × 3 is. Thus, we print 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.
Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element.
Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution.
```
find_missing([1, 2, 2, 3], [1, 2, 3]) => 2
```
```
find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8
```
The first array will always have at least one element.
Write your solution by modifying this code:
```python
def find_missing(arr1, arr2):
```
Your solution should implemented in the function "find_missing". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$ of length $n$ consisting of characters a and/or b.
Let $\operatorname{AB}(s)$ be the number of occurrences of string ab in $s$ as a substring. Analogically, $\operatorname{BA}(s)$ is the number of occurrences of ba in $s$ as a substring.
In one step, you can choose any index $i$ and replace $s_i$ with character a or b.
What is the minimum number of steps you need to make to achieve $\operatorname{AB}(s) = \operatorname{BA}(s)$?
Reminder:
The number of occurrences of string $d$ in $s$ as substring is the number of indices $i$ ($1 \le i \le |s| - |d| + 1$) such that substring $s_i s_{i + 1} \dots s_{i + |d| - 1}$ is equal to $d$. For example, $\operatorname{AB}($aabbbabaa$) = 2$ since there are two indices $i$: $i = 2$ where aabbbabaa and $i = 6$ where aabbbabaa.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 1000$). Description of the test cases follows.
The first and only line of each test case contains a single string $s$ ($1 \le |s| \le 100$, where $|s|$ is the length of the string $s$), consisting only of characters a and/or b.
-----Output-----
For each test case, print the resulting string $s$ with $\operatorname{AB}(s) = \operatorname{BA}(s)$ you'll get making the minimum number of steps.
If there are multiple answers, print any of them.
-----Examples-----
Input
4
b
aabbbabaa
abbb
abbaab
Output
b
aabbbabaa
bbbb
abbaaa
-----Note-----
In the first test case, both $\operatorname{AB}(s) = 0$ and $\operatorname{BA}(s) = 0$ (there are no occurrences of ab (ba) in b), so can leave $s$ untouched.
In the second test case, $\operatorname{AB}(s) = 2$ and $\operatorname{BA}(s) = 2$, so you can leave $s$ untouched.
In the third test case, $\operatorname{AB}(s) = 1$ and $\operatorname{BA}(s) = 0$. For example, we can change $s_1$ to b and make both values zero.
In the fourth test case, $\operatorname{AB}(s) = 2$ and $\operatorname{BA}(s) = 1$. For example, we can change $s_6$ to a and make both values equal to $1$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.
The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.
Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
-----Input-----
The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland.
Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive).
It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.
-----Output-----
Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.
-----Examples-----
Input
5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503
Output
Sidorov Ivanov
Andreev Semenov
Input
5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503
Output
?
Andreev Semenov
-----Note-----
In the first sample region teams are uniquely determined.
In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $n$ machines, and the power of the $i$-th machine is $a_i$.
This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $x$, then choose one machine and reduce the power of its machine by $x$ times, and at the same time increase the power of one another machine by $x$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $i$ and $j$, and one integer $x$ such that $x$ is a divisor of $a_i$, and change powers as following: $a_i = \frac{a_i}{x}$, $a_j = a_j \cdot x$
Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 5 \cdot 10^4$) — the number of machines.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$) — the powers of the machines.
-----Output-----
Print one integer — minimum total power.
-----Examples-----
Input
5
1 2 3 4 5
Output
14
Input
4
4 2 4 4
Output
14
Input
5
2 4 2 3 7
Output
18
-----Note-----
In the first example, the farmer can reduce the power of the $4$-th machine by $2$ times, and increase the power of the $1$-st machine by $2$ times, then the powers will be: $[2, 2, 3, 2, 5]$.
In the second example, the farmer can reduce the power of the $3$-rd machine by $2$ times, and increase the power of the $2$-nd machine by $2$ times. At the same time, the farmer can leave is be as it is and the total power won't change.
In the third example, it is optimal to leave it be as it is.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term:
`25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1`
The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient of `1` or `-1` instead:
`25 = 1*16 + 1*8 + 1*4 - 1*2 - 1*1`
Now *this* looks binary.
---
Given any positive number `n`, expand it using the true binary expansion, and return the result as an array, from the most significant digit to the least significant digit.
`true_binary(25) == [1,1,1,-1,-1]`
It should be trivial (the proofs are left as an exercise to the reader) to see that:
- Every odd number has infinitely many true binary expansions
- Every even number has no true binary expansions
Hence, `n` will always be an odd number, and you should return the *least* true binary expansion for any `n`.
Also, note that `n` can be very, very large, so your code should be very efficient.
Write your solution by modifying this code:
```python
def true_binary(n):
```
Your solution should implemented in the function "true_binary". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.
Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.
Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.
Next line describe the second permutation in the same format.
Output
Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.
Examples
Input
3
3 2 1
1 2 3
Output
2
Input
5
1 2 3 4 5
1 5 2 3 4
Output
1
Input
5
1 5 2 3 4
1 2 3 4 5
Output
3
Note
In the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.
In the second sample, he removes number 5 and inserts it after 1.
In the third sample, the sequence of changes are like this:
* 1 5 2 3 4
* 1 4 5 2 3
* 1 3 4 5 2
* 1 2 3 4 5
So he needs three moves.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.
Input
The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.
The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.
The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.
Output
Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).
Examples
Input
6
-2 1
0 3
3 3
4 1
3 -2
2 -2
4
0 1
2 2
3 1
1 0
Output
YES
Input
5
1 2
4 2
3 -3
-2 -2
-2 1
4
0 1
1 2
4 1
2 -1
Output
NO
Input
5
-1 2
2 3
4 1
3 -2
0 -3
5
1 0
1 1
3 1
5 -1
2 -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.
It’s still hot every day, but September has already come. It’s autumn according to the calendar. Looking around, I see two red dragonflies at rest on the wall in front of me. It’s autumn indeed.
When two red dragonflies’ positional information as measured from the end of the wall is given, make a program to calculate the distance between their heads.
Input
The input is given in the following format.
$x_1$ $x_2$
The input line provides dragonflies’ head positions $x_1$ and $x_2$ ($0 \leq x_1, x_2 \leq 100$) as integers.
Output
Output the distance between the two red dragonflies in a line.
Examples
Input
20 30
Output
10
Input
50 25
Output
25
Input
25 25
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.
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day k_{i} products will be put up for sale and exactly l_{i} clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.
For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale k_{i} products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·k_{i} products. Consequently, there is an opportunity to sell two times more products on days of sell-out.
Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.
-----Input-----
The first line contains two integers n and f (1 ≤ n ≤ 10^5, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.
Each line of the following n subsequent lines contains two integers k_{i}, l_{i} (0 ≤ k_{i}, l_{i} ≤ 10^9) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.
-----Output-----
Print a single integer denoting the maximal number of products that shop can sell.
-----Examples-----
Input
4 2
2 1
3 5
2 3
1 5
Output
10
Input
4 1
0 2
0 3
3 5
0 6
Output
5
-----Note-----
In the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.
In the second example it is possible to sell 5 products, if you choose third day for sell-out.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} is 0 if the cow number i is facing left, and 1 if it is facing right.
-----Output-----
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
-----Note-----
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.
Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?
-----Constraints-----
- 1 ≤ X ≤ 9
- X is an integer.
-----Input-----
Input is given from Standard Input in the following format:
X
-----Output-----
If Takahashi's growth will be celebrated, print YES; if it will not, print NO.
-----Sample Input-----
5
-----Sample Output-----
YES
The growth of a five-year-old child will be celebrated.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 students of AtCoder Kindergarten are fighting over candy packs.
There are three candy packs, each of which contains a, b, and c candies, respectively.
Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.
Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.
-----Constraints-----
- 1 ≦ a, b, c ≦ 100
-----Input-----
The input is given from Standard Input in the following format:
a b c
-----Output-----
If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.
-----Sample Input-----
10 30 20
-----Sample Output-----
Yes
Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Карта звёздного неба представляет собой прямоугольное поле, состоящее из n строк по m символов в каждой строке. Каждый символ — это либо «.» (означает пустой участок неба), либо «*» (означает то, что в этом месте на небе есть звезда).
Новое издание карты звёздного неба будет напечатано на квадратных листах, поэтому требуется найти минимально возможную сторону квадрата, в который могут поместиться все звезды. Границы искомого квадрата должны быть параллельны сторонам заданного прямоугольного поля.
-----Входные данные-----
В первой строке входных данных записаны два числа n и m (1 ≤ n, m ≤ 1000) — количество строк и столбцов на карте звездного неба.
В следующих n строках задано по m символов. Каждый символ — это либо «.» (пустой участок неба), либо «*» (звезда).
Гарантируется, что на небе есть хотя бы одна звезда.
-----Выходные данные-----
Выведите одно число — минимально возможную сторону квадрата, которым можно накрыть все звезды.
-----Примеры-----
Входные данные
4 4
....
..*.
...*
..**
Выходные данные
3
Входные данные
1 3
*.*
Выходные данные
3
Входные данные
2 1
.
*
Выходные данные
1
-----Примечание-----
Один из возможных ответов на первый тестовый пример:
[Image]
Один из возможных ответов на второй тестовый пример (обратите внимание, что покрывающий квадрат выходит за пределы карты звездного неба):
[Image]
Ответ на третий тестовый пример:
[Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Complete the function which returns the weekday according to the input number:
* `1` returns `"Sunday"`
* `2` returns `"Monday"`
* `3` returns `"Tuesday"`
* `4` returns `"Wednesday"`
* `5` returns `"Thursday"`
* `6` returns `"Friday"`
* `7` returns `"Saturday"`
* Otherwise returns `"Wrong, please enter a number between 1 and 7"`
Write your solution by modifying this code:
```python
def whatday(num):
```
Your solution should implemented in the function "whatday". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**.
### Abundant Numbers
An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself.
The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).
### Deficient Numbers
A deficient number is a number for which the sum of its proper divisors is less than the number itself.
The first few deficient numbers are: 1, 2, 3, 4, 5, 7, 8, 9.
### Perfect Numbers
A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.
The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6.
### Amicable Numbers
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.)
For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220.
### The Function
For a given two numbers, derive function `deficientlyAbundantAmicableNumbers(num1, num2)` which returns a string with first and second word either abundant or deficient depending on whether `num1` or `num2` are abundant, deficient or perfect. The string should finish with either amicable or not amicable depending on the relationship between `num1` and `num2`.
e.g. `deficientlyAbundantAmicableNumbers(220, 284)` returns `"abundant deficient amicable"` as 220 is an abundant number, 284 is a deficient number and amicable because 220 and 284 are an amicable number pair.
See Part 1 - [Excessively Abundant Numbers](http://www.codewars.com/kata/56a75b91688b49ad94000015)
See Part 2 - [The Most Amicable of Numbers](http://www.codewars.com/kata/56b5ebaa26fd54188b000018)
Write your solution by modifying this code:
```python
def deficiently_abundant_amicable_numbers(n1, n2):
```
Your solution should implemented in the function "deficiently_abundant_amicable_numbers". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Obesity is cited as the cause of many adult diseases. In the past, with a few exceptions, it was unrelated to high school students. However, it is no longer unrealistic to suffer from lack of exercise due to excessive studying for entrance exams, or to become bulimia nervosa due to stress. It may be a problem that high school students should be fully interested in.
So you decided to work as an assistant to a teacher in the health room to create a program to find students suspected of being obese from student data.
The method is to calculate a numerical value called BMI (Body Mass Index). BMI is given by the following formula.
<image>
BMI = 22 is standard, and above 25 is suspected of being obese.
Create a program that calculates BMI from each student's weight and height information and outputs the student ID numbers of 25 or more students.
input
The input is given in the following format:
s1, w1, h1
s2, w2, h2
...
...
si (1 ≤ si ≤ 2,000), wi (1 ≤ wi ≤ 200), hi (1.0 ≤ hi ≤ 2.0) are the student ID numbers (integers), weight (real numbers), and height (real numbers) of the i-th student, respectively. Represents.
The number of students does not exceed 50.
output
The student ID numbers of students with a BMI of 25 or higher are output on one line in the order in which they were entered.
Example
Input
1001,50.0,1.60
1002,60.0,1.70
1003,70.0,1.80
1004,80.0,1.70
1005,90.0,1.60
Output
1004
1005
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 her way to programming school tiger Dasha faced her first test — a huge staircase! [Image]
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers.
You need to check whether there is an interval of steps from the l-th to the r-th (1 ≤ l ≤ r), for which values that Dasha has found are correct.
-----Input-----
In the only line you are given two integers a, b (0 ≤ a, b ≤ 100) — the number of even and odd steps, accordingly.
-----Output-----
In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise.
-----Examples-----
Input
2 3
Output
YES
Input
3 1
Output
NO
-----Note-----
In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps — 2 and 4, and three odd: 1, 3 and 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an integer `n`, find two integers `a` and `b` such that:
```Pearl
A) a >= 0 and b >= 0
B) a + b = n
C) DigitSum(a) + Digitsum(b) is maximum of all possibilities.
```
You will return the digitSum(a) + digitsum(b).
```
For example:
solve(29) = 11. If we take 15 + 14 = 29 and digitSum = 1 + 5 + 1 + 4 = 11. There is no larger outcome.
```
`n` will not exceed `10e10`.
More examples in test cases.
Good luck!
Write your solution by modifying this code:
```python
def solve(n):
```
Your solution should implemented in the function "solve". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi is going to set a 3-character password.
How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?
-----Constraints-----
- 1 \leq N \leq 9
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the number of possible passwords.
-----Sample Input-----
2
-----Sample Output-----
8
There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence.
Input
The input consists of multiple datasets. Each data set consists of:
n
a1
a2
.
.
an
You can assume that 1 ≤ n ≤ 5000 and -100000 ≤ ai ≤ 100000.
The input end with a line consisting of a single 0.
Output
For each dataset, print the maximum sum in a line.
Example
Input
7
-5
-1
6
4
9
-6
-7
13
1
2
3
2
-2
-1
1
2
3
2
1
-2
1
3
1000
-200
201
0
Output
19
14
1001
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.
Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.
The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.
Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.
Output
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
Examples
Input
7 4
4
1 6 2
6 2 2
2 4 2
2 7 1
Output
6
Input
4 3
4
2 1 2
1 3 2
3 4 2
4 1 1
Output
3
Note
In the first example Oleg visiting banks by path 1 → 6 → 2 → 4.
Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4 → 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 have A balls with the string S written on each of them and B balls with the string T written on each of them.
From these balls, Takahashi chooses one with the string U written on it and throws it away.
Find the number of balls with the string S and balls with the string T that we have now.
-----Constraints-----
- S, T, and U are strings consisting of lowercase English letters.
- The lengths of S and T are each between 1 and 10 (inclusive).
- S \not= T
- S=U or T=U.
- 1 \leq A,B \leq 10
- A and B are integers.
-----Input-----
Input is given from Standard Input in the following format:
S T
A B
U
-----Output-----
Print the answer, with space in between.
-----Sample Input-----
red blue
3 4
red
-----Sample Output-----
2 4
Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
```
12 ==> 21
513 ==> 531
2017 ==> 2071
```
If the digits can't be rearranged to form a bigger number, return `-1` (or `nil` in Swift):
```
9 ==> -1
111 ==> -1
531 ==> -1
```
Write your solution by modifying this code:
```python
def next_bigger(n):
```
Your solution should implemented in the function "next_bigger". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob have participated to a Rock Off with their bands. A jury of true metalheads rates the two challenges, awarding points to the bands on a scale from 1 to 50 for three categories: Song Heaviness, Originality, and Members' outfits.
For each one of these 3 categories they are going to be awarded one point, should they get a better judgement from the jury. No point is awarded in case of an equal vote.
You are going to receive two arrays, containing first the score of Alice's band and then those of Bob's. Your task is to find their total score by comparing them in a single line.
Example:
Alice's band plays a Nirvana inspired grunge and has been rated
``20`` for Heaviness,
``32`` for Originality and only
``18`` for Outfits.
Bob listens to Slayer and has gotten a good
``48`` for Heaviness,
``25`` for Originality and a rather honest
``40`` for Outfits.
The total score should be followed by a colon ```:``` and by one of the following quotes:
if Alice's band wins: ```Alice made "Kurt" proud!```
if Bob's band wins: ```Bob made "Jeff" proud!```
if they end up with a draw: ```that looks like a "draw"! Rock on!```
The solution to the example above should therefore appear like
``'1, 2: Bob made "Jeff" proud!'``.
Write your solution by modifying this code:
```python
def solve(a, b):
```
Your solution should implemented in the function "solve". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.
Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)
For example, when n=7, it becomes 0 after two operations, as follows:
* \mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.
* \mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.
You are given an integer X with N digits in binary. For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted. Find f(X_1), f(X_2), \ldots, f(X_N).
Constraints
* 1 \leq N \leq 2 \times 10^5
* X is an integer with N digits in binary, possibly with leading zeros.
Input
Input is given from Standard Input in the following format:
N
X
Output
Print N lines. The i-th line should contain the value f(X_i).
Examples
Input
3
011
Output
2
1
1
Input
23
00110111001011011001110
Output
2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Russian also.
Chef likes playing with strings. The most interesting game are named "CHEF in string". The move of the game consists of the following: Chef takes a subsequence of string's letters that form the word "CHEF" and then he removes that symbols. The goal of the game is to make the maximal number of moves. Please, help Chef and tell him the maximal possible number of moves that he is able to make for the given string S.
------ Input ------
The first line of each test case contains a given string. This string consists of uppercase letters from the set {"C", "H", "E", "F"}.
------ Output ------
Output a single line containing the maximal possible number of moves.
------ Constraints ------
$1 ≤ |S| ≤ 100000$
------ Scoring ------
Subtask 1 (25 points): |S| ≤ 2000
Subtask 2 (75 points): See the constraints.
----- Sample Input 1 ------
CHEFCHEFFFF
----- Sample Output 1 ------
2
----- explanation 1 ------
- In the first move, Chef can pick the subsequence $[1, 2, 3, 4]$. Thus the characters at these indices are C, H, E, and F. Chef removes this subsequence. The remaining string is CHEFFFF.
- In the second move, Chef can pick the indices $[1, 2, 3, 4]$ of the remaining string CHEFFFF as the subsequence. The characters at these indices are C, H, E, and F. Chef removes this subsequence. The remaining string is FFF.
- Chef cannot make any more valid moves.
----- Sample Input 2 ------
CHHHEEEFFCC
----- Sample Output 2 ------
1
----- explanation 2 ------
- In the first move, Chef can pick the subsequence $[1, 2, 5, 8]$. Thus the characters at these indices are C, H, E, and F. Chef removes this subsequence. The remaining string is HHEEFCC.
- Chef cannot make any more valid moves.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
F: Grid number
problem
Ebi-chan is trying to write exactly one integer from 1 to 2 \ times n in a grid with n columns horizontally and 2 rows vertically.
Only one integer can be written to each cell in the grid.
It's not fun just to write normally, so I set the following rules.
* The absolute value of the difference between the integers written in two adjacent cells is less than or equal to k.
* When there is a cell to the right of a cell, the integer written to the cell is truly smaller than the integer written to the cell to the right.
* When there is a cell under a cell, the integer written in the cell is truly smaller than the integer written in the cell below.
Here, two adjacent squares represent squares that share the top, bottom, left, and right sides with a certain square.
How many ways to write this? The answer can be very large, so print the remainder after dividing by the prime number m.
Supplement
The second and third rules above require you to write an integer so that it doesn't violate the inequality sign, as shown in the figure below.
<image>
Input format
You will be given three integers as input.
n k m
Constraint
* 1 \ leq n \ leq 100
* 1 \ leq k \ leq 10
* 2 \ leq m \ leq 10 ^ 9 + 7
* m is a prime number
Output format
Please output the number on one line according to how to write the number. Also, be careful not to forget the trailing line break.
Input example 1
3 2 7
Output example 1
1
<image>
* The above writing method meets the conditions, and there is no other writing method that meets the conditions.
Input example 2
5 10 11
Output example 2
9
* Output the remainder divided by m.
Example
Input
3 2 7
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by a and after each fashion show decreases by b (designers do too many experiments nowadays). Moreover, sometimes top-models participates in talk shows. After participating in talk show model becomes more popular and increasing of her rating after photo shoots become c and decreasing of her rating after fashion show becomes d.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will never become negative. Help her to find a suitable moment for participating in the talk show.
Let's assume that model's career begins in moment 0. At that moment Izabella's rating was equal to start. If talk show happens in moment t if will affect all events in model's life in interval of time [t..t + len) (including t and not including t + len), where len is duration of influence.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will not become become negative before talk show or during period of influence of talk show. Help her to find a suitable moment for participating in the talk show.
Input
In first line there are 7 positive integers n, a, b, c, d, start, len (1 ≤ n ≤ 3·105, 0 ≤ start ≤ 109, 1 ≤ a, b, c, d, len ≤ 109), where n is a number of fashion shows and photo shoots, a, b, c and d are rating changes described above, start is an initial rating of model and len is a duration of influence of talk show.
In next n lines descriptions of events are given. Each of those lines contains two integers ti and qi (1 ≤ ti ≤ 109, 0 ≤ q ≤ 1) — moment, in which event happens and type of this event. Type 0 corresponds to the fashion show and type 1 — to photo shoot.
Events are given in order of increasing ti, all ti are different.
Output
Print one non-negative integer t — the moment of time in which talk show should happen to make Izabella's rating non-negative before talk show and during period of influence of talk show. If there are multiple answers print smallest of them. If there are no such moments, print - 1.
Examples
Input
5 1 1 1 4 0 5
1 1
2 1
3 1
4 0
5 0
Output
6
Input
1 1 2 1 2 1 2
1 0
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The goddess of programming is reviewing a thick logbook, which is a yearly record of visitors to her holy altar of programming. The logbook also records her visits at the altar.
The altar attracts programmers from all over the world because one visitor is chosen every year and endowed with a gift of miracle programming power by the goddess. The endowed programmer is chosen from those programmers who spent the longest time at the altar during the goddess's presence. There have been enthusiastic visitors who spent very long time at the altar but failed to receive the gift because the goddess was absent during their visits.
Now, your mission is to write a program that finds how long the programmer to be endowed stayed at the altar during the goddess's presence.
Input
The input is a sequence of datasets. The number of datasets is less than 100. Each dataset is formatted as follows.
n
M1/D1 h1:m1e1 p1
M2/D2 h2:m2e2 p2
.
.
.
Mn/Dn hn:mnen pn
The first line of a dataset contains a positive even integer, n ≤ 1000, which denotes the number of lines of the logbook. This line is followed by n lines of space-separated data, where Mi/Di identifies the month and the day of the visit, hi:mi represents the time of either the entrance to or exit from the altar, ei is either I for entrance, or O for exit, and pi identifies the visitor.
All the lines in the logbook are formatted in a fixed-column format. Both the month and the day in the month are represented by two digits. Therefore April 1 is represented by 04/01 and not by 4/1. The time is described in the 24-hour system, taking two digits for the hour, followed by a colon and two digits for minutes, 09:13 for instance and not like 9:13. A programmer is identified by an ID, a unique number using three digits. The same format is used to indicate entrance and exit of the goddess, whose ID is 000.
All the lines in the logbook are sorted in ascending order with respect to date and time. Because the altar is closed at midnight, the altar is emptied at 00:00. You may assume that each time in the input is between 00:01 and 23:59, inclusive.
A programmer may leave the altar just after entering it. In this case, the entrance and exit time are the same and the length of such a visit is considered 0 minute. You may assume for such entrance and exit records, the line that corresponds to the entrance appears earlier in the input than the line that corresponds to the exit. You may assume that at least one programmer appears in the logbook.
The end of the input is indicated by a line containing a single zero.
Output
For each dataset, output the total sum of the blessed time of the endowed programmer. The blessed time of a programmer is the length of his/her stay at the altar during the presence of the goddess. The endowed programmer is the one whose total blessed time is the longest among all the programmers. The output should be represented in minutes. Note that the goddess of programming is not a programmer.
Example
Input
14
04/21 09:00 I 000
04/21 09:00 I 001
04/21 09:15 I 002
04/21 09:30 O 001
04/21 09:45 O 000
04/21 10:00 O 002
04/28 09:00 I 003
04/28 09:15 I 000
04/28 09:30 I 004
04/28 09:45 O 004
04/28 10:00 O 000
04/28 10:15 O 003
04/29 20:00 I 002
04/29 21:30 O 002
20
06/01 09:00 I 001
06/01 09:15 I 002
06/01 09:15 I 003
06/01 09:30 O 002
06/01 10:00 I 000
06/01 10:15 O 001
06/01 10:30 I 002
06/01 10:45 O 002
06/01 11:00 I 001
06/01 11:15 O 000
06/01 11:30 I 002
06/01 11:45 O 001
06/01 12:00 O 002
06/01 12:15 I 000
06/01 12:30 I 002
06/01 12:45 O 000
06/01 13:00 I 000
06/01 13:15 O 000
06/01 13:30 O 002
06/01 13:45 O 003
0
Output
45
120
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.
Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on.
For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.
At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.
He asks you to help to find the initial arrangement of the balls in the boxes.
-----Input-----
The first line of the input contains two integers n and x (2 ≤ n ≤ 10^5, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n}, where integer a_{i} (0 ≤ a_{i} ≤ 10^9, a_{x} ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.
-----Examples-----
Input
4 4
4 3 1 6
Output
3 2 5 4
Input
5 2
3 2 0 2 7
Output
2 1 4 1 6
Input
3 3
2 3 1
Output
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.
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $1$, $5$, $10$ and $50$ respectively. The use of other roman digits is not allowed.
Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it.
For example, the number XXXV evaluates to $35$ and the number IXI — to $12$.
Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $11$, not $9$.
One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by exactly $n$ roman digits I, V, X, L.
-----Input-----
The only line of the input file contains a single integer $n$ ($1 \le n \le 10^9$) — the number of roman digits to use.
-----Output-----
Output a single integer — the number of distinct integers which can be represented using $n$ roman digits exactly.
-----Examples-----
Input
1
Output
4
Input
2
Output
10
Input
10
Output
244
-----Note-----
In the first sample there are exactly $4$ integers which can be represented — I, V, X and L.
In the second sample it is possible to represent integers $2$ (II), $6$ (VI), $10$ (VV), $11$ (XI), $15$ (XV), $20$ (XX), $51$ (IL), $55$ (VL), $60$ (XL) and $100$ (LL).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 positive integer $m$ and two integer sequence: $a=[a_1, a_2, \ldots, a_n]$ and $b=[b_1, b_2, \ldots, b_n]$. Both of these sequence have a length $n$.
Permutation is a sequence of $n$ different positive integers from $1$ to $n$. For example, these sequences are permutations: $[1]$, $[1,2]$, $[2,1]$, $[6,7,3,4,1,2,5]$. These are not: $[0]$, $[1,1]$, $[2,3]$.
You need to find the non-negative integer $x$, and increase all elements of $a_i$ by $x$, modulo $m$ (i.e. you want to change $a_i$ to $(a_i + x) \bmod m$), so it would be possible to rearrange elements of $a$ to make it equal $b$, among them you need to find the smallest possible $x$.
In other words, you need to find the smallest non-negative integer $x$, for which it is possible to find some permutation $p=[p_1, p_2, \ldots, p_n]$, such that for all $1 \leq i \leq n$, $(a_i + x) \bmod m = b_{p_i}$, where $y \bmod m$ — remainder of division of $y$ by $m$.
For example, if $m=3$, $a = [0, 0, 2, 1], b = [2, 0, 1, 1]$, you can choose $x=1$, and $a$ will be equal to $[1, 1, 0, 2]$ and you can rearrange it to make it equal $[2, 0, 1, 1]$, which is equal to $b$.
-----Input-----
The first line contains two integers $n,m$ ($1 \leq n \leq 2000, 1 \leq m \leq 10^9$): number of elemens in arrays and $m$.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i < m$).
The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($0 \leq b_i < m$).
It is guaranteed that there exists some non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$.
-----Output-----
Print one integer, the smallest non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$ for all $1 \leq i \leq n$.
-----Examples-----
Input
4 3
0 0 2 1
2 0 1 1
Output
1
Input
3 2
0 0 0
1 1 1
Output
1
Input
5 10
0 0 0 1 2
2 1 0 0 0
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if:
* the Euclidean distance between A and B is one unit and neither A nor B is blocked;
* or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B.
Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
Input
The first line contains an integer n (0 ≤ n ≤ 4·107).
Output
Print a single integer — the minimum number of points that should be blocked.
Examples
Input
1
Output
4
Input
2
Output
8
Input
3
Output
16
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum.
Assume that the input n will always be a positive integer.
Examples:
```python
sum_cubes(2)
> 9
# sum of the cubes of 1 and 2 is 1 + 8
```
Write your solution by modifying this code:
```python
def sum_cubes(n):
```
Your solution should implemented in the function "sum_cubes". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.
Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!
Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.
Help Polycarpus and find any suitable method to cut the public key.
-----Input-----
The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 10^6 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 10^8).
-----Output-----
In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them.
If there is no answer, print in a single line "NO" (without the quotes).
-----Examples-----
Input
116401024
97 1024
Output
YES
11640
1024
Input
284254589153928171911281811000
1009 1000
Output
YES
2842545891539
28171911281811000
Input
120
12 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.
AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.
The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.
How many different PIN codes can he set this way?
Both the lucky number and the PIN code may begin with a 0.
Constraints
* 4 \leq N \leq 30000
* S is a string of length N consisting of digits.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the number of different PIN codes Takahashi can set.
Examples
Input
4
0224
Output
3
Input
6
123123
Output
17
Input
19
3141592653589793238
Output
329
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Miki is a high school student. She has a part time job, so she cannot take enough sleep on weekdays. She wants to take good sleep on holidays, but she doesn't know the best length of sleeping time for her. She is now trying to figure that out with the following algorithm:
1. Begin with the numbers K, R and L.
2. She tries to sleep for H=(R+L)/2 hours.
3. If she feels the time is longer than or equal to the optimal length, then update L with H. Otherwise, update R with H.
4. After repeating step 2 and 3 for K nights, she decides her optimal sleeping time to be T' = (R+L)/2.
If her feeling is always correct, the steps described above should give her a very accurate optimal sleeping time. But unfortunately, she makes mistake in step 3 with the probability P.
Assume you know the optimal sleeping time T for Miki. You have to calculate the probability PP that the absolute difference of T' and T is smaller or equal to E. It is guaranteed that the answer remains unaffected by the change of E in 10^{-10}.
Input
The input follows the format shown below
K R L
P
E
T
Where the integers 0 \leq K \leq 30, 0 \leq R \leq L \leq 12 are the parameters for the algorithm described above. The decimal numbers on the following three lines of the input gives the parameters for the estimation. You can assume 0 \leq P \leq 1, 0 \leq E \leq 12, 0 \leq T \leq 12.
Output
Output PP in one line. The output should not contain an error greater than 10^{-5}.
Examples
Input
3 0 2
0.10000000000
0.50000000000
1.00000000000
Output
0.900000
Input
3 0 2
0.10000000000
0.37499999977
1.00000000000
Output
0.810000
Input
3 0 2
0.10000000000
0.00000100000
0.37500000000
Output
0.729000
Input
3 0 2
0.20000000000
0.00000100000
0.37500000000
Output
0.512000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bob is about to take a hot bath.
There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second.
If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be:
<image>
Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible.
Determine how much each tap should be opened so that Bob was pleased with the result in the end.
Input
You are given five integers t1, t2, x1, x2 and t0 (1 ≤ t1 ≤ t0 ≤ t2 ≤ 106, 1 ≤ x1, x2 ≤ 106).
Output
Print two space-separated integers y1 and y2 (0 ≤ y1 ≤ x1, 0 ≤ y2 ≤ x2).
Examples
Input
10 70 100 100 25
Output
99 33
Input
300 500 1000 1000 300
Output
1000 0
Input
143 456 110 117 273
Output
76 54
Note
In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.
The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.
Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions:
* climb one area up;
* climb one area down;
* jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall.
If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.
The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" — first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.
The level is considered completed if the ninja manages to get out of the canyon.
After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 105) — the height of the canyon and the height of ninja's jump, correspondingly.
The second line contains the description of the left wall — a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area.
The third line describes the right wall in the same format.
It is guaranteed that the first area of the left wall is not dangerous.
Output
Print "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes).
Examples
Input
7 3
---X--X
-X--XX-
Output
YES
Input
6 2
--X-X-
X--XX-
Output
NO
Note
In the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon.
In the second sample there's no way the ninja can get out of the canyon.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Gru has not been in the limelight for a long time and is, therefore, planning something particularly nefarious. Frustrated by his minions' incapability which has kept him away from the limelight, he has built a transmogrifier — a machine which mutates minions.
Each minion has an intrinsic characteristic value (similar to our DNA), which is an integer. The transmogrifier adds an integer K to each of the minions' characteristic value.
Gru knows that if the new characteristic value of a minion is divisible by 7, then it will have Wolverine-like mutations.
Given the initial characteristic integers of N minions, all of which are then transmogrified, find out how many of them become Wolverine-like.
-----Input Format:-----
The first line contains one integer, T, which is the number of test cases. Each test case is then described in two lines.
The first line contains two integers N and K, as described in the statement.
The next line contains N integers, which denote the initial characteristic values for the minions.
-----Output Format:-----
For each testcase, output one integer in a new line, which is the number of Wolverine-like minions after the transmogrification.
-----Constraints:-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 100
- 1 ≤ K ≤ 100
- All initial characteristic values lie between 1 and 105, both inclusive.
-----Example-----
Input:
1
5 10
2 4 1 35 1
Output:
1
-----Explanation:-----
After transmogrification, the characteristic values become {12,14,11,45,11}, out of which only 14 is divisible by 7. So only the second minion becomes Wolverine-like.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array $a$ of length $n$, find another array, $b$, of length $n$ such that:
for each $i$ $(1 \le i \le n)$ $MEX(\{b_1$, $b_2$, $\ldots$, $b_i\})=a_i$.
The $MEX$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.
If such array doesn't exist, determine this.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^5$) — the length of the array $a$.
The second line contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_n$ ($0 \le a_i \le i$) — the elements of the array $a$. It's guaranteed that $a_i \le a_{i+1}$ for $1\le i < n$.
-----Output-----
If there's no such array, print a single line containing $-1$.
Otherwise, print a single line containing $n$ integers $b_1$, $b_2$, $\ldots$, $b_n$ ($0 \le b_i \le 10^6$)
If there are multiple answers, print any.
-----Examples-----
Input
3
1 2 3
Output
0 1 2
Input
4
0 0 0 2
Output
1 3 4 0
Input
3
1 1 3
Output
0 2 1
-----Note-----
In the second test case, other answers like $[1,1,1,0]$, for example, are valid.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An `non decreasing` number is one containing no two consecutive digits (left to right), whose the first is higer than the second. For example, 1235 is an non decreasing number, 1229 is too, but 123429 isn't.
Write a function that finds the number of non decreasing numbers up to `10**N` (exclusive) where N is the input of your function. For example, if `N=3`, you have to count all non decreasing numbers from 0 to 999.
You'll definitely need something smarter than brute force for large values of N!
Write your solution by modifying this code:
```python
def increasing_numbers(n):
```
Your solution should implemented in the function "increasing_numbers". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.
Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k_1 knights with lightsabers of the first color, k_2 knights with lightsabers of the second color, ..., k_{m} knights with lightsabers of the m-th color.
However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights.
-----Input-----
The first line of the input contains n (1 ≤ n ≤ 2·10^5) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k_1, k_2, ..., k_{m} (with $1 \leq \sum_{i = 1}^{m} k_{i} \leq n$) – the desired counts of Jedi Knights with lightsabers of each color from 1 to m.
-----Output-----
Output one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output - 1.
-----Example-----
Input
8 3
3 3 1 2 2 1 1 3
3 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.
The magic sum of 3s is calculated on an array by summing up odd numbers which include the digit `3`. Write a function `magic_sum` which accepts an array of integers and returns the sum.
*Example:* `[3, 12, 5, 8, 30, 13]` results in `16` (`3` + `13`)
If the sum cannot be calculated, `0` should be returned.
Write your solution by modifying this code:
```python
def magic_sum(arr):
```
Your solution should implemented in the function "magic_sum". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of h_{i} identical blocks. For clarification see picture for the first sample.
Limak will repeat the following operation till everything is destroyed.
Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.
Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 10^5).
The second line contains n space-separated integers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9) — sizes of towers.
-----Output-----
Print the number of operations needed to destroy all towers.
-----Examples-----
Input
6
2 1 4 6 2 2
Output
3
Input
7
3 3 3 1 3 3 3
Output
2
-----Note-----
The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. [Image] After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third 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.
You are given an integer sequence $1, 2, \dots, n$. You have to divide it into two sets $A$ and $B$ in such a way that each element belongs to exactly one set and $|sum(A) - sum(B)|$ is minimum possible.
The value $|x|$ is the absolute value of $x$ and $sum(S)$ is the sum of elements of the set $S$.
-----Input-----
The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^9$).
-----Output-----
Print one integer — the minimum possible value of $|sum(A) - sum(B)|$ if you divide the initial sequence $1, 2, \dots, n$ into two sets $A$ and $B$.
-----Examples-----
Input
3
Output
0
Input
5
Output
1
Input
6
Output
1
-----Note-----
Some (not all) possible answers to examples:
In the first example you can divide the initial sequence into sets $A = \{1, 2\}$ and $B = \{3\}$ so the answer is $0$.
In the second example you can divide the initial sequence into sets $A = \{1, 3, 4\}$ and $B = \{2, 5\}$ so the answer is $1$.
In the third example you can divide the initial sequence into sets $A = \{1, 4, 5\}$ and $B = \{2, 3, 6\}$ 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.
Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.
The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.
-----Input-----
The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively.
The next n lines each contain two space-separated integers f_{i} and t_{i} (1 ≤ f_{i} ≤ s, 1 ≤ t_{i} ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.
-----Output-----
Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.
-----Examples-----
Input
3 7
2 1
3 8
5 2
Output
11
Input
5 10
2 77
3 33
8 21
9 12
10 64
Output
79
-----Note-----
In the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:
1. Move to floor 5: takes 2 seconds.
2. Pick up passenger 3.
3. Move to floor 3: takes 2 seconds.
4. Wait for passenger 2 to arrive: takes 4 seconds.
5. Pick up passenger 2.
6. Go to floor 2: takes 1 second.
7. Pick up passenger 1.
8. Go to floor 0: takes 2 seconds.
This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.
Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.
Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.
Input
The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109).
Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.
Output
If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).
Examples
Input
2 3
a
b
Output
First
Input
3 1
a
b
c
Output
First
Input
1 2
ab
Output
Second
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
John has an important number, and he doesn't want others to see it.
He decided to encrypt the number, using the following steps:
```
His number is always a non strict increasing sequence
ie. "123"
He converted each digit into English words.
ie. "123"--> "ONETWOTHREE"
And then, rearrange the letters randomly.
ie. "ONETWOTHREE" --> "TTONWOHREEE"
```
John felt that his number were safe in doing so. In fact, such encryption can be easily decrypted :(
Given the encrypted string `s`, your task is to decrypt it, return the original number in string format.
Note, You can assume that the input string `s` is always valid; It contains only uppercase Letters; The decrypted numbers are arranged in ascending order; The leading zeros are allowed.
# Example
For `s = "ONE"`, the output should be `1`.
For `s = "EON"`, the output should be `1` too.
For `s = "ONETWO"`, the output should be `12`.
For `s = "OONETW"`, the output should be `12` too.
For `s = "ONETWOTHREE"`, the output should be `123`.
For `s = "TTONWOHREEE"`, the output should be `123` too.
Write your solution by modifying this code:
```python
def original_number(s):
```
Your solution should implemented in the function "original_number". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert a grams of sand into b grams of lead, the second one allows you to convert c grams of lead into d grams of gold and third one allows you to convert e grams of gold into f grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable...
Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand.
Input
The first line contains 6 integers a, b, c, d, e, f (0 ≤ a, b, c, d, e, f ≤ 1000).
Output
Print "Ron", if it is possible to get an infinitely large amount of gold having a certain finite amount of sand (and not having any gold and lead at all), i.e., Ron is right. Otherwise, print "Hermione".
Examples
Input
100 200 250 150 200 250
Output
Ron
Input
100 50 50 200 200 100
Output
Hermione
Input
100 10 200 20 300 30
Output
Hermione
Input
0 0 0 0 0 0
Output
Hermione
Input
1 1 0 1 1 1
Output
Ron
Input
1 0 1 2 1 2
Output
Hermione
Input
100 1 100 1 0 1
Output
Ron
Note
Consider the first sample. Let's start with the 500 grams of sand. Apply the first spell 5 times and turn the sand into 1000 grams of lead. Then apply the second spell 4 times to get 600 grams of gold. Let’s take 400 grams from the resulting amount of gold turn them back into sand. We get 500 grams of sand and 200 grams of gold. If we apply the same operations to 500 grams of sand again, we can get extra 200 grams of gold every time. Thus, you can get 200, 400, 600 etc. grams of gold, i.e., starting with a finite amount of sand (500 grams), you can get the amount of gold which is greater than any preassigned number.
In the forth sample it is impossible to get sand, or lead, or gold, applying the spells.
In the fifth sample an infinitely large amount of gold can be obtained by using only the second spell, which allows you to receive 1 gram of gold out of nothing. Note that if such a second spell is available, then the first and the third one do not affect the answer at all.
The seventh sample is more interesting. We can also start with a zero amount of sand there. With the aid of the third spell you can get sand out of nothing. We get 10000 grams of sand in this manner. Let's get 100 grams of lead using the first spell 100 times. Then make 1 gram of gold from them. We managed to receive 1 gram of gold, starting with a zero amount of sand! Clearly, in this manner you can get an infinitely large amount of gold.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequences A and B consisting of non-negative integers.
The lengths of both A and B are N, and the sums of the elements in A and B are equal.
The i-th element in A is A_i, and the i-th element in B is B_i.
Tozan and Gezan repeats the following sequence of operations:
- If A and B are equal sequences, terminate the process.
- Otherwise, first Tozan chooses a positive element in A and decrease it by 1.
- Then, Gezan chooses a positive element in B and decrease it by 1.
- Then, give one candy to Takahashi, their pet.
Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.
-----Constraints-----
- 1 \leq N \leq 2 × 10^5
- 0 \leq A_i,B_i \leq 10^9(1\leq i\leq N)
- The sums of the elements in A and B are equal.
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 B_1
:
A_N B_N
-----Output-----
Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.
-----Sample Input-----
2
1 2
3 2
-----Sample Output-----
2
When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:
- Tozan decreases A_1 by 1.
- Gezan decreases B_1 by 1.
- One candy is given to Takahashi.
- Tozan decreases A_2 by 1.
- Gezan decreases B_1 by 1.
- One candy is given to Takahashi.
- As A and B are equal, the process is terminated.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
-----Input-----
The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive.
-----Output-----
Output "Yes" or "No".
-----Examples-----
Input
373
Output
Yes
Input
121
Output
No
Input
436
Output
Yes
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his office exactly ai times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home.
Doctor plans to go home after receiving k animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out.
Input
The first line of input data contains two space-separated integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 1014). In the second line are given space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
Output
If the doctor will overall carry out less than k examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers — number of animals in the order in which they stand in the queue.
Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.
Examples
Input
3 3
1 2 1
Output
2
Input
4 10
3 3 2 1
Output
-1
Input
7 10
1 3 3 1 2 3 1
Output
6 2 3
Note
In the first sample test:
* Before examination: {1, 2, 3}
* After the first examination: {2, 3}
* After the second examination: {3, 2}
* After the third examination: {2}
In the second sample test:
* Before examination: {1, 2, 3, 4, 5, 6, 7}
* After the first examination: {2, 3, 4, 5, 6, 7}
* After the second examination: {3, 4, 5, 6, 7, 2}
* After the third examination: {4, 5, 6, 7, 2, 3}
* After the fourth examination: {5, 6, 7, 2, 3}
* After the fifth examination: {6, 7, 2, 3, 5}
* After the sixth examination: {7, 2, 3, 5, 6}
* After the seventh examination: {2, 3, 5, 6}
* After the eighth examination: {3, 5, 6, 2}
* After the ninth examination: {5, 6, 2, 3}
* After the tenth examination: {6, 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.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types:
* replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4);
* swap any pair of digits in string a.
Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.
Input
The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.
Output
Print on the single line the single number — the minimum number of operations needed to convert string a into string b.
Examples
Input
47
74
Output
1
Input
774
744
Output
1
Input
777
444
Output
3
Note
In the first sample it is enough simply to swap the first and the second digit.
In the second sample we should replace the second digit with its opposite.
In the third number we should replace all three digits with their opposites.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has a string $s$ of length $n$. He decides to make the following modification to the string: Pick an integer $k$, ($1 \leq k \leq n$). For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if string $s$ is qwer and $k = 2$, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length $2$) weqr (after reversing the second substring of length $2$) werq (after reversing the last substring of length $2$) Hence, the resulting string after modifying $s$ with $k = 2$ is werq.
Vasya wants to choose a $k$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $k$. Among all such $k$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.
A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: $a$ is a prefix of $b$, but $a \ne b$; in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
-----Input-----
Each test contains multiple test cases.
The first line contains the number of test cases $t$ ($1 \le t \le 5000$). The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 5000$) — the length of the string $s$.
The second line of each test case contains the string $s$ of $n$ lowercase latin letters.
It is guaranteed that the sum of $n$ over all test cases does not exceed $5000$.
-----Output-----
For each testcase output two lines:
In the first line output the lexicographically smallest string $s'$ achievable after the above-mentioned modification.
In the second line output the appropriate value of $k$ ($1 \leq k \leq n$) that you chose for performing the modification. If there are multiple values of $k$ that give the lexicographically smallest string, output the smallest value of $k$ among them.
-----Example-----
Input
6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
Output
abab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
-----Note-----
In the first testcase of the first sample, the string modification results for the sample abab are as follows : for $k = 1$ : abab for $k = 2$ : baba for $k = 3$ : abab for $k = 4$ : baba
The lexicographically smallest string achievable through modification is abab for $k = 1$ and $3$. Smallest value of $k$ needed to achieve is hence $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.
The concept of "[smooth number](https://en.wikipedia.org/wiki/Smooth_number)" is applied to all those numbers whose prime factors are lesser than or equal to `7`: `60` is a smooth number (`2 * 2 * 3 * 5`), `111` is not (`3 * 37`).
More specifically, smooth numbers are classified by their highest prime factor and your are tasked with writing a `isSmooth`/`is_smooth` function that returns a string with this classification as it follows:
* 2-smooth numbers should be all defined as a `"power of 2"`, as they are merely that;
* 3-smooth numbers are to return a result of `"3-smooth"`;
* 5-smooth numbers will be labelled as `"Hamming number"`s (incidentally, you might appreciate [this nice kata on them](https://www.codewars.com/kata/hamming-numbers));
* 7-smooth numbers are classified as `"humble numbers"`s;
* for all the other numbers, just return `non-smooth`.
Examples:
```python
is_smooth(16) == "power of 2"
is_smooth(36) == "3-smooth"
is_smooth(60) == "Hamming number"
is_smooth(98) == "humble number"
is_smooth(111) == "non-smooth"
```
The provided input `n` is always going to be a positive number `> 1`.
Write your solution by modifying this code:
```python
def is_smooth(n):
```
Your solution should implemented in the function "is_smooth". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you.
For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you the segment $p_l, p_{l + 1}, \dots, p_r$ in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly $n-1$ segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order.
For example, if the secret permutation is $p=[3, 1, 4, 6, 2, 5]$ then the possible given set of segments can be: $[2, 5, 6]$ $[4, 6]$ $[1, 3, 4]$ $[1, 3]$ $[1, 2, 4, 6]$
Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists).
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($2 \le n \le 200$) — the length of the permutation.
The next $n-1$ lines describe given segments.
The $i$-th line contains the description of the $i$-th segment. The line starts with the integer $k_i$ ($2 \le k_i \le n$) — the length of the $i$-th segment. Then $k_i$ integers follow. All integers in a line are distinct, sorted in ascending order, between $1$ and $n$, inclusive.
It is guaranteed that the required $p$ exists for each test case.
It is also guaranteed that the sum of $n$ over all test cases does not exceed $200$ ($\sum n \le 200$).
-----Output-----
For each test case, print the answer: $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input).
-----Example-----
Input
5
6
3 2 5 6
2 4 6
3 1 3 4
2 1 3
4 1 2 4 6
5
2 2 3
2 1 2
2 1 4
2 4 5
7
3 1 2 6
4 1 3 5 6
2 1 2
3 4 5 7
6 1 2 3 4 5 6
3 1 3 6
2
2 1 2
5
2 2 5
3 2 3 5
4 2 3 4 5
5 1 2 3 4 5
Output
3 1 4 6 2 5
3 2 1 4 5
2 1 6 3 5 4 7
1 2
2 5 3 4 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 to create a function named reverseIt.
Write your function so that in the case a string or a number is passed in as the data , you will return the data in reverse order. If the data is any other type, return it as it is.
Examples of inputs and subsequent outputs:
```
"Hello" -> "olleH"
"314159" -> "951413"
[1,2,3] -> [1,2,3]
```
Write your solution by modifying this code:
```python
def reverse_it(data):
```
Your solution should implemented in the function "reverse_it". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kristina has two arrays $a$ and $b$, each containing $n$ non-negative integers. She can perform the following operation on array $a$ any number of times:
apply a decrement to each non-zero element of the array, that is, replace the value of each element $a_i$ such that $a_i > 0$ with the value $a_i - 1$ ($1 \le i \le n$). If $a_i$ was $0$, its value does not change.
Determine whether Kristina can get an array $b$ from an array $a$ in some number of operations (probably zero). In other words, can she make $a_i = b_i$ after some number of operations for each $1 \le i \le n$?
For example, let $n = 4$, $a = [3, 5, 4, 1]$ and $b = [1, 3, 2, 0]$. In this case, she can apply the operation twice:
after the first application of the operation she gets $a = [2, 4, 3, 0]$;
after the second use of the operation she gets $a = [1, 3, 2, 0]$.
Thus, in two operations, she can get an array $b$ from an array $a$.
-----Input-----
The first line of the input contains an integer $t$ ($1 \le t \le 10^4$) —the number of test cases in the test.
The descriptions of the test cases follow.
The first line of each test case contains a single integer $n$ ($1 \le n \le 5 \cdot 10^4$).
The second line of each test case contains exactly $n$ non-negative integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$).
The third line of each test case contains exactly $n$ non-negative integers $b_1, b_2, \dots, b_n$ ($0 \le b_i \le 10^9$).
It is guaranteed that the sum of $n$ values over all test cases in the test does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output on a separate line:
YES, if by doing some number of operations it is possible to get an array $b$ from an array $a$;
NO otherwise.
You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).
-----Examples-----
Input
6
4
3 5 4 1
1 3 2 0
3
1 2 1
0 1 0
4
5 3 7 2
1 1 1 1
5
1 2 3 4 5
1 2 3 4 6
1
8
0
1
4
6
Output
YES
YES
NO
NO
YES
NO
-----Note-----
The first test case is analyzed in the statement.
In the second test case, it is enough to apply the operation to array $a$ once.
In the third test case, it is impossible to get array $b$ from array $a$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a multiset containing several integers. Initially, it contains $a_1$ elements equal to $1$, $a_2$ elements equal to $2$, ..., $a_n$ elements equal to $n$.
You may apply two types of operations: choose two integers $l$ and $r$ ($l \le r$), then remove one occurrence of $l$, one occurrence of $l + 1$, ..., one occurrence of $r$ from the multiset. This operation can be applied only if each number from $l$ to $r$ occurs at least once in the multiset; choose two integers $i$ and $x$ ($x \ge 1$), then remove $x$ occurrences of $i$ from the multiset. This operation can be applied only if the multiset contains at least $x$ occurrences of $i$.
What is the minimum number of operations required to delete all elements from the multiset?
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 5000$).
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$).
-----Output-----
Print one integer — the minimum number of operations required to delete all elements from the multiset.
-----Examples-----
Input
4
1 4 1 1
Output
2
Input
5
1 0 1 0 1
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n). The function should alphabetize the list based on the nth letter of each word.
The letters should be compared case-insensitive. If both letters are the same, order them normally (lexicographically), again, case-insensitive.
example:
```javascript
function sortIt('bid, zag', 2) //=> 'zag, bid'
```
```ruby
function sortIt('bid, zag', 2) //=> 'zag, bid'
```
```python
function sortIt('bid, zag', 2) #=> 'zag, bid'
```
The length of all words provided in the list will be >= n. The format will be "x, x, x". In Haskell you'll get a list of `String`s instead.
Write your solution by modifying this code:
```python
def sort_it(list_, n):
```
Your solution should implemented in the function "sort_it". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix".
Inna sees an n × m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix are adjacent if |i - p| + |j - q| = 1. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length.
Each cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the k candies in the matrix one by one. For each candy Inna chooses cell (i, j) that will contains the candy, and also chooses the path that starts in cell (1, 1) and ends in cell (i, j) and doesn't contain any candies. After that Inna moves the candy along the path from cell (1, 1) to cell (i, j), where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used.
Help Inna to minimize the penalty in the game.
-----Input-----
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 1 ≤ k ≤ n·m).
-----Output-----
In the first line print an integer — Inna's minimum penalty in the game.
In the next k lines print the description of the path for each candy. The description of the path of the candy that is placed i-th should follow on the i-th line. The description of a path is a sequence of cells. Each cell must be written in the format (i, j), where i is the number of the row and j is the number of the column. You are allowed to print extra whitespaces in the line. If there are multiple optimal solutions, print any of them.
Please follow the output format strictly! If your program passes the first pretest, then the output format is correct.
-----Examples-----
Input
4 4 4
Output
8
(1,1) (2,1) (2,2)
(1,1) (1,2)
(1,1) (2,1)
(1,1)
-----Note-----
Note to the sample. Initially the matrix is empty. Then Inna follows her first path, the path penalty equals the number of cells in it — 3. Note that now no path can go through cell (2, 2), as it now contains a candy. The next two candies go to cells (1, 2) and (2, 1). Inna simply leaves the last candy at cell (1, 1), the path contains only this cell. The total penalty is: 3 + 2 + 2 + 1 = 8.
Note that Inna couldn't use cell (1, 1) to place, for instance, the third candy as in this case she couldn't have made the path for the fourth candy.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is h_{i}.
Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).
You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.
As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (10^9 + 7).
-----Input-----
The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence.
The second line contains n space-separated numbers h_1, h_2, ..., h_{n} (1 ≤ h_{i} ≤ 10^9), where h_{i} equals the height of the i-th board to the left.
-----Output-----
Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.
-----Examples-----
Input
2
1 1
Output
0
Input
3
3 4 2
Output
13
-----Note-----
From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.
All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part): [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$, consisting of $n$ lowercase Latin letters.
A substring of string $s$ is a continuous segment of letters from $s$. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length $n$ diverse if and only if there is no letter to appear strictly more than $\frac n 2$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.
Your task is to find any diverse substring of string $s$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 1000$) — the length of string $s$.
The second line is the string $s$, consisting of exactly $n$ lowercase Latin letters.
-----Output-----
Print "NO" if there is no diverse substring in the string $s$.
Otherwise the first line should contain "YES". The second line should contain any diverse substring of string $s$.
-----Examples-----
Input
10
codeforces
Output
YES
code
Input
5
aaaaa
Output
NO
-----Note-----
The first example has lots of correct answers.
Please, restrain yourself from asking if some specific answer is correct for some specific test or not, these questions always lead to "No comments" answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Not so long ago as a result of combat operations the main Berland place of interest — the magic clock — was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin corresponds to the clock center. The clock was painted two colors as is shown in the picture:
<image>
The picture shows only the central part of the clock. This coloring naturally extends to infinity.
The balls can be taken to be points on the plane. Your task is to find the color of the area, damaged by the given ball.
All the points located on the border of one of the areas have to be considered painted black.
Input
The first and single line contains two integers x and y — the coordinates of the hole made in the clock by the ball. Each of the numbers x and y has an absolute value that does not exceed 1000.
Output
Find the required color.
All the points between which and the origin of coordinates the distance is integral-value are painted black.
Examples
Input
-2 1
Output
white
Input
2 1
Output
black
Input
4 3
Output
black
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.
Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word_1<3word_2<3 ... word_{n}<3.
Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.
Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 10^5.
The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 10^5. A text message can contain only small English letters, digits and signs more and less.
-----Output-----
In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.
-----Examples-----
Input
3
i
love
you
<3i<3love<23you<3
Output
yes
Input
7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3
Output
no
-----Note-----
Please note that Dima got a good old kick in the pants for the second sample from 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.
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!
Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index b_{i} from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index b_{i}, then this person acted like that: he pointed at the person with index (b_{i} + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y); if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player b_{i} on the current turn, then he had drunk a glass of juice; the turn went to person number (b_{i} + 1) mod n.
The person who was pointed on the last turn did not make any actions.
The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.
You can assume that in any scenario, there is enough juice for everybody.
-----Input-----
The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.
-----Output-----
Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well.
-----Examples-----
Input
4
abbba
Output
1
Input
4
abbab
Output
0
-----Note-----
In both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rouded to 10 places).
```
For example:
coordinates(90,1)
=> (0.0, 1.0)
coordinates(45, 1)
=> (0.7071067812, 0.7071067812)
```
Write your solution by modifying this code:
```python
def coordinates(degrees, radius):
```
Your solution should implemented in the function "coordinates". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A binary tree of n nodes is given. Nodes of the tree are numbered from 1 to n and the root is the node 1. Each node can have no child, only one left child, only one right child, or both children. For convenience, let's denote l_u and r_u as the left and the right child of the node u respectively, l_u = 0 if u does not have the left child, and r_u = 0 if the node u does not have the right child.
Each node has a string label, initially is a single character c_u. Let's define the string representation of the binary tree as the concatenation of the labels of the nodes in the in-order. Formally, let f(u) be the string representation of the tree rooted at the node u. f(u) is defined as follows: $$$ f(u) = \begin{cases} <empty string>, & if u = 0; \\\ f(l_u) + c_u + f(r_u) & otherwise, \end{cases} where +$$$ denotes the string concatenation operation.
This way, the string representation of the tree is f(1).
For each node, we can duplicate its label at most once, that is, assign c_u with c_u + c_u, but only if u is the root of the tree, or if its parent also has its label duplicated.
You are given the tree and an integer k. What is the lexicographically smallest string representation of the tree, if we can duplicate labels of at most k nodes?
A string a is lexicographically smaller than a string b if and only if one of the following holds:
* a is a prefix of b, but a ≠ b;
* in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5).
The second line contains a string c of n lower-case English letters, where c_i is the initial label of the node i for 1 ≤ i ≤ n. Note that the given string c is not the initial string representation of the tree.
The i-th of the next n lines contains two integers l_i and r_i (0 ≤ l_i, r_i ≤ n). If the node i does not have the left child, l_i = 0, and if the node i does not have the right child, r_i = 0.
It is guaranteed that the given input forms a binary tree, rooted at 1.
Output
Print a single line, containing the lexicographically smallest string representation of the tree if at most k nodes have their labels duplicated.
Examples
Input
4 3
abab
2 3
0 0
0 4
0 0
Output
baaaab
Input
8 2
kadracyn
2 5
3 4
0 0
0 0
6 8
0 7
0 0
0 0
Output
daarkkcyan
Input
8 3
kdaracyn
2 5
0 3
0 4
0 0
6 8
0 7
0 0
0 0
Output
darkcyan
Note
The images below present the tree for the examples. The number in each node is the node number, while the subscripted letter is its label. To the right is the string representation of the tree, with each letter having the same color as the corresponding node.
Here is the tree for the first example. Here we duplicated the labels of nodes 1 and 3. We should not duplicate the label of node 2 because it would give us the string "bbaaab", which is lexicographically greater than "baaaab".
<image>
In the second example, we can duplicate the labels of nodes 1 and 2. Note that only duplicating the label of the root will produce a worse result than the initial string.
<image>
In the third example, we should not duplicate any character at all. Even though we would want to duplicate the label of the node 3, by duplicating it we must also duplicate the label of the node 2, which produces a worse result.
<image>
There is no way to produce string "darkkcyan" from a tree with the initial string representation "darkcyan" :(.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
Output a single integer — the answer to the problem.
Examples
Input
3
3 1 2
Output
2
Note
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.