question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Given a string of characters, I want the function `findMiddle()`/`find_middle()` to return the middle number in the product of each digit in the string.
Example: 's7d8jd9' -> 7, 8, 9 -> 7\*8\*9=504, thus 0 should be returned as an integer.
Not all strings will contain digits. In this case and the case for any non-strings, return -1.
If the product has an even number of digits, return the middle two digits
Example: 1563 -> 56
NOTE: Remove leading zeros if product is even and the first digit of the two is a zero.
Example 2016 -> 1
Write your solution by modifying this code:
```python
def find_middle(string):
```
Your solution should implemented in the function "find_middle". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi ≠ yi).
In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n - 1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.
Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ 10^5; xi ≠ yi) — the colour numbers for the home and away kits of the i-th team.
Output
For each team, print on a single line two space-separated integers — the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.
Register for IndiaHacksSAMPLE INPUT
3
1 2
2 1
1 3
SAMPLE OUTPUT
3 1
4 0
2 2
Register for IndiaHacks
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the head of a large enterprise. $n$ people work at you, and $n$ is odd (i. e. $n$ is not divisible by $2$).
You have to distribute salaries to your employees. Initially, you have $s$ dollars for it, and the $i$-th employee should get a salary from $l_i$ to $r_i$ dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: the median of the sequence $[5, 1, 10, 17, 6]$ is $6$, the median of the sequence $[1, 2, 1]$ is $1$.
It is guaranteed that you have enough money to pay the minimum salary, i.e $l_1 + l_2 + \dots + l_n \le s$.
Note that you don't have to spend all your $s$ dollars on salaries.
You have to answer $t$ test cases.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases.
The first line of each query contains two integers $n$ and $s$ ($1 \le n < 2 \cdot 10^5$, $1 \le s \le 2 \cdot 10^{14}$) — the number of employees and the amount of money you have. The value $n$ is not divisible by $2$.
The following $n$ lines of each query contain the information about employees. The $i$-th line contains two integers $l_i$ and $r_i$ ($1 \le l_i \le r_i \le 10^9$).
It is guaranteed that the sum of all $n$ over all queries does not exceed $2 \cdot 10^5$.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. $\sum\limits_{i=1}^{n} l_i \le s$.
-----Output-----
For each test case print one integer — the maximum median salary that you can obtain.
-----Example-----
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
-----Note-----
In the first test case, you can distribute salaries as follows: $sal_1 = 12, sal_2 = 2, sal_3 = 11$ ($sal_i$ is the salary of the $i$-th employee). Then the median salary is $11$.
In the second test case, you have to pay $1337$ dollars to the only employee.
In the third test case, you can distribute salaries as follows: $sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7$. Then the median salary is $6$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.
Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.
He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
Input
The first line of the input data contains an integer n (1 ≤ n ≤ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
Output
Print on the single line the answer to the problem: the amount of subarrays, which are magical.
Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
Examples
Input
4
2 1 1 4
Output
5
Input
5
-2 -2 -2 0 1
Output
8
Note
Notes to sample tests:
Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.
In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].
In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?
Input
The first line contains an integer n — how many numbers Anna had (3 ≤ n ≤ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.
Output
Print the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).
Examples
Input
4
1 2 3 2
Output
YES
Input
6
1 1 2 2 2 3
Output
YES
Input
6
2 4 1 1 2 2
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.
As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by 100 exactly D times.
Find the N-th smallest integer that would make Ringo happy.
-----Constraints-----
- D is 0, 1 or 2.
- N is an integer between 1 and 100 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
D N
-----Output-----
Print the N-th smallest integer that can be divided by 100 exactly D times.
-----Sample Input-----
0 5
-----Sample Output-----
5
The integers that can be divided by 100 exactly 0 times (that is, not divisible by 100) are as follows: 1, 2, 3, 4, 5, 6, 7, ...
Thus, the 5-th smallest integer that would make Ringo happy 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.
## Task
An `ATM` ran out of 10 dollar bills and only has `100, 50 and 20` dollar bills.
Given an amount between `40 and 10000 dollars (inclusive)` and assuming that the ATM wants to use as few bills as possible, determinate the minimal number of 100, 50 and 20 dollar bills the ATM needs to dispense (in that order).
## Example
For `n = 250`, the result should be `[2, 1, 0]`.
For `n = 260`, the result should be `[2, 0, 3]`.
For `n = 370`, the result should be `[3, 1, 1]`.
## Input/Output
- `[input]` integer `n`
Amount of money to withdraw. Assume that `n` is always exchangeable with `[100, 50, 20]` bills.
- `[output]` integer array
An array of number of `100, 50 and 20` dollar bills needed to complete the withdraw (in that order).
Write your solution by modifying this code:
```python
def withdraw(n):
```
Your solution should implemented in the function "withdraw". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set.
Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x' ≥ x and y' ≥ y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4.
Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x, y) = y - x. Now he gives Wilbur some w_1, w_2,..., w_{n}, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to w_{i}, that is s(x_{i}, y_{i}) = y_{i} - x_{i} = w_{i}.
Now Wilbur asks you to help him with this challenge.
-----Input-----
The first line of the input consists of a single integer n (1 ≤ n ≤ 100 000) — the number of points in the set Wilbur is playing with.
Next follow n lines with points descriptions. Each line contains two integers x and y (0 ≤ x, y ≤ 100 000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y, are also present in the input.
The last line of the input contains n integers. The i-th of them is w_{i} ( - 100 000 ≤ w_{i} ≤ 100 000) — the required special value of the point that gets number i in any aesthetically pleasing numbering.
-----Output-----
If there exists an aesthetically pleasant numbering of points in the set, such that s(x_{i}, y_{i}) = y_{i} - x_{i} = w_{i}, then print "YES" on the first line of the output. Otherwise, print "NO".
If a solution exists, proceed output with n lines. On the i-th of these lines print the point of the set that gets number i. If there are multiple solutions, print any of them.
-----Examples-----
Input
5
2 0
0 0
1 0
1 1
0 1
0 -1 -2 1 0
Output
YES
0 0
1 0
2 0
0 1
1 1
Input
3
1 0
0 0
2 0
0 1 2
Output
NO
-----Note-----
In the first sample, point (2, 0) gets number 3, point (0, 0) gets number one, point (1, 0) gets number 2, point (1, 1) gets number 5 and point (0, 1) gets number 4. One can easily check that this numbering is aesthetically pleasing and y_{i} - x_{i} = w_{i}.
In the second sample, the special values of the points in the set are 0, - 1, and - 2 while the sequence that the friend gives to Wilbur is 0, 1, 2. Therefore, the answer does not exist.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
[Image]
After making a paper ship from the square piece, Vasya looked on the remaining (a - b) mm × b mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson?
-----Input-----
The first line of the input contains two integers a, b (1 ≤ b < a ≤ 10^12) — the sizes of the original sheet of paper.
-----Output-----
Print a single integer — the number of ships that Vasya will make.
-----Examples-----
Input
2 1
Output
2
Input
10 7
Output
6
Input
1000000000000 1
Output
1000000000000
-----Note-----
Pictures to the first and second sample test.
[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.
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.
The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 2^30.
-----Output-----
Print a single integer — the required maximal xor of a segment of consecutive elements.
-----Examples-----
Input
5
1 2 1 1 2
Output
3
Input
3
1 2 7
Output
7
Input
4
4 2 4 8
Output
14
-----Note-----
In the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.
The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 bus stop near the university. The lessons are over, and n students come to the stop. The i-th student will appear at the bus stop at time ti (all ti's are distinct).
We shall assume that the stop is located on the coordinate axis Ox, at point x = 0, and the bus goes along the ray Ox, that is, towards the positive direction of the coordinate axis, and back. The i-th student needs to get to the point with coordinate xi (xi > 0).
The bus moves by the following algorithm. Initially it is at point 0. The students consistently come to the stop and get on it. The bus has a seating capacity which is equal to m passengers. At the moment when m students get on the bus, it starts moving in the positive direction of the coordinate axis. Also it starts moving when the last (n-th) student gets on the bus. The bus is moving at a speed of 1 unit of distance per 1 unit of time, i.e. it covers distance y in time y.
Every time the bus passes the point at which at least one student needs to get off, it stops and these students get off the bus. The students need 1 + [k / 2] units of time to get off the bus, where k is the number of students who leave at this point. Expression [k / 2] denotes rounded down k / 2. As soon as the last student leaves the bus, the bus turns around and goes back to the point x = 0. It doesn't make any stops until it reaches the point. At the given point the bus fills with students once more, and everything is repeated.
If students come to the stop when there's no bus, they form a line (queue) and get on the bus in the order in which they came. Any number of students get on the bus in negligible time, you should assume that it doesn't take any time. Any other actions also take no time. The bus has no other passengers apart from the students.
Write a program that will determine for each student the time when he got off the bus. The moment a student got off the bus is the moment the bus stopped at the student's destination stop (despite the fact that the group of students need some time to get off).
Input
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of students and the number of passengers the bus can transport, correspondingly. Next n lines contain descriptions of the students, one per line. Each line contains a pair of integers ti, xi (1 ≤ ti ≤ 105, 1 ≤ xi ≤ 104). The lines are given in the order of strict increasing of ti. Values of xi can coincide.
Output
Print n numbers w1, w2, ..., wn, wi — the moment of time when the i-th student got off the bus. Print the numbers on one line and separate them with single spaces.
Examples
Input
1 10
3 5
Output
8
Input
2 1
3 5
4 5
Output
8 19
Input
5 4
3 5
4 5
5 5
6 5
7 1
Output
11 11 11 11 20
Input
20 4
28 13
31 13
35 6
36 4
52 6
53 4
83 2
84 4
87 1
93 6
108 4
113 6
116 1
125 2
130 2
136 13
162 2
166 4
184 1
192 2
Output
51 51 43 40 93 89 86 89 114 121 118 121 137 139 139 152 195 199 193 195
Note
In the first sample the bus waits for the first student for 3 units of time and drives him to his destination in additional 5 units of time. So the student leaves the bus at the moment of time 3 + 5 = 8.
In the second sample the capacity of the bus equals 1, that's why it will drive the first student alone. This student is the same as the student from the first sample. So the bus arrives to his destination at the moment of time 8, spends 1 + [1 / 2] = 1 units of time on getting him off, and returns back to 0 in additional 5 units of time. That is, the bus returns to the bus stop at the moment of time 14. By this moment the second student has already came to the bus stop. So he immediately gets in the bus, and is driven to his destination in additional 5 units of time. He gets there at the moment 14 + 5 = 19.
In the third sample the bus waits for the fourth student for 6 units of time, then drives for 5 units of time, then gets the passengers off for 1 + [4 / 2] = 3 units of time, then returns for 5 units of time, and then drives the fifth student for 1 unit of time.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
-----Output-----
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
-----Examples-----
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
-----Note-----
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice is the leader of the State Refactoring Party, and she is about to become the prime minister.
The elections have just taken place. There are $n$ parties, numbered from $1$ to $n$. The $i$-th party has received $a_i$ seats in the parliament.
Alice's party has number $1$. In order to become the prime minister, she needs to build a coalition, consisting of her party and possibly some other parties. There are two conditions she needs to fulfil: The total number of seats of all parties in the coalition must be a strict majority of all the seats, i.e. it must have strictly more than half of the seats. For example, if the parliament has $200$ (or $201$) seats, then the majority is $101$ or more seats. Alice's party must have at least $2$ times more seats than any other party in the coalition. For example, to invite a party with $50$ seats, Alice's party must have at least $100$ seats.
For example, if $n=4$ and $a=[51, 25, 99, 25]$ (note that Alice'a party has $51$ seats), then the following set $[a_1=51, a_2=25, a_4=25]$ can create a coalition since both conditions will be satisfied. However, the following sets will not create a coalition:
$[a_2=25, a_3=99, a_4=25]$ since Alice's party is not there; $[a_1=51, a_2=25]$ since coalition should have a strict majority; $[a_1=51, a_2=25, a_3=99]$ since Alice's party should have at least $2$ times more seats than any other party in the coalition.
Alice does not have to minimise the number of parties in a coalition. If she wants, she can invite as many parties as she wants (as long as the conditions are satisfied). If Alice's party has enough people to create a coalition on her own, she can invite no parties.
Note that Alice can either invite a party as a whole or not at all. It is not possible to invite only some of the deputies (seats) from another party. In other words, if Alice invites a party, she invites all its deputies.
Find and print any suitable coalition.
-----Input-----
The first line contains a single integer $n$ ($2 \leq n \leq 100$) — the number of parties.
The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq 100$) — the number of seats the $i$-th party has.
-----Output-----
If no coalition satisfying both conditions is possible, output a single line with an integer $0$.
Otherwise, suppose there are $k$ ($1 \leq k \leq n$) parties in the coalition (Alice does not have to minimise the number of parties in a coalition), and their indices are $c_1, c_2, \dots, c_k$ ($1 \leq c_i \leq n$). Output two lines, first containing the integer $k$, and the second the space-separated indices $c_1, c_2, \dots, c_k$.
You may print the parties in any order. Alice's party (number $1$) must be on that list. If there are multiple solutions, you may print any of them.
-----Examples-----
Input
3
100 50 50
Output
2
1 2
Input
3
80 60 60
Output
0
Input
2
6 5
Output
1
1
Input
4
51 25 99 25
Output
3
1 2 4
-----Note-----
In the first example, Alice picks the second party. Note that she can also pick the third party or both of them. However, she cannot become prime minister without any of them, because $100$ is not a strict majority out of $200$.
In the second example, there is no way of building a majority, as both other parties are too large to become a coalition partner.
In the third example, Alice already has the majority.
The fourth example is described in 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.
**Introduction**
Little Petya very much likes sequences. However, recently he received a sequence as a gift from his mother.
Petya didn't like it at all! He decided to make a single replacement. After this replacement, Petya would like to the sequence in increasing order.
He asks himself: What is the lowest possible value I could have got after making the replacement and sorting the sequence?
**About the replacement**
Choose exactly one element from the sequence and replace it with another integer > 0. You are **not allowed** to replace a number with itself, or to change no number at all.
**Task**
Find the lowest possible sequence after performing a valid replacement, and sorting the sequence.
**Input:**
Input contains sequence with `N` integers. All elements of the sequence > 0. The sequence will never be empty.
**Output:**
Return sequence with `N` integers — which includes the lowest possible values of each sequence element, after the single replacement and sorting has been performed.
**Examples**:
```
([1,2,3,4,5]) => [1,1,2,3,4]
([4,2,1,3,5]) => [1,1,2,3,4]
([2,3,4,5,6]) => [1,2,3,4,5]
([2,2,2]) => [1,2,2]
([42]) => [1]
```
Write your solution by modifying this code:
```python
def sort_number(a):
```
Your solution should implemented in the function "sort_number". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Playing with Stones
Koshiro and Ukiko are playing a game with black and white stones. The rules of the game are as follows:
1. Before starting the game, they define some small areas and place "one or more black stones and one or more white stones" in each of the areas.
2. Koshiro and Ukiko alternately select an area and perform one of the following operations.
(a) Remove a white stone from the area
(b) Remove one or more black stones from the area. Note, however, that the number of the black stones must be less than or equal to white ones in the area.
(c) Pick up a white stone from the stone pod and replace it with a black stone. There are plenty of white stones in the pod so that there will be no shortage during the game.
3. If either Koshiro or Ukiko cannot perform 2 anymore, he/she loses.
They played the game several times, with Koshiro’s first move and Ukiko’s second move, and felt the winner was determined at the onset of the game. So, they tried to calculate the winner assuming both players take optimum actions.
Given the initial allocation of black and white stones in each area, make a program to determine which will win assuming both players take optimum actions.
Input
The input is given in the following format.
$N$
$w_1$ $b_1$
$w_2$ $b_2$
:
$w_N$ $b_N$
The first line provides the number of areas $N$ ($1 \leq N \leq 10000$). Each of the subsequent $N$ lines provides the number of white stones $w_i$ and black stones $b_i$ ($1 \leq w_i, b_i \leq 100$) in the $i$-th area.
Output
Output 0 if Koshiro wins and 1 if Ukiko wins.
Examples
Input
4
24 99
15 68
12 90
95 79
Output
0
Input
3
2 46
94 8
46 57
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.
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #18
Create a function called that accepts 2 string arguments and returns an integer of the count of occurrences the 2nd argument is found in the first one.
If no occurrences can be found, a count of 0 should be returned.
Notes:
* The first argument can be an empty string
* The second string argument will always be of length 1
Write your solution by modifying this code:
```python
def str_count(strng, letter):
```
Your solution should implemented in the function "str_count". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ of $n$ non-negative integers. In one operation you can change any number in the array to any other non-negative integer.
Let's define the cost of the array as $\operatorname{DIFF}(a) - \operatorname{MEX}(a)$, where $\operatorname{MEX}$ of a set of non-negative integers is the smallest non-negative integer not present in the set, and $\operatorname{DIFF}$ is the number of different numbers in the array.
For example, $\operatorname{MEX}(\{1, 2, 3\}) = 0$, $\operatorname{MEX}(\{0, 1, 2, 4, 5\}) = 3$.
You should find the minimal cost of the array $a$ if you are allowed to make at most $k$ operations.
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows.
The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 10^5$, $0 \le k \le 10^5$) — the length of the array $a$ and the number of operations that you are allowed to make.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the elements of the array $a$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case output a single integer — minimal cost that it is possible to get making at most $k$ operations.
-----Examples-----
Input
4
4 1
3 0 1 2
4 1
0 2 4 5
7 2
4 13 0 0 13 1337 1000000000
6 2
1 2 8 0 0 0
Output
0
1
2
0
-----Note-----
In the first test case no operations are needed to minimize the value of $\operatorname{DIFF} - \operatorname{MEX}$.
In the second test case it is possible to replace $5$ by $1$. After that the array $a$ is $[0,\, 2,\, 4,\, 1]$, $\operatorname{DIFF} = 4$, $\operatorname{MEX} = \operatorname{MEX}(\{0, 1, 2, 4\}) = 3$, so the answer is $1$.
In the third test case one possible array $a$ is $[4,\, 13,\, 0,\, 0,\, 13,\, 1,\, 2]$, $\operatorname{DIFF} = 5$, $\operatorname{MEX} = 3$.
In the fourth test case one possible array $a$ is $[1,\, 2,\, 3,\, 0,\, 0,\, 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.
A text editor is a useful software tool that can help people in various situations including writing and programming. Your job in this problem is to construct an offline text editor, i.e., to write a program that first reads a given text and a sequence of editing commands and finally reports the text obtained by performing successively the commands in the given sequence.
The editor has a text buffer and a cursor. The target text is stored in the text buffer and most editing commands are performed around the cursor. The cursor has its position that is either the beginning of the text, the end of the text, or between two consecutive characters in the text. The initial cursor position (i.e., the cursor position just after reading the initial text) is the beginning of the text.
A text manipulated by the editor is a single line consisting of a sequence of characters, each of which must be one of the following: 'a' through 'z', 'A' through 'Z', '0' through '9', '.' (period), ',' (comma), and ' ' (blank). You can assume that any other characters never occur in the text buffer. You can also assume that the target text consists of at most 1,000 characters at any time. The definition of words in this problem is a little strange: a word is a non-empty character sequence delimited by not only blank characters but also the cursor. For instance, in the following text with a cursor represented as '^',
He^llo, World.
the words are the following.
He
llo,
World.
Notice that punctuation characters may appear in words as shown in this example.
The editor accepts the following set of commands. In the command list, "any-text" represents any text surrounded by a pair of double quotation marks such as "abc" and "Co., Ltd.".
Command |
Descriptions
---|---
forward char |
Move the cursor by one character to the right, unless the cursor is already at the end of the text.
forward word |
Move the cursor to the end of the leftmost word in the right. If no words occur in the right, move it to the end of the text.
backward char |
Move the cursor by one character to the left, unless the cursor is already at the beginning of the text.
backward word |
Move the cursor to the beginning of the rightmost word in the left. If no words occur in the left, move it to the beginning of the text.
insert "any-text" |
Insert any-text (excluding double quotation marks) at the position specified by the cursor. After performing this command, the new cursor position is at the end of the inserted text. The length of any-text is less than or equal to 100.
delete char |
Delete the character that is right next to the cursor, if it exists.
delete word |
Delete the leftmost word in the right of the cursor. If one or more blank characters occur between the cursor and the word before performing this command, delete these blanks, too. If no words occur in the right, delete no characters in the text buffer.
Input
The first input line contains a positive integer, which represents the number of texts the editor will edit. For each text, the input contains the following descriptions:
* The first line is an initial text whose length is at most 100.
* The second line contains an integer M representing the number of editing commands.
* Each of the third through the M+2nd lines contains an editing command.
You can assume that every input line is in a proper format or has no syntax errors. You can also assume that every input line has no leading or trailing spaces and that just a single blank character occurs between a command name (e.g., forward) and its argument (e.g., char).
Output
For each input text, print the final text with a character '^' representing the cursor position. Each output line shall contain exactly a single text with a character '^'.
Examples
Input
Output
Input
3
A sample input
9
forward word
delete char
forward word
delete char
forward word
delete char
backward word
backward word
forward word
Hallow, Word.
7
forward char
delete word
insert "ello, "
forward word
backward char
backward char
insert "l"
3
forward word
backward word
delete word
Output
Asampleinput^
Hello, Worl^d.
^
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: $1$, $4$, $8$, $9$, ....
For a given number $n$, count the number of integers from $1$ to $n$ that Polycarp likes. In other words, find the number of such $x$ that $x$ is a square of a positive integer number or a cube of a positive integer number (or both a square and a cube simultaneously).
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 20$) — the number of test cases.
Then $t$ lines contain the test cases, one per line. Each of the lines contains one integer $n$ ($1 \le n \le 10^9$).
-----Output-----
For each test case, print the answer you are looking for — the number of integers from $1$ to $n$ that Polycarp likes.
-----Examples-----
Input
6
10
1
25
1000000000
999999999
500000000
Output
4
1
6
32591
32590
23125
-----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.
Not so long ago, Vlad came up with an interesting function:
$f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x mod a$, where $\left\lfloor\frac{x}{a}\right\rfloor$ is $\frac{x}{a}$, rounded down, $x mod a$ — the remainder of the integer division of $x$ by $a$.
For example, with $a=3$ and $x=11$, the value $f_3(11) = \left\lfloor\frac{11}{3}\right\rfloor + 11 mod 3 = 3 + 2 = 5$.
The number $a$ is fixed and known to Vlad. Help Vlad find the maximum value of $f_a(x)$ if $x$ can take any integer value from $l$ to $r$ inclusive ($l \le x \le r$).
-----Input-----
The first line of input data contains an integer $t$ ($1 \le t \le 10^4$) — the number of input test cases.
This is followed by $t$ lines, each of which contains three integers $l_i$, $r_i$ and $a_i$ ($1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9$) — the left and right boundaries of the segment and the fixed value of $a$.
-----Output-----
For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given $a$.
-----Examples-----
Input
5
1 4 3
5 8 4
6 10 6
1 1000000000 1000000000
10 12 8
Output
2
4
5
999999999
5
-----Note-----
In the first sample:
$f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 mod 3 = 0 + 1 = 1$,
$f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 mod 3 = 0 + 2 = 2$,
$f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 mod 3 = 1 + 0 = 1$,
$f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 mod 3 = 1 + 1 = 2$
As an answer, obviously, $f_3(2)$ and $f_3(4)$ are suitable.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Chanek has an integer represented by a string $s$. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit.
Mr. Chanek wants to count the number of possible integer $s$, where $s$ is divisible by $25$. Of course, $s$ must not contain any leading zero. He can replace the character _ with any digit. He can also replace the character X with any digit, but it must be the same for every character X.
As a note, a leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, 0025 has two leading zeroes. An exception is the integer zero, (0 has no leading zero, but 0000 has three leading zeroes).
-----Input-----
One line containing the string $s$ ($1 \leq |s| \leq 8$). The string $s$ consists of the characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, _, and X.
-----Output-----
Output an integer denoting the number of possible integer $s$.
-----Examples-----
Input
25
Output
1
Input
_00
Output
9
Input
_XX
Output
9
Input
0
Output
1
Input
0_25
Output
0
-----Note-----
In the first example, the only possible $s$ is $25$.
In the second and third example, $s \in \{100, 200,300,400,500,600,700,800,900\}$.
In the fifth example, all possible $s$ will have at least one leading zero.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Princess Rupsa saw one of her friends playing a special game. The game goes as follows:
N+1 numbers occur sequentially (one at a time) from A_{0} to A_{N}.
You must write the numbers on a sheet of paper, such that A_{0} is written first. The other numbers are written according to an inductive rule — after A_{i-1} numbers have been written in a row, then A_{i} can be written at either end of the row. That is, you first write A_{0}, and then A_{1} can be written on its left or right to make A_{0}A_{1} or A_{1}A_{0}, and so on.
A_{i} must be written before writing A_{j}, for every i < j.
For a move in which you write a number A_{i} (i>0), your points increase by the product of A_{i} and its neighbour. (Note that for any move it will have only one neighbour as you write the number at an end).
Total score of a game is the score you attain after placing all the N + 1 numbers.
Princess Rupsa wants to find out the sum of scores obtained by all possible different gameplays. Two gameplays are different, if after writing down all N + 1 numbers, when we read from left to right, there exists some position i, at which the gameplays have a_{j} and a_{k} written at the i^{th} position such that j ≠ k. But since she has recently found her true love, a frog Prince, and is in a hurry to meet him, you must help her solve the problem as fast as possible. Since the answer can be very large, print the answer modulo 10^{9} + 7.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains a single integer N.
The second line contains N + 1 space-separated integers denoting A_{0} to A_{N}.
------ Output ------
For each test case, output a single line containing an integer denoting the answer.
------ Constraints ------
1 ≤ T ≤ 10
1 ≤ N ≤ 10^{5}
1 ≤ A_{i} ≤ 10^{9}
------ Sub tasks ------
Subtask #1: 1 ≤ N ≤ 10 (10 points)
Subtask #2: 1 ≤ N ≤ 1000 (20 points)
Subtask #3: Original Constraints (70 points)
----- Sample Input 1 ------
2
1
1 2
2
1 2 1
----- Sample Output 1 ------
4
14
----- explanation 1 ------
There are 2 possible gameplays. A0A1 which gives score of 2 and A1A0 which also gives score of 2. So the answer is 2 + 2 = 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Aizu Gakuen High School holds a school festival every year. The most popular of these is the haunted house. The most popular reason is that 9 classes do haunted houses instead of 1 or 2 classes. Each one has its own unique haunted house. Therefore, many visitors come from the neighborhood these days.
Therefore, the school festival executive committee decided to unify the admission fee for the haunted house in the school as shown in the table below, and based on this, total the total number of visitors and income for each class.
Admission fee list (admission fee per visitor)
Morning Afternoon
200 yen 300 yen
Enter the number of visitors in the morning and afternoon for each class, and create a program that creates a list of the total number of visitors and income for each class.
Input
The input is given in the following format:
name1 a1 b1
name2 a2 b2
::
name9 a9 b9
The input consists of 9 lines, the class name of the i-th class on the i-line namei (a half-width character string of 1 to 15 characters including numbers and alphabets), the number of visitors in the morning ai (0 ≤ ai ≤ 400) , Afternoon attendance bi (0 ≤ bi ≤ 400) is given.
Output
On the i-line, output the class name of the i-class, the total number of visitors, and the fee income on one line separated by blanks.
Example
Input
1a 132 243
1c 324 183
1f 93 199
2b 372 163
2c 229 293
2e 391 206
3a 118 168
3b 263 293
3d 281 102
Output
1a 375 99300
1c 507 119700
1f 292 78300
2b 535 123300
2c 522 133700
2e 597 140000
3a 286 74000
3b 556 140500
3d 383 86800
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya is preparing for his birthday. He decided that there would be $n$ different dishes on the dinner table, numbered from $1$ to $n$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.
Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from $n$ different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it: the dish will be delivered by a courier from the restaurant $i$, in this case the courier will arrive in $a_i$ minutes, Petya goes to the restaurant $i$ on his own and picks up the dish, he will spend $b_i$ minutes on this.
Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.
For example, if Petya wants to order $n = 4$ dishes and $a = [3, 7, 4, 5]$, and $b = [2, 1, 2, 4]$, then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in $3$ minutes, the courier of the fourth restaurant will bring the order in $5$ minutes, and Petya will pick up the remaining dishes in $1 + 2 = 3$ minutes. Thus, in $5$ minutes all the dishes will be at Petya's house.
Find the minimum time after which all the dishes can be at Petya's home.
-----Input-----
The first line contains one positive integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases. Then $t$ test cases follow.
Each test case begins with a line containing one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of dishes that Petya wants to order.
The second line of each test case contains $n$ integers $a_1 \ldots a_n$ ($1 \le a_i \le 10^9$) — the time of courier delivery of the dish with the number $i$.
The third line of each test case contains $n$ integers $b_1 \ldots b_n$ ($1 \le b_i \le 10^9$) — the time during which Petya will pick up the dish with the number $i$.
The sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case output one integer — the minimum time after which all dishes can be at Petya's home.
-----Example-----
Input
4
4
3 7 4 5
2 1 2 4
4
1 2 3 4
3 3 3 3
2
1 2
10 10
2
10 10
1 2
Output
5
3
2
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are some stones on Bob's table in a row, and each of them can be red, green or blue, indicated by the characters `R`, `G`, and `B`.
Help Bob find the minimum number of stones he needs to remove from the table so that the stones in each pair of adjacent stones have different colours.
Examples:
```
"RGBRGBRGGB" => 1
"RGGRGBBRGRR" => 3
"RRRRGGGGBBBB" => 9
```
Write your solution by modifying this code:
```python
def solution(stones):
```
Your solution should implemented in the function "solution". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $n$ days of summer. On the $i$-th day, $a_i$ millimeters of rain will fall. All values $a_i$ are distinct.
The mayor knows that citizens will watch the weather $x$ days before the celebration and $y$ days after. Because of that, he says that a day $d$ is not-so-rainy if $a_d$ is smaller than rain amounts at each of $x$ days before day $d$ and and each of $y$ days after day $d$. In other words, $a_d < a_j$ should hold for all $d - x \le j < d$ and $d < j \le d + y$. Citizens only watch the weather during summer, so we only consider such $j$ that $1 \le j \le n$.
Help mayor find the earliest not-so-rainy day of summer.
-----Input-----
The first line contains three integers $n$, $x$ and $y$ ($1 \le n \le 100\,000$, $0 \le x, y \le 7$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains $n$ distinct integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$), where $a_i$ denotes the rain amount on the $i$-th day.
-----Output-----
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
-----Examples-----
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
-----Note-----
In the first example days $3$ and $8$ are not-so-rainy. The $3$-rd day is earlier.
In the second example day $3$ is not not-so-rainy, because $3 + y = 6$ and $a_3 > a_6$. Thus, day $8$ is the answer. Note that $8 + y = 11$, but we don't consider day $11$, because it is not summer.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points.
Each of the next n lines contains two integers (x_{i}, y_{i}) (0 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th point.
-----Output-----
Print the only integer c — the number of parallelograms with the vertices at the given points.
-----Example-----
Input
4
0 1
1 0
1 1
2 0
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter t_{ij} units of time.
Order is important everywhere, so the painters' work is ordered by the following rules: Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n); each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.
Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
-----Input-----
The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers t_{i}1, t_{i}2, ..., t_{in} (1 ≤ t_{ij} ≤ 1000), where t_{ij} is the time the j-th painter needs to work on the i-th picture.
-----Output-----
Print the sequence of m integers r_1, r_2, ..., r_{m}, where r_{i} is the moment when the n-th painter stopped working on the i-th picture.
-----Examples-----
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 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.
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.
Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!
It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.
Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:
<image>
Determine the probability with which an aim can be successfully hit by an anvil.
You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.
Input
The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases.
Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106).
Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10.
Output
Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.
Examples
Input
2
4 2
1 2
Output
0.6250000000
0.5312500000
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 simple weighted connected undirected graph, consisting of $n$ vertices and $m$ edges.
A path in the graph of length $k$ is a sequence of $k+1$ vertices $v_1, v_2, \dots, v_{k+1}$ such that for each $i$ $(1 \le i \le k)$ the edge $(v_i, v_{i+1})$ is present in the graph. A path from some vertex $v$ also has vertex $v_1=v$. Note that edges and vertices are allowed to be included in the path multiple times.
The weight of the path is the total weight of edges in it.
For each $i$ from $1$ to $q$ consider a path from vertex $1$ of length $i$ of the maximum weight. What is the sum of weights of these $q$ paths?
Answer can be quite large, so print it modulo $10^9+7$.
-----Input-----
The first line contains a three integers $n$, $m$, $q$ ($2 \le n \le 2000$; $n - 1 \le m \le 2000$; $m \le q \le 10^9$) — the number of vertices in the graph, the number of edges in the graph and the number of lengths that should be included in the answer.
Each of the next $m$ lines contains a description of an edge: three integers $v$, $u$, $w$ ($1 \le v, u \le n$; $1 \le w \le 10^6$) — two vertices $v$ and $u$ are connected by an undirected edge with weight $w$. The graph contains no loops and no multiple edges. It is guaranteed that the given edges form a connected graph.
-----Output-----
Print a single integer — the sum of the weights of the paths from vertex $1$ of maximum weights of lengths $1, 2, \dots, q$ modulo $10^9+7$.
-----Examples-----
Input
7 8 25
1 2 1
2 3 10
3 4 2
1 5 2
5 6 7
6 4 15
5 3 1
1 7 3
Output
4361
Input
2 1 5
1 2 4
Output
60
Input
15 15 23
13 10 12
11 14 12
2 15 5
4 10 8
10 2 4
10 7 5
3 10 1
5 6 11
1 13 8
9 15 4
4 2 9
11 15 1
11 12 14
10 8 12
3 6 11
Output
3250
Input
5 10 10000000
2 4 798
1 5 824
5 2 558
4 1 288
3 4 1890
3 1 134
2 3 1485
4 5 284
3 5 1025
1 2 649
Output
768500592
-----Note-----
Here is the graph for the first example: [Image]
Some maximum weight paths are: length $1$: edges $(1, 7)$ — weight $3$; length $2$: edges $(1, 2), (2, 3)$ — weight $1+10=11$; length $3$: edges $(1, 5), (5, 6), (6, 4)$ — weight $2+7+15=24$; length $4$: edges $(1, 5), (5, 6), (6, 4), (6, 4)$ — weight $2+7+15+15=39$; $\dots$
So the answer is the sum of $25$ terms: $3+11+24+39+\dots$
In the second example the maximum weight paths have weights $4$, $8$, $12$, $16$ and $20$.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 following problem is well-known: given integers n and m, calculate $2^{n} \operatorname{mod} m$,
where 2^{n} = 2·2·...·2 (n factors), and $x \operatorname{mod} y$ denotes the remainder of division of x by y.
You are asked to solve the "reverse" problem. Given integers n and m, calculate $m \operatorname{mod} 2^{n}$.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^8).
The second line contains a single integer m (1 ≤ m ≤ 10^8).
-----Output-----
Output a single integer — the value of $m \operatorname{mod} 2^{n}$.
-----Examples-----
Input
4
42
Output
10
Input
1
58
Output
0
Input
98765432
23456789
Output
23456789
-----Note-----
In the first example, the remainder of division of 42 by 2^4 = 16 is equal to 10.
In the second example, 58 is divisible by 2^1 = 2 without remainder, and the answer is 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.
R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.
The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.
-----Input-----
The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 2·10^4; 1 ≤ m ≤ 10; 1 ≤ k ≤ 2·10^5) — the number of the employees, the number of chats and the number of events in the log, correspondingly.
Next n lines contain matrix a of size n × m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as a_{ij}) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m.
Next k lines contain the description of the log events. The i-th line contains two space-separated integers x_{i} and y_{i} (1 ≤ x_{i} ≤ n; 1 ≤ y_{i} ≤ m) which mean that the employee number x_{i} sent one message to chat number y_{i}. It is guaranteed that employee number x_{i} is a participant of chat y_{i}. It is guaranteed that each chat contains at least two employees.
-----Output-----
Print in the single line n space-separated integers, where the i-th integer shows the number of message notifications the i-th employee receives.
-----Examples-----
Input
3 4 5
1 1 1 1
1 0 1 1
1 1 0 0
1 1
3 1
1 3
2 4
3 2
Output
3 3 1
Input
4 3 4
0 1 1
1 0 1
1 1 1
0 0 0
1 2
2 1
3 1
1 3
Output
0 2 3 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.
A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right.
Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the places are shown on the picture: [Image]
Here, the desks in the top row are the closest to the blackboard, while the desks in the bottom row are the furthest from the blackboard.
You are given a plan of the class, where '*' denotes an occupied place, '.' denotes a vacant place, and the aisles are denoted by '-'.
Find any of the most convenient vacant places for Petya.
-----Input-----
The input consists of 6 lines. Each line describes one row of desks, starting from the closest to the blackboard. Each line is given in the following format: two characters, each is '*' or '.' — the description of the left desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the center desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the right desk in the current row. So, the length of each of the six lines is 8.
It is guaranteed that there is at least one vacant place in the classroom.
-----Output-----
Print the plan of the classroom after Petya takes one of the most convenient for him places. Mark this place with the letter 'P'. There should be exactly one letter 'P' in the plan. Petya can only take a vacant place. In all other places the output should coincide with the input.
If there are multiple answers, print any.
-----Examples-----
Input
..-**-..
..-**-..
..-..-..
..-..-..
..-..-..
..-..-..
Output
..-**-..
..-**-..
..-..-..
..-P.-..
..-..-..
..-..-..
Input
**-**-**
**-**-**
..-**-.*
**-**-**
..-..-..
..-**-..
Output
**-**-**
**-**-**
..-**-.*
**-**-**
..-P.-..
..-**-..
Input
**-**-*.
*.-*.-**
**-**-**
**-**-**
..-..-..
..-**-..
Output
**-**-*.
*.-*P-**
**-**-**
**-**-**
..-..-..
..-**-..
-----Note-----
In the first example the maximum convenience is 3.
In the second example the maximum convenience is 2.
In the third example the maximum convenience 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.
The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card.
The numbers in the lines are separated by single spaces.
Output
On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.
Examples
Input
3
4 7
4 7
7 4
Output
0
Input
5
4 7
7 4
2 11
9 7
1 1
Output
2
Note
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.
In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 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 vampire family of N members. Vampires are also known as extreme gourmets. Of course vampires' foods are human blood. However, not all kinds of blood is acceptable for them. Vampires drink blood that K blood types of ones are mixed, and each vampire has his/her favorite amount for each blood type.
You, cook of the family, are looking inside a fridge to prepare dinner. Your first task is to write a program that judges if all family members' dinner can be prepared using blood in the fridge.
Constraints
* Judge data includes at most 100 data sets.
* 1 ≤ N ≤ 100
* 1 ≤ K ≤ 100
* 0 ≤ Si ≤ 100000
* 0 ≤ Bij ≤ 1000
Input
Input file consists of a number of data sets. One data set is given in following format:
N K
S1 S2 ... SK
B11 B12 ... B1K
B21 B22 ... B2K
:
BN1 BN2 ... BNK
N and K indicate the number of family members and the number of blood types respectively.
Si is an integer that indicates the amount of blood of the i-th blood type that is in a fridge.
Bij is an integer that indicates the amount of blood of the j-th blood type that the i-th vampire uses.
The end of input is indicated by a case where N = K = 0. You should print nothing for this data set.
Output
For each set, print "Yes" if everyone's dinner can be prepared using blood in a fridge, "No" otherwise (without quotes).
Example
Input
2 3
5 4 5
1 2 3
3 2 1
3 5
1 2 3 4 5
0 1 0 1 2
0 1 1 2 2
1 0 3 1 1
0 0
Output
Yes
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.
Long time ago there was a symmetric array $a_1,a_2,\ldots,a_{2n}$ consisting of $2n$ distinct integers. Array $a_1,a_2,\ldots,a_{2n}$ is called symmetric if for each integer $1 \le i \le 2n$, there exists an integer $1 \le j \le 2n$ such that $a_i = -a_j$.
For each integer $1 \le i \le 2n$, Nezzar wrote down an integer $d_i$ equal to the sum of absolute differences from $a_i$ to all integers in $a$, i. e. $d_i = \sum_{j = 1}^{2n} {|a_i - a_j|}$.
Now a million years has passed and Nezzar can barely remember the array $d$ and totally forget $a$. Nezzar wonders if there exists any symmetric array $a$ consisting of $2n$ distinct integers that generates the array $d$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$).
The second line of each test case contains $2n$ integers $d_1, d_2, \ldots, d_{2n}$ ($0 \le d_i \le 10^{12}$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case, print "YES" in a single line if there exists a possible array $a$. Otherwise, print "NO".
You can print letters in any case (upper or lower).
-----Examples-----
Input
6
2
8 12 8 12
2
7 7 9 11
2
7 11 7 11
1
1 1
4
40 56 48 40 80 56 80 48
6
240 154 210 162 174 154 186 240 174 186 162 210
Output
YES
NO
NO
NO
NO
YES
-----Note-----
In the first test case, $a=[1,-3,-1,3]$ is one possible symmetric array that generates the array $d=[8,12,8,12]$.
In the second test case, it can be shown that there is no symmetric array consisting of distinct integers that can generate array $d$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array consisting of $n$ integers $a_1, a_2, \dots , a_n$ and an integer $x$. It is guaranteed that for every $i$, $1 \le a_i \le x$.
Let's denote a function $f(l, r)$ which erases all values such that $l \le a_i \le r$ from the array $a$ and returns the resulting array. For example, if $a = [4, 1, 1, 4, 5, 2, 4, 3]$, then $f(2, 4) = [1, 1, 5]$.
Your task is to calculate the number of pairs $(l, r)$ such that $1 \le l \le r \le x$ and $f(l, r)$ is sorted in non-descending order. Note that the empty array is also considered sorted.
-----Input-----
The first line contains two integers $n$ and $x$ ($1 \le n, x \le 10^6$) — the length of array $a$ and the upper limit for its elements, respectively.
The second line contains $n$ integers $a_1, a_2, \dots a_n$ ($1 \le a_i \le x$).
-----Output-----
Print the number of pairs $1 \le l \le r \le x$ such that $f(l, r)$ is sorted in non-descending order.
-----Examples-----
Input
3 3
2 3 1
Output
4
Input
7 4
1 3 1 2 2 4 3
Output
6
-----Note-----
In the first test case correct pairs are $(1, 1)$, $(1, 2)$, $(1, 3)$ and $(2, 3)$.
In the second test case correct pairs are $(1, 3)$, $(1, 4)$, $(2, 3)$, $(2, 4)$, $(3, 3)$ and $(3, 4)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The princess is going to escape the dragon's cave, and she needs to plan it carefully.
The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess noticed that the dragon is very greedy and not too smart. To delay him, the princess decides to borrow a couple of bijous from his treasury. Once the dragon overtakes the princess, she will drop one bijou to distract him. In this case he will stop, pick up the item, return to the cave and spend f hours to straighten the things out in the treasury. Only after this will he resume the chase again from the very beginning.
The princess is going to run on the straight. The distance between the cave and the king's castle she's aiming for is c miles. How many bijous will she need to take from the treasury to be able to reach the castle? If the dragon overtakes the princess at exactly the same moment she has reached the castle, we assume that she reached the castle before the dragon reached her, and doesn't need an extra bijou to hold him off.
Input
The input data contains integers vp, vd, t, f and c, one per line (1 ≤ vp, vd ≤ 100, 1 ≤ t, f ≤ 10, 1 ≤ c ≤ 1000).
Output
Output the minimal number of bijous required for the escape to succeed.
Examples
Input
1
2
1
1
10
Output
2
Input
1
2
1
1
8
Output
1
Note
In the first case one hour after the escape the dragon will discover it, and the princess will be 1 mile away from the cave. In two hours the dragon will overtake the princess 2 miles away from the cave, and she will need to drop the first bijou. Return to the cave and fixing the treasury will take the dragon two more hours; meanwhile the princess will be 4 miles away from the cave. Next time the dragon will overtake the princess 8 miles away from the cave, and she will need the second bijou, but after this she will reach the castle without any further trouble.
The second case is similar to the first one, but the second time the dragon overtakes the princess when she has reached the castle, and she won't need the second bijou.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function that takes one or more arrays and returns a new array of unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
Check the assertion tests for examples.
*Courtesy of [FreeCodeCamp](https://www.freecodecamp.com/challenges/sorted-union), a great place to learn web-dev; plus, its founder Quincy Larson is pretty cool and amicable. I made the original one slightly more tricky ;)*
Write your solution by modifying this code:
```python
def unite_unique(*args):
```
Your solution should implemented in the function "unite_unique". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic.
One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon.[Image]
The dragon has a hit point of $x$ initially. When its hit point goes to $0$ or under $0$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells. Void Absorption
Assume that the dragon's current hit point is $h$, after casting this spell its hit point will become $\left\lfloor \frac{h}{2} \right\rfloor + 10$. Here $\left\lfloor \frac{h}{2} \right\rfloor$ denotes $h$ divided by two, rounded down. Lightning Strike
This spell will decrease the dragon's hit point by $10$. Assume that the dragon's current hit point is $h$, after casting this spell its hit point will be lowered to $h-10$.
Due to some reasons Kana can only cast no more than $n$ Void Absorptions and $m$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 1000$) — the number of test cases.
The next $t$ lines describe test cases. For each test case the only line contains three integers $x$, $n$, $m$ ($1\le x \le 10^5$, $0\le n,m\le30$) — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.
-----Output-----
If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
-----Example-----
Input
7
100 3 4
189 3 4
64 2 3
63 2 3
30 27 7
10 9 1
69117 21 2
Output
YES
NO
NO
YES
YES
YES
YES
-----Note-----
One possible casting sequence of the first test case is shown below: Void Absorption $\left\lfloor \frac{100}{2} \right\rfloor + 10=60$. Lightning Strike $60-10=50$. Void Absorption $\left\lfloor \frac{50}{2} \right\rfloor + 10=35$. Void Absorption $\left\lfloor \frac{35}{2} \right\rfloor + 10=27$. Lightning Strike $27-10=17$. Lightning Strike $17-10=7$. Lightning Strike $7-10=-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.
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree.
A k-tree is an infinite rooted tree where:
each vertex has exactly k children; each edge has some weight; if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k.
The picture below shows a part of a 3-tree.
[Image]
As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?".
Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (10^9 + 7).
-----Input-----
A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k).
-----Output-----
Print a single integer — the answer to the problem modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
3 3 2
Output
3
Input
3 3 3
Output
1
Input
4 3 2
Output
6
Input
4 5 2
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.
[Image]
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.
Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length l_{i}.
The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle $180^{\circ}$.
Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.
Help sculptor!
-----Input-----
The first line contains an integer n (3 ≤ n ≤ 10^5) — a number of rod-blanks.
The second line contains n integers l_{i} (1 ≤ l_{i} ≤ 10^9) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.
-----Output-----
Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.
-----Examples-----
Input
3
1 2 1
Output
1
Input
5
20 4 3 2 1
Output
11
-----Note-----
In the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}.
In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a program that reads poker hand data and outputs the role for each. However, this issue follows the rules below.
* Poker is a competition with 5 playing cards.
* No more than 5 cards with the same number.
* There is no joker.
* Suppose you only consider the following poker roles: (The higher the number, the higher the role.)
1. No role (does not apply to any of the following)
2. One pair (two cards with the same number)
3. Two pairs (two pairs of cards with the same number)
4. Three cards (one set of three cards with the same number)
5. Straight (the numbers on 5 cards are consecutive)
However, in the case of a straight containing A, the sequence ending with A is also straight. In other words, there are two types of straights containing A: A 2 3 4 5 and 10 J Q K A. Lines that straddle A, such as J Q K A 2, are not straight. (In this case, it will be "no role").
6. Full House (one set of three cards with the same number and the other two cards with the same number)
7. Four Cards (one set of four cards with the same number)
Input
The input consists of multiple datasets. Each dataset is given in the following format:
Hand 1, Hand 2, Hand 3, Hand 4, Hand 5
In your hand, Trump's J (jack) is 11, Q (queen) is 12, K (king) is 13, A (ace) is 1, and the others are represented by their respective numbers.
The number of datasets does not exceed 50.
Output
For each dataset, output one of the highest roles you can play in your hand. Follow the output example for the notation of the role.
Example
Input
1,2,3,4,1
2,3,2,3,12
12,13,11,12,12
7,6,7,6,7
3,3,2,3,3
6,7,8,9,10
11,12,10,1,13
11,12,13,1,2
Output
one pair
two pair
three card
full house
four card
straight
straight
null
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
THE BY DOLM @ STER is a training simulation game scheduled to be released on EXIDNA by 1rem on April 1, 2010. For the time being, it probably has nothing to do with an arcade game where the network connection service stopped earlier this month.
This game is a game in which members of the unit (formation) to be produced are selected from the bidders, and through lessons and communication with the members, they (they) are raised to the top of the bidders, the top biddles.
Each bidle has three parameters, vocal, dance, and looks, and the unit's ability score is the sum of all the parameters of the biddles that belong to the unit. The highest of the three stats of a unit is the rank of the unit.
There is no limit to the number of people in a unit, and you can work as a unit with one, three, or 100 members. Of course, you can hire more than one of the same bidle, but hiring a bidle is expensive and must be taken into account.
As a producer, you decided to write and calculate a program to make the best unit.
Input
The input consists of multiple test cases.
The first line of each test case is given the number N of bid dollars and the available cost M. (1 <= N, M <= 300) The next 2 * N lines contain information about each bidle.
The name of the bidle is on the first line of the bidle information. Biddle names consist of alphabets and spaces, with 30 characters or less. Also, there is no bidle with the same name.
The second line is given the integers C, V, D, L. C is the cost of hiring one Biddle, V is the vocal, D is the dance, and L is the stat of the looks. (1 <= C, V, D, L <= 300)
Input ends with EOF.
Output
Answer the maximum rank of units that can be made within the given cost.
If you cannot make a unit, output 0.
Example
Input
3 10
Dobkeradops
7 5 23 10
PataPata
1 1 2 1
dop
5 3 11 14
2 300
Bydo System Alpha
7 11 4 7
Green Inferno
300 300 300 300
Output
29
462
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are $n$ piles of stones, the $i$-th pile of which has $a_i$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: $n=3$ and sizes of piles are $a_1=2$, $a_2=3$, $a_3=0$. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be $[1, 3, 0]$ and it is a good move. But if she chooses the second pile then the state will be $[2, 2, 0]$ and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of piles.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_1, a_2, \ldots, a_n \le 10^9$), which mean the $i$-th pile has $a_i$ stones.
-----Output-----
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
-----Examples-----
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
-----Note-----
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
Firstly, Tokitsukaze can choose the first pile and take a stone from that pile. Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately. Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this kata you need to create a function that takes a 2D array/list of non-negative integer pairs and returns the sum of all the "saving" that you can have getting the [LCM](https://en.wikipedia.org/wiki/Least_common_multiple) of each couple of number compared to their simple product.
For example, if you are given:
```
[[15,18], [4,5], [12,60]]
```
Their product would be:
```
[270, 20, 720]
```
While their respective LCM would be:
```
[90, 20, 60]
```
Thus the result should be:
```
(270-90)+(20-20)+(720-60)==840
```
This is a kata that I made, among other things, to let some of my trainees familiarize with the [euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm), a really neat tool to have on your belt ;)
Write your solution by modifying this code:
```python
def sum_differences_between_products_and_LCMs(pairs):
```
Your solution should implemented in the function "sum_differences_between_products_and_LCMs". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is yet another problem on regular bracket sequences.
A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.
For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
Input
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
Output
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.
Print -1, if there is no answer. If the answer is not unique, print any of them.
Examples
Input
(??)
1 2
2 8
Output
4
()()
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate x_{i} and weight w_{i}. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |x_{i} - x_{j}| ≥ w_{i} + w_{j}.
Find the size of the maximum clique in such graph.
-----Input-----
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers x_{i}, w_{i} (0 ≤ x_{i} ≤ 10^9, 1 ≤ w_{i} ≤ 10^9) — the coordinate and the weight of a point. All x_{i} are different.
-----Output-----
Print a single number — the number of vertexes in the maximum clique of the given graph.
-----Examples-----
Input
4
2 3
3 1
6 1
0 2
Output
3
-----Note-----
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test. [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.
Not to be confused with chessboard.
[Image]
-----Input-----
The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have.
The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.
-----Output-----
Output a single number.
-----Examples-----
Input
9
brie soft
camembert soft
feta soft
goat soft
muenster soft
asiago hard
cheddar hard
gouda hard
swiss hard
Output
3
Input
6
parmesan hard
emmental hard
edam hard
colby hard
gruyere hard
asiago hard
Output
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
If we multiply the integer `717 (n)` by `7 (k)`, the result will be equal to `5019`.
Consider all the possible ways that this last number may be split as a string and calculate their corresponding sum obtained by adding the substrings as integers. When we add all of them up,... surprise, we got the original number `717`:
```
Partitions as string Total Sums
['5', '019'] 5 + 19 = 24
['50', '19'] 50 + 19 = 69
['501', '9'] 501 + 9 = 510
['5', '0', '19'] 5 + 0 + 19 = 24
['5', '01', '9'] 5 + 1 + 9 = 15
['50', '1', '9'] 50 + 1 + 9 = 60
['5', '0', '1', '9'] 5 + 0 + 1 + 9 = 15
____________________
Big Total: 717
____________________
```
In fact, `717` is one of the few integers that has such property with a factor `k = 7`.
Changing the factor `k`, for example to `k = 3`, we may see that the integer `40104` fulfills this property.
Given an integer `start_value` and an integer `k`, output the smallest integer `n`, but higher than `start_value`, that fulfills the above explained properties.
If by chance, `start_value`, fulfills the property, do not return `start_value` as a result, only the next integer. Perhaps you may find this assertion redundant if you understood well the requirement of the kata: "output the smallest integer `n`, but higher than `start_value`"
The values for `k` in the input may be one of these: `3, 4, 5, 7`
### Features of the random tests
If you want to understand the style and features of the random tests, see the *Notes* at the end of these instructions.
The random tests are classified in three parts.
- Random tests each with one of the possible values of `k` and a random `start_value` in the interval `[100, 1300]`
- Random tests each with a `start_value` in a larger interval for each value of `k`, as follows:
- for `k = 3`, a random `start value` in the range `[30000, 40000]`
- for `k = 4`, a random `start value` in the range `[2000, 10000]`
- for `k = 5`, a random `start value` in the range `[10000, 20000]`
- for `k = 7`, a random `start value` in the range `[100000, 130000]`
- More challenging tests, each with a random `start_value` in the interval `[100000, 110000]`.
See the examples tests.
Enjoy it.
# Notes:
- As these sequences are finite, in other words, they have a maximum term for each value of k, the tests are prepared in such way that the `start_value` will always be less than this maximum term. So you may be confident that your code will always find an integer.
- The values of `k` that generate sequences of integers, for the constrains of this kata are: 2, 3, 4, 5, and 7. The case `k = 2` was not included because it generates only two integers.
- The sequences have like "mountains" of abundance of integers but also have very wide ranges like "valleys" of scarceness. Potential solutions, even the fastest ones, may time out searching the next integer due to an input in one of these valleys. So it was intended to avoid these ranges.
Javascript and Ruby versions will be released soon.
Write your solution by modifying this code:
```python
def next_higher(start,k):
```
Your solution should implemented in the function "next_higher". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.
The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.
An Example of some correct logos:
[Image]
An Example of some incorrect logos:
[Image]
Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of $n$ rows and $m$ columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').
Adhami gave Warawreh $q$ options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is $0$.
Warawreh couldn't find the best option himself so he asked you for help, can you help him?
-----Input-----
The first line of input contains three integers $n$, $m$ and $q$ $(1 \leq n , m \leq 500, 1 \leq q \leq 3 \cdot 10^{5})$ — the number of row, the number columns and the number of options.
For the next $n$ lines, every line will contain $m$ characters. In the $i$-th line the $j$-th character will contain the color of the cell at the $i$-th row and $j$-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.
For the next $q$ lines, the input will contain four integers $r_1$, $c_1$, $r_2$ and $c_2$ $(1 \leq r_1 \leq r_2 \leq n, 1 \leq c_1 \leq c_2 \leq m)$. In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell $(r_1, c_1)$ and with the bottom-right corner in the cell $(r_2, c_2)$.
-----Output-----
For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print $0$.
-----Examples-----
Input
5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
Output
16
4
4
4
0
Input
6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
Output
36
4
16
16
16
Input
8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
Output
64
0
16
4
16
4
36
0
-----Note-----
Picture for the first test:
[Image]
The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 us call two integers $x$ and $y$ adjacent if $\frac{lcm(x, y)}{gcd(x, y)}$ is a perfect square. For example, $3$ and $12$ are adjacent, but $6$ and $9$ are not.
Here $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$, and $lcm(x, y)$ denotes the least common multiple (LCM) of integers $x$ and $y$.
You are given an array $a$ of length $n$. Each second the following happens: each element $a_i$ of the array is replaced by the product of all elements of the array (including itself), that are adjacent to the current value.
Let $d_i$ be the number of adjacent elements to $a_i$ (including $a_i$ itself). The beauty of the array is defined as $\max_{1 \le i \le n} d_i$.
You are given $q$ queries: each query is described by an integer $w$, and you have to output the beauty of the array after $w$ seconds.
-----Input-----
The first input line contains a single integer $t$ ($1 \le t \le 10^5)$ — the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the length of the array.
The following line contains $n$ integers $a_1, \ldots, a_n$ ($1 \le a_i \le 10^6$) — array elements.
The next line contain a single integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of queries.
The following $q$ lines contain a single integer $w$ each ($0 \le w \le 10^{18}$) — the queries themselves.
It is guaranteed that the sum of values $n$ over all test cases does not exceed $3 \cdot 10^5$, and the sum of values $q$ over all test cases does not exceed $3 \cdot 10^5$
-----Output-----
For each query output a single integer — the beauty of the array at the corresponding moment.
-----Examples-----
Input
2
4
6 8 4 2
1
0
6
12 3 20 5 80 1
1
1
Output
2
3
-----Note-----
In the first test case, the initial array contains elements $[6, 8, 4, 2]$. Element $a_4=2$ in this array is adjacent to $a_4=2$ (since $\frac{lcm(2, 2)}{gcd(2, 2)}=\frac{2}{2}=1=1^2$) and $a_2=8$ (since $\frac{lcm(8,2)}{gcd(8, 2)}=\frac{8}{2}=4=2^2$). Hence, $d_4=2$, and this is the maximal possible value $d_i$ in this array.
In the second test case, the initial array contains elements $[12, 3, 20, 5, 80, 1]$. The elements adjacent to $12$ are $\{12, 3\}$, the elements adjacent to $3$ are $\{12, 3\}$, the elements adjacent to $20$ are $\{20, 5, 80\}$, the elements adjacent to $5$ are $\{20, 5, 80\}$, the elements adjacent to $80$ are $\{20, 5, 80\}$, the elements adjacent to $1$ are $\{1\}$. After one second, the array is transformed into $[36, 36, 8000, 8000, 8000, 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.
Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is a_{i}, and after a week of discounts its price will be b_{i}.
Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.
Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.
-----Input-----
In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·10^5, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now.
The second line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4) — prices of items during discounts (i.e. right now).
The third line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^4) — prices of items after discounts (i.e. after a week).
-----Output-----
Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.
-----Examples-----
Input
3 1
5 4 6
3 1 5
Output
10
Input
5 3
3 4 7 10 3
4 5 5 12 5
Output
25
-----Note-----
In the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.
In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 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.
You are given two arrays of length $n$: $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$.
You can perform the following operation any number of times:
Choose integer index $i$ ($1 \le i \le n$);
Swap $a_i$ and $b_i$.
What is the minimum possible sum $|a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n|$ $+$ $|b_1 - b_2| + |b_2 - b_3| + \dots + |b_{n-1} - b_n|$ (in other words, $\sum\limits_{i=1}^{n - 1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$) you can achieve after performing several (possibly, zero) operations?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 4000$) — the number of test cases. Then, $t$ test cases follow.
The first line of each test case contains the single integer $n$ ($2 \le n \le 25$) — the length of arrays $a$ and $b$.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the array $a$.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 10^9$) — the array $b$.
-----Output-----
For each test case, print one integer — the minimum possible sum $\sum\limits_{i=1}^{n-1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$.
-----Examples-----
Input
3
4
3 3 10 10
10 10 3 3
5
1 2 3 4 5
6 7 8 9 10
6
72 101 108 108 111 44
10 87 111 114 108 100
Output
0
8
218
-----Note-----
In the first test case, we can, for example, swap $a_3$ with $b_3$ and $a_4$ with $b_4$. We'll get arrays $a = [3, 3, 3, 3]$ and $b = [10, 10, 10, 10]$ with sum $3 \cdot |3 - 3| + 3 \cdot |10 - 10| = 0$.
In the second test case, arrays already have minimum sum (described above) equal to $|1 - 2| + \dots + |4 - 5| + |6 - 7| + \dots + |9 - 10|$ $= 4 + 4 = 8$.
In the third test case, we can, for example, swap $a_5$ and $b_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.
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?
-----Constraints-----
- All values in input are integers.
- 0 \leq A, B, C
- 1 \leq K \leq A + B + C \leq 2 \times 10^9
-----Input-----
Input is given from Standard Input in the following format:
A B C K
-----Output-----
Print the maximum possible sum of the numbers written on the cards chosen.
-----Sample Input-----
2 1 1 3
-----Sample Output-----
2
Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $1$ to $n$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $i$ ($1 \leq i \leq n$) will decide to go for boiled water at minute $t_i$.
Tank with a boiled water is located to the left of the $1$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $p$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small.
Nobody likes to stand in a queue. So when the passenger occupying the $i$-th seat wants to go for a boiled water, he will first take a look on all seats from $1$ to $i - 1$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $i$ are busy, he will go to the tank.
There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.
Your goal is to find for each passenger, when he will receive the boiled water for his noodles.
-----Input-----
The first line contains integers $n$ and $p$ ($1 \leq n \leq 100\,000$, $1 \leq p \leq 10^9$) — the number of people and the amount of time one person uses the tank.
The second line contains $n$ integers $t_1, t_2, \dots, t_n$ ($0 \leq t_i \leq 10^9$) — the moments when the corresponding passenger will go for the boiled water.
-----Output-----
Print $n$ integers, where $i$-th of them is the time moment the passenger on $i$-th seat will receive his boiled water.
-----Example-----
Input
5 314
0 310 942 628 0
Output
314 628 1256 942 1570
-----Note-----
Consider the example.
At the $0$-th minute there were two passengers willing to go for a water, passenger $1$ and $5$, so the first passenger has gone first, and returned at the $314$-th minute. At this moment the passenger $2$ was already willing to go for the water, so the passenger $2$ has gone next, and so on. In the end, $5$-th passenger was last to receive the boiled water.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.
There are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.
Also, there are $m$ boxes. All of them are for different people, so they are pairwise distinct (consider that the names of $m$ friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.
Alice wants to pack presents with the following rules: She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of $n$ kinds, empty boxes are allowed); For each kind at least one present should be packed into some box.
Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo $10^9+7$.
See examples and their notes for clarification.
-----Input-----
The first line contains two integers $n$ and $m$, separated by spaces ($1 \leq n,m \leq 10^9$) — the number of kinds of presents and the number of boxes that Alice has.
-----Output-----
Print one integer — the number of ways to pack the presents with Alice's rules, calculated by modulo $10^9+7$
-----Examples-----
Input
1 3
Output
7
Input
2 2
Output
9
-----Note-----
In the first example, there are seven ways to pack presents:
$\{1\}\{\}\{\}$
$\{\}\{1\}\{\}$
$\{\}\{\}\{1\}$
$\{1\}\{1\}\{\}$
$\{\}\{1\}\{1\}$
$\{1\}\{\}\{1\}$
$\{1\}\{1\}\{1\}$
In the second example there are nine ways to pack presents:
$\{\}\{1,2\}$
$\{1\}\{2\}$
$\{1\}\{1,2\}$
$\{2\}\{1\}$
$\{2\}\{1,2\}$
$\{1,2\}\{\}$
$\{1,2\}\{1\}$
$\{1,2\}\{2\}$
$\{1,2\}\{1,2\}$
For example, the way $\{2\}\{2\}$ is wrong, because presents of the first kind should be used in the least one box.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction.
A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of queries.
Next $n$ lines contain queries, one per line. Each line contains three integers $p$, $q$, and $b$ ($0 \le p \le 10^{18}$, $1 \le q \le 10^{18}$, $2 \le b \le 10^{18}$). All numbers are given in notation with base $10$.
-----Output-----
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
-----Examples-----
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
-----Note-----
$\frac{6}{12} = \frac{1}{2} = 0,5_{10}$
$\frac{4}{3} = 1,(3)_{10}$
$\frac{9}{36} = \frac{1}{4} = 0,01_2$
$\frac{4}{12} = \frac{1}{3} = 0,1_3$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You know that the Martians use a number system with base k. Digit b (0 ≤ b < k) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology).
A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of all digits of number x. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.
For example, d(35047) = d((3 + 5 + 0 + 4)7) = d(157) = d((1 + 5)7) = d(67) = 67. In this sample the calculations are performed in the 7-base notation.
If a number's digital root equals b, the Martians also call this number lucky.
You have string s, which consists of n digits in the k-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.
Note that substring s[i... j] of the string s = a1a2... an (1 ≤ i ≤ j ≤ n) is the string aiai + 1... aj. Two substrings s[i1... j1] and s[i2... j2] of the string s are different if either i1 ≠ i2 or j1 ≠ j2.
Input
The first line contains three integers k, b and n (2 ≤ k ≤ 109, 0 ≤ b < k, 1 ≤ n ≤ 105).
The second line contains string s as a sequence of n integers, representing digits in the k-base notation: the i-th integer equals ai (0 ≤ ai < k) — the i-th digit of string s. The numbers in the lines are space-separated.
Output
Print a single integer — the number of substrings that are lucky numbers.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
10 5 6
3 2 0 5 6 1
Output
5
Input
7 6 4
3 5 0 4
Output
1
Input
257 0 3
0 0 256
Output
3
Note
In the first sample the following substrings have the sought digital root: s[1... 2] = "3 2", s[1... 3] = "3 2 0", s[3... 4] = "0 5", s[4... 4] = "5" and s[2... 6] = "2 0 5 6 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.
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.
Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.
It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.
Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.
Input
The first line contains two space-separated integers: n (2 ≤ n ≤ 105), the number of planets in the galaxy, and m (0 ≤ m ≤ 105) — the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 ≤ ci ≤ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection.
Then n lines follow: the i-th line contains an integer ki (0 ≤ ki ≤ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 ≤ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.
Output
Print a single number — the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.
Examples
Input
4 6
1 2 2
1 3 3
1 4 8
2 3 4
2 4 5
3 4 3
0
1 3
2 3 4
0
Output
7
Input
3 1
1 2 3
0
1 3
0
Output
-1
Note
In the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then — to planet 4, then he spends a total of only 2 + 5 = 7 seconds.
In the second sample one can't get from planet 1 to planet 3 by moving through stargates.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integers N and M.
Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 10^5
- N \leq M \leq 10^9
-----Input-----
Input is given from Standard Input in the following format:
N M
-----Output-----
Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.
-----Sample Input-----
3 14
-----Sample Output-----
2
Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 define $S(x)$ to be the sum of digits of number $x$ written in decimal system. For example, $S(5) = 5$, $S(10) = 1$, $S(322) = 7$.
We will call an integer $x$ interesting if $S(x + 1) < S(x)$. In each test you will be given one integer $n$. Your task is to calculate the number of integers $x$ such that $1 \le x \le n$ and $x$ is interesting.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — number of test cases.
Then $t$ lines follow, the $i$-th line contains one integer $n$ ($1 \le n \le 10^9$) for the $i$-th test case.
-----Output-----
Print $t$ integers, the $i$-th should be the answer for the $i$-th test case.
-----Examples-----
Input
5
1
9
10
34
880055535
Output
0
1
1
3
88005553
-----Note-----
The first interesting number is equal to $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 an array of numbers, return the difference between the largest and smallest values.
For example:
`[23, 3, 19, 21, 16]` should return `20` (i.e., `23 - 3`).
`[1, 434, 555, 34, 112]` should return `554` (i.e., `555 - 1`).
The array will contain a minimum of two elements. Input data range guarantees that `max-min` will cause no integer overflow.
Write your solution by modifying this code:
```python
def between_extremes(numbers):
```
Your solution should implemented in the function "between_extremes". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The alphabetized kata
---------------------
Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!
The input is restricted to contain no numerals and only words containing the english alphabet letters.
Example:
```python
alphabetized("The Holy Bible") # "BbeehHilloTy"
```
_Inspired by [Tauba Auerbach](http://www.taubaauerbach.com/view.php?id=73)_
Write your solution by modifying this code:
```python
def alphabetized(s):
```
Your solution should implemented in the function "alphabetized". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least $3$ (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself $k$-multihedgehog.
Let us define $k$-multihedgehog as follows: $1$-multihedgehog is hedgehog: it has one vertex of degree at least $3$ and some vertices of degree 1. For all $k \ge 2$, $k$-multihedgehog is $(k-1)$-multihedgehog in which the following changes has been made for each vertex $v$ with degree 1: let $u$ be its only neighbor; remove vertex $v$, create a new hedgehog with center at vertex $w$ and connect vertices $u$ and $w$ with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby $k$-multihedgehog is a tree. Ivan made $k$-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed $k$-multihedgehog.
-----Input-----
First line of input contains $2$ integers $n$, $k$ ($1 \le n \le 10^{5}$, $1 \le k \le 10^{9}$) — number of vertices and hedgehog parameter.
Next $n-1$ lines contains two integers $u$ $v$ ($1 \le u, \,\, v \le n; \,\, u \ne v$) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
-----Output-----
Print "Yes" (without quotes), if given graph is $k$-multihedgehog, and "No" (without quotes) otherwise.
-----Examples-----
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
-----Note-----
2-multihedgehog from the first example looks like this:
[Image]
Its center is vertex $13$. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least $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.
ButCoder Inc. runs a programming competition site called ButCoder. In this site, a user is given an integer value called rating that represents his/her skill, which changes each time he/she participates in a contest. The initial value of a new user's rating is 0, and a user whose rating reaches K or higher is called Kaiden ("total transmission"). Note that a user's rating may become negative.
Hikuhashi is a new user in ButCoder. It is estimated that, his rating increases by A in each of his odd-numbered contests (first, third, fifth, ...), and decreases by B in each of his even-numbered contests (second, fourth, sixth, ...).
According to this estimate, after how many contests will he become Kaiden for the first time, or will he never become Kaiden?
Constraints
* 1 ≤ K, A, B ≤ 10^{18}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
K A B
Output
If it is estimated that Hikuhashi will never become Kaiden, print `-1`. Otherwise, print the estimated number of contests before he become Kaiden for the first time.
Examples
Input
4000 2000 500
Output
5
Input
4000 500 2000
Output
-1
Input
1000000000000000000 2 1
Output
1999999999999999997
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $v$ (different from root) is the previous to $v$ vertex on the shortest path from the root to the vertex $v$. Children of the vertex $v$ are all vertices for which $v$ is the parent.
A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied:
it is not a root,
it has at least one child, and
all its children are leaves.
You are given a rooted tree with $n$ vertices. The vertex $1$ is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.
What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of the vertices in the given tree.
Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1 \le u, v \le n$, $u \neq v$) meaning that there is an edge between vertices $u$ and $v$ in the tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case print a single integer — the minimal number of leaves that is possible to get after some operations.
-----Examples-----
Input
5
7
1 2
1 3
1 4
2 5
2 6
4 7
6
1 2
1 3
2 4
2 5
3 6
2
1 2
7
7 3
1 5
1 3
4 6
4 7
2 1
6
2 1
2 3
4 5
3 4
3 6
Output
2
2
1
2
1
-----Note-----
In the first test case the tree looks as follows:
Firstly you can choose a bud vertex $4$ and re-hang it to vertex $3$. After that you can choose a bud vertex $2$ and re-hang it to vertex $7$. As a result, you will have the following tree with $2$ leaves:
It can be proved that it is the minimal number of leaves possible to get.
In the second test case the tree looks as follows:
You can choose a bud vertex $3$ and re-hang it to vertex $5$. As a result, you will have the following tree with $2$ leaves:
It can be proved that it is the minimal number of leaves possible to get.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have been assigned to develop a filter for bad messages in the in-game chat. A message is a string $S$ of length $n$, consisting of lowercase English letters and characters ')'. The message is bad if the number of characters ')' at the end of the string strictly greater than the number of remaining characters. For example, the string ")bc)))" has three parentheses at the end, three remaining characters, and is not considered bad.
-----Input-----
The first line contains the number of test cases $t$ ($1 \leq t \leq 100$). Description of the $t$ test cases follows.
The first line of each test case contains an integer $n$ ($1 \leq n \leq 100$). The second line of each test case contains a string $S$ of length $n$, consisting of lowercase English letters and characters ')'.
-----Output-----
For each of $t$ test cases, print "Yes" if the string is bad. Otherwise, print "No".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
5
2
))
12
gl))hf))))))
9
gege)))))
14
)aa))b))))))))
1
)
Output
Yes
No
Yes
Yes
Yes
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Implement a function, so it will produce a sentence out of the given parts.
Array of parts could contain:
- words;
- commas in the middle;
- multiple periods at the end.
Sentence making rules:
- there must always be a space between words;
- there must not be a space between a comma and word on the left;
- there must always be one and only one period at the end of a sentence.
**Example:**
Write your solution by modifying this code:
```python
def make_sentences(parts):
```
Your solution should implemented in the function "make_sentences". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n integers a_1, a_2, ..., a_{n}. Find the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2 (i. e. some integer x exists so that a_{i} + a_{j} = 2^{x}).
-----Input-----
The first line contains the single positive integer n (1 ≤ n ≤ 10^5) — the number of integers.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2.
-----Examples-----
Input
4
7 3 2 1
Output
2
Input
3
1 1 1
Output
3
-----Note-----
In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).
In the second example all pairs of indexes (i, j) (where i < j) include in answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.
Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:
* Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.
For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure. If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward. Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.
864abc2e4a08c26015ffd007a30aab03.png
Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.
Constraints
* 1 ≦ x ≦ 10^{15}
* x is an integer.
Input
The input is given from Standard Input in the following format:
x
Output
Print the answer.
Examples
Input
7
Output
2
Input
149696127901
Output
27217477801
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 pair of positive integers $(a,b)$ is called special if $\lfloor \frac{a}{b} \rfloor = a mod b$. Here, $\lfloor \frac{a}{b} \rfloor$ is the result of the integer division between $a$ and $b$, while $a mod b$ is its remainder.
You are given two integers $x$ and $y$. Find the number of special pairs $(a,b)$ such that $1\leq a \leq x$ and $1 \leq b \leq y$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases.
The only line of the description of each test case contains two integers $x$, $y$ ($1 \le x,y \le 10^9$).
-----Output-----
For each test case print the answer on a single line.
-----Examples-----
Input
9
3 4
2 100
4 3
50 3
12 4
69 420
12345 6789
123456 789
12345678 9
Output
1
0
2
3
5
141
53384
160909
36
-----Note-----
In the first test case, the only special pair is $(3, 2)$.
In the second test case, there are no special pairs.
In the third test case, there are two special pairs: $(3, 2)$ and $(4, 3)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC^2 (Handbook of Crazy Constructions) and looks for the right chapter:
How to build a wall: Take a set of bricks. Select one of the possible wall designs. Computing the number of possible designs is left as an exercise to the reader. Place bricks on top of each other, according to the chosen design.
This seems easy enough. But Heidi is a Coding Cow, not a Constructing Cow. Her mind keeps coming back to point 2b. Despite the imminent danger of a zombie onslaught, she wonders just how many possible walls she could build with up to n bricks.
A wall is a set of wall segments as defined in the easy version. How many different walls can be constructed such that the wall consists of at least 1 and at most n bricks? Two walls are different if there exist a column c and a row r such that one wall has a brick in this spot, and the other does not.
Along with n, you will be given C, the width of the wall (as defined in the easy version). Return the number of different walls modulo 10^6 + 3.
-----Input-----
The first line contains two space-separated integers n and C, 1 ≤ n ≤ 500000, 1 ≤ C ≤ 200000.
-----Output-----
Print the number of different walls that Heidi could build, modulo 10^6 + 3.
-----Examples-----
Input
5 1
Output
5
Input
2 2
Output
5
Input
3 2
Output
9
Input
11 5
Output
4367
Input
37 63
Output
230574
-----Note-----
The number 10^6 + 3 is prime.
In the second sample case, the five walls are:
B B
B., .B, BB, B., and .B
In the third sample case, the nine walls are the five as in the second sample case and in addition the following four:
B B
B B B B
B., .B, BB, and BB
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books).
# Zero Terminated Sum
Mary has another puzzle book, and it's up to you to help her out! This book is filled with zero-terminated substrings, and you have to find the substring with the largest sum of its digits. For example, one puzzle looks like this:
```
"72102450111111090"
```
Here, there are 4 different substrings: `721`, `245`, `111111`, and `9`. The sums of their digits are `10`, `11`, `6`, and `9` respectively. Therefore, the substring with the largest sum of its digits is `245`, and its sum is `11`.
Write a function `largest_sum` which takes a string and returns the maximum of the sums of the substrings. In the example above, your function should return `11`.
### Notes:
- A substring can have length 0. For example, `123004560` has three substrings, and the middle one has length 0.
- All inputs will be valid strings of digits, and the last digit will always be `0`.
Write your solution by modifying this code:
```python
def largest_sum(s):
```
Your solution should implemented in the function "largest_sum". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible — he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 — the board sizes and the coordinates of the first and second chips, correspondingly (1 ≤ n, m ≤ 100; 2 ≤ n × m; 1 ≤ x1, x2 ≤ n; 1 ≤ y1, y2 ≤ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Generalized leap year
Normally, whether or not the year x is a leap year is defined as follows.
1. If x is a multiple of 400, it is a leap year.
2. Otherwise, if x is a multiple of 100, it is not a leap year.
3. Otherwise, if x is a multiple of 4, it is a leap year.
4. If not, it is not a leap year.
This can be generalized as follows. For a sequence A1, ..., An, we define whether the year x is a "generalized leap year" as follows.
1. For the smallest i (1 ≤ i ≤ n) such that x is a multiple of Ai, if i is odd, it is a generalized leap year, and if it is even, it is not a generalized leap year.
2. When such i does not exist, it is not a generalized leap year if n is odd, but a generalized leap year if n is even.
For example, when A = [400, 100, 4], the generalized leap year for A is equivalent to a normal leap year.
Given the sequence A1, ..., An and the positive integers l, r. Answer the number of positive integers x such that l ≤ x ≤ r such that year x is a generalized leap year for A.
Input
The input consists of up to 50 datasets. Each dataset is represented in the following format.
> n l r A1 A2 ... An
The integer n satisfies 1 ≤ n ≤ 50. The integers l and r satisfy 1 ≤ l ≤ r ≤ 4000. For each i, the integer Ai satisfies 1 ≤ Ai ≤ 4000.
The end of the input is represented by a line of three zeros.
Output
Print the answer in one line for each dataset.
Sample Input
3 1988 2014
400
100
Four
1 1000 1999
1
2 1111 3333
2
2
6 2000 3000
Five
7
11
9
3
13
0 0 0
Output for the Sample Input
7
1000
2223
785
Example
Input
3 1988 2014
400
100
4
1 1000 1999
1
2 1111 3333
2
2
6 2000 3000
5
7
11
9
3
13
0 0 0
Output
7
1000
2223
785
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Hitachi string is a concatenation of one or more copies of the string `hi`.
For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not.
Given a string S, determine whether S is a Hitachi string.
Constraints
* The length of S is between 1 and 10 (inclusive).
* S is a string consisting of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If S is a Hitachi string, print `Yes`; otherwise, print `No`.
Examples
Input
hihi
Output
Yes
Input
hi
Output
Yes
Input
ha
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.
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.
At first day Mister B read v_0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v_0 pages, at second — v_0 + a pages, at third — v_0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v_1 pages per day.
Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.
Help Mister B to calculate how many days he needed to finish the book.
-----Input-----
First and only line contains five space-separated integers: c, v_0, v_1, a and l (1 ≤ c ≤ 1000, 0 ≤ l < v_0 ≤ v_1 ≤ 1000, 0 ≤ a ≤ 1000) — the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.
-----Output-----
Print one integer — the number of days Mister B needed to finish the book.
-----Examples-----
Input
5 5 10 5 4
Output
1
Input
12 4 12 4 1
Output
3
Input
15 1 100 0 0
Output
15
-----Note-----
In the first sample test the book contains 5 pages, so Mister B read it right at the first day.
In the second sample test at first day Mister B read pages number 1 - 4, at second day — 4 - 11, at third day — 11 - 12 and finished the book.
In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Binary with 0 and 1 is good, but binary with only 0 is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages.
Can you write a program that can send and receive this messages?
Rules
The input message consists of ASCII characters between 32 and 127 (7-bit)
The encoded output message consists of blocks of 0
A block is separated from another block by a space
Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):
First block is always 0 or 00. If it is 0, then the series contains 1, if not, it contains 0
The number of 0 in the second block is the number of bits in the series
Example
Let’s take a simple example with a message which consists of only one character (Letter 'C').'C' in binary is represented as 1000011, so with Chuck Norris’ technique this gives:
0 0 - the first series consists of only a single 1
00 0000 - the second series consists of four 0
0 00 - the third consists of two 1
So 'C' is coded as: 0 0 00 0000 0 00
Second example, we want to encode the message "CC" (i.e. the 14 bits 10000111000011) :
0 0 - one single 1
00 0000 - four 0
0 000 - three 1
00 0000 - four 0
0 00 - two 1
So "CC" is coded as: 0 0 00 0000 0 000 00 0000 0 00
Note of thanks
Thanks to the author of the original kata. I really liked this kata. I hope that other warriors will enjoy it too.
Write your solution by modifying this code:
```python
def send(s):
```
Your solution should implemented in the function "send". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.
Sometimes the government makes payouts to the poor: all citizens who have strictly less money than x are paid accordingly so that after the payout they have exactly x money. In this case the citizens don't send a receipt.
You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the numer of citizens.
The next line contains n integers a_1, a_2, ..., a_n (0 ≤ a_{i} ≤ 10^{9}) — the initial balances of citizens.
The next line contains a single integer q (1 ≤ q ≤ 2 ⋅ 10^{5}) — the number of events.
Each of the next q lines contains a single event. The events are given in chronological order.
Each event is described as either 1 p x (1 ≤ p ≤ n, 0 ≤ x ≤ 10^{9}), or 2 x (0 ≤ x ≤ 10^{9}). In the first case we have a receipt that the balance of the p-th person becomes equal to x. In the second case we have a payoff with parameter x.
Output
Print n integers — the balances of all citizens after all events.
Examples
Input
4
1 2 3 4
3
2 3
1 2 2
2 1
Output
3 2 3 4
Input
5
3 50 2 1 10
3
1 2 0
2 8
1 3 20
Output
8 8 20 8 10
Note
In the first example the balances change as follows: 1 2 3 4 → 3 3 3 4 → 3 2 3 4 → 3 2 3 4
In the second example the balances change as follows: 3 50 2 1 10 → 3 0 2 1 10 → 8 8 8 8 10 → 8 8 20 8 10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on.
The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0.
What is the minimum time for the car to get from point A to point B without breaking the traffic rules?
Input
The first line contains integers l, d, v, g, r (1 ≤ l, d, v, g, r ≤ 1000, d < l) — the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light.
Output
Output a single number — the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6.
Examples
Input
2 1 3 4 5
Output
0.66666667
Input
5 4 3 1 1
Output
2.33333333
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle $n \times m$, where each cell is either empty, or contains a digit from $1$ to $8$, or a bomb. The field is valid if for each cell: if there is a digit $k$ in the cell, then exactly $k$ neighboring cells have bombs. if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $8$ neighboring cells).
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 100$) — the sizes of the field.
The next $n$ lines contain the description of the field. Each line contains $m$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $1$ to $8$, inclusive.
-----Output-----
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
-----Examples-----
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
-----Note-----
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 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.
C: Namo .. Cut
problem
-Defeat the mysterious giant jellyfish, codenamed "Nari"-
"Nari" has a very strong vitality, so if you don't keep cutting quickly, it will be revived in a blink of an eye. We are making trial and error every day to find out how to cut "Nari" efficiently. In the process, you needed the help of a programmer.
"Na ◯ ri" can be represented by a connected undirected graph consisting of N vertices and N edges. From now on, suppose each vertex is named with a different number from 1 to N.
We ask Q questions about "Nari". I want you to create a program that answers all of them.
Questions have numbers from 1 to Q, and each question is structured as follows:
* Question i specifies two vertices a_i and b_i. Answer the minimum number of edges that need to be deleted in order to unlink a_i and b_i.
Here, the fact that the vertices u and v are unconnected means that there is no route that can go back and forth between u and v.
Input format
N
u_1 v_1
u_2 v_2
...
u_N v_N
Q
a_1 b_1
a_2 b_2
...
a_Q b_Q
All inputs are integers.
The number of vertices N is given in the first line. The i-th line of the following N lines is given the numbers u_i and v_i of the two vertices connected by the i-th edge, separated by blanks.
Then the number of questions Q is given. The i-th line of the following Q lines is given the numbers a_i and b_i of the two vertices specified in the i-th question, separated by blanks.
Constraint
* 3 \ leq N \ leq 100,000
* 1 \ leq Q \ leq 100,000
* There are no self-loops or multiple edges in the graph
* 1 \ leq a_i, b_i \ leq N and a_i \ neq b_i (1 \ leq i \ leq Q)
Output format
The output consists of Q lines. On line i, output an integer that represents the minimum number of edges that need to be deleted in order to unlink a_i and b_i.
Input example 1
3
1 2
13
twenty three
1
13
Output example 1
2
Input example 2
7
1 2
1 6
3 5
twenty five
5 4
14
3 7
3
twenty four
3 1
6 7
Output example 2
2
1
1
Example
Input
3
1 2
1 3
2 3
1
1 3
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.
<image>
Input
The input contains a single integer a (1 ≤ a ≤ 18257).
Output
Print a single integer output (1 ≤ output ≤ 2·109).
Examples
Input
2
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.
You are given an array $a$ of length $n$, and an integer $x$. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was $[3, 6, 9]$, in a single operation one can replace the last two elements by their sum, yielding an array $[3, 15]$, or replace the first two elements to get an array $[9, 9]$. Note that the size of the array decreases after each operation.
The beauty of an array $b=[b_1, \ldots, b_k]$ is defined as $\sum_{i=1}^k \left\lceil \frac{b_i}{x} \right\rceil$, which means that we divide each element by $x$, round it up to the nearest integer, and sum up the resulting values. For example, if $x = 3$, and the array is $[4, 11, 6]$, the beauty of the array is equal to $\left\lceil \frac{4}{3} \right\rceil + \left\lceil \frac{11}{3} \right\rceil + \left\lceil \frac{6}{3} \right\rceil = 2 + 4 + 2 = 8$.
Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.
-----Input-----
The first input line contains a single integer $t$ — the number of test cases ($1 \le t \le 1000$).
The first line of each test case contains two integers $n$ and $x$ ($1 \leq n \leq 10^5$, $1 \leq x \leq 10^9$).
The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$), the elements of the array $a$.
It is guaranteed that the sum of values of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case output two integers — the minimal and the maximal possible beauty.
-----Examples-----
Input
2
3 3
3 6 9
3 3
6 4 11
Output
6 6
7 8
-----Note-----
In the first test case the beauty of the array does not change if we perform any operations.
In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements $4$ and $11$ with their sum, yielding an array $[6, 15]$, which has its beauty equal to $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.
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.
In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.
Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).
Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.
To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses:
* "Success" if the activation was successful.
* "Already on", if the i-th collider was already activated before the request.
* "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them.
The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program:
* "Success", if the deactivation was successful.
* "Already off", if the i-th collider was already deactivated before the request.
You don't need to print quotes in the output of the responses to the requests.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of colliders and the number of requests, correspondingly.
Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) — activate the i-th collider, or "- i" (without the quotes) — deactivate the i-th collider (1 ≤ i ≤ n).
Output
Print m lines — the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.
Examples
Input
10 10
+ 6
+ 10
+ 5
- 10
- 5
- 6
+ 10
+ 3
+ 6
+ 3
Output
Success
Conflict with 6
Success
Already off
Success
Success
Success
Success
Conflict with 10
Already on
Note
Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 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.
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.
This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good.
Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.
Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
Input
The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Output
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.
Examples
Input
11 4 3 9
Output
3
Input
20 5 2 20
Output
2
Note
The images below illustrate statement tests.
The first test:
<image>
In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.
The second test:
<image>
In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.
Input
The first line contains integer n (3 ≤ n ≤ 100) — amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.
Output
Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.
Examples
Input
5
2 4 7 8 10
Output
3
Input
4
1 2 1 1
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You had $n$ positive integers $a_1, a_2, \dots, a_n$ arranged in a circle. For each pair of neighboring numbers ($a_1$ and $a_2$, $a_2$ and $a_3$, ..., $a_{n - 1}$ and $a_n$, and $a_n$ and $a_1$), you wrote down: are the numbers in the pair equal or not.
Unfortunately, you've lost a piece of paper with the array $a$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $a$ which is consistent with information you have about equality or non-equality of corresponding pairs?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Next $t$ cases follow.
The first and only line of each test case contains a non-empty string $s$ consisting of characters E and/or N. The length of $s$ is equal to the size of array $n$ and $2 \le n \le 50$. For each $i$ from $1$ to $n$:
if $s_i =$ E then $a_i$ is equal to $a_{i + 1}$ ($a_n = a_1$ for $i = n$);
if $s_i =$ N then $a_i$ is not equal to $a_{i + 1}$ ($a_n \neq a_1$ for $i = n$).
-----Output-----
For each test case, print YES if it's possible to choose array $a$ that are consistent with information from $s$ you know. Otherwise, print NO.
It can be proved, that if there exists some array $a$, then there exists an array $a$ of positive integers with values less or equal to $10^9$.
-----Examples-----
Input
4
EEE
EN
ENNEENE
NENN
Output
YES
NO
YES
YES
-----Note-----
In the first test case, you can choose, for example, $a_1 = a_2 = a_3 = 5$.
In the second test case, there is no array $a$, since, according to $s_1$, $a_1$ is equal to $a_2$, but, according to $s_2$, $a_2$ is not equal to $a_1$.
In the third test case, you can, for example, choose array $a = [20, 20, 4, 50, 50, 50, 20]$.
In the fourth test case, you can, for example, choose $a = [1, 3, 3, 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.
An element in an array is dominant if it is greater than all elements to its right. You will be given an array and your task will be to return a list of all dominant elements. For example:
```Haskell
solve([1,21,4,7,5]) = [21,7,5] because 21, 7 and 5 are greater than elments to their right.
solve([5,4,3,2,1]) = [5,4,3,2,1]
Notice that the last element is always included.
```
More examples in the test cases.
Good luck!
Write your solution by modifying this code:
```python
def solve(arr):
```
Your solution should implemented in the function "solve". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You still have partial information about the score during the historic football match. You are given a set of pairs $(a_i, b_i)$, indicating that at some point during the match the score was "$a_i$: $b_i$". It is known that if the current score is «$x$:$y$», then after the goal it will change to "$x+1$:$y$" or "$x$:$y+1$". What is the largest number of times a draw could appear on the scoreboard?
The pairs "$a_i$:$b_i$" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10000$) — the number of known moments in the match.
Each of the next $n$ lines contains integers $a_i$ and $b_i$ ($0 \le a_i, b_i \le 10^9$), denoting the score of the match at that moment (that is, the number of goals by the first team and the number of goals by the second team).
All moments are given in chronological order, that is, sequences $x_i$ and $y_j$ are non-decreasing. The last score denotes the final result of the match.
-----Output-----
Print the maximum number of moments of time, during which the score was a draw. The starting moment of the match (with a score 0:0) is also counted.
-----Examples-----
Input
3
2 0
3 1
3 4
Output
2
Input
3
0 0
0 0
0 0
Output
1
Input
1
5 4
Output
5
-----Note-----
In the example one of the possible score sequences leading to the maximum number of draws is as follows: 0:0, 1:0, 2:0, 2:1, 3:1, 3:2, 3:3, 3:4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.
The input to the function will be an array of three distinct numbers (Haskell: a tuple).
For example:
gimme([2, 3, 1]) => 0
*2* is the number that fits between *1* and *3* and the index of *2* in the input array is *0*.
Another example (just to make sure it is clear):
gimme([5, 10, 14]) => 1
*10* is the number that fits between *5* and *14* and the index of *10* in the input array is *1*.
Write your solution by modifying this code:
```python
def gimme(input_array):
```
Your solution should implemented in the function "gimme". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
How many multiples of d are there among the integers between L and R (inclusive)?
Constraints
* All values in input are integers.
* 1 \leq L \leq R \leq 100
* 1 \leq d \leq 100
Input
Input is given from Standard Input in the following format:
L R d
Output
Print the number of multiples of d among the integers between L and R (inclusive).
Examples
Input
5 10 2
Output
3
Input
6 20 7
Output
2
Input
1 100 1
Output
100
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$, consisting of $n$ positive integers.
Let's call a concatenation of numbers $x$ and $y$ the number that is obtained by writing down numbers $x$ and $y$ one right after another without changing the order. For example, a concatenation of numbers $12$ and $3456$ is a number $123456$.
Count the number of ordered pairs of positions $(i, j)$ ($i \neq j$) in array $a$ such that the concatenation of $a_i$ and $a_j$ is divisible by $k$.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $2 \le k \le 10^9$).
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).
-----Output-----
Print a single integer — the number of ordered pairs of positions $(i, j)$ ($i \neq j$) in array $a$ such that the concatenation of $a_i$ and $a_j$ is divisible by $k$.
-----Examples-----
Input
6 11
45 1 10 12 11 7
Output
7
Input
4 2
2 78 4 10
Output
12
Input
5 2
3 7 19 3 3
Output
0
-----Note-----
In the first example pairs $(1, 2)$, $(1, 3)$, $(2, 3)$, $(3, 1)$, $(3, 4)$, $(4, 2)$, $(4, 3)$ suffice. They produce numbers $451$, $4510$, $110$, $1045$, $1012$, $121$, $1210$, respectively, each of them is divisible by $11$.
In the second example all $n(n - 1)$ pairs suffice.
In the third example no pair is sufficient.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Andrii is good in Math, but not in Programming. He is asking you to solve following problem: Given an integer number N and two sets of integer A and B. Let set A contain all numbers from 1 to N and set B contain all numbers from N + 1 to 2N. Multiset C contains all sums a + b such that a belongs to A and b belongs to B. Note that multiset may contain several elements with the same values. For example, if N equals to three, then A = {1, 2, 3}, B = {4, 5, 6} and C = {5, 6, 6, 7, 7, 7, 8, 8, 9}. Andrii has M queries about multiset C. Every query is defined by a single integer q. Andrii wants to know the number of times q is contained in C. For example, number 6 is contained two times, 1 is not contained in C at all.
Please, help Andrii to answer all the queries.
-----Input-----
The first line of the input contains two integers N and M. Each of the next M line contains one integer q, the query asked by Andrii.
-----Output-----
Output the answer for each query in separate lines as in example.
-----Constraints-----
- 1 ≤ N ≤ 109
- 1 ≤ M ≤ 105
- 1 ≤ q ≤ 3N
-----Example-----
Input:
3 5
6
2
9
7
5
Output:
2
0
1
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.
### Count the number of Duplicates
Write a function that will return the count of **distinct case-insensitive** alphabetic characters and numeric digits that occur more than
once in the input string.
The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
### Example
"abcde" -> 0 `# no characters repeats more than once`
"aabbcde" -> 2 `# 'a' and 'b'`
"aabBcde" -> 2 ``# 'a' occurs twice and 'b' twice (`b` and `B`)``
"indivisibility" -> 1 `# 'i' occurs six times`
"Indivisibilities" -> 2 `# 'i' occurs seven times and 's' occurs twice`
"aA11" -> 2 `# 'a' and '1'`
"ABBA" -> 2 `# 'A' and 'B' each occur twice`
Write your solution by modifying this code:
```python
def duplicate_count(text):
```
Your solution should implemented in the function "duplicate_count". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A bracket sequence is a string that is one of the following:
- An empty string;
- The concatenation of (, A, and ) in this order, for some bracket sequence A ;
- The concatenation of A and B in this order, for some non-empty bracket sequences A and B /
Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?
-----Constraints-----
- 1 \leq N \leq 10^6
- The total length of the strings S_i is at most 10^6.
- S_i is a non-empty string consisting of ( and ).
-----Input-----
Input is given from Standard Input in the following format:
N
S_1
:
S_N
-----Output-----
If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.
-----Sample Input-----
2
)
(()
-----Sample Output-----
Yes
Concatenating (() and ) in this order forms a bracket sequence.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
D: Sontaku (Surmise)
Some twins like even numbers.
Count how many even numbers are in $ N $ integers $ A_1, A_2, A_3, \ dots, A_N $.
input
The integer $ N $ is given on the first line.
On the second line, $ N $ integers $ A_1, A_2, A_3, \ dots, A_N $ are given, separated by blanks.
output
Output an even number. However, insert a line break at the end.
Constraint
* $ N $ is an integer greater than or equal to $ 1 $ and less than or equal to $ 100 $
* $ A_1, A_2, A_3, \ dots, A_N $ are integers between $ 1 $ and $ 100 $
Input example 1
Five
4 3 5 2 6
Output example 1
3
$ A_1 = 4 $, $ A_4 = 2 $ and $ A_5 = 6 $ are even numbers. Therefore, the even number is $ 3 $.
Input example 2
3
2 2 2
Output example 2
3
Even if the numbers are the same, if the positions in $ A_1, A_2, A_3, \ dots, A_N $ are different, they are counted as different numbers.
Example
Input
5
4 3 5 2 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.
You will get an array of numbers.
Every preceding number is smaller than the one following it.
Some numbers will be missing, for instance:
```
[-3,-2,1,5] //missing numbers are: -1,0,2,3,4
```
Your task is to return an array of those missing numbers:
```
[-1,0,2,3,4]
```
Write your solution by modifying this code:
```python
def find_missing_numbers(arr):
```
Your solution should implemented in the function "find_missing_numbers". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.