question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Luba has to do n chores today. i-th chore takes a_{i} units of time to complete. It is guaranteed that for every $i \in [ 2 . . n ]$ the condition a_{i} ≥ a_{i} - 1 is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a_{i} ($x < \operatorname{min}_{i = 1}^{n} a_{i}$).
Luba is very responsible, so she has to do all n chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously.
-----Input-----
The first line contains three integers n, k, x (1 ≤ k ≤ n ≤ 100, 1 ≤ x ≤ 99) — the number of chores Luba has to do, the number of chores she can do in x units of time, and the number x itself.
The second line contains n integer numbers a_{i} (2 ≤ a_{i} ≤ 100) — the time Luba has to spend to do i-th chore.
It is guaranteed that $x < \operatorname{min}_{i = 1}^{n} a_{i}$, and for each $i \in [ 2 . . n ]$ a_{i} ≥ a_{i} - 1.
-----Output-----
Print one number — minimum time Luba needs to do all n chores.
-----Examples-----
Input
4 2 2
3 6 7 10
Output
13
Input
5 2 1
100 100 100 100 100
Output
302
-----Note-----
In the first example the best option would be to do the third and the fourth chore, spending x = 2 time on each instead of a_3 and a_4, respectively. Then the answer is 3 + 6 + 2 + 2 = 13.
In the second example Luba can choose any two chores to spend x time on them instead of a_{i}. So the answer is 100·3 + 2·1 = 302.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 string s consisting of lowercase English letters. Snuke can perform the following operation repeatedly:
* Insert a letter `x` to any position in s of his choice, including the beginning and end of s.
Snuke's objective is to turn s into a palindrome. Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.
Constraints
* 1 \leq |s| \leq 10^5
* s consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
Output
If the objective is achievable, print the number of operations required. If it is not, print `-1` instead.
Examples
Input
xabxa
Output
2
Input
ab
Output
-1
Input
a
Output
0
Input
oxxx
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.
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ≤ 9).
What is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of r burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.
-----Input-----
The single line of input contains two integers k and r (1 ≤ k ≤ 1000, 1 ≤ r ≤ 9) — the price of one shovel and the denomination of the coin in Polycarp's pocket that is different from "10-burle coins".
Remember that he has an unlimited number of coins in the denomination of 10, that is, Polycarp has enough money to buy any number of shovels.
-----Output-----
Print the required minimum number of shovels Polycarp has to buy so that he can pay for them without any change.
-----Examples-----
Input
117 3
Output
9
Input
237 7
Output
1
Input
15 2
Output
2
-----Note-----
In the first example Polycarp can buy 9 shovels and pay 9·117 = 1053 burles. Indeed, he can pay this sum by using 10-burle coins and one 3-burle coin. He can't buy fewer shovels without any change.
In the second example it is enough for Polycarp to buy one shovel.
In the third example Polycarp should buy two shovels and pay 2·15 = 30 burles. It is obvious that he can pay this sum without any change.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.
Applying the simplest variant of median smoothing to the sequence of numbers a1, a2, ..., an will result a new sequence b1, b2, ..., bn obtained by the following algorithm:
* b1 = a1, bn = an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence.
* For i = 2, ..., n - 1 value bi is equal to the median of three values ai - 1, ai and ai + 1.
The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.
In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.
Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.
Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.
Input
The first input line of the input contains a single integer n (3 ≤ n ≤ 500 000) — the length of the initial sequence.
The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 1), giving the initial sequence itself.
Output
If the sequence will never become stable, print a single number - 1.
Otherwise, first print a single integer — the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space — the resulting sequence itself.
Examples
Input
4
0 0 1 1
Output
0
0 0 1 1
Input
5
0 1 0 1 0
Output
2
0 0 0 0 0
Note
In the second sample the stabilization occurs in two steps: <image>, and the sequence 00000 is obviously stable.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Chef has learned a new technique for comparing two recipes. A recipe contains a list of ingredients in increasing order of the times they will be processed. An ingredient is represented by a letter 'a'-'z'. The i-th letter in a recipe denotes the i-th ingredient. An ingredient can be used multiple times in a recipe.
The technique is as follows. Compare two recipes by comparing their respective lists. If the sets of ingredients used in both recipes are equal and each ingredient is used the same number of times in both of them (processing order does not matter), they are declared as granama recipes. ("granama" is the Chef-ian word for "similar".)
Chef took two recipes he invented yesterday. He wanted to compare them using the technique. Unfortunately, Chef forgot to keep track of the number of times each ingredient has been used in a recipe. He only compared the ingredients but NOT their frequencies. More precisely, Chef considers two recipes as granama if there are no ingredients which are used in one recipe and not used in the other recipe.
Your task is to report whether Chef has correctly classified the two recipes (as granama or not granama) although he forgot to keep track of the frequencies.
------ Input ------
The first line of the input contains a single integer T denoting the number of test cases. The description for T test cases follows. Each test case consists of a single line containing two space-separated strings R and S denoting the two recipes.
------ Output ------
For each test case, output a single line containing "YES" (quotes for clarity) if Chef correctly classified the two recipes as granama or not granama. Otherwise, output a single line containing "NO" (quotes for clarity) if Chef declared two recipes as granama when they actually are not.
------ Constraints ------
1 ≤ T ≤ 100
1 ≤ |R|, |S| ≤ 1000
----- Sample Input 1 ------
3
alex axle
paradise diapers
alice bob
----- Sample Output 1 ------
YES
NO
YES
----- explanation 1 ------
Example case 1: Chef declared them as granama recipes. They are actually granama because the sets of ingredients and the number of times each ingredient has been used are equal. The Chef got it right!
Example case 2: Chef declared them as granama recipes because both sets of ingredients are equal. But they are NOT granama since ingredient 'a' has been used twice in the first recipe but only once in the second. The Chef was incorrect!
Example case 3: Chef declare them as not granama. They are not granama as the sets of ingredients are different. Hence, the Chef was right!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a keyboard that consists of $26$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.
You have to type the word $s$ on this keyboard. It also consists only of lowercase Latin letters.
To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.
Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.
For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $8$, $5$, $12$ and $15$, respectively. Therefore, it will take $|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$ units of time to type the word "hello".
Determine how long it will take to print the word $s$.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 1000$) — the number of test cases.
The next $2t$ lines contain descriptions of the test cases.
The first line of a description contains a keyboard — a string of length $26$, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard.
The second line of the description contains the word $s$. The word has a length from $1$ to $50$ letters inclusive and consists of lowercase Latin letters.
-----Output-----
Print $t$ lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word $s$ on the given keyboard.
-----Examples-----
Input
5
abcdefghijklmnopqrstuvwxyz
hello
abcdefghijklmnopqrstuvwxyz
i
abcdefghijklmnopqrstuvwxyz
codeforces
qwertyuiopasdfghjklzxcvbnm
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
qwertyuiopasdfghjklzxcvbnm
abacaba
Output
13
0
68
0
74
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is the hard version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.
First, Aoi came up with the following idea for the competitive programming problem:
Yuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies.
Yuzu is going to determine a permutation $P$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $\{2,3,1,5,4\}$ is a permutation, but $\{1,2,2\}$ is not a permutation ($2$ appears twice in the array) and $\{1,3,4\}$ is also not a permutation (because $n=3$ but there is the number $4$ in the array).
After that, she will do $n$ duels with the enemies with the following rules:
If Yuzu has equal or more number of candies than enemy $P_i$, she wins the duel and gets $1$ candy. Otherwise, she loses the duel and gets nothing. The candy which Yuzu gets will be used in the next duels.
Yuzu wants to win all duels. How many valid permutations $P$ exist?
This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:
Let's define $f(x)$ as the number of valid permutations for the integer $x$.
You are given $n$, $a$ and a prime number $p \le n$. Let's call a positive integer $x$ good, if the value $f(x)$ is not divisible by $p$. Find all good integers $x$.
Your task is to solve this problem made by Akari.
-----Input-----
The first line contains two integers $n$, $p$ $(2 \le p \le n \le 10^5)$. It is guaranteed, that the number $p$ is prime (it has exactly two divisors $1$ and $p$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(1 \le a_i \le 10^9)$.
-----Output-----
In the first line, print the number of good integers $x$.
In the second line, output all good integers $x$ in the ascending order.
It is guaranteed that the number of good integers $x$ does not exceed $10^5$.
-----Examples-----
Input
3 2
3 4 5
Output
1
3
Input
4 3
2 3 5 6
Output
2
3 4
Input
4 3
9 1 1 1
Output
0
Input
3 2
1000000000 1 999999999
Output
1
999999998
-----Note-----
In the first test, $p=2$.
If $x \le 2$, there are no valid permutations for Yuzu. So $f(x)=0$ for all $x \le 2$. The number $0$ is divisible by $2$, so all integers $x \leq 2$ are not good. If $x = 3$, $\{1,2,3\}$ is the only valid permutation for Yuzu. So $f(3)=1$, so the number $3$ is good. If $x = 4$, $\{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\}$ are all valid permutations for Yuzu. So $f(4)=4$, so the number $4$ is not good. If $x \ge 5$, all $6$ permutations are valid for Yuzu. So $f(x)=6$ for all $x \ge 5$, so all integers $x \ge 5$ are not good.
So, the only good number is $3$.
In the third test, for all positive integers $x$ the value $f(x)$ is divisible by $p = 3$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.
Constraints
* 1 \leq |S| \leq 2 \times 10^5
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum positive integer K that satisfies the condition.
Examples
Input
aabbaa
Output
4
Input
aaaccacabaababc
Output
12
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have.
Frodo will sleep on the k-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?
-----Input-----
The only line contain three integers n, m and k (1 ≤ n ≤ m ≤ 10^9, 1 ≤ k ≤ n) — the number of hobbits, the number of pillows and the number of Frodo's bed.
-----Output-----
Print single integer — the maximum number of pillows Frodo can have so that no one is hurt.
-----Examples-----
Input
4 6 2
Output
2
Input
3 10 3
Output
4
Input
3 6 1
Output
3
-----Note-----
In the first example Frodo can have at most two pillows. In this case, he can give two pillows to the hobbit on the first bed, and one pillow to each of the hobbits on the third and the fourth beds.
In the second example Frodo can take at most four pillows, giving three pillows to each of the others.
In the third example Frodo can take three pillows, giving two pillows to the hobbit in the middle and one pillow to the hobbit on the third bed.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
JOI decided to make a signboard for the store.
There are N old signboards with letters written at equal intervals. JOI makes a sign by erasing some letters from the old sign. I want the remaining characters to be the name of the store, and the remaining characters to be evenly spaced. Signs must be made from one old sign, and old signs must not be cut or connected.
Given the name of the store and information on N old signboards, create a program that asks for the number of signboards that JOI can make. However, even if there are multiple signboards that can be made from one old signboard, it is considered that only one signboard can be made.
input
The input consists of 2 + N lines.
The integer N (1 & leqq; N & leqq; 100) is written on the first line, which indicates the number of old signboards.
On the second line, a character string consisting of 3 to 25 characters of lowercase letters is written, which indicates the name of the store.
The i-th line (1 & leqq; i & leqq; N) of the following N lines contains a character string consisting of 1 to 100 lowercase letters of the alphabet, which is written on the i-th old signboard. Represents a character string.
output
JOI Output an integer representing the number of signboards you can make in one line.
Input / output example
Input example
Four
bar
abracadabra
bear
bar
baraxbara
Output example
3
The name of the shop is bar.
The first old sign has the string abracadabra written on it. You can make a sign by erasing all but the 2nd, 6th, and 10th letters from this old sign.
On the second sheet, if you erase the second character, you can create a character string called bar, but this means that the remaining characters are not evenly spaced.
The third piece is a signboard without erasing any characters.
There are two ways to make a sign from the fourth old sign. One method is to erase all but the first, second, and third characters. Another method is to erase all but the 6th, 7th, and 8th characters.
Therefore, JOI can make a signboard from the 1st, 3rd, and 4th old signboards, so 3 is output.
The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics.
Example
Input
4
bar
abracadabra
bear
bar
baraxbara
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.
A wise king declared a new calendar. "Tomorrow shall be the first day of the calendar, that is, the day 1 of the month 1 of the year 1. Each year consists of 10 months, from month 1 through month 10, and starts from a big month. A common year shall start with a big month, followed by small months and big months one after another. Therefore the first month is a big month, the second month is a small month, the third a big month, ..., and the 10th and last month a small one. A big month consists of 20 days and a small month consists of 19 days. However years which are multiples of three, that are year 3, year 6, year 9, and so on, shall consist of 10 big months and no small month."
Many years have passed since the calendar started to be used. For celebration of the millennium day (the year 1000, month 1, day 1), a royal lottery is going to be organized to send gifts to those who have lived as many days as the number chosen by the lottery. Write a program that helps people calculate the number of days since their birthdate to the millennium day.
Input
The input is formatted as follows.
> n
> Y1 M1 D1
> Y2 M2 D2
> ...
> Yn Mn Dn
Here, the first line gives the number of datasets as a positive integer n, which is less than or equal to 100. It is followed by n datasets. Each dataset is formatted in a line and gives three positive integers, Yi (< 1000), Mi (≤ 10), and Di (≤ 20), that correspond to the year, month and day, respectively, of a person's birthdate in the king's calendar. These three numbers are separated by a space.
Output
For the birthdate specified in each dataset, print in a line the number of days from the birthdate, inclusive, to the millennium day, exclusive. Output lines should not contain any character other than this number.
Sample Input
8
1 1 1
344 3 1
696 5 1
182 9 5
998 8 7
344 2 19
696 4 19
999 10 20
Output for the Sample Input
196470
128976
59710
160715
252
128977
59712
1
Example
Input
8
1 1 1
344 3 1
696 5 1
182 9 5
998 8 7
344 2 19
696 4 19
999 10 20
Output
196470
128976
59710
160715
252
128977
59712
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
A city in Canada where JOI lives is divided into a grid pattern by w roads that extend straight in the north-south direction and h roads that extend straight in the east-west direction.
The w roads in the north-south direction are numbered 1, 2, ..., w in order from the west. In addition, h roads in the east-west direction are numbered 1, 2, ..., h in order from the south. The intersection of the i-th north-south road from the west and the j-th east-west road from the south is represented by (i, j).
JOI lives near the intersection (1, 1) and drives to a company near the intersection (w, h). Cars can only move along the road. JOI travels only to the east or north to shorten his commute time. The city also has the following traffic rules to reduce traffic accidents:
* A car that turns at an intersection cannot turn at the intersection immediately after that.
That is, it is not permissible to go one block after turning at an intersection and turn again. At this time, how many possible commuting routes for Mr. JOI?
Given w and h, create a program that outputs the remainder of JOI's number of commuting routes divided by 100000.
input
The input consists of multiple datasets. Each dataset consists of one line, and two integers w, h (2 ≤ w ≤ 100, 2 ≤ h ≤ 100) are written, separated by a blank. w represents the number of roads in the north-south direction, and h represents the number of roads in the east-west direction.
When both w and h are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
For each data set, the remainder of JOI's number of commuting routes divided by 100000 is output on one line.
Example
Input
3 4
15 15
0 0
Output
5
43688
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alexey, a merry Berland entrant, got sick of the gray reality and he zealously wants to go to university. There are a lot of universities nowadays, so Alexey is getting lost in the diversity — he has not yet decided what profession he wants to get. At school, he had bad grades in all subjects, and it's only thanks to wealthy parents that he was able to obtain the graduation certificate.
The situation is complicated by the fact that each high education institution has the determined amount of voluntary donations, paid by the new students for admission — n_{i} berubleys. He cannot pay more than n_{i}, because then the difference between the paid amount and n_{i} can be regarded as a bribe!
Each rector is wearing the distinctive uniform of his university. Therefore, the uniform's pockets cannot contain coins of denomination more than r_{i}. The rector also does not carry coins of denomination less than l_{i} in his pocket — because if everyone pays him with so small coins, they gather a lot of weight and the pocket tears. Therefore, a donation can be paid only by coins of denomination x berubleys, where l_{i} ≤ x ≤ r_{i} (Berland uses coins of any positive integer denomination). Alexey can use the coins of different denominations and he can use the coins of the same denomination any number of times. When Alexey was first confronted with such orders, he was puzzled because it turned out that not all universities can accept him! Alexey is very afraid of going into the army (even though he had long wanted to get the green uniform, but his dad says that the army bullies will beat his son and he cannot pay to ensure the boy's safety). So, Alexey wants to know for sure which universities he can enter so that he could quickly choose his alma mater.
Thanks to the parents, Alexey is not limited in money and we can assume that he has an unlimited number of coins of each type.
In other words, you are given t requests, each of them contains numbers n_{i}, l_{i}, r_{i}. For each query you need to answer, whether it is possible to gather the sum of exactly n_{i} berubleys using only coins with an integer denomination from l_{i} to r_{i} berubleys. You can use coins of different denominations. Coins of each denomination can be used any number of times.
-----Input-----
The first line contains the number of universities t, (1 ≤ t ≤ 1000) Each of the next t lines contain three space-separated integers: n_{i}, l_{i}, r_{i} (1 ≤ n_{i}, l_{i}, r_{i} ≤ 10^9; l_{i} ≤ r_{i}).
-----Output-----
For each query print on a single line: either "Yes", if Alexey can enter the university, or "No" otherwise.
-----Examples-----
Input
2
5 2 3
6 4 5
Output
Yes
No
-----Note-----
You can pay the donation to the first university with two coins: one of denomination 2 and one of denomination 3 berubleys. The donation to the second university cannot be paid.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
AOR Ika is studying to pass the test.
AOR Ika-chan solved the $ N $ question. After that, round the solved problem according to the following procedure.
1. Check the correctness of the answer.
2. If the answer is correct, write a circle mark, and if it is incorrect, write a cross mark on the answer sheet.
AOR Ika faints because of the fear of failing the test the moment she finds that the answer is wrong for $ 2 $ in a row. And no further rounding is possible.
Syncope occurs between steps $ 1 $ and $ 2 $.
You will be given an integer $ N $, which represents the number of questions AOR Ika has solved, and a string $ S $, which is a length $ N $ and represents the correctness of the answer. The string consists of'o'and'x', with'o' indicating the correct answer and'x' indicating the incorrect answer. The $ i $ letter indicates the correctness of the $ i $ question, and AOR Ika-chan rounds the $ 1 $ question in order.
Please output the number of questions that AOR Ika-chan can write the correctness.
output
Output the number of questions that AOR Ika-chan could write in the $ 1 $ line. Also, output a line break at the end.
Example
Input
3
oxx
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.
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.
One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?
Input
Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.
Output
Output the maximum possible length of a regular bracket sequence.
Examples
Input
(()))(
Output
4
Input
((()())
Output
6
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tomya is a girl. She loves Chef Ciel very much.
Tomya like a positive integer p, and now she wants to get a receipt of Ciel's restaurant whose total price is exactly p.
The current menus of Ciel's restaurant are shown the following table.
Name of Menupriceeel flavored water1deep-fried eel bones2clear soup made with eel livers4grilled eel livers served with grated radish8savory egg custard with eel16eel fried rice (S)32eel fried rice (L)64grilled eel wrapped in cooked egg128eel curry rice256grilled eel over rice512deluxe grilled eel over rice1024eel full-course2048
Note that the i-th menu has the price 2i-1 (1 ≤ i ≤ 12).
Since Tomya is a pretty girl, she cannot eat a lot.
So please find the minimum number of menus whose total price is exactly p.
Note that if she orders the same menu twice, then it is considered as two menus are ordered. (See Explanations for details)
-----Input-----
The first line contains an integer T, the number of test cases.
Then T test cases follow.
Each test case contains an integer p.
-----Output-----
For each test case, print the minimum number of menus whose total price is exactly p.
-----Constraints-----
1 ≤ T ≤ 5
1 ≤ p ≤ 100000 (105)
There exists combinations of menus whose total price is exactly p.
-----Sample Input-----
4
10
256
255
4096
-----Sample Output-----
2
1
8
2
-----Explanations-----
In the first sample, examples of the menus whose total price is 10 are the following:
1+1+1+1+1+1+1+1+1+1 = 10 (10 menus)
1+1+1+1+1+1+1+1+2 = 10 (9 menus)
2+2+2+2+2 = 10 (5 menus)
2+4+4 = 10 (3 menus)
2+8 = 10 (2 menus)
Here the minimum number of menus is 2.
In the last sample, the optimal way is 2048+2048=4096 (2 menus).
Note that there is no menu whose price is 4096.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:
The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.
Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.
Input
The first line of the input contains two integers n and m (<image>) — the number of vertices and the number of edges in the graph.
Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1 ≤ aj ≤ 109, bj = {0, 1}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not.
It is guaranteed that exactly n - 1 number {bj} are equal to one and exactly m - n + 1 of them are equal to zero.
Output
If Vladislav has made a mistake and such graph doesn't exist, print - 1.
Otherwise print m lines. On the j-th line print a pair of vertices (uj, vj) (1 ≤ uj, vj ≤ n, uj ≠ vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj = 1 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.
Examples
Input
4 5
2 1
3 1
4 0
1 1
5 0
Output
2 4
1 4
3 4
3 1
3 2
Input
3 3
1 0
2 1
3 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.
Fox Ciel is playing a card game with her friend Jiro.
Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.
Now is Ciel's battle phase, Ciel can do the following operation many times: Choose one of her cards X. This card mustn't be chosen before. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then: If Y's position is Attack, then (X's strength) ≥ (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength). If Y's position is Defense, then (X's strength) > (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage.
Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have.
Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense.
Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card.
-----Output-----
Output an integer: the maximal damage Jiro can get.
-----Examples-----
Input
2 3
ATK 2000
DEF 1700
2500
2500
2500
Output
3000
Input
3 4
ATK 10
ATK 100
ATK 1000
1
11
101
1001
Output
992
Input
2 4
DEF 0
ATK 0
0
0
1
1
Output
1
-----Note-----
In the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.
In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.
In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
1. one resistor;
2. an element and one resistor plugged in sequence;
3. an element and one resistor plugged in parallel.
<image>
With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element.
Input
The single input line contains two space-separated integers a and b (1 ≤ a, b ≤ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists.
Output
Print a single number — the answer to the problem.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams or the %I64d specifier.
Examples
Input
1 1
Output
1
Input
3 2
Output
3
Input
199 200
Output
200
Note
In the first sample, one resistor is enough.
In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a frog staying to the left of the string $s = s_1 s_2 \ldots s_n$ consisting of $n$ characters (to be more precise, the frog initially stays at the cell $0$). Each character of $s$ is either 'L' or 'R'. It means that if the frog is staying at the $i$-th cell and the $i$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $i$-th cell and the $i$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $0$.
Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.
The frog wants to reach the $n+1$-th cell. The frog chooses some positive integer value $d$ before the first jump (and cannot change it later) and jumps by no more than $d$ cells at once. I.e. if the $i$-th character is 'L' then the frog can jump to any cell in a range $[max(0, i - d); i - 1]$, and if the $i$-th character is 'R' then the frog can jump to any cell in a range $[i + 1; min(n + 1; i + d)]$.
The frog doesn't want to jump far, so your task is to find the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it can jump by no more than $d$ cells at once. It is guaranteed that it is always possible to reach $n+1$ from $0$.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases.
The next $t$ lines describe test cases. The $i$-th test case is described as a string $s$ consisting of at least $1$ and at most $2 \cdot 10^5$ characters 'L' and 'R'.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed $2 \cdot 10^5$ ($\sum |s| \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer — the minimum possible value of $d$ such that the frog can reach the cell $n+1$ from the cell $0$ if it jumps by no more than $d$ at once.
-----Example-----
Input
6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
Output
3
2
3
1
7
1
-----Note-----
The picture describing the first test case of the example and one of the possible answers:
[Image]
In the second test case of the example, the frog can only jump directly from $0$ to $n+1$.
In the third test case of the example, the frog can choose $d=3$, jump to the cell $3$ from the cell $0$ and then to the cell $4$ from the cell $3$.
In the fourth test case of the example, the frog can choose $d=1$ and jump $5$ times to the right.
In the fifth test case of the example, the frog can only jump directly from $0$ to $n+1$.
In the sixth test case of the example, the frog can choose $d=1$ and jump $2$ times to the right.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.
- Operation 1: Pour 100A grams of water into the beaker.
- Operation 2: Pour 100B grams of water into the beaker.
- Operation 3: Put C grams of sugar into the beaker.
- Operation 4: Put D grams of sugar into the beaker.
In our experimental environment, E grams of sugar can dissolve into 100 grams of water.
Snuke will make sugar water with the highest possible density.
The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.
We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent.
Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.
-----Constraints-----
- 1 \leq A < B \leq 30
- 1 \leq C < D \leq 30
- 1 \leq E \leq 100
- 100A \leq F \leq 3 000
- A, B, C, D, E and F are all integers.
-----Inputs-----
Input is given from Standard Input in the following format:
A B C D E F
-----Outputs-----
Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.
-----Sample Input-----
1 2 10 20 15 200
-----Sample Output-----
110 10
In this environment, 15 grams of sugar can dissolve into 100 grams of water, and the beaker can contain at most 200 grams of substances.
We can make 110 grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:
- If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.
- If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed 200 grams.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 most important part of a GSM network is so called Base Transceiver Station (BTS). These transceivers form the areas called cells (this term gave the name to the cellular phone) and every phone connects to the BTS with the strongest signal (in a little simplified view). Of course, BTSes need some attention and technicians need to check their function periodically.
The technicians faced a very interesting problem recently. Given a set of BTSes to visit, they needed to find the shortest path to visit all of the given points and return back to the central company building. Programmers have spent several months studying this problem but with no results. They were unable to find the solution fast enough. After a long time, one of the programmers found this problem in a conference article. Unfortunately, he found that the problem is so called "Traveling Salesman Problem" and it is very hard to solve. If we have $N$ BTSes to be visited, we can visit them in any order, giving us $N!$ possibilities to examine. The function expressing that number is called factorial and can be computed as a product:
$1.2.3.4....N$. The number is very high even for a relatively small $N$.
The programmers understood they had no chance to solve the problem. But because they have already received the research grant from the government, they needed to continue with their studies and produce at least some results. So they started to study behaviour of the factorial function.
For example, they defined the function $Z$. For any positive integer $N$, $Z$($N$) is the number of zeros at the end of the decimal form of number $N!$. They noticed that this function never decreases. If we have two numbers $N_{1} < N_{2}$ then $Z(N_{1}) ≤ Z(N_{2})$. It is because we can never "lose" any
trailing zero by multiplying by any positive number. We can only get new and new zeros. The function $Z$ is very interesting, so we need a computer program that can determine its value efficiently.
------ Input: ------
There is a single positive integer $T$ on the first line of input (equal to about $100000$). It stands for the number of numbers to follow. Then there are $T$ lines, each containing exactly one positive integer number $N$, $1 ≤ N ≤ 10^{9}$.
------ Output: ------
For every number $N$, output a single line containing the single non-negative integer $Z(N)$.
----- Sample Input 1 ------
6
3
60
100
1024
23456
8735373
----- Sample Output 1 ------
0
14
24
253
5861
2183837
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x_1 километров вдоль улицы, второй — в точке x_2 и так далее, n-й велопрокат находится в точке x_{n}. Школа Аркадия находится в точке x_1 (то есть там же, где и первый велопрокат), а дом — в точке x_{n} (то есть там же, где и n-й велопрокат). Известно, что x_{i} < x_{i} + 1 для всех 1 ≤ i < n.
Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.
За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы.
Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.
-----Входные данные-----
В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде.
В следующей строке следует последовательность целых чисел x_1, x_2, ..., x_{n} (0 ≤ x_1 < x_2 < ... < x_{n} ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.
-----Выходные данные-----
Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.
-----Примеры-----
Входные данные
4 4
3 6 8 10
Выходные данные
2
Входные данные
2 9
10 20
Выходные данные
-1
Входные данные
12 3
4 6 7 9 10 11 13 15 17 18 20 21
Выходные данные
6
-----Примечание-----
В первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.
Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 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 are strings s and t of length N each, both consisting of lowercase English letters.
Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.
-----Constraints-----
- 1 \leq N \leq 100
- |S| = |T| = N
- S and T are strings consisting of lowercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
N
S T
-----Output-----
Print the string formed.
-----Sample Input-----
2
ip cc
-----Sample Output-----
icpc
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian as well.
Given n words w[1..n], which originate from the same stem (e.g. grace, graceful, disgraceful, gracefully), we are interested in the original stem. To simplify the problem, we define the stem as the longest consecutive substring that occurs in all the n words. If there are ties, we will choose the smallest one in the alphabetical (lexicographic) order.
------ Input ------
The first line contains an integer T denoting the total number of test cases.
In each test cases, the first line contains an integer n denoting the number of words. In the second line, n words w[1..n] consisting of lower case characters are given as a single space-spearated list.
------ Output ------
For each test case, output the stem in a new line.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ n ≤ 10$
$1 ≤ |w[i]| ≤ 20$
----- Sample Input 1 ------
1
4
grace graceful disgraceful gracefully
----- Sample Output 1 ------
grace
----- explanation 1 ------
The stem is grace.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string $s$, consisting of lowercase English letters. Find the longest string, $t$, which satisfies the following conditions: The length of $t$ does not exceed the length of $s$. $t$ is a palindrome. There exists two strings $a$ and $b$ (possibly empty), such that $t = a + b$ ( "$+$" represents concatenation), and $a$ is prefix of $s$ while $b$ is suffix of $s$.
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^5$), the number of test cases. The next $t$ lines each describe a test case.
Each test case is a non-empty string $s$, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed $10^6$.
-----Output-----
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
-----Example-----
Input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
-----Note-----
In the first test, the string $s = $"a" satisfies all conditions.
In the second test, the string "abcdfdcba" satisfies all conditions, because: Its length is $9$, which does not exceed the length of the string $s$, which equals $11$. It is a palindrome. "abcdfdcba" $=$ "abcdfdc" $+$ "ba", and "abcdfdc" is a prefix of $s$ while "ba" is a suffix of $s$.
It can be proven that there does not exist a longer string which satisfies the conditions.
In the fourth test, the string "c" is correct, because "c" $=$ "c" $+$ "" and $a$ or $b$ can be empty. The other possible solution for this test is "s".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations:
* push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$.
* randomAccess($p$): Print element $a_p$.
* pop($d$): Delete the first element of $A$, if $d = 0$. Delete the last element of $A$, if $d = 1$.
$A$ is a 0-origin array and it is empty in the initial state.
Constraints
* $1 \leq q \leq 400,000$
* $0 \leq p < $ the size of $A$
* $-1,000,000,000 \leq x \leq 1,000,000,000$
Input
The input is given in the following format.
$q$
$query_1$
$query_2$
:
$query_q$
Each query $query_i$ is given by
0 $d$ $x$
or
1 $p$
or
2 $d$
where the first digits 0, 1 and 2 represent push, randomAccess and pop operations respectively.
randomAccess and pop operations will not be given for an empty array.
Output
For each randomAccess, print $a_p$ in a line.
Example
Input
11
0 0 1
0 0 2
0 1 3
1 0
1 1
1 2
2 0
2 1
0 0 4
1 0
1 1
Output
2
1
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.
There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (b_1, b_2, ..., b_N). Here, each b_i is a non-negative integer.
Determine whether the objective is achievable, and find the minimum necessary number of operations if the answer is positive.
Constraints
* 2 ≤ N ≤ 10^5
* a_i and b_i are integers.
* 0 ≤ a_i, b_i < 2^{30}
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
b_1 b_2 ... b_N
Output
If the objective is achievable, print the minimum necessary number of operations. Otherwise, print `-1` instead.
Examples
Input
3
0 1 2
3 1 0
Output
2
Input
3
0 1 2
0 1 2
Output
0
Input
2
1 1
0 0
Output
-1
Input
4
0 1 2 3
1 0 3 2
Output
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.
Implement a function/class, which should return an integer if the input string is in one of the formats specified below, or `null/nil/None` otherwise.
Format:
* Optional `-` or `+`
* Base prefix `0b` (binary), `0x` (hexadecimal), `0o` (octal), or in case of no prefix decimal.
* Digits depending on base
Any extra character (including whitespace) makes the input invalid, in which case you should return `null/nil/None`.
Digits are case insensitive, but base prefix must be lower case.
See the test cases for examples.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata, you'll be given an integer of range `0 <= x <= 99` and have to return that number spelt out in English. A few examples:
```python
name_that_number(4) # returns "four"
name_that_number(19) # returns "nineteen"
name_that_number(99) # returns "ninety nine"
```
Words should be separated by only spaces and not hyphens. No need to validate parameters, they will always be in the range [0, 99]. Make sure that the returned String has no leading of trailing spaces. Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It's your Birthday. Your colleagues buy you a cake. The numbers of candles on the cake is provided (x). Please note this is not reality, and your age can be anywhere up to 1,000. Yes, you would look a mess.
As a surprise, your colleagues have arranged for your friend to hide inside the cake and burst out. They pretend this is for your benefit, but likely it is just because they want to see you fall over covered in cake. Sounds fun!
When your friend jumps out of the cake, he/she will knock some of the candles to the floor. If the number of candles that fall is higher than 70% of total candles (x), the carpet will catch fire.
You will work out the number of candles that will fall from the provided string (y). You must add up the character ASCII code of each even indexed (assume a 0 based indexing) character in y, with the alphabetical position of each odd indexed character in y to give the string a total.
example: 'abc' --> a=97, b=2, c=99 --> y total = 198.
If the carpet catches fire, return 'Fire!', if not, return 'That was close!'.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a matrix A of size x × y filled with integers. For every $i \in [ 1 . . x ]$, $j \in [ 1 . . y ]$ A_{i}, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix.
You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a_1, a_2, ..., a_{n} denoting that you started in the cell containing the number a_1, then moved to the cell with the number a_2, and so on.
From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i < x; (i, j + 1) — only if j < y; (i - 1, j) — only if i > 1; (i, j - 1) — only if j > 1.
Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a_1, then move to the cell containing a_2 (in one step), then move to the cell containing a_3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?
-----Input-----
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice).
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the integers in the cells on your path.
-----Output-----
If all possible values of x and y such that 1 ≤ x, y ≤ 10^9 contradict with the information about your path, print NO.
Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 10^9.
-----Examples-----
Input
8
1 2 3 6 9 8 5 2
Output
YES
3 3
Input
6
1 2 1 2 5 3
Output
NO
Input
2
1 10
Output
YES
4 9
-----Note-----
The matrix and the path on it in the first test looks like this: [Image]
Also there exist multiple correct answers for both the first and the third examples.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given N real values A_1, A_2, \ldots, A_N. Compute the number of pairs of indices (i, j) such that i < j and the product A_i \cdot A_j is integer.
Constraints
* 2 \leq N \leq 200\,000
* 0 < A_i < 10^4
* A_i is given with at most 9 digits after the decimal.
Input
Input is given from Standard Input in the following format.
N
A_1
A_2
\vdots
A_N
Output
Print the number of pairs with integer product A_i \cdot A_j (and i < j).
Examples
Input
5
7.5
2.4
17.000000001
17
16.000000000
Output
3
Input
11
0.9
1
1
1.25
2.30000
5
70
0.000000001
9999.999999999
0.999999999
1.000000001
Output
8
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.
An example of a trapezoid
Find the area of this trapezoid.
-----Constraints-----
- 1≦a≦100
- 1≦b≦100
- 1≦h≦100
- All input values are integers.
- h is even.
-----Input-----
The input is given from Standard Input in the following format:
a
b
h
-----Output-----
Print the area of the given trapezoid. It is guaranteed that the area is an integer.
-----Sample Input-----
3
4
2
-----Sample Output-----
7
When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:
Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1
Write a program which sorts elements of given array ascending order based on the counting sort.
Constraints
* 1 ≤ n ≤ 2,000,000
* 0 ≤ A[i] ≤ 10,000
Input
The first line of the input includes an integer n, the number of elements in the sequence.
In the second line, n elements of the sequence are given separated by spaces characters.
Output
Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.
Example
Input
7
2 5 1 3 2 3 0
Output
0 1 2 2 3 3 5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a string S consisting of N uppercase English letters. You are allowed to perform at most one operation of following kind: Choose any position in the string, remove the character at that position and insert it back to any other place in the string.
Find the lexicographically smallest string you can achieve.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains the single integer N denoting length of string S.
The second line contains the string S.
-----Output-----
For each test case, output a single line containing the answer to the corresponding test case.
-----Constraints-----
- 1 ≤ T ≤ 50
- 1 ≤ N ≤ 50
- S will consist of uppercase English letters.
-----Example-----
Input:
2
4
DCBA
7
XYZZYZZ
Output:
ADCB
XYYZZZZ
-----Explanation-----
Example case 1. The optimal solution here is to choose the last character and put it in the beginning of the string. So the answer will be ADCB
Example case 2. The optimal solution here is to choose the 5-th character (1-based index) and put it between the 2-nd and the 3-rd characters. So the answer will be XYYZZZZ
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
International Women's Day is coming soon! Polycarp is preparing for the holiday.
There are $n$ candy boxes in the shop for sale. The $i$-th box contains $d_i$ candies.
Polycarp wants to prepare the maximum number of gifts for $k$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $k$. In other words, two boxes $i$ and $j$ ($i \ne j$) can be combined as a gift if $d_i + d_j$ is divisible by $k$.
How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$) — the number the boxes and the number the girls.
The second line of the input contains $n$ integers $d_1, d_2, \dots, d_n$ ($1 \le d_i \le 10^9$), where $d_i$ is the number of candies in the $i$-th box.
-----Output-----
Print one integer — the maximum number of the boxes Polycarp can give as gifts.
-----Examples-----
Input
7 2
1 2 2 3 2 4 10
Output
6
Input
8 2
1 2 2 3 2 4 6 10
Output
8
Input
7 3
1 2 2 3 2 4 5
Output
4
-----Note-----
In the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $(2, 3)$; $(5, 6)$; $(1, 4)$.
So the answer is $6$.
In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $(6, 8)$; $(2, 3)$; $(1, 4)$; $(5, 7)$.
So the answer is $8$.
In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes): $(1, 2)$; $(6, 7)$.
So the answer is $4$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem
Given the strings $ s $, $ t $.
First, let the string set $ A = $ {$ s $}, $ B = \ phi $.
At this time, I want to perform the following operations as much as possible.
operation
step1
Perform the following processing for all $ u ∊ A $.
1. From all subsequences of $ u $ (not necessarily contiguous), choose any one that is equal to $ t $. Let the indexes corresponding to $ u $ of the selected subsequence be $ z_1 $, $ z_2 $,…, $ z_ {| t |} $ (however, 1 $ \ le $ $ z_1 $ $ \ lt $ $ z_2). $$ \ lt $… $ \ lt $ $ z_ {| t |} $ $ \ le $ $ | u | $). If there is no such subsequence, the operation ends.
2. Divide the original string with the selected substring characters $ u_ {z_1} $, $ u_ {z_2} $,…, $ u_ {z_ {| t |}} $ and convert them to $ B $ to add.
For example, in the case of $ u = $ "abcdcd" and $ t = $ "ac", the following two division methods can be considered.
If you choose the first and third characters of $ u $, it will be split into "", "b" and "dcd".
If you choose the first and fifth characters of $ u $, it will be split into "", "bcd" and "d".
step2
Replace $ A $ with $ B $ and empty $ B $.
Increase the number of operations by 1.
Subsequence example
The subsequences of "abac" are {"", "a", "b", "c", "aa", "ab", "ac", "ba", "bc", "aac", "aba" "," abc "," bac "," abac "}.
"a" is a subsequence created by extracting the first or third character of "abac".
"ac" is a subsequence created by extracting the 1st and 4th characters of "abac" or the 3rd and 4th characters.
Constraints
The input satisfies the following conditions.
* 1 $ \ le $ $ | t | $ $ \ le $ $ | s | $ $ \ le $ $ 10 ^ 5 $
* Characters contained in the strings $ s $ and $ t $ are uppercase or lowercase letters of the alphabet
Input
The input is given in the following format.
$ s $
$ t $
The string $ s $ is given on the first line, and the string $ t $ is given on the second line.
Output
Output the maximum number of operations.
Examples
Input
AABABCAC
A
Output
2
Input
abaabbabaabaabbabbabaabbab
ab
Output
3
Input
AbCdEfG
aBcDeFg
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 50) — the sizes of the sheet of paper.
Each of the next n lines contains m characters — the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<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.
There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.
We want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: Either this person does not go on the trip, Or at least $k$ of his friends also go on the trip.
Note that the friendship is not transitive. That is, if $a$ and $b$ are friends and $b$ and $c$ are friends, it does not necessarily imply that $a$ and $c$ are friends.
For each day, find the maximum number of people that can go on the trip on that day.
-----Input-----
The first line contains three integers $n$, $m$, and $k$ ($2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5$, $1 \le k < n$) — the number of people, the number of days and the number of friends each person on the trip should have in the group.
The $i$-th ($1 \leq i \leq m$) of the next $m$ lines contains two integers $x$ and $y$ ($1\leq x, y\leq n$, $x\ne y$), meaning that persons $x$ and $y$ become friends on the morning of day $i$. It is guaranteed that $x$ and $y$ were not friends before.
-----Output-----
Print exactly $m$ lines, where the $i$-th of them ($1\leq i\leq m$) contains the maximum number of people that can go on the trip on the evening of the day $i$.
-----Examples-----
Input
4 4 2
2 3
1 2
1 3
1 4
Output
0
0
3
3
Input
5 8 2
2 1
4 2
5 4
5 2
4 3
5 1
4 1
3 2
Output
0
0
0
3
3
4
4
5
Input
5 7 2
1 5
3 2
2 5
3 4
1 2
5 3
1 3
Output
0
0
0
0
3
4
4
-----Note-----
In the first example, $1,2,3$ can go on day $3$ and $4$.
In the second example, $2,4,5$ can go on day $4$ and $5$. $1,2,4,5$ can go on day $6$ and $7$. $1,2,3,4,5$ can go on day $8$.
In the third example, $1,2,5$ can go on day $5$. $1,2,3,5$ can go on day $6$ and $7$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two people are playing a game with a string $s$, consisting of lowercase latin letters.
On a player's turn, he should choose two consecutive equal letters in the string and delete them.
For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.
Your task is to determine which player will win if both play optimally.
-----Input-----
The only line contains the string $s$, consisting of lowercase latin letters ($1 \leq |s| \leq 100\,000$), where $|s|$ means the length of a string $s$.
-----Output-----
If the first player wins, print "Yes". If the second player wins, print "No".
-----Examples-----
Input
abacaba
Output
No
Input
iiq
Output
Yes
Input
abba
Output
No
-----Note-----
In the first example the first player is unable to make a turn, so he loses.
In the second example first player turns the string into "q", then second player is unable to move, so he loses.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs a_{i} minutes to read the i-th book.
Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it.
Print the maximum number of books Valera can read.
-----Input-----
The first line contains two integers n and t (1 ≤ n ≤ 10^5; 1 ≤ t ≤ 10^9) — the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4), where number a_{i} shows the number of minutes that the boy needs to read the i-th book.
-----Output-----
Print a single integer — the maximum number of books Valera can read.
-----Examples-----
Input
4 5
3 1 2 1
Output
3
Input
3 3
2 2 3
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. [Image]
The park consists of 2^{n} + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2^{n}, 2^{n} + 1, ..., 2^{n} + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≤ i < 2^{n} + 1) there is a road to the square $\lfloor \frac{i}{2} \rfloor$. Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. [Image] To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square $\lfloor \frac{i}{2} \rfloor$ has a_{i} lights.
Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe.
He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10) — the number of roads on the path from the entrance to any exit.
The next line contains 2^{n} + 1 - 2 numbers a_2, a_3, ... a_2^{n} + 1 - 1 — the initial numbers of street lights on each road of the park. Here a_{i} is the number of street lights on the road between squares i and $\lfloor \frac{i}{2} \rfloor$. All numbers a_{i} are positive integers, not exceeding 100.
-----Output-----
Print the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.
-----Examples-----
Input
2
1 2 3 4 5 6
Output
5
-----Note-----
Picture for the sample test. Green color denotes the additional street lights. [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.
Vlad enjoys listening to music. He lives in Sam's Town. A few days ago he had a birthday, so his parents gave him a gift: MP3-player! Vlad was the happiest man in the world! Now he can listen his favorite songs whenever he wants!
Vlad built up his own playlist. The playlist consists of N songs, each has a unique positive integer length. Vlad likes all the songs from his playlist, but there is a song, which he likes more than the others. It's named "Uncle Johny".
After creation of the playlist, Vlad decided to sort the songs in increasing order of their lengths. For example, if the lengths of the songs in playlist was {1, 3, 5, 2, 4} after sorting it becomes {1, 2, 3, 4, 5}. Before the sorting, "Uncle Johny" was on K-th position (1-indexing is assumed for the playlist) in the playlist.
Vlad needs your help! He gives you all the information of his playlist. Your task is to find the position of "Uncle Johny" in the sorted playlist.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains one integer N denoting the number of songs in Vlad's playlist. The second line contains N space-separated integers A1, A2, ..., AN denoting the lenghts of Vlad's songs.
The third line contains the only integer K - the position of "Uncle Johny" in the initial playlist.
-----Output-----
For each test case, output a single line containing the position of "Uncle Johny" in the sorted playlist.
-----Constraints-----
1 ≤ T ≤ 1000
1 ≤ K ≤ N ≤ 100
1 ≤ Ai ≤ 109
-----Example-----
Input:
3
4
1 3 4 2
2
5
1 2 3 9 4
5
5
1 2 3 9 4
1
Output:
3
4
1
-----Explanation-----
In the example test there are T=3 test cases.
Test case 1
In the first test case N equals to 4, K equals to 2, A equals to {1, 3, 4, 2}. The answer is 3, because {1, 3, 4, 2} -> {1, 2, 3, 4}. A2 now is on the 3-rd position.
Test case 2
In the second test case N equals to 5, K equals to 5, A equals to {1, 2, 3, 9, 4}. The answer is 4, because {1, 2, 3, 9, 4} -> {1, 2, 3, 4, 9}. A5 now is on the 4-th position.
Test case 3
In the third test case N equals to 5, K equals to 1, A equals to {1, 2, 3, 9, 4}. The answer is 1, because {1, 2, 3, 9, 4} -> {1, 2, 3, 4, 9}. A1 stays on the 1-th position.
-----Note-----
"Uncle Johny" is a real song performed by The Killers.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited.
The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.
Input
The first line contains positive integer n (1 ≤ n ≤ 100) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.
Output
If the given state is reachable in the described game, output YES, otherwise NO.
Examples
Input
5
5 4 3 2 1
1 1 1 1 1
Output
YES
Input
7
4 3 5 1 2 7 6
4 6 6 1 6 6 1
Output
NO
Input
7
4 2 5 1 3 7 6
4 6 6 1 6 6 1
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.
You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick.
Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.
-----Input-----
The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·10^5, 0 ≤ l ≤ 3·10^5).
-----Output-----
Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it.
-----Examples-----
Input
1 1 1 2
Output
4
Input
1 2 3 1
Output
2
Input
10 2 1 7
Output
0
-----Note-----
In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.
In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.
-----Constraints-----
- s_1, s_2 and s_3 are composed of lowercase English letters.
- 1 ≤ |s_i| ≤ 10 (1≤i≤3)
-----Input-----
Input is given from Standard Input in the following format:
s_1 s_2 s_3
-----Output-----
Print the answer.
-----Sample Input-----
atcoder beginner contest
-----Sample Output-----
ABC
The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem:
You've got some training set of documents. For each document you know its subject. The subject in this problem is an integer from 1 to 3. Each of these numbers has a physical meaning. For instance, all documents with subject 3 are about trade.
You can download the training set of documents at the following link: http://download4.abbyy.com/a2/X2RZ2ZWXBG5VYWAL61H76ZQM/train.zip. The archive contains three directories with names "1", "2", "3". Directory named "1" contains documents on the 1-st subject, directory "2" contains documents on the 2-nd subject, and directory "3" contains documents on the 3-rd subject. Each document corresponds to exactly one file from some directory.
All documents have the following format: the first line contains the document identifier, the second line contains the name of the document, all subsequent lines contain the text of the document. The document identifier is used to make installing the problem more convenient and has no useful information for the participants.
You need to write a program that should indicate the subject for a given document. It is guaranteed that all documents given as input to your program correspond to one of the three subjects of the training set.
Input
The first line contains integer id (0 ≤ id ≤ 106) — the document identifier. The second line contains the name of the document. The third and the subsequent lines contain the text of the document. It is guaranteed that the size of any given document will not exceed 10 kilobytes.
The tests for this problem are divided into 10 groups. Documents of groups 1 and 2 are taken from the training set, but their identifiers will not match the identifiers specified in the training set. Groups from the 3-rd to the 10-th are roughly sorted by the author in ascending order of difficulty (these groups contain documents which aren't present in the training set).
Output
Print an integer from 1 to 3, inclusive — the number of the subject the given document corresponds to.
Examples
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
How to make a cake you'll never eat.
Ingredients.
* 2 carrots
* 0 calories
* 100 g chocolate spread
* 1 pack of flour
* 1 egg
Method.
1. Put calories into the mixing bowl.
2. Take carrots from refrigerator.
3. Chop carrots.
4. Take chocolate spread from refrigerator.
5. Put chocolate spread into the mixing bowl.
6. Combine pack of flour into the mixing bowl.
7. Fold chocolate spread into the mixing bowl.
8. Add chocolate spread into the mixing bowl.
9. Put pack of flour into the mixing bowl.
10. Add egg into the mixing bowl.
11. Fold pack of flour into the mixing bowl.
12. Chop carrots until choped.
13. Pour contents of the mixing bowl into the baking dish.
Serves 1.
Input
The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).
Output
Output a single integer.
Examples
Input
4 1 2 3 4
Output
30
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.
Each digit is allowed to occur in the number the same number of times it occurs in the set.
Input
A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.
Output
On a single line print the answer to the problem. If such number does not exist, then you should print -1.
Examples
Input
1
0
Output
0
Input
11
3 4 5 4 5 3 5 3 4 4 0
Output
5554443330
Input
8
3 2 5 1 5 2 2 3
Output
-1
Note
In the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Description
Your job is to create a simple password validation function, as seen on many websites.
The rules for a valid password are as follows:
- There needs to be at least 1 uppercase letter.
- There needs to be at least 1 lowercase letter.
- There needs to be at least 1 number.
- The password needs to be at least 8 characters long.
You are permitted to use any methods to validate the password.
## Examples:
### Extra info
- You will only be passed strings.
- The string can contain any standard keyboard character.
- Accepted strings can be any length, as long as they are 8 characters or more.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and n water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost.
As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has (n - 1) friends. Determine if Sereja's friends can play the game so that nobody loses.
-----Input-----
The first line contains integers n and s (2 ≤ n ≤ 100; 1 ≤ s ≤ 1000) — the number of mugs and the volume of the cup. The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10). Number a_{i} means the volume of the i-th mug.
-----Output-----
In a single line, print "YES" (without the quotes) if his friends can play in the described manner, and "NO" (without the quotes) otherwise.
-----Examples-----
Input
3 4
1 1 1
Output
YES
Input
3 4
3 1 3
Output
YES
Input
3 4
4 4 4
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N squares arranged in a row, numbered 1, 2, ..., N from left to right. You are given a string S of length N consisting of `.` and `#`. If the i-th character of S is `#`, Square i contains a rock; if the i-th character of S is `.`, Square i is empty.
In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.
You can repeat the following operation any number of times:
* Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.
You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.
Determine whether this is possible.
Constraints
* 4 \leq N \leq 200\ 000
* S is a string of length N consisting of `.` and `#`.
* 1 \leq A, B, C, D \leq N
* Square A, B, C and D do not contain a rock.
* A, B, C and D are all different.
* A < B
* A < C
* B < D
Input
Input is given from Standard Input in the following format:
N A B C D
S
Output
Print `Yes` if the objective is achievable, and `No` if it is not.
Examples
Input
7 1 3 6 7
.#..#..
Output
Yes
Input
7 1 3 7 6
.#..#..
Output
No
Input
15 1 3 15 13
...#.#...#.#...
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.
You are given a chessboard of size $n \times n$. It is filled with numbers from $1$ to $n^2$ in the following way: the first $\lceil \frac{n^2}{2} \rceil$ numbers from $1$ to $\lceil \frac{n^2}{2} \rceil$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $n^2 - \lceil \frac{n^2}{2} \rceil$ numbers from $\lceil \frac{n^2}{2} \rceil + 1$ to $n^2$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $\lceil\frac{x}{y}\rceil$ means division $x$ by $y$ rounded up.
For example, the left board on the following picture is the chessboard which is given for $n=4$ and the right board is the chessboard which is given for $n=5$. [Image]
You are given $q$ queries. The $i$-th query is described as a pair $x_i, y_i$. The answer to the $i$-th query is the number written in the cell $x_i, y_i$ ($x_i$ is the row, $y_i$ is the column). Rows and columns are numbered from $1$ to $n$.
-----Input-----
The first line contains two integers $n$ and $q$ ($1 \le n \le 10^9$, $1 \le q \le 10^5$) — the size of the board and the number of queries.
The next $q$ lines contain two integers each. The $i$-th line contains two integers $x_i, y_i$ ($1 \le x_i, y_i \le n$) — description of the $i$-th query.
-----Output-----
For each query from $1$ to $q$ print the answer to this query. The answer to the $i$-th query is the number written in the cell $x_i, y_i$ ($x_i$ is the row, $y_i$ is the column). Rows and columns are numbered from $1$ to $n$. Queries are numbered from $1$ to $q$ in order of the input.
-----Examples-----
Input
4 5
1 1
4 4
4 3
3 2
2 4
Output
1
8
16
13
4
Input
5 4
2 1
4 2
3 3
3 4
Output
16
9
7
20
-----Note-----
Answers to the queries from examples are on the board in the picture from the problem 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.
There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.)
For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem:
- Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K.
Here, or denotes the bitwise OR.
-----Constraints-----
- 1 \leq N \leq 18
- 1 \leq A_i \leq 10^9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_0 A_1 ... A_{2^N-1}
-----Output-----
Print 2^N-1 lines.
In the i-th line, print the answer of the problem above for K=i.
-----Sample Input-----
2
1 2 3 1
-----Sample Output-----
3
4
5
For K=1, the only possible pair of i and j is (i,j)=(0,1), so the answer is A_0+A_1=1+2=3.
For K=2, the possible pairs of i and j are (i,j)=(0,1),(0,2).
When (i,j)=(0,2), A_i+A_j=1+3=4. This is the maximum value, so the answer is 4.
For K=3, the possible pairs of i and j are (i,j)=(0,1),(0,2),(0,3),(1,2),(1,3),(2,3) .
When (i,j)=(1,2), A_i+A_j=2+3=5. This is the maximum value, so the answer is 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given $n$ segments on a coordinate axis $OX$. The $i$-th segment has borders $[l_i; r_i]$. All points $x$, for which $l_i \le x \le r_i$ holds, belong to the $i$-th segment.
Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.
Two segments $[l_i; r_i]$ and $[l_j; r_j]$ are non-intersecting if they have no common points. For example, segments $[1; 2]$ and $[3; 4]$, $[1; 3]$ and $[5; 5]$ are non-intersecting, while segments $[1; 2]$ and $[2; 3]$, $[1; 2]$ and $[2; 2]$ are intersecting.
The segment $[l_i; r_i]$ lies inside the segment $[l_j; r_j]$ if $l_j \le l_i$ and $r_i \le r_j$. For example, segments $[2; 2]$, $[2, 3]$, $[3; 4]$ and $[2; 4]$ lie inside the segment $[2; 4]$, while $[2; 5]$ and $[1; 4]$ are not.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 3000$) — the number of segments. The next $n$ lines describe segments. The $i$-th segment is given as two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 2 \cdot 10^5$), where $l_i$ is the left border of the $i$-th segment and $r_i$ is the right border of the $i$-th segment.
Additional constraint on the input: there are no duplicates in the list of segments.
It is guaranteed that the sum of $n$ does not exceed $3000$ ($\sum n \le 3000$).
-----Output-----
For each test case, print the answer: the maximum possible size of the subset of the given set of segments such that each pair of segments in this subset either non-intersecting or one of them lies inside the other one.
-----Example-----
Input
4
4
1 5
2 4
2 3
3 4
5
1 5
2 3
2 5
3 5
2 2
3
1 3
2 4
2 3
7
1 10
2 8
2 5
3 4
4 4
6 8
7 7
Output
3
4
2
7
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a string $s$ of length $3$, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.
-----Input-----
The first line of the input contains an integer $t$ ($1 \leq t \leq 10^3$) — the number of testcases.
The description of each test consists of one line containing one string $s$ consisting of three characters. Each character of $s$ is either an uppercase or lowercase English letter.
-----Output-----
For each test case, output "YES" (without quotes) if $s$ satisfies the condition, and "NO" (without quotes) otherwise.
You can output "YES" and "NO" in any case (for example, strings "yES", "yes" and "Yes" will be recognized as a positive response).
-----Examples-----
Input
10
YES
yES
yes
Yes
YeS
Noo
orZ
yEz
Yas
XES
Output
YES
YES
YES
YES
YES
NO
NO
NO
NO
NO
-----Note-----
The first five test cases contain the strings "YES", "yES", "yes", "Yes", "YeS". All of these are equal to "YES", where each character is either uppercase or lowercase.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have $n$ chains, the $i$-th chain consists of $c_i$ vertices. Vertices in each chain are numbered independently from $1$ to $c_i$ along the chain. In other words, the $i$-th chain is the undirected graph with $c_i$ vertices and $(c_i - 1)$ edges connecting the $j$-th and the $(j + 1)$-th vertices for each $1 \le j < c_i$.
Now you decided to unite chains in one graph in the following way:
the first chain is skipped;
the $1$-st vertex of the $i$-th chain is connected by an edge with the $a_i$-th vertex of the $(i - 1)$-th chain;
the last ($c_i$-th) vertex of the $i$-th chain is connected by an edge with the $b_i$-th vertex of the $(i - 1)$-th chain.
Picture of the first test case. Dotted lines are the edges added during uniting process
Calculate the length of the longest simple cycle in the resulting graph.
A simple cycle is a chain where the first and last vertices are connected as well. If you travel along the simple cycle, each vertex of this cycle will be visited exactly once.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains the single integer $n$ ($2 \le n \le 10^5$) — the number of chains you have.
The second line of each test case contains $n$ integers $c_1, c_2, \dots, c_n$ ($2 \le c_i \le 10^9$) — the number of vertices in the corresponding chains.
The third line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($a_1 = -1$; $1 \le a_i \le c_{i - 1}$).
The fourth line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($b_1 = -1$; $1 \le b_i \le c_{i - 1}$).
Both $a_1$ and $b_1$ are equal to $-1$, they aren't used in graph building and given just for index consistency. It's guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, print the length of the longest simple cycle.
-----Examples-----
Input
3
4
3 4 3 3
-1 1 2 2
-1 2 2 3
2
5 6
-1 5
-1 1
3
3 5 2
-1 1 1
-1 3 5
Output
7
11
8
-----Note-----
In the first test case, the longest simple cycle is shown below:
We can't increase it with the first chain, since in such case it won't be simple — the vertex $2$ on the second chain will break simplicity.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that $f(k x \operatorname{mod} p) \equiv k \cdot f(x) \operatorname{mod} p$
for some function $f : \{0,1,2, \cdots, p - 1 \} \rightarrow \{0,1,2, \cdots, p - 1 \}$. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.)
It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 10^9 + 7.
-----Input-----
The input consists of two space-separated integers p and k (3 ≤ p ≤ 1 000 000, 0 ≤ k ≤ p - 1) on a single line. It is guaranteed that p is an odd prime number.
-----Output-----
Print a single integer, the number of distinct functions f modulo 10^9 + 7.
-----Examples-----
Input
3 2
Output
3
Input
5 4
Output
25
-----Note-----
In the first sample, p = 3 and k = 2. The following functions work: f(0) = 0, f(1) = 1, f(2) = 2. f(0) = 0, f(1) = 2, f(2) = 1. f(0) = f(1) = f(2) = 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply).
As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "If the squared distance between some two soldiers equals to 5, then those soldiers will conflict with each other!"
The drill exercises are held on a rectangular n × m field, split into nm square 1 × 1 segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares (x1, y1) and (x2, y2) equals exactly (x1 - x2)2 + (y1 - y2)2. Now not all nm squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square (2, 2), then he cannot put soldiers in the squares (1, 4), (3, 4), (4, 1) and (4, 3) — each of them will conflict with the soldier in the square (2, 2).
Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.
Input
The single line contains space-separated integers n and m (1 ≤ n, m ≤ 1000) that represent the size of the drill exercise field.
Output
Print the desired maximum number of warriors.
Examples
Input
2 4
Output
4
Input
3 4
Output
6
Note
In the first sample test Sir Lancelot can place his 4 soldiers on the 2 × 4 court as follows (the soldiers' locations are marked with gray circles on the scheme):
<image>
In the second sample test he can place 6 soldiers on the 3 × 4 site in the following manner:
<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.
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.
<image>
There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are indexed from 1 to n in the clockwise direction. Sectors i and i + 1 are adjacent for every i, 1 ≤ i < n. In addition, sectors 1 and n are also adjacent.
Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.
A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.
Unstable cells are marked red in the figure. Stable cells are marked green.
Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.
Input
The first line contains integer n (3 ≤ n ≤ 1000) — the number of main threads.
The i-th of following n lines describe the bridges located in the i-th sector: first it contains integer ki (1 ≤ ki ≤ 105) equal to the number of bridges in the given sector. Then follow ki different integers pij (1 ≤ pij ≤ 105; 1 ≤ j ≤ ki). Number pij equals the distance from the attachment points of the j-th bridge of the i-th sector to the center of the web.
It is guaranteed that any two bridges between adjacent sectors are attached at a different distance from the center of the web. It is guaranteed that the total number of the bridges doesn't exceed 105.
Output
Print a single integer — the number of unstable cells in Paw the Spider's web.
Examples
Input
7
3 1 6 7
4 3 5 2 9
2 8 1
4 3 7 6 4
3 2 5 9
3 6 3 8
3 4 2 9
Output
6
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation:
1. Select the subtree of the given tree that includes the vertex with number 1.
2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree.
Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
Input
The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree.
The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109).
Output
Print the minimum number of operations needed to solve the task.
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
3
1 2
1 3
1 -1 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.
The polar bears are going fishing. They plan to sail from (s_{x}, s_{y}) to (e_{x}, e_{y}). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y). If the wind blows to the east, the boat will move to (x + 1, y). If the wind blows to the south, the boat will move to (x, y - 1). If the wind blows to the west, the boat will move to (x - 1, y). If the wind blows to the north, the boat will move to (x, y + 1).
Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (e_{x}, e_{y})?
-----Input-----
The first line contains five integers t, s_{x}, s_{y}, e_{x}, e_{y} (1 ≤ t ≤ 10^5, - 10^9 ≤ s_{x}, s_{y}, e_{x}, e_{y} ≤ 10^9). The starting location and the ending location will be different.
The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).
-----Output-----
If they can reach (e_{x}, e_{y}) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).
-----Examples-----
Input
5 0 0 1 1
SESNW
Output
4
Input
10 5 3 3 6
NENSWESNEE
Output
-1
-----Note-----
In the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.
In the second sample, they cannot sail to the destination.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 time is 2020. There is data that saves the qualifying results of PC Koshien 2020. This data stores the reference number and the number of correct answers assigned to each team. Here, the ranking is determined by the number of correct answers, and the ranking is given in descending order of the number of correct answers, such as 1st, 2nd, and so on.
Enter the qualifying result data and reference number from the keyboard, and create a program that outputs the ranking of the team with that number.
Note
In the data of the input example, if the teams are arranged in order of the number of correct answers:
3,30
1,20
2,20
6,20
4,10
5,10
It will be. Here, in order to determine the ranking based on the number of correct answers, the 30-question correct answer team is ranked 1st, the 20-question correct answer team is ranked 2nd, and the 10-question correct answer team is ranked 3rd. Please note that this is different from the usual ranking with the correct team in 5th place).
Input
The input data consists of two parts. The first half is the qualifying result data, and the second half is the inquiry of the team number for which you want to know the ranking. The format of the qualifying result data is as follows.
p1, s1
p2, s2
...
...
0,0
pi (1 ≤ pi ≤ 100) and si (0 ≤ si ≤ 30) are integers representing the reference number and the number of correct answers for the i-th team, respectively. It is assumed that the input of this data is completed when both the reference number and the number of correct answers are 0.
Then multiple inquiries in the second half are given. The inquiry format is as follows.
q1
q2
::
Each query is given the reference number qi (1 ≤ qi ≤ 30) on one line. Please process this until the end of the input. The number of inquiries does not exceed 100.
Output
For each inquiry, print the team ranking on one line.
Example
Input
1,20
2,20
3,30
4,10
5,10
6,20
0,0
1
2
4
5
Output
2
2
3
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.
The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $n$ hotels, where the $i$-th hotel is located in the city with coordinate $x_i$. Sonya is a smart girl, so she does not open two or more hotels in the same city.
Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $d$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel.
Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $n$ hotels to the new one is equal to $d$.
-----Input-----
The first line contains two integers $n$ and $d$ ($1\leq n\leq 100$, $1\leq d\leq 10^9$) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others.
The second line contains $n$ different integers in strictly increasing order $x_1, x_2, \ldots, x_n$ ($-10^9\leq x_i\leq 10^9$) — coordinates of Sonya's hotels.
-----Output-----
Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $d$.
-----Examples-----
Input
4 3
-3 2 9 16
Output
6
Input
5 2
4 8 11 18 19
Output
5
-----Note-----
In the first example, there are $6$ possible cities where Sonya can build a hotel. These cities have coordinates $-6$, $5$, $6$, $12$, $13$, and $19$.
In the second example, there are $5$ possible cities where Sonya can build a hotel. These cities have coordinates $2$, $6$, $13$, $16$, and $21$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let S be the concatenation of 10^{10} copies of the string 110. (For reference, the concatenation of 3 copies of 110 is 110110110.)
We have a string T of length N.
Find the number of times T occurs in S as a contiguous substring.
-----Constraints-----
- 1 \leq N \leq 2 \times 10^5
- T is a string of length N consisting of 0 and 1.
-----Input-----
Input is given from Standard Input in the following format:
N
T
-----Output-----
Print the number of times T occurs in S as a contiguous substring.
-----Sample Input-----
4
1011
-----Sample Output-----
9999999999
S is so long, so let us instead count the number of times 1011 occurs in the concatenation of 3 copies of 110, that is, 110110110. We can see it occurs twice:
- 1 1011 0110
- 1101 1011 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.
"Fukusekiken" is a popular ramen shop where you can line up. But recently, I've heard some customers say, "I can't afford to have vacant seats when I enter the store, even though I have a long waiting time." I'd like to find out why such dissatisfaction occurs, but I'm too busy to check the actual procession while the shop is open. However, since I know the interval and number of customers coming from many years of experience, I decided to analyze the waiting time based on that.
There are 17 seats in the store facing the counter. The store opens at noon, and customers come as follows.
* 100 groups from 0 to 99 will come.
* The i-th group will arrive at the store 5i minutes after noon.
* The number of people in the i-th group is 5 when i% 5 is 1, and 2 otherwise.
(x% y represents the remainder when x is divided by y.)
* The i-th group finishes the meal in 17 (i% 2) + 3 (i% 3) + 19 minutes when seated.
The arrival times, number of people, and meal times for the first 10 groups are as follows:
Group number | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | ---
Arrival time (minutes later) | 0 | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45
Number of people (people) | 2 | 5 | 2 | 2 | 2 | 2 | 5 | 2 | 2 | 2
Meal time (minutes) | 19 | 39 | 25 | 36 | 22 | 42 | 19 | 39 | 25 | 36
In addition, when guiding customers to their seats, we do the following.
* Seats are numbered from 0 to 16.
* A group of x people can only be seated when there are x open seats in a row.
Also, if there are multiple places to sit, sit in the place with the lowest seat number. For example, if only seats 0, 1, 2, 4, and 5 are available, a group of 5 people cannot be seated. If you are in a group of two, you will be seated at number 0 and 1.
* Once you are seated, you will not be asked to move your seat.
* Customers come and go in 1 minute increments. At each time, we will guide customers in the following order.
1. The next group can be seated at the same time as the previous group leaves.
2. When seating customers, seat as many groups as possible at the same time, starting with the group at the top of the line. It does not overtake the order of the matrix. In other words, if the first group cannot be seated, even if other groups in the procession can be seated, they will not be seated.
3. Groups arriving at that time will line up at the end of the procession, if any. If there is no line and you can sit down, you will be seated, and if you cannot, you will wait in line. As an example, the following shows how the first 10 groups arrive. From left to right, the three columns in each row show the time, seating, and queue. For seats, the "_" is vacant and the number indicates that the group with that number is sitting in that seat.
Time: Seat procession
0: 00 _______________:
5: 0011111 ___________:
10: 001111122 ________:
15: 00111112233______:
18: 00111112233______:
19: __111112233______:
20: 44111112233 ______:
25: 4411111223355____:
30: 4411111223355____: 66666 Group 6 arrives
34: 4411111223355____: 66666
35: 4411111__3355____: 6666677 Group 7 arrives
40: 4411111__3355____: 666667788 Group 8 arrives
41: 4411111__3355____: 666667788
42: __11111__3355____: 666667788
43: __11111__3355____: 666667788
44: 6666677883355____: Groups 6, 7 and 8 are seated
45: 666667788335599__: Group 9 arrives and sits down
For example, at time 40, the eighth group arrives, but cannot be seated and joins the procession. The fourth group eats until time 41. At time 42, seats in the 4th group are available, but the 6th group is not yet seated due to the lack of consecutive seats. The first group eats until time 43. At time 44, the first group will be vacant, so the sixth group will be seated, and at the same time the seventh and eighth groups will be seated. The ninth group arrives at time 45 and will be seated as they are available.
Based on this information, create a program that outputs the time (in minutes) that the nth group of customers waits by inputting an integer n that is 0 or more and 99 or less.
Input
Given multiple datasets. Each dataset consists of one integer n.
The number of datasets does not exceed 20.
Output
For each dataset, print the minute wait time (integer greater than or equal to 0) for the nth customer on a single line.
Example
Input
5
6
7
8
Output
0
14
9
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.
Recently, the Fair Nut has written $k$ strings of length $n$, consisting of letters "a" and "b". He calculated $c$ — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.
Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $s$ and not bigger than string $t$. He is interested: what is the maximum value of $c$ that he could get.
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-----
The first line contains two integers $n$ and $k$ ($1 \leq n \leq 5 \cdot 10^5$, $1 \leq k \leq 10^9$).
The second line contains a string $s$ ($|s| = n$) — the string consisting of letters "a" and "b.
The third line contains a string $t$ ($|t| = n$) — the string consisting of letters "a" and "b.
It is guaranteed that string $s$ is lexicographically not bigger than $t$.
-----Output-----
Print one number — maximal value of $c$.
-----Examples-----
Input
2 4
aa
bb
Output
6
Input
3 3
aba
bba
Output
8
Input
4 5
abbb
baaa
Output
8
-----Note-----
In the first example, Nut could write strings "aa", "ab", "ba", "bb". These $4$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $6$ strings.
In the second example, Nut could write strings "aba", "baa", "bba".
In the third example, there are only two different strings that Nut could write. If both of them are written, $c=8$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It's a walking tour day in SIS.Winter, so $t$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student
Such string describes the row from the last to the first student.
Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index $i$ in the string describing a group then they will throw a snowball at the student that corresponds to the character with index $i+1$ (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.
[Image]
Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.
Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.
-----Input-----
The first line contains a single integer $t$ — the number of groups of students ($1 \le t \le 100$). The following $2t$ lines contain descriptions of groups of students.
The description of the group starts with an integer $k_i$ ($1 \le k_i \le 100$) — the number of students in the group, followed by a string $s_i$, consisting of $k_i$ letters "A" and "P", which describes the $i$-th group of students.
-----Output-----
For every group output single integer — the last moment a student becomes angry.
-----Examples-----
Input
1
4
PPAP
Output
1
Input
3
12
APPAPPPAPPPP
3
AAP
3
PPA
Output
4
1
0
-----Note-----
In the first test, after $1$ minute the state of students becomes PPAA. After that, no new angry students will appear.
In the second tets, state of students in the first group is: after $1$ minute — AAPAAPPAAPPP after $2$ minutes — AAAAAAPAAAPP after $3$ minutes — AAAAAAAAAAAP after $4$ minutes all $12$ students are angry
In the second group after $1$ minute, all students are angry.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 some day in January 2018, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January 23, 2018 should be written as 2018/01/23.
After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, S, is given as input, modifies the first four characters in S to 2018 and prints it.
-----Constraints-----
- S is a string of length 10.
- The first eight characters in S are 2017/01/.
- The last two characters in S are digits and represent an integer between 1 and 31 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Replace the first four characters in S with 2018 and print it.
-----Sample Input-----
2017/01/07
-----Sample Output-----
2018/01/07
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Elections in Berland are coming. There are only two candidates — Alice and Bob.
The main Berland TV channel plans to show political debates. There are $n$ people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views: supporting none of candidates (this kind is denoted as "00"), supporting Alice but not Bob (this kind is denoted as "10"), supporting Bob but not Alice (this kind is denoted as "01"), supporting both candidates (this kind is denoted as "11").
The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions: at least half of spectators support Alice (i.e. $2 \cdot a \ge m$, where $a$ is number of spectators supporting Alice and $m$ is the total number of spectators), at least half of spectators support Bob (i.e. $2 \cdot b \ge m$, where $b$ is number of spectators supporting Bob and $m$ is the total number of spectators), the total influence of spectators is maximal possible.
Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible.
-----Input-----
The first line contains integer $n$ ($1 \le n \le 4\cdot10^5$) — the number of people who want to take part in the debate as a spectator.
These people are described on the next $n$ lines. Each line describes a single person and contains the string $s_i$ and integer $a_i$ separated by space ($1 \le a_i \le 5000$), where $s_i$ denotes person's political views (possible values — "00", "10", "01", "11") and $a_i$ — the influence of the $i$-th person.
-----Output-----
Print a single integer — maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead.
-----Examples-----
Input
6
11 6
10 4
01 3
00 3
00 7
00 9
Output
22
Input
5
11 1
01 1
00 100
10 1
01 1
Output
103
Input
6
11 19
10 22
00 18
00 29
11 29
10 28
Output
105
Input
3
00 5000
00 5000
00 5000
Output
0
-----Note-----
In the first example $4$ spectators can be invited to maximize total influence: $1$, $2$, $3$ and $6$. Their political views are: "11", "10", "01" and "00". So in total $2$ out of $4$ spectators support Alice and $2$ out of $4$ spectators support Bob. The total influence is $6+4+3+9=22$.
In the second example the direction can select all the people except the $5$-th person.
In the third example the direction can select people with indices: $1$, $4$, $5$ and $6$.
In the fourth example it is impossible to select any non-empty set of spectators.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Riddle
The King of a small country invites 1000 senators to his annual party. As a tradition, each senator brings the King a bottle of wine. Soon after, the Queen discovers that one of the senators is trying to assassinate the King by giving him a bottle of poisoned wine. Unfortunately, they do not know which senator, nor which bottle of wine is poisoned, and the poison is completely indiscernible.
However, the King has 10 lab rats. He decides to use them as taste testers to determine which bottle of wine contains the poison. The poison when taken has no effect on the rats, until exactly 24 hours later when the infected rats suddenly die. The King needs to determine which bottle of wine is poisoned by tomorrow, so that the festivities can continue as planned.
Hence he only has time for one round of testing, he decides that each rat tastes multiple bottles, according to a certain scheme.
## Your Task
You receive an array of integers (`0 to 9`), each of them is the number of a rat which died after tasting the wine bottles. Return the number of the bottle (`1..1000`) which is poisoned.
**Good Luck!**
*Hint: think of rats as a certain representation of the number of the bottle...*
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
we obtain the table:
acd
efg
hjk
A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
Input
The first line contains two integers — n and m (1 ≤ n, m ≤ 100).
Next n lines contain m small English letters each — the characters of the table.
Output
Print a single number — the minimum number of columns that you need to remove in order to make the table good.
Examples
Input
1 10
codeforces
Output
0
Input
4 4
case
care
test
code
Output
2
Input
5 4
code
forc
esco
defo
rces
Output
4
Note
In the first sample the table is already good.
In the second sample you may remove the first and third column.
In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).
Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of 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.
Assume that you have $k$ one-dimensional segments $s_1, s_2, \dots s_k$ (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of $k$ vertexes, and there is an edge between the $i$-th and the $j$-th vertexes ($i \neq j$) if and only if the segments $s_i$ and $s_j$ intersect (there exists at least one point that belongs to both of them).
For example, if $s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18]$, then the resulting graph is the following: [Image]
A tree of size $m$ is good if it is possible to choose $m$ one-dimensional segments so that the graph built on these segments coincides with this tree.
You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree.
Note that you have to answer $q$ independent queries.
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 15 \cdot 10^4$) — the number of the queries.
The first line of each query contains one integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of vertices in the tree.
Each of the next $n - 1$ lines contains two integers $x$ and $y$ ($1 \le x, y \le n$) denoting an edge between vertices $x$ and $y$. It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of all $n$ does not exceed $3 \cdot 10^5$.
-----Output-----
For each query print one integer — the maximum size of a good subtree of the given tree.
-----Example-----
Input
1
10
1 2
1 3
1 4
2 5
2 6
3 7
3 8
4 9
4 10
Output
8
-----Note-----
In the first query there is a good subtree of size $8$. The vertices belonging to this subtree are ${9, 4, 10, 2, 5, 1, 6, 3}$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, $n+1$ meters of sea and an island at $n+1$ meters from the shore.
She measured the depth of the sea at $1, 2, \dots, n$ meters from the shore and saved them in array $d$. $d_i$ denotes the depth of the sea at $i$ meters from the shore for $1 \le i \le n$.
Like any beach this one has tide, the intensity of the tide is measured by parameter $k$ and affects all depths from the beginning at time $t=0$ in the following way:
For a total of $k$ seconds, each second, tide increases all depths by $1$.
Then, for a total of $k$ seconds, each second, tide decreases all depths by $1$.
This process repeats again and again (ie. depths increase for $k$ seconds then decrease for $k$ seconds and so on ...).
Formally, let's define $0$-indexed array $p = [0, 1, 2, \ldots, k - 2, k - 1, k, k - 1, k - 2, \ldots, 2, 1]$ of length $2k$. At time $t$ ($0 \le t$) depth at $i$ meters from the shore equals $d_i + p[t \bmod 2k]$ ($t \bmod 2k$ denotes the remainder of the division of $t$ by $2k$). Note that the changes occur instantaneously after each second, see the notes for better understanding.
At time $t=0$ Koa is standing at the shore and wants to get to the island. Suppose that at some time $t$ ($0 \le t$) she is at $x$ ($0 \le x \le n$) meters from the shore:
In one second Koa can swim $1$ meter further from the shore ($x$ changes to $x+1$) or not swim at all ($x$ stays the same), in both cases $t$ changes to $t+1$.
As Koa is a bad swimmer, the depth of the sea at the point where she is can't exceed $l$ at integer points of time (or she will drown). More formally, if Koa is at $x$ ($1 \le x \le n$) meters from the shore at the moment $t$ (for some integer $t\ge 0$), the depth of the sea at this point — $d_x + p[t \bmod 2k]$ — can't exceed $l$. In other words, $d_x + p[t \bmod 2k] \le l$ must hold always.
Once Koa reaches the island at $n+1$ meters from the shore, she stops and can rest.
Note that while Koa swims tide doesn't have effect on her (ie. she can't drown while swimming). Note that Koa can choose to stay on the shore for as long as she needs and neither the shore or the island are affected by the tide (they are solid ground and she won't drown there).
Koa wants to know whether she can go from the shore to the island. Help her!
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. Description of the test cases follows.
The first line of each test case contains three integers $n$, $k$ and $l$ ($1 \le n \le 100; 1 \le k \le 100; 1 \le l \le 100$) — the number of meters of sea Koa measured and parameters $k$ and $l$.
The second line of each test case contains $n$ integers $d_1, d_2, \ldots, d_n$ ($0 \le d_i \le 100$) — the depths of each meter of sea Koa measured.
It is guaranteed that the sum of $n$ over all test cases does not exceed $100$.
-----Output-----
For each test case:
Print Yes if Koa can get from the shore to the island, and No otherwise.
You may print each letter in any case (upper or lower).
-----Example-----
Input
7
2 1 1
1 0
5 2 3
1 2 3 2 2
4 3 4
0 2 4 3
2 3 5
3 0
7 2 3
3 0 2 1 3 0 1
7 1 4
4 4 3 0 2 4 2
5 2 3
1 2 3 2 2
Output
Yes
No
Yes
Yes
Yes
No
No
-----Note-----
In the following $s$ denotes the shore, $i$ denotes the island, $x$ denotes distance from Koa to the shore, the underline denotes the position of Koa, and values in the array below denote current depths, affected by tide, at $1, 2, \dots, n$ meters from the shore.
In test case $1$ we have $n = 2, k = 1, l = 1, p = [ 0, 1 ]$.
Koa wants to go from shore (at $x = 0$) to the island (at $x = 3$). Let's describe a possible solution:
Initially at $t = 0$ the beach looks like this: $[\underline{s}, 1, 0, i]$. At $t = 0$ if Koa would decide to swim to $x = 1$, beach would look like: $[s, \underline{2}, 1, i]$ at $t = 1$, since $2 > 1$ she would drown. So Koa waits $1$ second instead and beach looks like $[\underline{s}, 2, 1, i]$ at $t = 1$. At $t = 1$ Koa swims to $x = 1$, beach looks like $[s, \underline{1}, 0, i]$ at $t = 2$. Koa doesn't drown because $1 \le 1$. At $t = 2$ Koa swims to $x = 2$, beach looks like $[s, 2, \underline{1}, i]$ at $t = 3$. Koa doesn't drown because $1 \le 1$. At $t = 3$ Koa swims to $x = 3$, beach looks like $[s, 1, 0, \underline{i}]$ at $t = 4$. At $t = 4$ Koa is at $x = 3$ and she made it!
We can show that in test case $2$ Koa can't get to the island.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $n$. Let's call them $a$ and $b$.
Note that a permutation of $n$ elements is a sequence of numbers $a_1, a_2, \ldots, a_n$, in which every number from $1$ to $n$ appears exactly once.
The message can be decoded by an arrangement of sequence $a$ and $b$, such that the number of matching pairs of elements between them is maximum. A pair of elements $a_i$ and $b_j$ is said to match if: $i = j$, that is, they are at the same index. $a_i = b_j$
His two disciples are allowed to perform the following operation any number of times: choose a number $k$ and cyclically shift one of the permutations to the left or right $k$ times.
A single cyclic shift to the left on any permutation $c$ is an operation that sets $c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $c$ is an operation that sets $c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$ simultaneously.
Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.
-----Input-----
The first line of the input contains a single integer $n$ $(1 \le n \le 2 \cdot 10^5)$ — the size of the arrays.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ $(1 \le a_i \le n)$ — the elements of the first permutation.
The third line contains $n$ integers $b_1$, $b_2$, ..., $b_n$ $(1 \le b_i \le n)$ — the elements of the second permutation.
-----Output-----
Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.
-----Examples-----
Input
5
1 2 3 4 5
2 3 4 5 1
Output
5
Input
5
5 4 3 2 1
1 2 3 4 5
Output
1
Input
4
1 3 2 4
4 2 3 1
Output
2
-----Note-----
For the first case: $b$ can be shifted to the right by $k = 1$. The resulting permutations will be $\{1, 2, 3, 4, 5\}$ and $\{1, 2, 3, 4, 5\}$.
For the second case: The operation is not required. For all possible rotations of $a$ and $b$, the number of matching pairs won't exceed $1$.
For the third case: $b$ can be shifted to the left by $k = 1$. The resulting permutations will be $\{1, 3, 2, 4\}$ and $\{2, 3, 1, 4\}$. Positions $2$ and $4$ have matching pairs of elements. For all possible rotations of $a$ and $b$, the number of matching pairs won't exceed $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.
The Little Elephant likes permutations. This time he has a permutation A[1], A[2], ..., A[N] of numbers 1, 2, ..., N.
He calls a permutation A good, if the number of its inversions is equal to the number of its local inversions. The number of inversions is equal to the number of pairs of integers (i; j) such that 1 ≤ i < j ≤ N and A[i] > A[j], and the number of local inversions is the number of integers i such that 1 ≤ i < N and A[i] > A[i+1].
The Little Elephant has several such permutations. Help him to find for each permutation whether it is good or not. Print YES for a corresponding test case if it is good and NO otherwise.
------ Input ------
The first line of the input contains a single integer T, the number of test cases. T test cases follow. The first line of each test case contains a single integer N, the size of a permutation. The next line contains N space separated integers A[1], A[2], ..., A[N].
------ Output ------
For each test case output a single line containing the answer for the corresponding test case. It should be YES if the corresponding permutation is good and NO otherwise.
------ Constraints ------
1 ≤ T ≤ 474
1 ≤ N ≤ 100
It is guaranteed that the sequence A[1], A[2], ..., A[N] is a permutation of numbers 1, 2, ..., N.
----- Sample Input 1 ------
4
1
1
2
2 1
3
3 2 1
4
1 3 2 4
----- Sample Output 1 ------
YES
YES
NO
YES
----- explanation 1 ------
Case 1. Here N = 1, so we have no pairs (i; j) with 1 ? i . So the number of inversions is equal to zero. The number of local inversion is also equal to zero. Hence this permutation is good.
Case 2. Here N = 2, and we have one pair (i; j) with 1 ? i , the pair (1; 2). Since A[1] = 2 and A[2] = 1 then A[1] > A[2] and the number of inversions is equal to 1. The number of local inversion is also equal to 1 since we have one value of i for which 1 ? i (the value i = 1) and A[i] > A[i+1] for this value of i since A[1] > A[2]. Hence this permutation is also good.
Case 3. Here N = 3, and we have three pairs (i; j) with 1 ? i . We have A[1] = 3, A[2] = 2, A[3] = 1. Hence A[1] > A[2], A[1] > A[3] and A[2] > A[3]. So the number of inversions is equal to 3. To count the number of local inversion we should examine inequalities A[1] > A[2] and A[2] > A[3]. They both are satisfied in our case, so we have 2 local inversions. Since 2 ? 3 this permutations is not good.
Case 4. Here we have only one inversion and it comes from the pair (2; 3) since A[2] = 3 > 2 = A[3]. This pair gives also the only local inversion in this permutation. Hence the number of inversions equals to the number of local inversions and equals to one. So this permutation is good.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Shinya watched a program on TV called "Maya's Great Prophecy! Will the World End in 2012?" After all, I wasn't sure if the world would end, but I was interested in Maya's "long-term calendar," which was introduced in the program. The program explained as follows.
The Maya long-term calendar is a very long calendar consisting of 13 Baktuns (1872,000 days) in total, consisting of the units shown in the table on the right. One calculation method believes that the calendar begins on August 11, 3114 BC and ends on December 21, 2012, which is why the world ends on December 21, 2012. .. However, there is also the idea that 13 Baktun will be one cycle, and when the current calendar is over, a new cycle will be started.
| 1 kin = 1 day
1 winal = 20 kin
1 tun = 18 winals
1 Katun = 20 tons
1 Baktun = 20 Katun |
--- | --- | ---
"How many days will my 20th birthday be in the Maya calendar?" Shinya wanted to express various days in the Maya long-term calendar.
Now, instead of Shinya, create a program that converts between the Christian era and the Maya long-term calendar.
input
The input consists of multiple datasets. The end of the input is indicated by # 1 line. Each dataset is given in the following format:
b.ka.t.w.ki
Or
y.m.d
The dataset consists of one line containing one character string. b.ka.t.w.ki is the Mayan long-term date and y.m.d is the Christian era date. The units given are as follows.
Maya long calendar
b | Baktun | (0 ≤ b <13)
--- | --- | ---
ka | Katun | (0 ≤ ka <20)
t | Tun | (0 ≤ t <20)
w | Winal | (0 ≤ w <18)
ki | kin | (0 ≤ ki <20)
Year
y | year | (2012 ≤ y ≤ 10,000,000)
--- | --- | ---
m | month | (1 ≤ m ≤ 12)
d | day | (1 ≤ d ≤ 31)
The maximum value for a day in the Christian era depends on whether it is a large month, a small month, or a leap year (a leap year is a multiple of 4 that is not divisible by 100 or divisible by 400). The range of dates in the Maya long calendar is from 0.0.0.0.0 to 12.19.19.17.19. However, 0.0.0.0.0.0 of the Maya long-term calendar corresponds to 2012.12.21 of the Christian era. The range of dates in the Christian era is from 2012.12.21 to 10000000.12.31.
The number of datasets does not exceed 500.
output
When the input is the Western calendar, the Maya long calendar is output, and when the input is the Maya long calendar, the Western calendar is output in the same format as the input. As a result of converting the input year, even if the next cycle of the Maya long calendar is entered, it may be output in the format of b.ka.t.w.ki.
Example
Input
2012.12.31
2.12.16.14.14
7138.5.13
10.5.2.1.5
10000000.12.31
#
Output
0.0.0.0.10
3054.8.15
0.0.0.0.10
6056.2.29
8.19.3.13.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.
Cirno_9baka has a tree with $n$ nodes. He is willing to share it with you, which means you can operate on it.
Initially, there are two chess pieces on the node $1$ of the tree. In one step, you can choose any piece, and move it to the neighboring node. You are also given an integer $d$. You need to ensure that the distance between the two pieces doesn't ever exceed $d$.
Each of these two pieces has a sequence of nodes which they need to pass in any order, and eventually, they have to return to the root. As a curious boy, he wants to know the minimum steps you need to take.
-----Input-----
The first line contains two integers $n$ and $d$ ($2 \le d \le n \le 2\cdot 10^5$).
The $i$-th of the following $n - 1$ lines contains two integers $u_i, v_i$ $(1 \le u_i, v_i \le n)$, denoting the edge between the nodes $u_i, v_i$ of the tree.
It's guaranteed that these edges form a tree.
The next line contains an integer $m_1$ ($1 \le m_1 \le n$) and $m_1$ integers $a_1, a_2, \ldots, a_{m_1}$ ($1 \le a_i \le n$, all $a_i$ are distinct) — the sequence of nodes that the first piece needs to pass.
The second line contains an integer $m_2$ ($1 \le m_2 \le n$) and $m_2$ integers $b_1, b_2, \ldots, b_{m_2}$ ($1 \le b_i \le n$, all $b_i$ are distinct) — the sequence of nodes that the second piece needs to pass.
-----Output-----
Output a single integer — the minimum steps you need to take.
-----Examples-----
Input
4 2
1 2
1 3
2 4
1 3
1 4
Output
6
Input
4 2
1 2
2 3
3 4
4 1 2 3 4
1 1
Output
8
-----Note-----
In the first sample, here is one possible sequence of steps of length $6$.
The second piece moves by the route $1 \to 2 \to 4 \to 2 \to 1$.
Then, the first piece moves by the route $1 \to 3 \to 1$.
In the second sample, here is one possible sequence of steps of length $8$:
The first piece moves by the route $1 \to 2 \to 3$.
Then, the second piece moves by the route $1 \to 2$.
Then, the first piece moves by the route $3 \to 4 \to 3 \to 2 \to 1$.
Then, the second piece moves by the route $2 \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.
It is a complicated version of problem F1. The difference between them is the constraints (F1: $k \le 2$, F2: $k \le 10$).
You are given an integer $n$. Find the minimum integer $x$ such that $x \ge n$ and the number $x$ is $k$-beautiful.
A number is called $k$-beautiful if its decimal representation having no leading zeroes contains no more than $k$ different digits. E.g. if $k = 2$, the numbers $3434443$, $55550$, $777$ and $21$ are $k$-beautiful whereas the numbers $120$, $445435$ and $998244353$ are not.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow.
Each test case consists of one line containing two integers $n$ and $k$ ($1 \le n \le 10^9$, $1 \le k \le 10$).
-----Output-----
For each test case output on a separate line $x$ — the minimum $k$-beautiful integer such that $x \ge n$.
-----Examples-----
Input
6
2021 3
177890 2
34512 3
724533 4
998244353 1
12345678 10
Output
2021
181111
34533
724542
999999999
12345678
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a toy building consisting of $n$ towers. Each tower consists of several cubes standing on each other. The $i$-th tower consists of $h_i$ cubes, so it has height $h_i$.
Let's define operation slice on some height $H$ as following: for each tower $i$, if its height is greater than $H$, then remove some top cubes to make tower's height equal to $H$. Cost of one "slice" equals to the total number of removed cubes from all towers.
Let's name slice as good one if its cost is lower or equal to $k$ ($k \ge n$).
[Image]
Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $n \le k \le 10^9$) — the number of towers and the restriction on slices, respectively.
The second line contains $n$ space separated integers $h_1, h_2, \dots, h_n$ ($1 \le h_i \le 2 \cdot 10^5$) — the initial heights of towers.
-----Output-----
Print one integer — the minimum number of good slices you have to do to make all towers have the same heigth.
-----Examples-----
Input
5 5
3 1 2 2 4
Output
2
Input
4 5
2 3 4 5
Output
2
-----Note-----
In the first example it's optimal to make $2$ slices. The first slice is on height $2$ (its cost is $3$), and the second one is on height $1$ (its cost is $4$).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces.
All five kinds of polyhedrons are shown on the picture below:
[Image]
Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection.
Each of the following n lines of the input contains a string s_{i} — the name of the i-th polyhedron in Anton's collection. The string can look like this:
"Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.
-----Output-----
Output one number — the total number of faces in all the polyhedrons in Anton's collection.
-----Examples-----
Input
4
Icosahedron
Cube
Tetrahedron
Dodecahedron
Output
42
Input
3
Dodecahedron
Octahedron
Octahedron
Output
28
-----Note-----
In the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.
You are given two strings $s$ and $t$ of the same length $n$. Their characters are numbered from $1$ to $n$ from left to right (i.e. from the beginning to the end).
In a single move you can do the following sequence of actions:
choose any valid index $i$ ($1 \le i \le n$), move the $i$-th character of $s$ from its position to the beginning of the string or move the $i$-th character of $s$ from its position to the end of the string.
Note, that the moves don't change the length of the string $s$. You can apply a move only to the string $s$.
For example, if $s=$"test" in one move you can obtain:
if $i=1$ and you move to the beginning, then the result is "test" (the string doesn't change), if $i=2$ and you move to the beginning, then the result is "etst", if $i=3$ and you move to the beginning, then the result is "stet", if $i=4$ and you move to the beginning, then the result is "ttes", if $i=1$ and you move to the end, then the result is "estt", if $i=2$ and you move to the end, then the result is "tste", if $i=3$ and you move to the end, then the result is "tets", if $i=4$ and you move to the end, then the result is "test" (the string doesn't change).
You want to make the string $s$ equal to the string $t$. What is the minimum number of moves you need? If it is impossible to transform $s$ to $t$, print -1.
-----Input-----
The first line contains integer $q$ ($1 \le q \le 100$) — the number of independent test cases in the input.
Each test case is given in three lines. The first line of a test case contains $n$ ($1 \le n \le 100$) — the length of the strings $s$ and $t$. The second line contains $s$, the third line contains $t$. Both strings $s$ and $t$ have length $n$ and contain only lowercase Latin letters.
There are no constraints on the sum of $n$ in the test (i.e. the input with $q=100$ and all $n=100$ is allowed).
-----Output-----
For every test print minimum possible number of moves, which are needed to transform $s$ into $t$, or -1, if it is impossible to do.
-----Examples-----
Input
3
9
iredppipe
piedpiper
4
estt
test
4
tste
test
Output
2
1
2
Input
4
1
a
z
5
adhas
dasha
5
aashd
dasha
5
aahsd
dasha
Output
-1
2
2
3
-----Note-----
In the first example, the moves in one of the optimal answers are:
for the first test case $s=$"iredppipe", $t=$"piedpiper": "iredppipe" $\rightarrow$ "iedppiper" $\rightarrow$ "piedpiper"; for the second test case $s=$"estt", $t=$"test": "estt" $\rightarrow$ "test"; for the third test case $s=$"tste", $t=$"test": "tste" $\rightarrow$ "etst" $\rightarrow$ "test".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.
For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.
In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).
Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
<image>
Input
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Output
Print a single number — the number of uncomfortable situations in the company.
Examples
Input
MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output
3
Input
A:A..
Output
1
Input
A:C:C:C:C.....
Output
6
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You were lucky enough to get a map just before entering the legendary magical mystery world. The map shows the whole area of your planned exploration, including several countries with complicated borders. The map is clearly drawn, but in sepia ink only; it is hard to recognize at a glance which region belongs to which country, and this might bring you into severe danger. You have decided to color the map before entering the area. “A good deal depends on preparation,” you talked to yourself.
Each country has one or more territories, each of which has a polygonal shape. Territories belonging to one country may or may not “touch” each other, i.e. there may be disconnected territories. All the territories belonging to the same country must be assigned the same color. You can assign the same color to more than one country, but, to avoid confusion, two countries “adjacent” to each other should be assigned different colors. Two countries are considered to be “adjacent” if any of their territories share a border of non-zero length.
Write a program that finds the least number of colors required to color the map.
Input
The input consists of multiple map data. Each map data starts with a line containing the total number of territories n, followed by the data for those territories. n is a positive integer not more than 100. The data for a territory with m vertices has the following format:
String
x1 y1
x2 y2
...
xm ym
-1
“String” (a sequence of alphanumerical characters) gives the name of the country it belongs to. A country name has at least one character and never has more than twenty. When a country has multiple territories, its name appears in each of them.
Remaining lines represent the vertices of the territory. A vertex data line has a pair of nonneg- ative integers which represent the x- and y-coordinates of a vertex. x- and y-coordinates are separated by a single space, and y-coordinate is immediately followed by a newline. Edges of the territory are obtained by connecting vertices given in two adjacent vertex data lines, and byconnecting vertices given in the last and the first vertex data lines. None of x- and y-coordinates exceeds 1000. Finally, -1 in a line marks the end of vertex data lines. The number of vertices m does not exceed 100.
You may assume that the contours of polygons are simple, i.e. they do not cross nor touch themselves. No two polygons share a region of non-zero area. The number of countries in a map does not exceed 10.
The last map data is followed by a line containing only a zero, marking the end of the input data.
Output
For each map data, output one line containing the least possible number of colors required to color the map satisfying the specified conditions.
Example
Input
6
Blizid
0 0
60 0
60 60
0 60
0 50
50 50
50 10
0 10
-1
Blizid
0 10
10 10
10 50
0 50
-1
Windom
10 10
50 10
40 20
20 20
20 40
10 50
-1
Accent
50 10
50 50
35 50
35 25
-1
Pilot
35 25
35 50
10 50
-1
Blizid
20 20
40 20
20 40
-1
4
A1234567890123456789
0 0
0 100
100 100
100 0
-1
B1234567890123456789
100 100
100 200
200 200
200 100
-1
C1234567890123456789
0 100
100 100
100 200
0 200
-1
D123456789012345678
100 0
100 100
200 100
200 0
-1
0
Output
4
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.
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation:
The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you look on him from above. All barriers are located at integer distance from each other along the track.
Her friends the parrot Kefa and the leopard Sasha participated in competitions and each of them ran one lap. Each of the friends started from some integral point on the track. Both friends wrote the distance from their start along the track to each of the n barriers. Thus, each of them wrote n integers in the ascending order, each of them was between 0 and L - 1, inclusively. [Image] Consider an example. Let L = 8, blue points are barriers, and green points are Kefa's start (A) and Sasha's start (B). Then Kefa writes down the sequence [2, 4, 6], and Sasha writes down [1, 5, 7].
There are several tracks in the country, all of them have same length and same number of barriers, but the positions of the barriers can differ among different tracks. Now Dasha is interested if it is possible that Kefa and Sasha ran the same track or they participated on different tracks.
Write the program which will check that Kefa's and Sasha's tracks coincide (it means that one can be obtained from the other by changing the start position). Note that they always run the track in one direction — counterclockwise, if you look on a track from above.
-----Input-----
The first line contains two integers n and L (1 ≤ n ≤ 50, n ≤ L ≤ 100) — the number of barriers on a track and its length.
The second line contains n distinct integers in the ascending order — the distance from Kefa's start to each barrier in the order of its appearance. All integers are in the range from 0 to L - 1 inclusively.
The second line contains n distinct integers in the ascending order — the distance from Sasha's start to each barrier in the order of its overcoming. All integers are in the range from 0 to L - 1 inclusively.
-----Output-----
Print "YES" (without quotes), if Kefa and Sasha ran the coinciding tracks (it means that the position of all barriers coincides, if they start running from the same points on the track). Otherwise print "NO" (without quotes).
-----Examples-----
Input
3 8
2 4 6
1 5 7
Output
YES
Input
4 9
2 3 5 8
0 1 3 6
Output
YES
Input
2 4
1 3
1 2
Output
NO
-----Note-----
The first test is analyzed in the statement.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
coastline
Waves rush to the beach every second. There is data that observes and records how many meters the wave rushed beyond the reference point P every second for only T seconds. The data consists of T integers x1, ..., xT, and for each i (1 ≤ i ≤ T), a wave from point P to the point exactly xi m rushes in i seconds after the start of observation. Indicates that it was immersed in seawater.
The coast is known to dry D seconds after the last immersion in seawater. Note that the time to dry depends only on the time of the last soaking in the seawater, not on the number or time of the previous soaking in the waves.
Find out how many seconds the point, which is a distance L away from the reference point P in the land direction, was wet for at least 1 second and T seconds after the start of observation. However, it is known that the coast was dry at time 0.
The figure of the first case of Sample Input is shown below.
<image>
Figure B1: Sample Input Case 1
Input
> The input dataset consists of multiple cases. The maximum number of datasets does not exceed 40. Each case has the following format.
> T D L
> x1
> ...
> xT
>
T, D, L (1 ≤ T, D, L ≤ 100,000) are given on the first line, separated by half-width spaces. Of the following T lines, the i (1 ≤ i ≤ T) line is given xi (0 ≤ xi ≤ 100,000). These are all integers.
> The end of the dataset is represented by three 0 lines.
> ### Output
> For each case, output in one line the time (seconds) that the point separated by the distance L in the land direction from the reference point P was surely wet between 1 second and T seconds.
> ### Sample Input
5 2 3
3
Five
1
2
3
3 100 100
3
3
Four
20 3 8
3
2
6
1
9
1
8
Four
2
2
8
1
8
8
2
Five
3
Four
3
8
7 2 2
0
2
Five
2
Five
2
1
0 0 0
Output for Sample Input
3
0
11
Five
Example
Input
5 2 3
3
5
1
2
3
3 100 100
3
3
4
20 3 8
3
2
6
1
9
1
8
4
2
2
8
1
8
8
2
5
3
4
3
8
7 2 2
0
2
5
2
5
2
1
0 0 0
Output
3
0
11
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.
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: They are equal. If we split string a into two halves of the same size a_1 and a_2, and string b into two halves of the same size b_1 and b_2, then one of the following is correct: a_1 is equivalent to b_1, and a_2 is equivalent to b_2 a_1 is equivalent to b_2, and a_2 is equivalent to b_1
As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.
Gerald has already completed this home task. Now it's your turn!
-----Input-----
The first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.
-----Output-----
Print "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.
-----Examples-----
Input
aaba
abaa
Output
YES
Input
aabb
abab
Output
NO
-----Note-----
In the first sample you should split the first string into strings "aa" and "ba", the second one — into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".
In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
[Image]
-----Input-----
The input contains a single integer $a$ ($0 \le a \le 15$).
-----Output-----
Output a single integer.
-----Example-----
Input
3
Output
13
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
###Lucky number
Write a function to find if a number is lucky or not. If the sum of all digits is 0 or multiple of 9 then the number is lucky.
`1892376 => 1+8+9+2+3+7+6 = 36`. 36 is divisble by 9, hence number is lucky.
Function will return `true` for lucky numbers and `false` for others.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 finalGrade, which calculates the final grade of a student depending on two parameters: a grade for the exam and a number of completed projects.
This function should take two arguments:
exam - grade for exam (from 0 to 100);
projects - number of completed projects (from 0 and above);
This function should return a number (final grade).
There are four types of final grades:
- 100, if a grade for the exam is more than 90 or if a number of completed projects more than 10.
- 90, if a grade for the exam is more than 75 and if a number of completed projects is minimum 5.
- 75, if a grade for the exam is more than 50 and if a number of completed projects is minimum 2.
- 0, in other cases
Examples:
~~~if-not:nasm
```python
final_grade(100, 12) # 100
final_grade(99, 0) # 100
final_grade(10, 15) # 100
final_grade(85, 5) # 90
final_grade(55, 3) # 75
final_grade(55, 0) # 0
final_grade(20, 2) # 0
```
~~~
*Use Comparison and Logical Operators.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).
A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s_1s_2... s_{|}s| (|s| is a length of s) is string s_{l}s_{l} + 1... s_{r}.
Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.
We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
-----Input-----
The first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers p_{i}, l_{i}, r_{i}, separated by single spaces (0 ≤ l_{i} ≤ r_{i} ≤ |p_{i}|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.
The input limits for scoring 30 points are (subproblem G1): 0 ≤ n ≤ 10. The length of string s and the maximum length of string p is ≤ 200.
The input limits for scoring 70 points are (subproblems G1+G2): 0 ≤ n ≤ 10. The length of string s and the maximum length of string p is ≤ 2000.
The input limits for scoring 100 points are (subproblems G1+G2+G3): 0 ≤ n ≤ 10. The length of string s and the maximum length of string p is ≤ 50000.
-----Output-----
Print a single integer — the number of good substrings of string s.
-----Examples-----
Input
aaab
2
aa 0 0
aab 1 1
Output
3
Input
ltntlnen
3
n 0 0
ttlneenl 1 4
lelllt 1 1
Output
2
Input
a
0
Output
1
-----Note-----
There are three good substrings in the first sample test: «aab», «ab» and «b».
In the second test only substrings «e» and «t» are good.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to $1$ meter movement in the south, north, west or east direction respectively).
It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visited the first time), then the time of such movement is $5$ seconds. If he rolls along previously visited segment of a path (i.e., this segment of the path has been covered by his path before), then it takes $1$ second.
Find the skier's time to roll all the path.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow.
Each set is given by one nonempty string of the characters 'S', 'N', 'W', 'E'. The length of the string does not exceed $10^5$ characters.
The sum of the lengths of $t$ given lines over all test cases in the input does not exceed $10^5$.
-----Output-----
For each test case, print the desired path time in seconds.
-----Example-----
Input
5
NNN
NS
WWEN
WWEE
NWNWS
Output
15
6
16
12
25
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 ⋅ 10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane. For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).
When setting the departure times for buses under this condition, find the minimum required number of buses. Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.
Constraints
* 2 \leq N \leq 100000
* 1 \leq C \leq 10^9
* 1 \leq K \leq 10^9
* 1 \leq T_i \leq 10^9
* C, K and T_i are integers.
Input
The input is given from Standard Input in the following format:
N C K
T_1
T_2
:
T_N
Output
Print the minimum required number of buses.
Examples
Input
5 3 5
1
2
3
6
12
Output
3
Input
6 3 3
7
6
2
8
10
6
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.
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.
Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
Input
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
Output
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n.
If a tournir that meets the conditions of the problem does not exist, then print -1.
Examples
Input
3 1
Output
3
1 2
2 3
3 1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
$n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!
Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $i$-th robot is currently located at the point having coordinates ($x_i$, $y_i$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $X$ and $Y$, and when each robot receives this command, it starts moving towards the point having coordinates ($X$, $Y$). The robot stops its movement in two cases: either it reaches ($X$, $Y$); or it cannot get any closer to ($X$, $Y$).
Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($x_c$, $y_c$). Then the movement system allows it to move to any of the four adjacent points: the first action allows it to move from ($x_c$, $y_c$) to ($x_c - 1$, $y_c$); the second action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c + 1$); the third action allows it to move from ($x_c$, $y_c$) to ($x_c + 1$, $y_c$); the fourth action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c - 1$).
Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.
You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $X$ and $Y$ so that each robot can reach the point ($X$, $Y$). Is it possible to find such a point?
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries.
Then $q$ queries follow. Each query begins with one line containing one integer $n$ ($1 \le n \le 10^5$) — the number of robots in the query. Then $n$ lines follow, the $i$-th of these lines describes the $i$-th robot in the current query: it contains six integer numbers $x_i$, $y_i$, $f_{i, 1}$, $f_{i, 2}$, $f_{i, 3}$ and $f_{i, 4}$ ($-10^5 \le x_i, y_i \le 10^5$, $0 \le f_{i, j} \le 1$). The first two numbers describe the initial location of the $i$-th robot, and the following four numbers describe which actions the $i$-th robot can use to move ($f_{i, j} = 1$ if the $i$-th robot can use the $j$-th action, and $f_{i, j} = 0$ if it cannot use the $j$-th action).
It is guaranteed that the total number of robots over all queries does not exceed $10^5$.
-----Output-----
You should answer each query independently, in the order these queries appear in the input.
To answer a query, you should do one of the following: if it is impossible to find a point that is reachable by all $n$ robots, print one number $0$ on a separate line; if it is possible to find a point that is reachable by all $n$ robots, print three space-separated integers on the same line: $1$ $X$ $Y$, where $X$ and $Y$ are the coordinates of the point reachable by all $n$ robots. Both $X$ and $Y$ should not exceed $10^5$ by absolute value; it is guaranteed that if there exists at least one point reachable by all robots, then at least one of such points has both coordinates not exceeding $10^5$ by absolute value.
-----Example-----
Input
4
2
-1 -2 0 0 0 0
-1 -2 0 0 0 0
3
1 5 1 1 1 1
2 5 0 1 0 1
3 5 1 0 0 0
2
1337 1337 0 1 1 1
1336 1337 1 1 0 1
1
3 5 1 1 1 1
Output
1 -1 -2
1 2 5
0
1 -100000 -100000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a square table sized NxN (3 ≤ N ≤ 5,000; rows and columns are indexed from 1) with a robot on it. The robot has a mission of moving from cell (1, 1) to cell (N, N) using only the directions "right" or "down". You are requested to find the number of different ways for the robot using exactly K turns (we define a "turn" as a right move
followed immediately by a down move, or a down move followed immediately by a right move; 0 < K < 2N-2).
------ Input ------
There are several test cases (5,000 at most), each consisting of a single line containing two positive integers N, K.
The input is ended with N = K = 0.
------ Output ------
For each test case, output on a line an integer which is the result calculated. The number of ways may be very large, so compute the answer modulo 1,000,000,007.
----- Sample Input 1 ------
4 2
4 3
5 3
0 0
----- Sample Output 1 ------
4
8
18
----- explanation 1 ------
Explanation for the first sample test case: 4 ways are RRDDDR, RDDDRR, DRRRDD, DDRRRD ('R' or 'D' represents a right or down move respectively).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has the coordinate xi and the height hi. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that.
Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate x and height h leads to the fall of all dominoes on the segment [x + 1, x + h - 1].
<image>
Input
The first line contains integer n (1 ≤ n ≤ 105) which is the number of dominoes. Then follow n lines containing two integers xi and hi ( - 108 ≤ xi ≤ 108, 2 ≤ hi ≤ 108) each, which are the coordinate and height of every domino. No two dominoes stand on one point.
Output
Print n space-separated numbers zi — the number of dominoes that will fall if Vasya pushes the i-th domino to the right (including the domino itself).
Examples
Input
4
16 5
20 5
10 10
18 2
Output
3 1 4 1
Input
4
0 10
1 5
9 10
15 10
Output
4 1 2 1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $n$ cells, with each cell either being alive or dead.
Evolution of the array in William's cellular automaton occurs iteratively in the following way:
If the element is dead and it has exactly $1$ alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index $i$ the neighbors would be elements with indices $i - 1$ and $i + 1$. If there is no element at that index, it is considered to be a dead neighbor.
William is a humane person so all alive elements stay alive.
Check the note section for examples of the evolution.
You are given some initial state of all elements and you need to help William find the state of the array after $m$ iterations of evolution.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). Description of the test cases follows.
The first line of each test case contains two integers $n$ and $m$ ($2 \le n \le 10^3, 1 \le m \le 10^9$), which are the total number of cells in the array and the number of iterations.
The second line of each test case contains a string of length $n$ made up of characters "0" and "1" and defines the initial state of the array. "1" means a cell is alive and "0" means it is dead.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^4$.
-----Output-----
In each test case output a string of length $n$, made up of characters "0" and "1" — the state of the array after $m$ iterations of evolution.
-----Examples-----
Input
4
11 3
01000000001
10 2
0110100101
5 2
10101
3 100
000
Output
11111001111
1110111101
10101
000
-----Note-----
Sequence of iterations of evolution for the first test case
01000000001 — initial state
11100000011 — first iteration of evolution
11110000111 — second iteration of evolution
11111001111 — third iteration of evolution
Sequence of iterations of evolution for the second test case
0110100101 — initial state
1110111101 — first iteration of evolution
1110111101 — second iteration of evolution
Read the inputs from 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.