question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
An array of size N x M represents pixels of an image.
Each cell of this array contains an array of size 3 with the pixel's color information: `[R,G,B]`
Convert the color image, into an *average* greyscale image.
The `[R,G,B]` array contains integers between 0 and 255 for each color.
To transform a color pixel into a greyscale pixel, average the values of that pixel:
```
p = [R,G,B] => [(R+G+B)/3, (R+G+B)/3, (R+G+B)/3]
```
**Note:** the values for the pixel must be integers, therefore you should round floats to the nearest integer.
## Example
Here's an example of a 2x2 image:
Here's the expected image after transformation:
You are always welcome to check out some of my other katas:
Very Easy (Kyu 8)
Add Numbers
Easy (Kyu 7-6)
Convert Color image to greyscale
Array Transformations
Basic Compression
Find Primes in Range
No Ifs No Buts
Medium (Kyu 5-4)
Identify Frames In An Image
Photoshop Like - Magic Wand
Scientific Notation
Vending Machine - FSA
Find Matching Parenthesis
Hard (Kyu 3-2)
Ascii Art Generator
Write your solution by modifying this code:
```python
def color_2_grey(colors):
```
Your solution should implemented in the function "color_2_grey". 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.
Compute A \times B, truncate its fractional part, and print the result as an integer.
-----Constraints-----
- 0 \leq A \leq 10^{15}
- 0 \leq B < 10
- A is an integer.
- B is a number with two digits after the decimal point.
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
Print the answer as an integer.
-----Sample Input-----
198 1.10
-----Sample Output-----
217
We have 198 \times 1.10 = 217.8. After truncating the fractional part, we have the answer: 217.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.
There are $n_1$ different types of first courses Ivan can buy (the $i$-th of them costs $a_i$ coins), $n_2$ different types of second courses (the $i$-th of them costs $b_i$ coins), $n_3$ different types of drinks (the $i$-th of them costs $c_i$ coins) and $n_4$ different types of desserts (the $i$-th of them costs $d_i$ coins).
Some dishes don't go well with each other. There are $m_1$ pairs of first courses and second courses that don't go well with each other, $m_2$ pairs of second courses and drinks, and $m_3$ pairs of drinks and desserts that don't go well with each other.
Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!
-----Input-----
The first line contains four integers $n_1$, $n_2$, $n_3$ and $n_4$ ($1 \le n_i \le 150000$) — the number of types of first courses, second courses, drinks and desserts, respectively.
Then four lines follow. The first line contains $n_1$ integers $a_1, a_2, \dots, a_{n_1}$ ($1 \le a_i \le 10^8$), where $a_i$ is the cost of the $i$-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way ($1 \le b_i, c_i, d_i \le 10^8$).
The next line contains one integer $m_1$ ($0 \le m_1 \le 200000$) — the number of pairs of first and second courses that don't go well with each other. Each of the next $m_1$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i \le n_1$; $1 \le y_i \le n_2$) denoting that the first course number $x_i$ doesn't go well with the second course number $y_i$. All these pairs are different.
The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other ($0 \le m_2, m_3 \le 200000$).
-----Output-----
If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print $-1$. Otherwise, print one integer — the minimum total cost of the dinner.
-----Examples-----
Input
4 3 2 1
1 2 3 4
5 6 7
8 9
10
2
1 2
1 1
2
3 1
3 2
1
1 1
Output
26
Input
1 1 1 1
1
1
1
1
1
1 1
0
0
Output
-1
-----Note-----
The best option in the first example is to take the first course $2$, the second course $1$, the drink $2$ and the dessert $1$.
In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 string $b$ is a subsequence of a string $a$ if $b$ can be obtained from $a$ by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx".
You are given a string $a$. Your task is to reorder the characters of $a$ so that "trygub" is not a subsequence of the resulting string.
In other words, you should find a string $b$ which is a permutation of symbols of the string $a$ and "trygub" is not a subsequence of $b$.
We have a truly marvelous proof that any string can be arranged not to contain "trygub" as a subsequence, but this problem statement is too short to contain it.
-----Input-----
The first line contains a single integer $t$ ($1\le t\le 100$) — the number of test cases.
The first line of each test case contains a single integer $n$ ($1\le n\le 200$) — the length of $a$.
The next line contains the string $a$ of length $n$, consisting of lowercase English letters.
-----Output-----
For each test case, output a string $b$ of length $n$ which is a permutation of characters of the string $a$, and such that "trygub" is not a subsequence of it.
If there exist multiple possible strings $b$, you can print any.
-----Examples-----
Input
3
11
antontrygub
15
bestcoordinator
19
trywatchinggurabruh
Output
bugyrtnotna
bestcoordinator
bruhtrywatchinggura
-----Note-----
In the first test case, "bugyrtnotna" does not contain "trygub" as a subsequence. It does contain the letters of "trygub", but not in the correct order, so it is not a subsequence.
In the second test case, we did not change the order of characters because it is not needed.
In the third test case, "bruhtrywatchinggura" does contain "trygu" as a subsequence, but not "trygub".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 cities numbered 1 through N, and M bidirectional roads numbered 1 through M. Road i connects City A_i and City B_i.
Snuke can perform the following operation zero or more times:
* Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.
After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).
What is the minimum number of roads he must build to achieve the goal?
Constraints
* 2 \leq N \leq 100,000
* 1 \leq M \leq 100,000
* 1 \leq A_i < B_i \leq N
* No two roads connect the same pair of cities.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1
:
A_M B_M
Output
Print the answer.
Example
Input
3 1
1 2
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.
Dima's got a staircase that consists of n stairs. The first stair is at height a_1, the second one is at a_2, the last one is at a_{n} (1 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n}).
Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width w_{i} and height h_{i}. Dima throws each box vertically down on the first w_{i} stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., w_{i}. Each thrown box flies vertically down until at least one of the two following events happen: the bottom of the box touches the top of a stair; the bottom of the box touches the top of a box, thrown earlier.
We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width w_{i} cannot touch the stair number w_{i} + 1.
You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5) — the number of stairs in the staircase. The second line contains a non-decreasing sequence, consisting of n integers, a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9; a_{i} ≤ a_{i} + 1).
The next line contains integer m (1 ≤ m ≤ 10^5) — the number of boxes. Each of the following m lines contains a pair of integers w_{i}, h_{i} (1 ≤ w_{i} ≤ n; 1 ≤ h_{i} ≤ 10^9) — the size of the i-th thrown box.
The numbers in the lines are separated by spaces.
-----Output-----
Print m integers — for each box the height, where the bottom of the box will be after landing. Print the answers for the boxes in the order, in which the boxes are given in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
5
1 2 3 6 6
4
1 1
3 1
1 1
4 3
Output
1
3
4
6
Input
3
1 2 3
2
1 1
3 1
Output
1
3
Input
1
1
5
1 2
1 10
1 10
1 10
1 10
Output
1
3
13
23
33
-----Note-----
The first sample are shown on the picture. [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.
Share price
===========
You spent all your saved money to buy some shares.
You bought it for `invested`, and want to know how much it's worth, but all the info you can quickly get are just the change the shares price made in percentages.
Your task:
----------
Write the function `sharePrice()` that calculates, and returns the current price of your share, given the following two arguments:
- `invested`(number), the amount of money you initially invested in the given share
- `changes`(array of numbers), contains your shares daily movement percentages
The returned number, should be in string format, and it's precision should be fixed at 2 decimal numbers.
Have fun!
>**Hint:** Try to write the function in a functional manner!
Write your solution by modifying this code:
```python
def share_price(invested, changes):
```
Your solution should implemented in the function "share_price". 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 integer $x$ of $n$ digits $a_1, a_2, \ldots, a_n$, which make up its decimal notation in order from left to right.
Also, you are given a positive integer $k < n$.
Let's call integer $b_1, b_2, \ldots, b_m$ beautiful if $b_i = b_{i+k}$ for each $i$, such that $1 \leq i \leq m - k$.
You need to find the smallest beautiful integer $y$, such that $y \geq x$.
-----Input-----
The first line of input contains two integers $n, k$ ($2 \leq n \leq 200\,000, 1 \leq k < n$): the number of digits in $x$ and $k$.
The next line of input contains $n$ digits $a_1, a_2, \ldots, a_n$ ($a_1 \neq 0$, $0 \leq a_i \leq 9$): digits of $x$.
-----Output-----
In the first line print one integer $m$: the number of digits in $y$.
In the next line print $m$ digits $b_1, b_2, \ldots, b_m$ ($b_1 \neq 0$, $0 \leq b_i \leq 9$): digits of $y$.
-----Examples-----
Input
3 2
353
Output
3
353
Input
4 2
1234
Output
4
1313
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:
* find(s, t): report the minimum element in as, as+1, . . . ,at.
* update(i, x): change ai to x.
Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1.
* If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n.
Input
n q
com0 x0 y0
com1 x1 y1
...
comq−1 xq−1 yq−1
In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi).
Output
For each find operation, print the minimum element.
Examples
Input
3 5
0 0 1
0 1 2
0 2 3
1 0 2
1 1 2
Output
1
2
Input
1 3
1 0 0
0 0 5
1 0 0
Output
2147483647
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.
The last stage of Football World Cup is played using the play-off system.
There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.
Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids a and b can meet.
-----Input-----
The only line contains three integers n, a and b (2 ≤ n ≤ 256, 1 ≤ a, b ≤ n) — the total number of teams, and the ids of the teams that Arkady is interested in.
It is guaranteed that n is such that in each round an even number of team advance, and that a and b are not equal.
-----Output-----
In the only line print "Final!" (without quotes), if teams a and b can meet in the Final.
Otherwise, print a single integer — the number of the round in which teams a and b can meet. The round are enumerated from 1.
-----Examples-----
Input
4 1 2
Output
1
Input
8 2 6
Output
Final!
Input
8 7 5
Output
2
-----Note-----
In the first example teams 1 and 2 meet in the first round.
In the second example teams 2 and 6 can only meet in the third round, which is the Final, if they win all their opponents in earlier rounds.
In the third example the teams with ids 7 and 5 can meet in the second round, if they win their opponents in the first round.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata.
Write your solution by modifying this code:
```python
def reverse_alternate(string):
```
Your solution should implemented in the function "reverse_alternate". 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.
Dr .: Peter, I've finally done it.
Peter: See you again? What kind of silly invention is this time?
Dr .: I finally came up with a revolutionary way to process mathematical formulas on a computer. Look at this table.
Ordinary notation | Dr.'s "breakthrough" notation
--- | ---
1 + 2 | 1 2 +
3 * 4 + 7 | 3 4 * 7 +
10 / (2 --12) | 10 2 12-/
(3-4) * (7 + 2 * 3) | 3 4 --7 2 3 * + *
Peter: Yeah.
Dr .: Fufufu. This alone won't tell you what it means to an inexperienced person. It's important from here.
Peter: I mean ...
Dr .: You know that computers have a data structure called a stack. Look, that's "first in, then out".
Peter: Yes. I know, that ...
Dr .: This groundbreaking notation uses that stack. For example, this 10 2 12-/, but process as follows.
Processing target | 10 | 2 | 12 |-| /
--- | --- | --- | --- | --- | ---
| ↓ | ↓ | ↓ | ↓ 2-12 | ↓ 10 / -10
Stack | |.
---
..
Ten
| ..
---
2
Ten
| 12
---
2
Ten
| ..
---
-Ten
Ten
| ..
---
..
-1
Dr .: How is it? You don't have to worry about parentheses or operator precedence, right? The word order is also "10 divided by 2 minus 12", which is somewhat similar to his Far Eastern island nation, Japanese. With this epoch-making invention, our laboratory is safe. Fafafa.
Peter: I mean, Doctor. I learned this in the basic course at the University of Aizu when I was in Japan. Everyone had a simple program called "Reverse Polish Notation".
Dr .: ...
So, instead of Peter, I decided to teach this program to the doctor. Create a program that inputs the formula written in "Reverse Polish Notation" and outputs the calculation result.
input
Given multiple datasets. For each dataset, a formula in Reverse Polish Notation (a string of up to 80 characters with integers and arithmetic symbols separated by one blank character (half-width)) is given on one line. No formula is given that divides a value by 0 or a value that is as close to 0 as possible.
The number of datasets does not exceed 50.
output
Output the calculation result (real number) on one line for each data set. The calculation result may include an error of 0.00001 or less.
Example
Input
10 2 12 - /
3 4 - 7 2 3 * + *
-1 -2 3 + +
Output
-1.000000
-13.000000
0.000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer.
Example: `countMe('1123')` (`count_me` in Ruby)
- Here 1 comes twice so `` will be `"21"`
- then 2 comes once so `` will be `"12"`
- then 3 comes once so `` will be `"13"`
hence output string will be `"211213"`.
Similarly `countMe('211213')` will return `'1221121113'`
(1 time 2, 2 times 1, 1 time 2, 1 time 1, 1 time 3)
Return `""` for empty, nil or non numeric strings
Write your solution by modifying this code:
```python
def count_me(data):
```
Your solution should implemented in the function "count_me". 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.
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
Input
There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.
Output
Write one line — the corresponding answer. Do not omit the leading 0s.
Examples
Input
1010100
0100101
Output
1110001
Input
000
111
Output
111
Input
1110
1010
Output
0100
Input
01110
01100
Output
00010
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
At the JOI pasta shop, the recommended pasta for lunch and the set menu of freshly squeezed juice are popular. When ordering this set menu, choose one from each of the three pasta and two juices of the day. The price is the total price of pasta and juice minus 50 yen.
Given the price of pasta and juice for a day, create a program to find the minimum price for the set menu for that day.
output
Output the minimum price of the set menu for the day in one line.
Example
Input
800
700
900
198
330
Output
848
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An array is called `centered-N` if some `consecutive sequence` of elements of the array sum to `N` and this sequence is preceded and followed by the same number of elements.
Example:
```
[3,2,10,4,1,6,9] is centered-15
because the sequence 10,4,1 sums to 15 and the sequence
is preceded by two elements [3,2] and followed by two elements [6,9]
```
Write a method called `isCenteredN` that returns :
- `true` if its array argument is `not empty` and `centered-N` or empty and centered-0
- otherwise returns `false`.
Write your solution by modifying this code:
```python
def is_centered(arr,n):
```
Your solution should implemented in the function "is_centered". 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.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a collection of lovely poems. Unfortuantely they aren't formatted very well. They're all on one line, like this:
```
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.
```
What you want is to present each sentence on a new line, so that it looks like this:
```
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
```
Write a function, `format_poem()` that takes a string like the one line example as an argument and returns a new string that is formatted across multiple lines with each new sentence starting on a new line when you print it out.
Try to solve this challenge with the [str.split()](https://docs.python.org/3/library/stdtypes.html#str.split) and the [str.join()](https://docs.python.org/3/library/stdtypes.html#str.join) string methods.
Every sentence will end with a period, and every new sentence will have one space before the previous period. Be careful about trailing whitespace in your solution.
Write your solution by modifying this code:
```python
def format_poem(poem):
```
Your solution should implemented in the function "format_poem". 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.
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a].
By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT.
The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon?
Input
The single line of the input contains two integers a, b (1 ≤ a, b ≤ 107).
Output
Print a single integer representing the answer modulo 1 000 000 007 (109 + 7).
Examples
Input
1 1
Output
0
Input
2 2
Output
8
Note
For the first sample, there are no nice integers because <image> is always zero.
For the second sample, the set of nice integers is {3, 5}.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Carol is currently curling.
She has n disks each with radius r on the 2D plane.
Initially she has all these disks above the line y = 10^100.
She then will slide the disks towards the line y = 0 one by one in order from 1 to n.
When she slides the i-th disk, she will place its center at the point (x_{i}, 10^100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk.
Compute the y-coordinates of centers of all the disks after all disks have been pushed.
-----Input-----
The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively.
The next line will contain n integers x_1, x_2, ..., x_{n} (1 ≤ x_{i} ≤ 1 000) — the x-coordinates of the disks.
-----Output-----
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10^{ - 6}.
Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$ for all coordinates.
-----Example-----
Input
6 2
5 5 6 8 3 12
Output
2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613
-----Note-----
The final positions of the disks will look as follows: [Image]
In particular, note the position of the last disk.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ninja Atsushi guards the town from the roof of the Ninja Building from early morning to late night every day. This Ninja Building is two adjacent buildings of the same floor, and Atsushi's daily routine is to jump between buildings and head to the rooftop for security.
Because these two buildings are cleaned frequently, there are ladders and slippery areas that can help you climb the building. Moreover, the position of ladders and slippery parts changes every day. Therefore, Atsushi has to think about how to get to the roof every day.
Atsushi jumps over the walls of two buildings of the same floor, aiming for the rooftop of the building. Jumps can be started on the first floor of either building. When jumping to the opposite building, you can jump to the same floor, one floor up, or two floors up.
There are three types of walls, and the movement after jumping to each wall is decided.
* 0. Ordinary wall: Do not move up and down. The next jump will be made from there.
* 1. Ladder: The ladder spans two or more floors and moves to the top of the current ladder. The next jump will be made from there.
* 2. Sliding wall: A normal wall or slides down to the top of the ladder. The next jump will be made from there.
Also, the walls run from the first floor to the top floor just below the roof, and the roof can only be reached from the top floor of the building. Also, the wall on the bottom floor of the building will not be a slippery wall.
Create a program that takes in the number of floors n of the two buildings and the type of wall of the two buildings, and outputs the minimum number of jumps to reach the top floor and reach the rooftop. You may reach the roof of either building. However, if Atsushi cannot reach the roof of either building, please output "NA".
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
a1 a2 ... an
b1 b2 ... bn
The first line gives the building floor n (3 ≤ n ≤ 100). The second line gives the wall information ai from the first floor to the nth floor of the first building, and the third line gives the wall information bi from the first floor to the nth floor of the second building. ai and bi represent the information of the wall on the i-th floor, 0 is the ordinary wall, 1 is the ladder (straddling the i-th floor and the i + 1-floor), and 2 is the sliding wall.
The number of datasets does not exceed 60.
Output
Outputs the number of jumps on one line for each input dataset.
Example
Input
8
0 0 0 2 2 2 0 0
1 1 1 1 0 0 0 0
4
1 1 2 2
0 0 2 2
0
Output
4
NA
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Twin adventurers Rin and Len are searching for treasure in the Mirror Cave. The cave has two pairs of rooms, the Hall of Mirrors, and an expensive treasure lies behind the door of the room.
For convenience, each of the two rooms is considered to have W × H cells arranged in a grid pattern. The outside of the room is surrounded by a wall. In addition, walls are installed in places inside the room, and it is not possible to enter the cells where the walls are located. To open the door to the treasure room, the two must move symmetrically to reach a particular cell at the same time. Moreover, if only one arrives first, the door will be locked and will not open.
Symmetrical movement means moving north and north, west and east, east and west, and south and south at the same time. However, it is recognized that the movement is symmetrical even in a situation where one has a wall at the end where it is trying to move and the other has no wall at the end. In this case, those with a wall will stay there, and those without a wall will move to the next cell.
As inputs, the initial position of the twins, the destination, and the placement of obstacles are given. Your job is to write a program to determine if the twins can open the door.
Input
The input consists of multiple datasets. Each dataset is given in the following format.
> W H
> RoomL1 RoomR1
> RoomL2 RoomR2
> ...
> RoomLH RoomRH
The first line gives two positive integers W, H (1 ≤ W, H ≤ 50) separated by a single space. After that, information on two rooms is given over H lines. RoomLi and RoomRi correspond to the i-th row of the left and right rooms, respectively. Both are strings of length W, with the jth character corresponding to the jth column of the room. Each character is one of the following:
* `.`: Freely moveable cell
* `#`: Cell with wall (cannot enter)
* `%`: Destination
* `R`: Initial position of Rin
* `L`: Initial position of Len
In each room, the first row corresponds to the north end of the room and the first row corresponds to the west end of the room. Also, each room always has exactly one destination, with exactly one initial position for Len in the left room and one for Rin in the right room.
The end of the input is indicated by a line containing two zeros separated by a blank.
Output
For each dataset, print Yes if the twins can open the door, and No if they can't.
Sample Input
5 5
% # ... ... #%
. #. #.. #. #.
. #. #.. #. #.
. #. #.. #. #.
... # L R # ...
3 2
.L. .R #
% .. .%.
4 1
L.%.% .. R
0 0
Output for the Sample Input
Yes
Yes
No
Example
Input
5 5
%#... ...#%
.#.#. .#.#.
.#.#. .#.#.
.#.#. .#.#.
...#L R#...
3 2
.L. .R#
%.. .%.
4 1
L.%. %..R
0 0
Output
Yes
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.
Homer has two friends Alice and Bob. Both of them are string fans.
One day, Alice and Bob decide to play a game on a string $s = s_1 s_2 \dots s_n$ of length $n$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.
In a move, a player must choose an index $i$ ($1 \leq i \leq n$) that has not been chosen before, and change $s_i$ to any other lowercase English letter $c$ that $c \neq s_i$.
When all indices have been chosen, the game ends.
The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.
A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:
$a$ is a prefix of $b$, but $a \ne b$;
in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
-----Input-----
Each test contains multiple test cases. The first line contains $t$ ($1 \le t \le 1000$) — the number of test cases. Description of the test cases follows.
The only line of each test case contains a single string $s$ ($1 \leq |s| \leq 50$) consisting of lowercase English letters.
-----Output-----
For each test case, print the final string in a single line.
-----Examples-----
Input
3
a
bbbb
az
Output
b
azaz
by
-----Note-----
In the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.
In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.
In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a name, turn that name into a perfect square matrix (nested array with the amount of arrays equivalent to the length of each array).
You will need to add periods (`.`) to the end of the name if necessary, to turn it into a matrix.
If the name has a length of 0, return `"name must be at least one letter"`
## Examples
"Bill" ==> [ ["B", "i"],
["l", "l"] ]
"Frank" ==> [ ["F", "r", "a"],
["n", "k", "."],
[".", ".", "."] ]
Write your solution by modifying this code:
```python
def matrixfy(st):
```
Your solution should implemented in the function "matrixfy". 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.
Your dad doesn't really *get* punctuation, and he's always putting extra commas in when he posts. You can tolerate the run-on sentences, as he does actually talk like that, but those extra commas have to go!
Write a function called ```dadFilter``` that takes a string as argument and returns a string with the extraneous commas removed. The returned string should not end with a comma or any trailing whitespace.
Write your solution by modifying this code:
```python
def dad_filter(string):
```
Your solution should implemented in the function "dad_filter". 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.
Vasya has got $n$ books, numbered from $1$ to $n$, arranged in a stack. The topmost book has number $a_1$, the next one — $a_2$, and so on. The book at the bottom of the stack has number $a_n$. All numbers are distinct.
Vasya wants to move all the books to his backpack in $n$ steps. During $i$-th step he wants to move the book number $b_i$ into his backpack. If the book with number $b_i$ is in the stack, he takes this book and all the books above the book $b_i$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $[1, 2, 3]$ (book $1$ is the topmost), and Vasya moves the books in the order $[2, 1, 3]$, then during the first step he will move two books ($1$ and $2$), during the second step he will do nothing (since book $1$ is already in the backpack), and during the third step — one book (the book number $3$). Note that $b_1, b_2, \dots, b_n$ are distinct.
Help Vasya! Tell him the number of books he will put into his backpack during each step.
-----Input-----
The first line contains one integer $n~(1 \le n \le 2 \cdot 10^5)$ — the number of books in the stack.
The second line contains $n$ integers $a_1, a_2, \dots, a_n~(1 \le a_i \le n)$ denoting the stack of books.
The third line contains $n$ integers $b_1, b_2, \dots, b_n~(1 \le b_i \le n)$ denoting the steps Vasya is going to perform.
All numbers $a_1 \dots a_n$ are distinct, the same goes for $b_1 \dots b_n$.
-----Output-----
Print $n$ integers. The $i$-th of them should be equal to the number of books Vasya moves to his backpack during the $i$-th step.
-----Examples-----
Input
3
1 2 3
2 1 3
Output
2 0 1
Input
5
3 1 4 2 5
4 5 1 3 2
Output
3 2 0 0 0
Input
6
6 5 4 3 2 1
6 5 3 4 2 1
Output
1 1 2 0 1 1
-----Note-----
The first example is described in the statement.
In the second example, during the first step Vasya will move the books $[3, 1, 4]$. After that only books $2$ and $5$ remain in the stack ($2$ is above $5$). During the second step Vasya will take the books $2$ and $5$. After that the stack becomes empty, so during next steps Vasya won't move any books.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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: The Diversity of Prime Factorization
Problem
Ebi-chan has the FACTORIZATION MACHINE, which can factorize natural numbers M (greater than 1) in O ($ \ log $ M) time! But unfortunately, the machine could display only digits and white spaces.
In general, we consider the factorization of M as p_1 ^ {e_1} \ times p_2 ^ {e_2} \ times ... \ times p_K ^ {e_K} where (1) i <j implies p_i <p_j and (2) p_i is prime. Now, she gives M to the machine, and the machine displays according to the following rules in ascending order with respect to i:
* If e_i = 1, then displays p_i,
* otherwise, displays p_i e_i.
For example, if she gives either `22` or` 2048`, then `2 11` is displayed. If either` 24` or `54`, then` 2 3 3`.
Okay, Ebi-chan has written down the output of the machine, but she notices that she has forgotten to write down the input! Now, your task is to count how many natural numbers result in a noted output. Note that Ebi-chan has mistaken writing and no input could result in the output.
The answer could be too large, so, you must output it modulo 10 ^ 9 + 7 (prime number).
Input
N
q_1 q_2 $ \ cdots $ q_N
In the first line, the number of the output of the machine is given. In the second line, the output of the machine is given.
Constraints
* 1 \ leq N \ leq 10 ^ 5
* 2 \ leq q_i \ leq 10 ^ 6 (1 \ leq i \ leq N)
Output
Print the number of the natural numbers that result in the given output of the machine.
Sample Input 1
3
2 3 3
Sample Output for Input 1
2
24 = 2 ^ 3 \ times 3 and 54 = 2 \ times 3 ^ 3 satisfy the condition.
Sample Input 2
3
2 3 4
Sample Output 2 for Input 2
1
Only 162 = 2 \ times 3 ^ 4 satisfies the condition. Note that 4 is not prime.
Sample Input 3
3
3 5 2
Sample Output for Input 3
1
Since 2 <3 <5, only 75 = 3 \ times 5 ^ 2 satisfies the condition.
Sample Input 4
1
Four
Sample Output for Input 4
0
Ebi-chan should have written down it more carefully.
Example
Input
3
2 3 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.
We start with a permutation $a_1, a_2, \ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times.
On the $i$-th iteration, we select an index $t_i$ ($1 \le t_i \le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are within the array bounds) to the right end of the array $b$. Then we move elements $a_{t_i+1}, \ldots, a_n$ to the left in order to fill in the empty space.
You are given the initial permutation $a_1, a_2, \ldots, a_n$ and the resulting array $b_1, b_2, \ldots, b_k$. All elements of an array $b$ are distinct. Calculate the number of possible sequences of indices $t_1, t_2, \ldots, t_k$ modulo $998\,244\,353$.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100\,000$), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains two integers $n, k$ ($1 \le k < n \le 200\,000$): sizes of arrays $a$ and $b$.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$): elements of $a$. All elements of $a$ are distinct.
The third line of each test case contains $k$ integers $b_1, b_2, \ldots, b_k$ ($1 \le b_i \le n$): elements of $b$. All elements of $b$ are distinct.
The sum of all $n$ among all test cases is guaranteed to not exceed $200\,000$.
-----Output-----
For each test case print one integer: the number of possible sequences modulo $998\,244\,353$.
-----Example-----
Input
3
5 3
1 2 3 4 5
3 2 5
4 3
4 3 2 1
4 3 1
7 4
1 4 7 3 6 2 5
3 2 4 5
Output
2
0
4
-----Note-----
$\require{cancel}$
Let's denote as $a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$ an operation over an element with index $i$: removal of element $a_i$ from array $a$ and appending element $a_{i+1}$ to array $b$.
In the first example test, the following two options can be used to produce the given array $b$: $1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2$; $(t_1, t_2, t_3) = (4, 3, 2)$; $1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5$; $(t_1, t_2, t_3) = (4, 1, 2)$.
In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to $4$, namely number $3$, which means that it couldn't be added to array $b$ on the second step.
In the third example test, there are four options to achieve the given array $b$: $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5$; $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$;
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti:
* If Petya has visited this room before, he writes down the minute he was in this room last time;
* Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.
Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — then number of notes in Petya's logbook.
The second line contains n non-negative integers t1, t2, ..., tn (0 ≤ ti < i) — notes in the logbook.
Output
In the only line print a single integer — the minimum possible number of rooms in Paris catacombs.
Examples
Input
2
0 0
Output
2
Input
5
0 1 0 1 3
Output
3
Note
In the first sample, sequence of rooms Petya visited could be, for example 1 → 1 → 2, 1 → 2 → 1 or 1 → 2 → 3. The minimum possible number of rooms is 2.
In the second sample, the sequence could be 1 → 2 → 3 → 1 → 2 → 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Number is a palindrome if it is equal to the number with digits in reversed order.
For example, 5, 44, 171, 4884 are palindromes and 43, 194, 4773 are not palindromes.
Write a method `palindrome_chain_length` which takes a positive number and returns the number of special steps needed to obtain a palindrome. The special step is: "reverse the digits, and add to the original number". If the resulting number is not a palindrome, repeat the procedure with the sum until the resulting number is a palindrome.
If the input number is already a palindrome, the number of steps is 0.
Input will always be a positive integer.
For example, start with 87:
87 + 78 = 165;
165 + 561 = 726;
726 + 627 = 1353;
1353 + 3531 = 4884
4884 is a palindrome and we needed 4 steps to obtain it, so `palindrome_chain_length(87) == 4`
Write your solution by modifying this code:
```python
def palindrome_chain_length(n):
```
Your solution should implemented in the function "palindrome_chain_length". 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 input string.
For each symbol in the string if it's the first character occurrence, replace it with a '1', else replace it with the amount of times you've already seen it...
But will your code be **performant enough**?
___
## Examples:
```
input = "Hello, World!"
result = "1112111121311"
input = "aaaaaaaaaaaa"
result = "123456789101112"
```
There might be some non-ascii characters in the string.
~~~if:java
Note: there will be no int domain overflow (character occurrences will be less than 2 billion).
~~~
~~~if:c
(this does not apply to the C language translation)
~~~
Write your solution by modifying this code:
```python
def numericals(s):
```
Your solution should implemented in the function "numericals". 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 are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking device allows one to be placed on an elevating pallet (a flat iron plate on which a car is placed) and parked in the upper tier, and the other to be parked in the lower tier.
In a parking lot that uses such a two-stage parking device, it is necessary to take out the car parked in the lower tier and dismiss it each time to put in and out the car in the upper tier, so be sure to manage it. Keeps the key to the parked car and puts it in and out as needed.
| <image>
--- | ---
Tsuruga Parking Lot is also one of the parking lots equipped with such a two-stage parking device, but due to lack of manpower, the person who cannot drive the car has become the manager. Therefore, once the car was parked, it could not be moved until the customer returned, and the car in the upper tier could not be put out until the owner of the car in the lower tier returned.
Create a program that meets the rules of the Tsuruga parking lot to help the caretaker who has to handle the cars that come to park one after another.
Tsuruga parking lot facilities
* There is one or more parking spaces, all equipped with a two-stage parking device.
* Each parking space is numbered starting from 1.
* Initially, it is assumed that no car is parked in the parking lot.
Tsuruga parking lot adopts the following rules.
When to stop the car
* The caretaker will be informed of the parking time of the car to be parked.
* We will park first in the parking space where no car is parked.
* If there is no parking space where no car is parked, park in an empty parking space. However, if there are multiple such parking spaces, follow the procedure below to park.
1. If the remaining parking time of a parked car is longer than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
2. If the remaining parking time of any parked car is less than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
* If the car is full (no parking space available), the car you are trying to park will wait in turn until the parking space is available. As soon as it becomes available, we will park in order from the first car we were waiting for.
* Under each condition, if there are multiple applicable parking spaces, the parking space number will be the smallest. In addition, if there are cars leaving at the same time, parking will start after all the cars leaving at the same time, and as long as there are cars waiting, the cars that can be parked will be parked at the same time.
When the car leaves
* Cars that have passed the parking time notified by the manager will be shipped.
* If there are cars in multiple parking spaces that have passed the parking time at the same time, the car with the smallest parking space number will be shipped first.
* If the parking time of the car parked in the upper row has expired, you will have to wait until the car in the lower row leaves the garage. The upper car will be delivered at the same time after the lower car is delivered.
The figure below shows an example of how to park at Tsuruga Parking Lot. In this example, the number of parking spaces is 3, and cars B to E are already parked. Consider that car A, which has a parking time of 70 minutes, arrives there. You cannot park because two cars are already parked in parking space 3, and you will have to park in either parking space 1 or parking space 2 that is still vacant. Car B parked in parking space 1 has 50 minutes remaining and car C parked in parking space 2 has 22 minutes remaining, both of which are less than car A's parking time, so car A's parking Park in parking space 1 where car B, which has a smaller time difference, is parked. As a result, car B, which was parked earlier, will be in the upper row.
<image>
Create a program that inputs the number of parking spaces m, the number of cars parked n, and the parking time t of each car, and outputs the car reference numbers in the order in which they come out of the parking lot. However, cars are assigned an integer reference number starting with 1 in the order of input, and cars will come to park one by one every 10 minutes in the order of the reference number.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
m n
t1
t2
::
tn
The first line gives the number of two-stage parking devices m (1 ≤ m ≤ 10) and the number of cars parked n (1 ≤ n ≤ 100). The next n lines are given the parking time ti (1 ≤ ti ≤ 120) for the i-th car.
The number of datasets does not exceed 20.
Output
The reference number of the car is output to one line in the order of coming out of the parking lot for each data set. Please output the reference numbers separated by blanks.
Example
Input
3 5
90
52
82
84
70
2 4
10
30
40
60
0 0
Output
2 5 1 4 3
1 2 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.
Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!
Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $0$. Also, let's say that the train will visit $n$ stations numbered from $1$ to $n$ along its way, and that Alexey destination is the station $n$.
Alexey learned from the train schedule $n$ integer pairs $(a_i, b_i)$ where $a_i$ is the expected time of train's arrival at the $i$-th station and $b_i$ is the expected time of departure.
Also, using all information he has, Alexey was able to calculate $n$ integers $tm_1, tm_2, \dots, tm_n$ where $tm_i$ is the extra time the train need to travel from the station $i - 1$ to the station $i$. Formally, the train needs exactly $a_i - b_{i-1} + tm_i$ time to travel from station $i - 1$ to station $i$ (if $i = 1$ then $b_0$ is the moment the train leave the terminal, and it's equal to $0$).
The train leaves the station $i$, if both conditions are met:
it's on the station for at least $\left\lceil \frac{b_i - a_i}{2} \right\rceil$ units of time (division with ceiling);
current time $\ge b_i$.
Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of arrival at the station $n$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.
The first line of each test case contains the single integer $n$ ($1 \le n \le 100$) — the number of stations.
Next $n$ lines contain two integers each: $a_i$ and $b_i$ ($1 \le a_i < b_i \le 10^6$). It's guaranteed that $b_i < a_{i+1}$.
Next line contains $n$ integers $tm_1, tm_2, \dots, tm_n$ ($0 \le tm_i \le 10^6$).
-----Output-----
For each test case, print one integer — the time of Alexey's arrival at the last station.
-----Examples-----
Input
2
2
2 4
10 12
0 2
5
1 4
7 8
9 10
13 15
19 20
1 2 3 4 5
Output
12
32
-----Note-----
In the first test case, Alexey arrives at station $1$ without any delay at the moment $a_1 = 2$ (since $tm_1 = 0$). After that, he departs at moment $b_1 = 4$. Finally, he arrives at station $2$ with $tm_2 = 2$ extra time, or at the moment $12$.
In the second test case, Alexey arrives at the first station with $tm_1 = 1$ extra time, or at moment $2$. The train, from one side, should stay at the station at least $\left\lceil \frac{b_1 - a_1}{2} \right\rceil = 2$ units of time and from the other side should depart not earlier than at moment $b_1 = 4$. As a result, the trains departs right at the moment $4$.
Using the same logic, we can figure out that the train arrives at the second station at the moment $9$ and departs at the moment $10$; at the third station: arrives at $14$ and departs at $15$; at the fourth: arrives at $22$ and departs at $23$. And, finally, arrives at the fifth station at $32$.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ ($n \geq 2$) positive integers and an integer $p$. Consider an undirected weighted graph of $n$ vertices numbered from $1$ to $n$ for which the edges between the vertices $i$ and $j$ ($i<j$) are added in the following manner:
If $gcd(a_i, a_{i+1}, a_{i+2}, \dots, a_{j}) = min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$, then there is an edge of weight $min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$ between $i$ and $j$.
If $i+1=j$, then there is an edge of weight $p$ between $i$ and $j$.
Here $gcd(x, y, \ldots)$ denotes the greatest common divisor (GCD) of integers $x$, $y$, ....
Note that there could be multiple edges between $i$ and $j$ if both of the above conditions are true, and if both the conditions fail for $i$ and $j$, then there is no edge between these vertices.
The goal is to find the weight of the minimum spanning tree of this graph.
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases.
The first line of each test case contains two integers $n$ ($2 \leq n \leq 2 \cdot 10^5$) and $p$ ($1 \leq p \leq 10^9$) — the number of nodes and the parameter $p$.
The second line contains $n$ integers $a_1, a_2, a_3, \dots, a_n$ ($1 \leq a_i \leq 10^9$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
Output $t$ lines. For each test case print the weight of the corresponding graph.
-----Examples-----
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
-----Note-----
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
For test case 2
For test case 3
For test case 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 goal of this exercise is to convert a string to a new string where each character in the new string is `"("` if that character appears only once in the original string, or `")"` if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
## Examples
```
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
```
**Notes**
Assertion messages may be unclear about what they display in some languages. If you read `"...It Should encode XXX"`, the `"XXX"` is the expected result, not the input!
Write your solution by modifying this code:
```python
def duplicate_encode(word):
```
Your solution should implemented in the function "duplicate_encode". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have to restore the wall. The wall consists of $N$ pillars of bricks, the height of the $i$-th pillar is initially equal to $h_{i}$, the height is measured in number of bricks. After the restoration all the $N$ pillars should have equal heights.
You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $A$; remove a brick from the top of one non-empty pillar, the cost of this operation is $R$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $M$.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $0$.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
-----Input-----
The first line of input contains four integers $N$, $A$, $R$, $M$ ($1 \le N \le 10^{5}$, $0 \le A, R, M \le 10^{4}$) — the number of pillars and the costs of operations.
The second line contains $N$ integers $h_{i}$ ($0 \le h_{i} \le 10^{9}$) — initial heights of pillars.
-----Output-----
Print one integer — the minimal cost of restoration.
-----Examples-----
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
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.
Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.
Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.
Now, the following Q operations will be performed:
- Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.
Find the value of the counter on each vertex after all operations.
-----Constraints-----
- 2 \leq N \leq 2 \times 10^5
- 1 \leq Q \leq 2 \times 10^5
- 1 \leq a_i < b_i \leq N
- 1 \leq p_j \leq N
- 1 \leq x_j \leq 10^4
- The given graph is a tree.
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q
-----Output-----
Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.
-----Sample Input-----
4 3
1 2
2 3
2 4
2 10
1 100
3 1
-----Sample Output-----
100 110 111 110
The tree in this input is as follows:
Each operation changes the values of the counters on the vertices as follows:
- Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.
- Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.
- Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
When naming identifiers (variables and functions) in programming, compound words that concatenate words are used. However, if you concatenate them as they are, you will not be able to understand the word breaks, so in general, select and apply the one that is unified from the following naming conventions:
* Set to Upper CamelCase
Connect words directly to form a compound word, and capitalize only the first letter of each word.
Example: GetUserName
* Set to Lower CamelCase
Connect words directly to form a compound word, and capitalize only the first letter of each word. However, the first letter of the compound word should be lowercase.
Example: getUserName
* Connect with underscore
Words are concatenated with underscores to form a compound word. Make all letters of the word lowercase.
Example: get_user_name
Create a program that outputs the given identifier by applying the specified naming convention. It is assumed that any of the above naming conventions has already been applied to the identifier given.
Input
Multiple datasets are given as input. Each dataset is given in the following format:
name type (identifier, naming convention: space-separated strings and characters)
type is a character indicating the naming convention and is as shown in the table below:
type | Naming convention
--- | ---
U | Upper CamelCase
L | Lower CamelCase
D | Connect with underscore
The number of characters in the given identifier is 1 or more and 100 or less.
End of input when type is'X'. Do not output to this input.
Output
For each dataset, print the identifier with the naming convention on one line.
Example
Input
get_user_name L
getUserName U
GetUserName D
EndOfInput X
Output
getUserName
GetUserName
get_user_name
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ integers, where $n$ is odd. You can make the following operation with it: Choose one of the elements of the array (for example $a_i$) and increase it by $1$ (that is, replace it with $a_i + 1$).
You want to make the median of the array the largest possible using at most $k$ operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $[1, 5, 2, 3, 5]$ is $3$.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $n$ is odd, $1 \le k \le 10^9$) — the number of elements in the array and the largest number of operations you can make.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$).
-----Output-----
Print a single integer — the maximum possible median after the operations.
-----Examples-----
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
-----Note-----
In the first example, you can increase the second element twice. Than array will be $[1, 5, 5]$ and it's median is $5$.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $3$.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $[5, 1, 2, 5, 3, 5, 5]$ and the median will be $5$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.
Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.
Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
-----Input-----
The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 10^5). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^3), where a_{i} is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task.
It is guaranteed that n is divisible by k.
-----Output-----
In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.
-----Examples-----
Input
6 2
3 2 1 6 5 4
Output
1
Input
10 5
1 3 5 7 9 9 4 1 8 5
Output
3
-----Note-----
Explanation of the first example.
If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12.
Explanation of the second example.
In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 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.
**Principal Diagonal** -- The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East.
**Secondary Diagonal** -- the secondary diagonal of a matrix identifies those elements of the matrix running from North-East to South-West.
For example:
```
matrix: [1, 2, 3]
[4, 5, 6]
[7, 8, 9]
principal diagonal: [1, 5, 9]
secondary diagonal: [3, 5, 7]
```
## Task
Your task is to find which diagonal is "larger": which diagonal has a bigger sum of their elements.
* If the principal diagonal is larger, return `"Principal Diagonal win!"`
* If the secondary diagonal is larger, return `"Secondary Diagonal win!"`
* If they are equal, return `"Draw!"`
**Note:** You will always receive matrices of the same dimension.
Write your solution by modifying this code:
```python
def diagonal(matrix):
```
Your solution should implemented in the function "diagonal". 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 Fair Nut lives in $n$ story house. $a_i$ people live on the $i$-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening.
It was decided that elevator, when it is not used, will stay on the $x$-th floor, but $x$ hasn't been chosen yet. When a person needs to get from floor $a$ to floor $b$, elevator follows the simple algorithm: Moves from the $x$-th floor (initially it stays on the $x$-th floor) to the $a$-th and takes the passenger. Moves from the $a$-th floor to the $b$-th floor and lets out the passenger (if $a$ equals $b$, elevator just opens and closes the doors, but still comes to the floor from the $x$-th floor). Moves from the $b$-th floor back to the $x$-th. The elevator never transposes more than one person and always goes back to the floor $x$ before transposing a next passenger. The elevator spends one unit of electricity to move between neighboring floors. So moving from the $a$-th floor to the $b$-th floor requires $|a - b|$ units of electricity.
Your task is to help Nut to find the minimum number of electricity units, that it would be enough for one day, by choosing an optimal the $x$-th floor. Don't forget than elevator initially stays on the $x$-th floor.
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 100$) — the number of floors.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 100$) — the number of people on each floor.
-----Output-----
In a single line, print the answer to the problem — the minimum number of electricity units.
-----Examples-----
Input
3
0 2 1
Output
16
Input
2
1 1
Output
4
-----Note-----
In the first example, the answer can be achieved by choosing the second floor as the $x$-th floor. Each person from the second floor (there are two of them) would spend $4$ units of electricity per day ($2$ to get down and $2$ to get up), and one person from the third would spend $8$ units of electricity per day ($4$ to get down and $4$ to get up). $4 \cdot 2 + 8 \cdot 1 = 16$.
In the second example, the answer can be achieved by choosing the first floor as the $x$-th floor.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.
Given are two integers A and B.
If Takahashi can calculate A \times B, print the result; if he cannot, print -1 instead.
-----Constraints-----
- 1 \leq A \leq 20
- 1 \leq B \leq 20
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
If Takahashi can calculate A \times B, print the result; if he cannot, print -1.
-----Sample Input-----
2 5
-----Sample Output-----
10
2 \times 5 = 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.
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
Task:
Write
```
smallest(n)
```
that will find the smallest positive number that is evenly divisible by all of the numbers from 1 to n (n <= 40).
E.g
```python
smallest(5) == 60 # 1 to 5 can all divide evenly into 60
smallest(10) == 2520
```
Write your solution by modifying this code:
```python
def smallest(n):
```
Your solution should implemented in the function "smallest". 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.
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $k$ such that Mr. Black can exit the house after opening the first $k$ doors.
We have to note that Mr. Black opened each door at most once, and in the end all doors became open.
-----Input-----
The first line contains integer $n$ ($2 \le n \le 200\,000$) — the number of doors.
The next line contains $n$ integers: the sequence in which Mr. Black opened the doors. The $i$-th of these integers is equal to $0$ in case the $i$-th opened door is located in the left exit, and it is equal to $1$ in case it is in the right exit.
It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.
-----Output-----
Print the smallest integer $k$ such that after Mr. Black opened the first $k$ doors, he was able to exit the house.
-----Examples-----
Input
5
0 0 1 0 0
Output
3
Input
4
1 0 0 1
Output
3
-----Note-----
In the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.
When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.
In the second example when the first two doors were opened, there was open closed door in each of the exit.
With three doors opened Mr. Black was able to use the left exit.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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: Prayer (Pray)
Some twins are famous for praying before the contest.
There are four integers $ H, W, X, Y $, and it seems unlucky if $ H \ times W $ and $ x + y $ are both odd numbers.
input
Four integers $ H, W, X, Y $ are given, separated by spaces.
output
Output "No" if you are unlucky, or "Yes" if not. But don't forget the last line break.
Constraint
* $ H, W, X, Y $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 $
Input example 1
3 5 1 4
Output example 1
No
$ 3 \ times 5 = 15 $, $ 1 + 4 = 5 $, both odd numbers, so it's unlucky.
Input example 2
3 5 2 4
Output example 2
Yes
$ 3 \ times 5 = 15 $ is odd, but $ 2 + 4 = 6 $ is even, so good luck isn't bad.
Example
Input
3 5 1 4
Output
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base b_{x} and a number Y represented in base b_{y}. Compare those two numbers.
-----Input-----
The first line of the input contains two space-separated integers n and b_{x} (1 ≤ n ≤ 10, 2 ≤ b_{x} ≤ 40), where n is the number of digits in the b_{x}-based representation of X.
The second line contains n space-separated integers x_1, x_2, ..., x_{n} (0 ≤ x_{i} < b_{x}) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and b_{y} (1 ≤ m ≤ 10, 2 ≤ b_{y} ≤ 40, b_{x} ≠ b_{y}), where m is the number of digits in the b_{y}-based representation of Y, and the fourth line contains m space-separated integers y_1, y_2, ..., y_{m} (0 ≤ y_{i} < b_{y}) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
-----Output-----
Output a single character (quotes for clarity): '<' if X < Y '>' if X > Y '=' if X = Y
-----Examples-----
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
-----Note-----
In the first sample, X = 101111_2 = 47_10 = Y.
In the second sample, X = 102_3 = 21_5 and Y = 24_5 = 112_3, thus X < Y.
In the third sample, $X = FF 4007 A_{16}$ and Y = 4803150_9. We may notice that X starts with much larger digits and b_{x} is much larger than b_{y}, so X is clearly larger than Y.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
X and A are integers between 0 and 9 (inclusive).
If X is less than A, print 0; if X is not less than A, print 10.
-----Constraints-----
- 0 \leq X, A \leq 9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
X A
-----Output-----
If X is less than A, print 0; if X is not less than A, print 10.
-----Sample Input-----
3 5
-----Sample Output-----
0
3 is less than 5, so we should print 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Task
Given a positive integer, `n`, return the number of possible ways such that `k` positive integers multiply to `n`. Order matters.
**Examples**
```
n = 24
k = 2
(1, 24), (2, 12), (3, 8), (4, 6), (6, 4), (8, 3), (12, 2), (24, 1) -> 8
n = 100
k = 1
100 -> 1
n = 20
k = 3
(1, 1, 20), (1, 2, 10), (1, 4, 5), (1, 5, 4), (1, 10, 2), (1, 20, 1),
(2, 1, 10), (2, 2, 5), (2, 5, 2), (2, 10, 1), (4, 1, 5), (4, 5, 1),
(5, 1, 4), (5, 2, 2), (5, 4, 1), (10, 1, 2), (10, 2, 1), (20, 1, 1) -> 18
```
**Constraints**
`1 <= n <= 500_000_000`
and `1 <= k <= 1000`
Write your solution by modifying this code:
```python
def multiply(n, k):
```
Your solution should implemented in the function "multiply". 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.
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
Input
The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
Output
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
Examples
Input
3 3
cba
Output
NO
Input
3 4
cba
Output
cbd
Input
4 4
abcd
Output
abda
Note
String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.
The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.
A palindrome is a string that reads the same forward or reversed.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Edo has got a collection of n refrigerator magnets!
He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers.
Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.
Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of the door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.
Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x1, y1) and the upper right corner (x2, y2), then its center is located at (<image>, <image>) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.
The sides of the refrigerator door must also be parallel to coordinate axes.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ min(10, n - 1)) — the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator.
Next n lines describe the initial plan of placing magnets. Each line contains four integers x1, y1, x2, y2 (1 ≤ x1 < x2 ≤ 109, 1 ≤ y1 < y2 ≤ 109) — the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide.
Output
Print a single integer — the minimum area of the door of refrigerator, which can be used to place at least n - k magnets, preserving the relative positions.
Examples
Input
3 1
1 1 2 2
2 2 3 3
3 3 4 4
Output
1
Input
4 1
1 1 2 2
1 9 2 10
9 9 10 10
9 1 10 2
Output
64
Input
3 0
1 1 2 2
1 1 1000000000 1000000000
1 3 8 12
Output
249999999000000001
Note
In the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly.
In the second test sample it doesn't matter which magnet to remove, the answer will not change — we need a fridge with door width 8 and door height 8.
In the third sample you cannot remove anything as k = 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.
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.
Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.
Find the inversion number of B, modulo 10^9 + 7.
Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.
Constraints
* All values in input are integers.
* 1 \leq N \leq 2000
* 1 \leq K \leq 10^9
* 1 \leq A_i \leq 2000
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 ... A_{N - 1}
Output
Print the inversion number of B, modulo 10^9 + 7.
Examples
Input
2 2
2 1
Output
3
Input
3 5
1 1 1
Output
0
Input
10 998244353
10 9 8 7 5 6 3 4 2 1
Output
185297239
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ela likes Chess a lot. During breaks, she usually challenges her co-worker in DTL to some chess games. She's not an expert at classic chess, but she's very interested in Chess variants, where she has to adapt to new rules and test her tactical mindset to win the game.
The problem, which involves a non-standard chess pieces type that is described below, reads: given $3$ white crickets on a $n \cdot n$ board, arranged in an "L" shape next to each other, there are no other pieces on the board. Ela wants to know with a finite number of moves, can she put any white cricket on the square on row $x$, column $y$?
An "L"-shape piece arrangement can only be one of the below:
For simplicity, we describe the rules for crickets on the board where only three white crickets are. It can move horizontally, vertically, or diagonally, but only to a square in some direction that is immediately after another cricket piece (so that it must jump over it). If the square immediately behind the piece is unoccupied, the cricket will occupy the square. Otherwise (when the square is occupied by another cricket, or does not exist), the cricket isn't allowed to make such a move.
See an example of valid crickets' moves on the pictures in the Note section.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.
The first line of each test case contains $n$ ($4 \le n \le 10^5$) — denotes the size of the chessboard.
The second line of each test case contains 6 numbers: $r_1$, $c_1$, $r_2$, $c_2$, $r_3$, $c_3$ ($1 \le r_1, c_1, r_2, c_2, r_3, c_3 \le n$) — coordinates of the crickets. The input ensures that the three crickets are arranged in an "L" shape that the legend stated.
The third line of each test case contains 2 numbers: $x$, $y$ ($1 \le x, y \le n$) — coordinates of the target square.
-----Output-----
For each test case, print "YES" or "NO" to denotes whether Ela can put a cricket on the target square.
-----Examples-----
Input
6
8
7 2 8 2 7 1
5 1
8
2 2 1 2 2 1
5 5
8
2 2 1 2 2 1
6 6
8
1 1 1 2 2 1
5 5
8
2 2 1 2 2 1
8 8
8
8 8 8 7 7 8
4 8
Output
YES
NO
YES
NO
YES
YES
-----Note-----
Here's the solution for the first test case. The red square denotes where the crickets need to reach. Note that in chess horizontals are counted from bottom to top, as well as on this picture.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.
Input
The single line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number.
Output
Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.
Examples
Input
11
Output
47
Input
10
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ water tanks in a row, $i$-th of them contains $a_i$ liters of water. The tanks are numbered from $1$ to $n$ from left to right.
You can perform the following operation: choose some subsegment $[l, r]$ ($1\le l \le r \le n$), and redistribute water in tanks $l, l+1, \dots, r$ evenly. In other words, replace each of $a_l, a_{l+1}, \dots, a_r$ by $\frac{a_l + a_{l+1} + \dots + a_r}{r-l+1}$. For example, if for volumes $[1, 3, 6, 7]$ you choose $l = 2, r = 3$, new volumes of water will be $[1, 4.5, 4.5, 7]$. You can perform this operation any number of times.
What is the lexicographically smallest sequence of volumes of water that you can achieve?
As a reminder:
A sequence $a$ is lexicographically smaller than a sequence $b$ of the same length if and only if the following holds: in the first (leftmost) position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^6$) — the number of water tanks.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — initial volumes of water in the water tanks, in liters.
Because of large input, reading input as doubles is not recommended.
-----Output-----
Print the lexicographically smallest sequence you can get. In the $i$-th line print the final volume of water in the $i$-th tank.
Your answer is considered correct if the absolute or relative error of each $a_i$ does not exceed $10^{-9}$.
Formally, let your answer be $a_1, a_2, \dots, a_n$, and the jury's answer be $b_1, b_2, \dots, b_n$. Your answer is accepted if and only if $\frac{|a_i - b_i|}{\max{(1, |b_i|)}} \le 10^{-9}$ for each $i$.
-----Examples-----
Input
4
7 5 5 7
Output
5.666666667
5.666666667
5.666666667
7.000000000
Input
5
7 8 8 10 12
Output
7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
Input
10
3 9 5 5 1 7 5 3 8 7
Output
3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
-----Note-----
In the first sample, you can get the sequence by applying the operation for subsegment $[1, 3]$.
In the second sample, you can't get any lexicographically smaller 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.
Petya recieved a gift of a string s with length up to 10^5 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves: Extract the first character of s and append t with this character. Extract the last character of t and append u with this character.
Petya wants to get strings s and t empty and string u lexicographically minimal.
You should write a program that will help Petya win the game.
-----Input-----
First line contains non-empty string s (1 ≤ |s| ≤ 10^5), consisting of lowercase English letters.
-----Output-----
Print resulting string u.
-----Examples-----
Input
cab
Output
abc
Input
acdb
Output
abdc
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Zane the wizard is going to perform a magic show shuffling the cups.
There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.
The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = u_{i} and x = v_{i}. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.
Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation. [Image]
Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.
-----Input-----
The first line contains three integers n, m, and k (2 ≤ n ≤ 10^6, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·10^5) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively.
The second line contains m distinct integers h_1, h_2, ..., h_{m} (1 ≤ h_{i} ≤ n) — the positions along the x-axis where there is a hole on the table.
Each of the next k lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — the positions of the cups to be swapped.
-----Output-----
Print one integer — the final position along the x-axis of the bone.
-----Examples-----
Input
7 3 4
3 4 6
1 2
2 5
5 7
7 1
Output
1
Input
5 1 2
2
1 2
2 4
Output
2
-----Note-----
In the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.
In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties: All the integers in the array were between $l$ and $r$ (inclusive). The sum of all the elements was divisible by $3$.
Unfortunately, Ayoub has lost his array, but he remembers the size of the array $n$ and the numbers $l$ and $r$, so he asked you to find the number of ways to restore the array.
Since the answer could be very large, print it modulo $10^9 + 7$ (i.e. the remainder when dividing by $10^9 + 7$). In case there are no satisfying arrays (Ayoub has a wrong memory), print $0$.
-----Input-----
The first and only line contains three integers $n$, $l$ and $r$ ($1 \le n \le 2 \cdot 10^5 , 1 \le l \le r \le 10^9$) — the size of the lost array and the range of numbers in the array.
-----Output-----
Print the remainder when dividing by $10^9 + 7$ the number of ways to restore the array.
-----Examples-----
Input
2 1 3
Output
3
Input
3 2 2
Output
1
Input
9 9 99
Output
711426616
-----Note-----
In the first example, the possible arrays are : $[1,2], [2,1], [3, 3]$.
In the second example, the only possible array is $[2, 2, 2]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Definition
**_Jumping number_** is the number that *All adjacent digits in it differ by 1*.
____
# Task
**_Given_** a number, **_Find if it is Jumping or not_** .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_** .
* **_Return_** *the result as* **_String_** .
* **_The difference between_** *‘9’ and ‘0’* is **_not considered as 1_** .
* **_All single digit numbers_** are considered as **_Jumping numbers_**.
___
# Input >> Output Examples
```
jumpingNumber(9) ==> return "Jumping!!"
```
## **_Explanation_**:
* It's **_single-digit number_**
___
```
jumpingNumber(79) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(23) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
```
jumpingNumber(556847) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(4343456) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
```
jumpingNumber(89098) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(32) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Write your solution by modifying this code:
```python
def jumping_number(number):
```
Your solution should implemented in the function "jumping_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.
Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
-----Input-----
The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 5\,000$; $1 \leq m \leq 20\,000$) — the number of stations and the number of candies, respectively.
The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively.
-----Output-----
In the first and only line, print $n$ space-separated integers, the $i$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $i$.
-----Examples-----
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
-----Note-----
Consider the second sample.
If the train started at station $1$, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the first candy. Proceed to station $1$. This step takes $1$ second. Load the second candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the second candy. Proceed to station $1$. This step takes $1$ second. Load the third candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the third candy.
Hence, the train needs $5$ seconds to complete the tasks.
If the train were to start at station $2$, however, it would need to move to station $1$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $5+1 = 6$ seconds.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Modify the `kebabize` function so that it converts a camel case string into a kebab case.
Notes:
- the returned string should only contain lowercase letters
Write your solution by modifying this code:
```python
def kebabize(string):
```
Your solution should implemented in the function "kebabize". 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.
"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.
Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.
Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.
Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.
Constraints
* 1 ≤ N ≤ 10^5
* 2 ≤ C ≤ 10^{14}
* 1 ≤ x_1 < x_2 < ... < x_N < C
* 1 ≤ v_i ≤ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N C
x_1 v_1
x_2 v_2
:
x_N v_N
Output
If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.
Examples
Input
3 20
2 80
9 120
16 1
Output
191
Input
3 20
2 80
9 1
16 120
Output
192
Input
1 100000000000000
50000000000000 1
Output
0
Input
15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000
Output
6500000000
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 `sumTimesTables` which sums the result of the sums of the elements specified in `tables` multiplied by all the numbers in between `min` and `max` including themselves.
For example, for `sumTimesTables([2,5],1,3)` the result should be the same as
```
2*1 + 2*2 + 2*3 +
5*1 + 5*2 + 5*3
```
i.e. the table of two from 1 to 3 plus the table of five from 1 to 3
All the numbers are integers but you must take in account:
* `tables` could be empty.
* `min` could be negative.
* `max` could be really big.
Write your solution by modifying this code:
```python
def sum_times_tables(table,a,b):
```
Your solution should implemented in the function "sum_times_tables". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array $a_1, a_2, \dots, a_n$, you need to handle a total of $q$ updates and queries of two types:
$1$ $l$ $r$ — for each index $i$ with $l \leq i \leq r$, update the value of $a_i$ to the sum of the digits of $a_i$.
$2$ $x$ — output $a_x$.
-----Input-----
The first line of the input contains an integer $t$ ($1 \leq t \leq 1000$) — the number of testcases.
The first line of each test case contains two integers $n$ and $q$ ($1 \le n, q \le 2 \cdot 10^5$) — the size of the array and the number of queries, respectively.
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 next $q$ lines of each test case are of two forms:
$1$ $l$ $r$ ($1 \leq l \leq r \leq n$) — it means, for each index $i$ with $l \leq i \leq r$, you should update the value of $a_i$ to the sum of its digits.
$2$ $x$ ($1 \leq x \leq n$) — it means you should output $a_x$.
There is at least one query of the second type.
The sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
The sum of $q$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output the answers of queries of the second type, in the order they are given.
-----Examples-----
Input
3
5 8
1 420 69 1434 2023
1 2 3
2 2
2 3
2 4
1 2 5
2 1
2 3
2 5
2 3
9999 1000
1 1 2
2 1
2 2
1 1
1
2 1
Output
6
15
1434
1
6
7
36
1
1
-----Note-----
In the first test case, the following process occurs:
Initially, $a = [1, 420, 69, 1434, 2023]$.
The operation is performed for $l=2$, $r=3$, yielding $[1, {6}, {15}, 1434, 2023]$.
We are queried for $x=2$, $x=3$, and $x=4$, and output $6$, $15$, and $1434$.
The operation is performed for $l=2$, $r=5$, yielding $[1, {6}, {6}, {12}, {7}]$.
We are queried for $x=1$, $x=3$, and $x=5$, and output $1$, $6$, and $7$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.
Help guys determine the winner photo by the records of likes.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1 000 000), where a_{i} is the identifier of the photo which got the i-th like.
-----Output-----
Print the identifier of the photo which won the elections.
-----Examples-----
Input
5
1 3 2 2 1
Output
2
Input
9
100 200 300 200 100 300 300 100 200
Output
300
-----Note-----
In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second).
Thus, the winner is the photo with identifier 2, as it got: more likes than the photo with id 3; as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!
Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.
Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.
According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.
-----Input-----
The only line contains three integers b, d and s (0 ≤ b, d, s ≤ 10^18, b + d + s ≥ 1) — the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium.
-----Output-----
Print single integer — the minimum possible number of meals which Vasiliy could have missed during his vacation.
-----Examples-----
Input
3 2 1
Output
1
Input
1 0 0
Output
0
Input
1 1 1
Output
0
Input
1000000000000000000 0 1000000000000000000
Output
999999999999999999
-----Note-----
In the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day.
In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal.
In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=«aba», then strings «baobab», «aabbaa», «helloabahello» make him very happy and strings «aab», «baaa» and «helloabhello» do not.
However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.
Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.
-----Input-----
The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters.
The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 10^6 letters.
-----Output-----
Print the sought number of ways to cut string t in two so that each part made s happy.
-----Examples-----
Input
aba
baobababbah
Output
2
Input
mars
sunvenusearthmarsjupitersaturnuranusneptune
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
[Image]
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes).
Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L.
Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today?
-----Input-----
The first line of the input contains three integers t, w and b (1 ≤ t, w, b ≤ 5·10^18) — the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively.
-----Output-----
Print the answer to the problem as an irreducible fraction [Image]. Follow the format of the samples output.
The fraction [Image] (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d.
-----Examples-----
Input
10 3 2
Output
3/10
Input
7 1 2
Output
3/7
-----Note-----
In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ piles of stones, where the $i$-th pile has $a_i$ stones. Two people play a game, where they take alternating turns removing stones.
In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.
-----Input-----
The first line contains a single integer $t$ ($1\le t\le 1000$) — the number of test cases. Next $2t$ lines contain descriptions of test cases.
The first line of each test case contains a single integer $n$ ($1\le n\le 10^5$) — the number of piles.
The second line of each test case contains $n$ integers $a_1,\ldots,a_n$ ($1\le a_i\le 10^9$) — $a_i$ is equal to the number of stones in the $i$-th pile.
It is guaranteed that the sum of $n$ for all test cases does not exceed $10^5$.
-----Output-----
For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".
-----Example-----
Input
7
3
2 5 4
8
1 1 1 1 1 1 1 1
6
1 2 3 4 5 6
6
1 1 2 1 2 2
1
1000000000
5
1 2 2 1 1
3
1 1 1
Output
First
Second
Second
First
First
Second
First
-----Note-----
In the first test case, the first player will win the game. His winning strategy is: The first player should take the stones from the first pile. He will take $1$ stone. The numbers of stones in piles will be $[1, 5, 4]$. The second player should take the stones from the first pile. He will take $1$ stone because he can't take any other number of stones. The numbers of stones in piles will be $[0, 5, 4]$. The first player should take the stones from the second pile because the first pile is empty. He will take $4$ stones. The numbers of stones in piles will be $[0, 1, 4]$. The second player should take the stones from the second pile because the first pile is empty. He will take $1$ stone because he can't take any other number of stones. The numbers of stones in piles will be $[0, 0, 4]$. The first player should take the stones from the third pile because the first and second piles are empty. He will take $4$ stones. The numbers of stones in piles will be $[0, 0, 0]$. The second player will lose the game because all piles will be empty.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.
Find the total number of biscuits produced within T + 0.5 seconds after activation.
-----Constraints-----
- All values in input are integers.
- 1 \leq A, B, T \leq 20
-----Input-----
Input is given from Standard Input in the following format:
A B T
-----Output-----
Print the total number of biscuits produced within T + 0.5 seconds after activation.
-----Sample Input-----
3 5 7
-----Sample Output-----
10
- Five biscuits will be produced three seconds after activation.
- Another five biscuits will be produced six seconds after activation.
- Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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. Your task is to divide it into several contiguous subarrays. Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order. At least how many subarrays do you need to divide A into?
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* Each A_i is an integer.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible number of subarrays after division of A.
Examples
Input
6
1 2 3 2 2 1
Output
2
Input
9
1 2 1 2 1 2 1 2 1
Output
5
Input
7
1 2 3 2 1 999999999 1000000000
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.
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.
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.
You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
Input
The first line contains one integer n (1 ≤ n ≤ 3000) — the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 3000) — indexes of these tests.
Output
Output the required default value for the next test index.
Examples
Input
3
1 7 2
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're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawns on you that you have been watching the musician for some 10 odd minutes. You ask, "How much do people normally tip for something like this?" The artist looks up. "Its always gonna be about tree fiddy."
It was then that you realize the musician was a 400 foot tall beast from the paleolithic era. The Loch Ness Monster almost tricked you!
There are only 2 guaranteed ways to tell if you are speaking to The Loch Ness Monster: A.) It is a 400 foot tall beast from the paleolithic era B.) It will ask you for tree fiddy
Since Nessie is a master of disguise, the only way accurately tell is to look for the phrase "tree fiddy". Since you are tired of being grifted by this monster, the time has come to code a solution for finding The Loch Ness Monster.
Note: It can also be written as 3.50 or three fifty.
Write your solution by modifying this code:
```python
def is_lock_ness_monster(string):
```
Your solution should implemented in the function "is_lock_ness_monster". 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 fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!
$m$
Initially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-th type, you decrease the number of Gorynich's heads by $min(d_i, curX)$, there $curX$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $h_i$ new heads. If $curX = 0$ then Gorynich is defeated.
You can deal each blow any number of times, in any order.
For example, if $curX = 10$, $d = 7$, $h = 10$ then the number of heads changes to $13$ (you cut $7$ heads off, but then Zmei grows $10$ new ones), but if $curX = 10$, $d = 11$, $h = 100$ then number of heads changes to $0$ and Zmei Gorynich is considered defeated.
Calculate the minimum number of blows to defeat Zmei Gorynich!
You have to answer $t$ independent queries.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) – the number of queries.
The first line of each query contains two integers $n$ and $x$ ($1 \le n \le 100$, $1 \le x \le 10^9$) — the number of possible types of blows and the number of heads Zmei initially has, respectively.
The following $n$ lines of each query contain the descriptions of types of blows you can deal. The $i$-th line contains two integers $d_i$ and $h_i$ ($1 \le d_i, h_i \le 10^9$) — the description of the $i$-th blow.
-----Output-----
For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.
If Zmei Gorynuch cannot be defeated print $-1$.
-----Example-----
Input
3
3 10
6 3
8 2
1 4
4 10
4 1
3 2
2 6
1 100
2 15
10 11
14 100
Output
2
3
-1
-----Note-----
In the first query you can deal the first blow (after that the number of heads changes to $10 - 6 + 3 = 7$), and then deal the second blow.
In the second query you just deal the first blow three times, and Zmei is defeated.
In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 board of size $n \times n$, where $n$ is odd (not divisible by $2$). Initially, each cell of the board contains one figure.
In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $(i, j)$ you can move the figure to cells: $(i - 1, j - 1)$; $(i - 1, j)$; $(i - 1, j + 1)$; $(i, j - 1)$; $(i, j + 1)$; $(i + 1, j - 1)$; $(i + 1, j)$; $(i + 1, j + 1)$;
Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.
Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $n^2-1$ cells should contain $0$ figures and one cell should contain $n^2$ figures).
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 200$) — the number of test cases. Then $t$ test cases follow.
The only line of the test case contains one integer $n$ ($1 \le n < 5 \cdot 10^5$) — the size of the board. It is guaranteed that $n$ is odd (not divisible by $2$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $5 \cdot 10^5$ ($\sum n \le 5 \cdot 10^5$).
-----Output-----
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
-----Example-----
Input
3
1
5
499993
Output
0
40
41664916690999888
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a set of points $x_1$, $x_2$, ..., $x_n$ on the number line.
Two points $i$ and $j$ can be matched with each other if the following conditions hold: neither $i$ nor $j$ is matched with any other point; $|x_i - x_j| \ge z$.
What is the maximum number of pairs of points you can match with each other?
-----Input-----
The first line contains two integers $n$ and $z$ ($2 \le n \le 2 \cdot 10^5$, $1 \le z \le 10^9$) — the number of points and the constraint on the distance between matched points, respectively.
The second line contains $n$ integers $x_1$, $x_2$, ..., $x_n$ ($1 \le x_i \le 10^9$).
-----Output-----
Print one integer — the maximum number of pairs of points you can match with each other.
-----Examples-----
Input
4 2
1 3 3 7
Output
2
Input
5 5
10 9 5 8 7
Output
1
-----Note-----
In the first example, you may match point $1$ with point $2$ ($|3 - 1| \ge 2$), and point $3$ with point $4$ ($|7 - 3| \ge 2$).
In the second example, you may match point $1$ with point $3$ ($|5 - 10| \ge 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.
# Description
Write a function that checks whether a credit card number is correct or not, using the Luhn algorithm.
The algorithm is as follows:
* From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or alternatively subtract 9 from the product (e.g., 16: 16 - 9 = 7, 18: 18 - 9 = 9).
* Take the sum of all the digits.
* If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
The input is a string with the full credit card number, in groups of 4 digits separated by spaces, i.e. "1234 5678 9012 3456"
Don´t worry about wrong inputs, they will always be a string with 4 groups of 4 digits each separated by space.
# Examples
`valid_card?("5457 6238 9823 4311") # True`
`valid_card?("5457 6238 9323 4311") # False`
for reference check: https://en.wikipedia.org/wiki/Luhn_algorithm
Write your solution by modifying this code:
```python
def valid_card(card):
```
Your solution should implemented in the function "valid_card". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array a_1, a_2, ..., a_{n} of n integers, find the largest number in the array that is not a perfect square.
A number x is said to be a perfect square if there exists an integer y such that x = y^2.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array.
The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^6 ≤ a_{i} ≤ 10^6) — the elements of the array.
It is guaranteed that at least one element of the array is not a perfect square.
-----Output-----
Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.
-----Examples-----
Input
2
4 2
Output
2
Input
8
1 2 4 8 16 32 64 576
Output
32
-----Note-----
In the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 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.
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.
You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type).
If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of friends.
Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0 ≤ si ≤ 100) — the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as "XX-XX-XX", where X is arbitrary digits from 0 to 9.
Output
In the first line print the phrase "If you want to call a taxi, you should call: ". Then print names of all friends whose phone books contain maximal number of taxi phone numbers.
In the second line print the phrase "If you want to order a pizza, you should call: ". Then print names of all friends who have maximal number of pizza phone numbers.
In the third line print the phrase "If you want to go to a cafe with a wonderful girl, you should call: ". Then print names of all friends who have maximal number of girls' phone numbers.
Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.
Examples
Input
4
2 Fedorov
22-22-22
98-76-54
3 Melnikov
75-19-09
23-45-67
99-99-98
7 Rogulenko
22-22-22
11-11-11
33-33-33
44-44-44
55-55-55
66-66-66
95-43-21
3 Kaluzhin
11-11-11
99-99-99
98-65-32
Output
If you want to call a taxi, you should call: Rogulenko.
If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.
If you want to go to a cafe with a wonderful girl, you should call: Melnikov.
Input
3
5 Gleb
66-66-66
55-55-55
01-01-01
65-43-21
12-34-56
3 Serega
55-55-55
87-65-43
65-55-21
5 Melnik
12-42-12
87-73-01
36-04-12
88-12-22
82-11-43
Output
If you want to call a taxi, you should call: Gleb.
If you want to order a pizza, you should call: Gleb, Serega.
If you want to go to a cafe with a wonderful girl, you should call: Melnik.
Input
3
3 Kulczynski
22-22-22
65-43-21
98-12-00
4 Pachocki
11-11-11
11-11-11
11-11-11
98-76-54
0 Smietanka
Output
If you want to call a taxi, you should call: Pachocki.
If you want to order a pizza, you should call: Kulczynski, Pachocki.
If you want to go to a cafe with a wonderful girl, you should call: Kulczynski.
Note
In the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.
Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Round the given number `n` to the nearest multiple of `m`.
If `n` is exactly in the middle of 2 multiples of m, return `n` instead.
# Example
For `n = 20, m = 3`, the output should be `21`.
For `n = 19, m = 3`, the output should be `18`.
For `n = 50, m = 100`, the output should be `50`.
# Input/Output
- `[input]` integer `n`
`1 ≤ n < 10^9.`
- `[input]` integer `m`
`3 ≤ m < 109`.
- `[output]` an integer
Write your solution by modifying this code:
```python
def rounding(n, m):
```
Your solution should implemented in the function "rounding". 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.
# Definition
**_Extra perfect number_** *is the number that* **_first_** and **_last_** *bits* are **_set bits_**.
____
# Task
**_Given_** *a positive integer* `N` , **_Return_** the **_extra perfect numbers_** *in range from* `1` to `N` .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_** .
* **_Returned array/list_** should *contain the extra perfect numbers in ascending order* **from lowest to highest**
___
# Input >> Output Examples
```
extraPerfect(3) ==> return {1,3}
```
## **_Explanation_**:
# (1)10 =(1)2
**First** and **last** bits as **_set bits_**.
# (3)10 = (11)2
**First** and **last** bits as **_set bits_**.
___
```
extraPerfect(7) ==> return {1,3,5,7}
```
## **_Explanation_**:
# (5)10 = (101)2
**First** and **last** bits as **_set bits_**.
# (7)10 = (111)2
**First** and **last** bits as **_set bits_**.
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Write your solution by modifying this code:
```python
def extra_perfect(n):
```
Your solution should implemented in the function "extra_perfect". 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.
Write a function that solves an algebraic expression given as a string.
* The expression can include only sums and products.
* The numbers in the expression are in standard notation (NOT scientific).
* In contrast, the function should return a string with the calculated value given in scientific notation with 5 decimal digits.
# Example:
```python
strexpression = "5 * 4 + 6"
sum_prod(strexpression) = "2.60000e+01"
```
Write your solution by modifying this code:
```python
def sum_prod(strexpression):
```
Your solution should implemented in the function "sum_prod". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two integers $A$ and $B$, calculate the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true; $conc(a, b)$ is the concatenation of $a$ and $b$ (for example, $conc(12, 23) = 1223$, $conc(100, 11) = 10011$). $a$ and $b$ should not contain leading zeroes.
-----Input-----
The first line contains $t$ ($1 \le t \le 100$) — the number of test cases.
Each test case contains two integers $A$ and $B$ $(1 \le A, B \le 10^9)$.
-----Output-----
Print one integer — the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true.
-----Example-----
Input
3
1 11
4 2
191 31415926
Output
1
0
1337
-----Note-----
There is only one suitable pair in the first test case: $a = 1$, $b = 9$ ($1 + 9 + 1 \cdot 9 = 19$).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \\{a,b,c,b,d,a,b\\}$ and $Y = \\{b,d,c,a,b,a\\}$, the sequence $\\{b,c,a\\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\\{b,c,a\\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\\{b,c,b,a\\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\\{b,c,b,a\\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.
Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.
Constraints
* $1 \leq q \leq 150$
* $1 \leq$ length of $X$ and $Y$ $\leq 1,000$
* $q \leq 20$ if the dataset includes a sequence whose length is more than 100
Input
The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.
Output
For each dataset, print the length of LCS of $X$ and $Y$ in a line.
Example
Input
3
abcbdab
bdcaba
abc
abc
abc
bc
Output
4
3
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `φ(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k ≤ n` for which `gcd(n, k) = 1`.
The totient function is important in number theory, mainly because it gives the order of the multiplicative group of integers modulo `n`. The totient function also plays a key role in the definition of the RSA encryption system.
For example `let n = 9`.
Then `gcd(9, 3) = gcd(9, 6) = 3` and `gcd(9, 9) = 9`.
The other six numbers in the range `1 ≤ k ≤ 9` i.e. `1, 2, 4, 5, 7, 8` are relatively prime to `9`.
Therefore, `φ(9) = 6`.
As another example, `φ(1) = 1` since `gcd(1, 1) = 1`.
There are generally two approaches to this function:
* Iteratively counting the numbers `k ≤ n` such that `gcd(n,k) = 1`.
* Using the Euler product formula.
This is an explicit formula for calculating `φ(n)` depending on the prime divisor of `n`:
`φ(n) = n * Product (1 - 1/p)` where the product is taken over the primes `p ≤ n` that divide `n`.
For example: `φ(36) = 36 * (1 - 1/2) * (1 - 1/3) = 36 * 1/2 * 2/3 = 12`.
This second method seems more complex and not likely to be faster, but in practice we will often look for `φ(n)` with `n` prime. It correctly gives `φ(n) = n - 1` if `n` is prime.
You have to code the Euler totient function, that takes an integer `1 ≤ n` as input and returns `φ(n)`.
```if:javascript
You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`.
```
```if:python
You do have to check if `n` is a number, is an integer and that `1 ≤ n`; if that is not the case, the function should return `0`.
```
```if:racket
`n` is always a positive integer.
```
Input range: `1 ≤ n ≤ 1e10`
Write your solution by modifying this code:
```python
def totient(n):
```
Your solution should implemented in the function "totient". 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.
Suppose I have two vectors: `(a1, a2, a3, ..., aN)` and `(b1, b2, b3, ..., bN)`. The dot product between these two vectors is defined as:
```
a1*b1 + a2*b2 + a3*b3 + ... + aN*bN
```
The vectors are classified as orthogonal if the dot product equals zero.
Complete the function that accepts two sequences as inputs and returns `true` if the vectors are orthogonal, and `false` if they are not. The sequences will always be correctly formatted and of the same length, so there is no need to check them first.
## Examples
```
[1, 1, 1], [2, 5, 7] --> false
[1, 0, 0, 1], [0, 1, 1, 0] --> true
```
Write your solution by modifying this code:
```python
def is_orthogonal(u, v):
```
Your solution should implemented in the function "is_orthogonal". 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.
Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.
Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.
In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal — compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if x_{i} < y_{i}, where i is the first index in which the permutations x and y differ.
Determine the array Ivan will obtain after performing all the changes.
-----Input-----
The first line contains an single integer n (2 ≤ n ≤ 200 000) — the number of elements in Ivan's array.
The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — the description of Ivan's array.
-----Output-----
In the first line print q — the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.
-----Examples-----
Input
4
3 2 2 3
Output
2
1 2 4 3
Input
6
4 5 6 3 2 1
Output
0
4 5 6 3 2 1
Input
10
6 8 4 6 7 1 6 3 4 5
Output
3
2 8 4 6 7 1 9 3 10 5
-----Note-----
In the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers — this permutation is lexicographically minimal among all suitable.
In the second example Ivan does not need to change anything because his array already is a permutation.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a given array $a$ consisting of $n$ integers and a given integer $m$ find if it is possible to reorder elements of the array $a$ in such a way that $\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$ equals $m$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $\frac{5}{2}=2.5$.
-----Input-----
The first line contains a single integer $t$ — the number of test cases ($1 \le t \le 100$). The test cases follow, each in two lines.
The first line of a test case contains two integers $n$ and $m$ ($1 \le n \le 100$, $0 \le m \le 10^6$). The second line contains integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^6$) — the elements of the array.
-----Output-----
For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.
-----Example-----
Input
2
3 8
2 5 1
4 4
0 1 2 3
Output
YES
NO
-----Note-----
In the first test case one of the reorders could be $[1, 2, 5]$. The sum is equal to $(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$. The brackets denote the inner sum $\sum_{j=i}^{n}{\frac{a_j}{j}}$, while the summation of brackets corresponds to the sum over $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.
Villages were scattered in the Wakamatsu Plain of Aizu. Several settlements are connected by straight roads that allow them to travel to and from each other, and any settlement in the plain can be traced back and forth. Each road has a lengthy maintenance fee, but all the settlements funded the road to maintain it.
At one point, it was decided that all the settlements would be united in one village, and the boundaries surrounding the villages would be drawn. According to national rules, no straight line connecting any of the two settlements that make up a village should pass outside the village (it is permissible to pass on the border). In addition, in Aizu, there must be a road on the border that surrounds the village. Where there is no road on the border, the country will create a new one.
However, the village pays for the maintenance of the road, so the villagers want to keep the boundaries as short as possible. In addition, the villagers decided to minimize the total length of the roads by eliminating roads that were not on the border, while maintaining the ability to travel between all settlements.
Information on the location of the village and the original road is given. Create a program that calculates the minimum total length of the roads when the roads are on the border and all settlements are allowed to come and go. However, the village shall be a point with no size, and the road shall be a line segment with no width.
Input
The input is given in the following format.
VR
x1 y1
x2 y2
::
xV yV
s1 t1
s2 t2
::
sR tR
The number of settlements V (3 ≤ V ≤ 100) and the number of roads R (2 ≤ R ≤ 1000) are given in the first line.
The following V line gives information on the points that represent the settlement. The two integers xi, yi (-1000 ≤ xi, yi ≤ 1000) given in each row represent the x-coordinate and y-coordinate of the i-th settlement, respectively.
The following R line is given information on the original road. The two integers si, ti (1 ≤ si <ti ≤ V) given in each row indicate that the i-th road connects the si-th and ti-th settlements.
The input satisfies the following conditions.
* If i ≠ j, the coordinates of the i-th and j-th settlements are different.
* In each of the two settlements, there is at most one way to connect them directly.
* Two different roads do not share any points other than the endpoints.
* Three or more settlements are never lined up on the same straight line.
Output
The minimum value of the total length of roads that satisfy the conditions is output as a real number on one line. However, the error must not exceed plus or minus 0.001. If this condition is satisfied, any number of digits after the decimal point may be displayed.
Examples
Input
5 5
0 0
1 1
3 0
3 2
0 2
1 2
2 3
2 4
3 4
1 5
Output
11.4142
Input
7 6
0 2
3 0
2 2
1 0
4 1
2 3
3 5
1 3
2 4
2 3
3 5
3 7
6 7
Output
18.2521
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Write a function named `sumEvenNumbers`, taking a sequence of numbers as single parameter. Your function must return the sum of **the even values** of this sequence.
Only numbers without decimals like `4` or `4.0` can be even.
## Input
* sequence of numbers: those numbers could be integers and/or floats.
For example, considering this input value : `[4,3,1,2,5,10,6,7,9,8]`, then your function should return `30` (because `4 + 2 + 10 + 6 + 8 = 30`).
Write your solution by modifying this code:
```python
def sum_even_numbers(seq):
```
Your solution should implemented in the function "sum_even_numbers". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
-----Input-----
The first line contains integer number n (1 ≤ n ≤ 10^9) — current year in Berland.
-----Output-----
Output amount of years from the current year to the next lucky one.
-----Examples-----
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
-----Note-----
In the first example next lucky year is 5. In the second one — 300. In the third — 5000.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 king's birthday dinner was attended by $k$ guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from $1$ to $100$. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife.
After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.
-----Input-----
The first line contains two integer numbers $n$ and $k$ ($1 \le n \le 100, 1 \le k \le 100$) — the number of kitchen utensils remaining after the dinner and the number of guests correspondingly.
The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$) — the types of the utensils remaining. Equal values stand for identical utensils while different values stand for different utensils.
-----Output-----
Output a single value — the minimum number of utensils that could be stolen by the guests.
-----Examples-----
Input
5 2
1 2 2 1 3
Output
1
Input
10 3
1 3 3 1 3 5 5 5 5 100
Output
14
-----Note-----
In the first example it is clear that at least one utensil of type $3$ has been stolen, since there are two guests and only one such utensil. But it is also possible that every person received only one dish and there were only six utensils in total, when every person got a set $(1, 2, 3)$ of utensils. Therefore, the answer is $1$.
One can show that in the second example at least $2$ dishes should have been served for every guest, so the number of utensils should be at least $24$: every set contains $4$ utensils and every one of the $3$ guests gets two such sets. Therefore, at least $14$ objects have been stolen. Please note that utensils of some types (for example, of types $2$ and $4$ in this example) may be not present in the set served for dishes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Taro is a member of a programming contest circle. In this circle, the members manage their schedules in the system called Great Web Calender.
Taro has just added some of his friends to his calendar so that he can browse their schedule on his calendar. Then he noticed that the system currently displays all the schedules in only one color, mixing the schedules for all his friends. This is difficult to manage because it's hard to tell whose schedule each entry is.
But actually this calender system has the feature to change the color of schedule entries, based on the person who has the entries. So Taro wants to use that feature to distinguish their plans by color.
Given the colors Taro can use and the number of members, your task is to calculate the subset of colors to color all schedule entries. The colors are given by "Lab color space".
In Lab color space, the distance between two colors is defined by the square sum of the difference of each element. Taro has to pick up the subset of colors that maximizes the sum of distances of all color pairs in the set.
Input
The input is like the following style.
N M
L_{0} a_{0} b_{0}
L_{1} a_{1} b_{1}
...
L_{N-1} a_{N-1} b_{N-1}
The first line contains two integers N and M (0 \leq M \leq N \leq 20), where N is the number of colors in the input, and M is the number of friends Taro wants to select the colors for. Each of the following N lines contains three decimal integers L(0.0 \leq L \leq 100.0), a(-134.0 \leq a \leq 220.0) and b(-140.0 \leq b \leq 122.0) which represents a single color in Lab color space.
Output
Output the maximal of the total distance. The output should not contain an error greater than 10^{-5}.
Examples
Input
3 2
0 0 0
10 10 10
100 100 100
Output
30000.00000000000000000000
Input
5 3
12.0 15.0 9.0
10.0 -3.0 2.2
3.5 6.8 9.0
2.1 4.4 5.9
1.2 4.0 -5.4
Output
1003.44000000000005456968
Input
2 1
1.0 1.0 1.0
0.0 0.0 0.0
Output
0.00000000000000000000
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 21XX, an annual programming contest, Japan Algorithmist GrandPrix (JAG) has become one of the most popular mind sports events.
JAG is conducted as a knockout tournament. This year, $N$ contestants will compete in JAG. A tournament chart is represented as a string. '[[a-b]-[c-d]]' is an easy example. In this case, there are 4 contestants named a, b, c, and d, and all matches are described as follows:
* Match 1 is the match between a and b.
* Match 2 is the match between c and d.
* Match 3 is the match between [the winner of match 1] and [the winner of match 2].
More precisely, the tournament chart satisfies the following BNF:
* <winner> ::= <person> | "[" <winner> "-" <winner> "]"
* <person> ::= "a" | "b" | "c" | ... | "z"
You, the chairperson of JAG, are planning to announce the results of this year's JAG competition. However, you made a mistake and lost the results of all the matches. Fortunately, you found the tournament chart that was printed before all of the matches of the tournament. Of course, it does not contains results at all. Therefore, you asked every contestant for the number of wins in the tournament, and got $N$ pieces of information in the form of "The contestant $a_i$ won $v_i$ times".
Now, your job is to determine whether all of these replies can be true.
Input
The input consists of a single test case in the format below.
$S$
$a_1$ $v_1$
:
$a_N$ $v_N$
$S$ represents the tournament chart. $S$ satisfies the above BNF. The following $N$ lines represent the information of the number of wins. The ($i+1$)-th line consists of a lowercase letter $a_i$ and a non-negative integer $v_i$ ($v_i \leq 26$) separated by a space, and this means that the contestant $a_i$ won $v_i$ times. Note that $N$ ($2 \leq N \leq 26$) means that the number of contestants and it can be identified by string $S$. You can assume that each letter $a_i$ is distinct. It is guaranteed that $S$ contains each $a_i$ exactly once and doesn't contain any other lowercase letters.
Output
Print 'Yes' in one line if replies are all valid for the tournament chart. Otherwise, print 'No' in one line.
Examples
Input
[[m-y]-[a-o]]
o 0
a 1
y 2
m 0
Output
Yes
Input
[[r-i]-[m-e]]
e 0
r 1
i 1
m 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.
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5) — the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 — the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.
-----Output-----
Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".
-----Examples-----
Input
4
25 25 50 50
Output
YES
Input
2
25 100
Output
NO
Input
4
50 50 25 25
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.
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.
The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.
One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move.
Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.
Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
-----Input-----
The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall.
The second line contains n integers a_1, a_2, ..., a_{n} ( - 10 000 ≤ a_{i} ≤ 10 000) — the numbers on stickers in order from left to right.
-----Output-----
Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.
-----Examples-----
Input
3
2 4 8
Output
14
Input
4
1 -7 -2 3
Output
-3
-----Note-----
In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.
In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 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.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for $n$ days. On the $i$-th day: If Du can speak, he'll make fun of Boboniu with fun factor $a_i$. But after that, he may be muzzled depending on Boboniu's mood. Otherwise, Du won't do anything.
Boboniu's mood is a constant $m$. On the $i$-th day: If Du can speak and $a_i>m$, then Boboniu will be angry and muzzle him for $d$ days, which means that Du won't be able to speak on the $i+1, i+2, \cdots, \min(i+d,n)$-th days. Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of $a$.
-----Input-----
The first line contains three integers $n$, $d$ and $m$ ($1\le d\le n\le 10^5,0\le m\le 10^9$).
The next line contains $n$ integers $a_1, a_2, \ldots,a_n$ ($0\le a_i\le 10^9$).
-----Output-----
Print one integer: the maximum total fun factor among all permutations of $a$.
-----Examples-----
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
-----Note-----
In the first example, you can set $a'=[15, 5, 8, 10, 23]$. Then Du's chatting record will be: Make fun of Boboniu with fun factor $15$. Be muzzled. Be muzzled. Make fun of Boboniu with fun factor $10$. Make fun of Boboniu with fun factor $23$.
Thus the total fun factor is $48$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.
Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.
The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):
* a mug (costs a points),
* a towel (costs b points),
* a bag (costs c points),
* a bicycle (costs d points),
* a car (costs e points).
Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.
Output
Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed.
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
3
3 10 4
2 4 10 15 20
Output
1 1 1 0 0
1
Input
4
10 4 39 2
3 5 10 11 12
Output
3 0 1 0 3
0
Note
In the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way. [Image]
An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.
A dungeon consists of n segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.
One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number i_1, he can make a sequence of jumps through the platforms i_1 < i_2 < ... < i_{k}, if i_2 - i_1 = i_3 - i_2 = ... = i_{k} - i_{k} - 1. Of course, all segments i_1, i_2, ... i_{k} should be exactly the platforms, not pits.
Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence i_1, i_2, ..., i_5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of segments on the level.
Next line contains the scheme of the level represented as a string of n characters '*' and '.'.
-----Output-----
If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes).
-----Examples-----
Input
16
.**.*..*.***.**.
Output
yes
Input
11
.*.*...*.*.
Output
no
-----Note-----
In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14.
Read the inputs from 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.