question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Alice and Bob are playing One Card Poker.
One Card Poker is a two-player game using playing cards.
Each card in this game shows an integer between 1 and 13, inclusive.
The strength of a card is determined by the number written on it, as follows:
Weak 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < 11 < 12 < 13 < 1 Strong
One Card Poker is played as follows:
- Each player picks one card from the deck. The chosen card becomes the player's hand.
- The players reveal their hands to each other. The player with the stronger card wins the game.
If their cards are equally strong, the game is drawn.
You are watching Alice and Bob playing the game, and can see their hands.
The number written on Alice's card is A, and the number written on Bob's card is B.
Write a program to determine the outcome of the game.
-----Constraints-----
- 1≦A≦13
- 1≦B≦13
- A and B are integers.
-----Input-----
The input is given from Standard Input in the following format:
A B
-----Output-----
Print Alice if Alice will win. Print Bob if Bob will win. Print Draw if the game will be drawn.
-----Sample Input-----
8 6
-----Sample Output-----
Alice
8 is written on Alice's card, and 6 is written on Bob's card.
Alice has the stronger card, and thus the output should be Alice.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
During a break in the buffet of the scientific lyceum of the Kingdom of Kremland, there was formed a queue of $n$ high school students numbered from $1$ to $n$. Initially, each student $i$ is on position $i$. Each student $i$ is characterized by two numbers — $a_i$ and $b_i$. Dissatisfaction of the person $i$ equals the product of $a_i$ by the number of people standing to the left of his position, add the product $b_i$ by the number of people standing to the right of his position. Formally, the dissatisfaction of the student $i$, which is on the position $j$, equals $a_i \cdot (j-1) + b_i \cdot (n-j)$.
The director entrusted Stas with the task: rearrange the people in the queue so that minimize the total dissatisfaction.
Although Stas is able to solve such problems, this was not given to him. He turned for help to you.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of people in the queue.
Each of the following $n$ lines contains two integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq 10^8$) — the characteristic of the student $i$, initially on the position $i$.
-----Output-----
Output one integer — minimum total dissatisfaction which can be achieved by rearranging people in the queue.
-----Examples-----
Input
3
4 2
2 3
6 1
Output
12
Input
4
2 4
3 3
7 1
2 3
Output
25
Input
10
5 10
12 4
31 45
20 55
30 17
29 30
41 32
7 1
5 5
3 15
Output
1423
-----Note-----
In the first example it is optimal to put people in this order: ($3, 1, 2$). The first person is in the position of $2$, then his dissatisfaction will be equal to $4 \cdot 1+2 \cdot 1=6$. The second person is in the position of $3$, his dissatisfaction will be equal to $2 \cdot 2+3 \cdot 0=4$. The third person is in the position of $1$, his dissatisfaction will be equal to $6 \cdot 0+1 \cdot 2=2$. The total dissatisfaction will be $12$.
In the second example, you need to put people in this order: ($3, 2, 4, 1$). The total dissatisfaction will be $25$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function that returns a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return "invalid string".
For example:
`````
"abcdefghijklm" --> ["b", "d", "f", "h", "j", "l"]
"a" --> "invalid string"
`````
Write your solution by modifying this code:
```python
def even_chars(st):
```
Your solution should implemented in the function "even_chars". 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.
B: Parentheses Number
problem
Define the correct parenthesis string as follows:
* The empty string is the correct parenthesis string
* For the correct parenthesis string S, `(` S `)` is the correct parenthesis string
* For correct parentheses S, T ST is the correct parentheses
Here, the permutations are associated with the correct parentheses according to the following rules.
* When the i-th closing brace corresponds to the j-th opening brace, the i-th value in the sequence is j.
Given a permutation of length n, P = (p_1, p_2, $ \ ldots $, p_n), restore the corresponding parenthesis string.
However, if the parenthesis string corresponding to the permutation does not exist, output `: (`.
Input format
n
p_1 p_2 $ \ ldots $ p_n
The number of permutations n is given in the first row.
Permutations p_1, p_2, $ \ ldots $, p_i, $ \ ldots $, p_n are given in the second row, separated by blanks.
Constraint
* 1 \ leq n \ leq 10 ^ 5
* 1 \ leq p_i \ leq n
* All inputs are integers.
* P = (p_1, p_2, $ \ ldots $, p_n) is a permutation.
Output format
Output the parenthesized string corresponding to the permutation.
Print `: (` if such a parenthesis string does not exist.
Input example 1
2
twenty one
Output example 1
(())
Input example 2
Ten
1 2 3 4 5 6 7 8 9 10
Output example 2
() () () () () () () () () ()
Input example 3
3
3 1 2
Output example 3
:(
Example
Input
2
2 1
Output
(())
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a_1, a_2, \dots, a_n$ of integer numbers.
Your task is to divide the array into the maximum number of segments in such a way that:
each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to $0$.
Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the array.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$).
-----Output-----
Print the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists.
-----Examples-----
Input
4
5 5 7 2
Output
2
Input
3
1 2 3
Output
-1
Input
3
3 1 10
Output
3
-----Note-----
In the first example $2$ is the maximum number. If you divide the array into $\{[5], [5, 7, 2]\}$, the XOR value of the subset of only the second segment is $5 \oplus 7 \oplus 2 = 0$. $\{[5, 5], [7, 2]\}$ has the value of the subset of only the first segment being $5 \oplus 5 = 0$. However, $\{[5, 5, 7], [2]\}$ will lead to subsets $\{[5, 5, 7]\}$ of XOR $7$, $\{[2]\}$ of XOR $2$ and $\{[5, 5, 7], [2]\}$ of XOR $5 \oplus 5 \oplus 7 \oplus 2 = 5$.
Let's take a look at some division on $3$ segments — $\{[5], [5, 7], [2]\}$. It will produce subsets:
$\{[5]\}$, XOR $5$; $\{[5, 7]\}$, XOR $2$; $\{[5], [5, 7]\}$, XOR $7$; $\{[2]\}$, XOR $2$; $\{[5], [2]\}$, XOR $7$; $\{[5, 7], [2]\}$, XOR $0$; $\{[5], [5, 7], [2]\}$, XOR $5$;
As you can see, subset $\{[5, 7], [2]\}$ has its XOR equal to $0$, which is unacceptable. You can check that for other divisions of size $3$ or $4$, non-empty subset with $0$ XOR always exists.
The second example has no suitable divisions.
The third example array can be divided into $\{[3], [1], [10]\}$. No subset of these segments has its XOR equal to $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.
Snuke and Ciel went to a strange stationery store. Each of them got a transparent graph paper with H rows and W columns.
Snuke painted some of the cells red in his paper. Here, the cells painted red were 4-connected, that is, it was possible to traverse from any red cell to any other red cell, by moving to vertically or horizontally adjacent red cells only.
Ciel painted some of the cells blue in her paper. Here, the cells painted blue were 4-connected.
Afterwards, they precisely overlaid the two sheets in the same direction. Then, the intersection of the red cells and the blue cells appeared purple.
You are given a matrix of letters a_{ij} (1≤i≤H, 1≤j≤W) that describes the positions of the purple cells. If the cell at the i-th row and j-th column is purple, then a_{ij} is `#`, otherwise a_{ij} is `.`. Here, it is guaranteed that no outermost cell is purple. That is, if i=1, H or j = 1, W, then a_{ij} is `.`.
Find a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation described. It can be shown that a solution always exists.
Constraints
* 3≤H,W≤500
* a_{ij} is `#` or `.`.
* If i=1,H or j=1,W, then a_{ij} is `.`.
* At least one of a_{ij} is `#`.
Input
The input is given from Standard Input in the following format:
H W
a_{11}...a_{1W}
:
a_{H1}...a_{HW}
Output
Print a pair of the set of the positions of the red cells and the blue cells that is consistent with the situation, as follows:
* The first H lines should describe the positions of the red cells.
* The following 1 line should be empty.
* The following H lines should describe the positions of the blue cells.
The description of the positions of the red or blue cells should follow the format of the description of the positions of the purple cells.
Examples
Input
5 5
.....
.#.#.
.....
.#.#.
.....
Output
.....
#####
#....
#####
.....
.###.
.#.#.
.#.#.
.#.#.
.....
Input
7 13
.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#.###.###.
.............
Output
.............
.###########.
.###.###.###.
.###.###.###.
.###.###.###.
.###.###.###.
.............
.............
.###.###.###.
.#.#.#...#...
.###.#...#...
.#.#.#.#.#...
.#.#########.
.............
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an integer $n$, find the maximum value of integer $k$ such that the following condition holds:
$n$ & ($n-1$) & ($n-2$) & ($n-3$) & ... ($k$) = $0$
where & denotes the bitwise AND operation.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 3 \cdot 10^4$). Then $t$ test cases follow.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^9$).
-----Output-----
For each test case, output a single integer — the required integer $k$.
-----Examples-----
Input
3
2
5
17
Output
1
3
15
-----Note-----
In the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.
In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0.
$5 \, \& \, 4 \neq 0$,
$5 \, \& \, 4 \, \& \, 3 = 0$.
Hence, 3 is the answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice got an array of length $n$ as a birthday present once again! This is the third year in a row!
And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.
Bob has chosen $m$ changes of the following form. For some integer numbers $x$ and $d$, he chooses an arbitrary position $i$ ($1 \le i \le n$) and for every $j \in [1, n]$ adds $x + d \cdot dist(i, j)$ to the value of the $j$-th cell. $dist(i, j)$ is the distance between positions $i$ and $j$ (i.e. $dist(i, j) = |i - j|$, where $|x|$ is an absolute value of $x$).
For example, if Alice currently has an array $[2, 1, 2, 2]$ and Bob chooses position $3$ for $x = -1$ and $d = 2$ then the array will become $[2 - 1 + 2 \cdot 2,~1 - 1 + 2 \cdot 1,~2 - 1 + 2 \cdot 0,~2 - 1 + 2 \cdot 1]$ = $[5, 2, 1, 3]$. Note that Bob can't choose position $i$ outside of the array (that is, smaller than $1$ or greater than $n$).
Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.
What is the maximum arithmetic mean value Bob can achieve?
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 10^5$) — the number of elements of the array and the number of changes.
Each of the next $m$ lines contains two integers $x_i$ and $d_i$ ($-10^3 \le x_i, d_i \le 10^3$) — the parameters for the $i$-th change.
-----Output-----
Print the maximal average arithmetic mean of the elements Bob can achieve.
Your answer is considered correct if its absolute or relative error doesn't exceed $10^{-6}$.
-----Examples-----
Input
2 3
-1 3
0 0
-1 -4
Output
-2.500000000000000
Input
3 2
0 2
5 0
Output
7.000000000000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Imagine that you are given two sticks. You want to end up with three sticks of equal length. You are allowed to cut either or both of the sticks to accomplish this, and can throw away leftover pieces.
Write a function, maxlen, that takes the lengths of the two sticks (L1 and L2, both positive values), that will return the maximum length you can make the three sticks.
Write your solution by modifying this code:
```python
def maxlen(l1, l2):
```
Your solution should implemented in the function "maxlen". 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 containing only zeros and ones, find the index of the zero that, if converted to one, will make the longest sequence of ones.
For instance, given the array:
```
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1]
```
replacing the zero at index 10 (counting from 0) forms a sequence of 9 ones:
```
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1]
'------------^------------'
```
Your task is to complete the function that determines where to replace a zero with a one to make the maximum length subsequence.
**Notes:**
- If there are multiple results, return the last one:
`[1, 1, 0, 1, 1, 0, 1, 1] ==> 5`
- The array will always contain only zeros and ones.
Can you do this in one pass?
Write your solution by modifying this code:
```python
def replace_zero(arr):
```
Your solution should implemented in the function "replace_zero". 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.
Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.
At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat. To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column). While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.
Compute the number of pairs of viewers (x, y) such that y will hate x forever.
Constraints
* 2 \le N \le 500
* The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \\{1, 2, \dots, N^2\\}.
Input
The input is given from Standard Input in the format
N
P_1 P_2 \cdots P_{N^2}
Output
If ans is the number of pairs of viewers described in the statement, you should print on Standard Output
ans
Output
If ans is the number of pairs of viewers described in the statement, you should print on Standard Output
ans
Examples
Input
3
1 3 7 9 5 4 8 6 2
Output
1
Input
4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8
Output
3
Input
6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30
Output
11
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.
Ivar has $n$ warriors, he places them on a straight line in front of the main gate, in a way that the $i$-th warrior stands right after $(i-1)$-th warrior. The first warrior leads the attack.
Each attacker can take up to $a_i$ arrows before he falls to the ground, where $a_i$ is the $i$-th warrior's strength.
Lagertha orders her warriors to shoot $k_i$ arrows during the $i$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $t$, they will all be standing to fight at the end of minute $t$.
The battle will last for $q$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.
-----Input-----
The first line contains two integers $n$ and $q$ ($1 \le n, q \leq 200\,000$) — the number of warriors and the number of minutes in the battle.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) that represent the warriors' strengths.
The third line contains $q$ integers $k_1, k_2, \ldots, k_q$ ($1 \leq k_i \leq 10^{14}$), the $i$-th of them represents Lagertha's order at the $i$-th minute: $k_i$ arrows will attack the warriors.
-----Output-----
Output $q$ lines, the $i$-th of them is the number of standing warriors after the $i$-th minute.
-----Examples-----
Input
5 5
1 2 1 2 1
3 10 1 1 1
Output
3
5
4
4
3
Input
4 4
1 2 3 4
9 1 10 6
Output
1
4
4
1
-----Note-----
In the first example: after the 1-st minute, the 1-st and 2-nd warriors die. after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive. after the 3-rd minute, the 1-st warrior dies. after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1. after the 5-th minute, the 2-nd warrior dies.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2 × 2 which are the Cheaterius' magic amulets!
<image> That's what one of Cheaterius's amulets looks like
After a hard night Cheaterius made n amulets. Everyone of them represents a square 2 × 2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.
Write a program that by the given amulets will find the number of piles on Cheaterius' desk.
Input
The first line contains an integer n (1 ≤ n ≤ 1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located.
Output
Print the required number of piles.
Examples
Input
4
31
23
**
31
23
**
13
32
**
32
13
Output
1
Input
4
51
26
**
54
35
**
25
61
**
45
53
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.
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
-----Input-----
The single line contains integer y (1000 ≤ y ≤ 9000) — the year number.
-----Output-----
Print a single integer — the minimum year number that is strictly larger than y and all it's digits are distinct. It is guaranteed that the answer exists.
-----Examples-----
Input
1987
Output
2013
Input
2013
Output
2014
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Deadpool wants to decorate his girlfriend’s house with a series of bulbs. The number of bulbs is M. Initially, all the bulbs are switched off. Deadpool finds that there are K numbers of buttons, each of them is connected to a set of bulbs. Deadpool can press any of these buttons because he is DEADPOOL. When the button is pressed, it turns on all the bulbs it’s connected to. Can Deadpool accomplish his task to switch on all the bulbs?
If Deadpool presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
Help him in his task to impress his valentine.
Here bulbs are numbered from 1 to M.
INPUT:::
The First line of Input contains integers K and M- the numbers of buttons and bulbs respectively.Each of the next K lines contains Xi - the number of bulbs that are turned on by the i-th button, and then Xi numbers Yij — the numbers of these bulbs.
OUTPUT:::
If it's possible to turn on all m bulbs print "YES", otherwise print "NO" (quotes for clarity).
CONSTRAINTS:::
1 ≤ M,K ≤ 100,
0 ≤ Xi ≤ M,
1 ≤ Yij ≤ M.
SAMPLE INPUT
3 4
2 1 4
3 1 3 1
1 2
SAMPLE OUTPUT
YES
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have an analog clock whose three hands (the second hand, the minute hand and the hour hand) rotate quite smoothly. You can measure two angles between the second hand and two other hands.
Write a program to find the time at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on or after a given time.
<image>
Figure D.1. Angles between the second hand and two other hands
Clocks are not limited to 12-hour clocks. The hour hand of an H-hour clock goes around once in H hours. The minute hand still goes around once every hour, and the second hand goes around once every minute. At 0:0:0 (midnight), all the hands are at the upright position.
Input
The input consists of multiple datasets. Each of the dataset has four integers H, h, m and s in one line, separated by a space. H means that the clock is an H-hour clock. h, m and s mean hour, minute and second of the specified time, respectively.
You may assume 2 ≤ H ≤ 100, 0 ≤ h < H, 0 ≤ m < 60, and 0 ≤ s < 60.
The end of the input is indicated by a line containing four zeros.
<image>
Figure D.2. Examples of H-hour clock (6-hour clock and 15-hour clock)
Output
Output the time T at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on and after the specified time.
For T being ho:mo:so (so seconds past mo minutes past ho o'clock), output four non-negative integers ho, mo, n, and d in one line, separated by a space, where n/d is the irreducible fraction representing so. For integer so including 0, let d be 1.
The time should be expressed in the remainder of H hours. In other words, one second after (H − 1):59:59 is 0:0:0, not H:0:0.
Example
Input
12 0 0 0
12 11 59 59
12 1 56 0
12 1 56 3
12 1 56 34
12 3 9 43
12 3 10 14
12 7 17 58
12 7 18 28
12 7 23 0
12 7 23 31
2 0 38 29
2 0 39 0
2 0 39 30
2 1 6 20
2 1 20 1
2 1 20 31
3 2 15 0
3 2 59 30
4 0 28 48
5 1 5 40
5 1 6 10
5 1 7 41
11 0 55 0
0 0 0 0
Output
0 0 43200 1427
0 0 43200 1427
1 56 4080 1427
1 56 47280 1427
1 57 4860 1427
3 10 18600 1427
3 10 61800 1427
7 18 39240 1427
7 18 82440 1427
7 23 43140 1427
7 24 720 1427
0 38 4680 79
0 39 2340 79
0 40 0 1
1 6 3960 79
1 20 2400 79
1 21 60 79
2 15 0 1
0 0 2700 89
0 28 48 1
1 6 320 33
1 6 40 1
1 8 120 11
0 55 0 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.
Recently you've discovered a new shooter. They say it has realistic game mechanics.
Your character has a gun with magazine size equal to $k$ and should exterminate $n$ waves of monsters. The $i$-th wave consists of $a_i$ monsters and happens from the $l_i$-th moment of time up to the $r_i$-th moments of time. All $a_i$ monsters spawn at moment $l_i$ and you have to exterminate all of them before the moment $r_i$ ends (you can kill monsters right at moment $r_i$). For every two consecutive waves, the second wave starts not earlier than the first wave ends (though the second wave can start at the same moment when the first wave ends) — formally, the condition $r_i \le l_{i + 1}$ holds. Take a look at the notes for the examples to understand the process better.
You are confident in yours and your character's skills so you can assume that aiming and shooting are instant and you need exactly one bullet to kill one monster. But reloading takes exactly $1$ unit of time.
One of the realistic mechanics is a mechanic of reloading: when you reload you throw away the old magazine with all remaining bullets in it. That's why constant reloads may cost you excessive amounts of spent bullets.
You've taken a liking to this mechanic so now you are wondering: what is the minimum possible number of bullets you need to spend (both used and thrown) to exterminate all waves.
Note that you don't throw the remaining bullets away after eradicating all monsters, and you start with a full magazine.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 2000$; $1 \le k \le 10^9$) — the number of waves and magazine size.
The next $n$ lines contain descriptions of waves. The $i$-th line contains three integers $l_i$, $r_i$ and $a_i$ ($1 \le l_i \le r_i \le 10^9$; $1 \le a_i \le 10^9$) — the period of time when the $i$-th wave happens and the number of monsters in it.
It's guaranteed that waves don't overlap (but may touch) and are given in the order they occur, i. e. $r_i \le l_{i + 1}$.
-----Output-----
If there is no way to clear all waves, print $-1$. Otherwise, print the minimum possible number of bullets you need to spend (both used and thrown) to clear all waves.
-----Examples-----
Input
2 3
2 3 6
3 4 3
Output
9
Input
2 5
3 7 11
10 12 15
Output
30
Input
5 42
42 42 42
42 43 42
43 44 42
44 45 42
45 45 1
Output
-1
Input
1 10
100 111 1
Output
1
-----Note-----
In the first example: At the moment $2$, the first wave occurs and $6$ monsters spawn. You kill $3$ monsters and start reloading. At the moment $3$, the second wave occurs and $3$ more monsters spawn. You kill remaining $3$ monsters from the first wave and start reloading. At the moment $4$, you kill remaining $3$ monsters from the second wave. In total, you'll spend $9$ bullets.
In the second example: At moment $3$, the first wave occurs and $11$ monsters spawn. You kill $5$ monsters and start reloading. At moment $4$, you kill $5$ more monsters and start reloading. At moment $5$, you kill the last monster and start reloading throwing away old magazine with $4$ bullets. At moment $10$, the second wave occurs and $15$ monsters spawn. You kill $5$ monsters and start reloading. At moment $11$, you kill $5$ more monsters and start reloading. At moment $12$, you kill last $5$ monsters. In total, you'll spend $30$ bullets.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
B: 階層的計算機 (Hierarchical Calculator)
Problem
Ebi-chan has N formulae: y = a_i x for i =1, ..., N (inclusive). Now she considers a subsequence of indices with length k: s_1, s_2, ..., s_k. At first, let x_0 be 1 and evaluate s_1-th formulae with x = x_0. Next, let x_1 be the output of s_1 and evaluate s_2-th formulae with x = x_1, and so on.
She wants to maximize the final output of the procedure, x_{s_k}. If there are many candidates, she wants the """shortest one""". If there are still many candidates, she wants the """lexicographically smallest one""".
Sequence s is lexicographically smaller than sequence t, if and only if either of the following conditions hold:
* there exists m < |s| such that s_i = t_i for i in 1 to m (inclusive) and s_{m+1} < t_{m+1}, or
* s_i = t_i for i in 1 to |s| (inclusive) and |s| < |t|,
where |s| is the length of the s.
Input
N
a_1 a_2 $\cdots$ a_N
Constraints
* 1 \leq N \leq 60
* -2 \leq a_i \leq 2 for i=1, ...,N (inclusive)
* Every input is given as the integer.
Output
Output k+1 lines. First line, the length of the sequence, k. Following k lines, the index of the i-th element of the subsequence, s_i (one element per line).
Sample Input 1
4
2 0 -2 1
Sample Output for Input 1
1
1
She evaluates the first one and gets the maximum value 2.
Sample Input 2
3
2 -2 -2
Sample Output for Input 2
3
1
2
3
She evaluates all of them and gets the maximum value 8.
Sample Input 3
2
-1 0
Sample Output for Input 3
0
She evaluates none of them and gets the maximum value 0. Empty sequence is the shorter and lexicographically smaller than any other sequences.
Sample Input 4
5
-1 2 1 -2 -1
Sample Output for Input 4
3
1
2
4
She evaluates $\langle$ 1, 2, 4 $\rangle$ ones and gets the maximum value 4. Note that $\langle$ 2, 4, 5 $\rangle$ is not lexicographically smallest one.
Example
Input
4
2 0 -2 1
Output
1
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
If there is an integer not less than 0 satisfying the following conditions, print the smallest such integer; otherwise, print -1.
- The integer has exactly N digits in base ten. (We assume 0 to be a 1-digit integer. For other integers, leading zeros are not allowed.)
- The s_i-th digit from the left is c_i. \left(i = 1, 2, \cdots, M\right)
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 3
- 0 \leq M \leq 5
- 1 \leq s_i \leq N
- 0 \leq c_i \leq 9
-----Input-----
Input is given from Standard Input in the following format:
N M
s_1 c_1
\vdots
s_M c_M
-----Output-----
Print the answer.
-----Sample Input-----
3 3
1 7
3 2
1 7
-----Sample Output-----
702
702 satisfies the conditions - its 1-st and 3-rd digits are 7 and 2, respectively - while no non-negative integer less than 702 satisfies them.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is t_{i} and its pages' width is equal to w_{i}. The thickness of each book is either 1 or 2. All books have the same page heights. $1$
Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. [Image]
Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
-----Input-----
The first line of the input contains an integer n, (1 ≤ n ≤ 100). Each of the next n lines contains two integers t_{i} and w_{i} denoting the thickness and width of the i-th book correspondingly, (1 ≤ t_{i} ≤ 2, 1 ≤ w_{i} ≤ 100).
-----Output-----
On the only line of the output print the minimum total thickness of the vertical books that we can achieve.
-----Examples-----
Input
5
1 12
1 3
2 15
2 5
2 1
Output
5
Input
3
1 10
2 1
2 4
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.
Anadi has a set of dominoes. Every domino has two parts, and each part contains some dots. For every a and b such that 1 ≤ a ≤ b ≤ 6, there is exactly one domino with a dots on one half and b dots on the other half. The set contains exactly 21 dominoes. Here is an exact illustration of his set:
<image>
Also, Anadi has an undirected graph without self-loops and multiple edges. He wants to choose some dominoes and place them on the edges of this graph. He can use at most one domino of each type. Each edge can fit at most one domino. It's not necessary to place a domino on each edge of the graph.
When placing a domino on an edge, he also chooses its direction. In other words, one half of any placed domino must be directed toward one of the endpoints of the edge and the other half must be directed toward the other endpoint. There's a catch: if there are multiple halves of dominoes directed toward the same vertex, each of these halves must contain the same number of dots.
How many dominoes at most can Anadi place on the edges of his graph?
Input
The first line contains two integers n and m (1 ≤ n ≤ 7, 0 ≤ m ≤ (n⋅(n-1))/(2)) — the number of vertices and the number of edges in the graph.
The next m lines contain two integers each. Integers in the i-th line are a_i and b_i (1 ≤ a, b ≤ n, a ≠ b) and denote that there is an edge which connects vertices a_i and b_i.
The graph might be disconnected. It's however guaranteed that the graph doesn't contain any self-loops, and that there is at most one edge between any pair of vertices.
Output
Output one integer which denotes the maximum number of dominoes which Anadi can place on the edges of the graph.
Examples
Input
4 4
1 2
2 3
3 4
4 1
Output
4
Input
7 0
Output
0
Input
3 1
1 3
Output
1
Input
7 21
1 2
1 3
1 4
1 5
1 6
1 7
2 3
2 4
2 5
2 6
2 7
3 4
3 5
3 6
3 7
4 5
4 6
4 7
5 6
5 7
6 7
Output
16
Note
Here is an illustration of Anadi's graph from the first sample test:
<image>
And here is one of the ways to place a domino on each of its edges:
<image>
Note that each vertex is faced by the halves of dominoes with the same number of dots. For instance, all halves directed toward vertex 1 have three dots.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.
Let's call a positive integer a undoubtedly lucky, if there are such digits x and y (0 ≤ x, y ≤ 9), that the decimal representation of number a (without leading zeroes) contains only digits x and y.
Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^9) — Polycarpus's number.
-----Output-----
Print a single integer that says, how many positive integers that do not exceed n are undoubtedly lucky.
-----Examples-----
Input
10
Output
10
Input
123
Output
113
-----Note-----
In the first test sample all numbers that do not exceed 10 are undoubtedly lucky.
In the second sample numbers 102, 103, 104, 105, 106, 107, 108, 109, 120, 123 are not undoubtedly lucky.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 we have a sequence of non-negative integers, Namely a_1, a_2, ... ,a_n. At each time we can choose one term a_i with 0 < i < n and we subtract 1 from both a_i and a_i+1. We wonder whether we can get a sequence of all zeros after several operations.
Input
The first line of test case is a number N. (0 < N ≤ 10000)
The next line is N non-negative integers, 0 ≤ a_i ≤ 109
Output
If it can be modified into all zeros with several operations output “YES” in a single line, otherwise output “NO” instead.
SAMPLE INPUT
2
1 2
SAMPLE OUTPUT
NO
Explanation
It is clear that [1 2] can be reduced to [0 1] but no further to convert all integers to 0. Hence, the output is NO.
Consider another input for more clarification:
2
2 2
Output is YES as [2 2] can be reduced to [1 1] and then to [0 0] in just two steps.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The aim of the kata is to decompose `n!` (factorial n) into its prime factors.
Examples:
```
n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"
since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once.
n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"
n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23
```
Prime numbers should be in increasing order. When the exponent of a prime is 1 don't put the exponent.
Notes
- the function is `decomp(n)` and should return the decomposition of `n!` into its prime factors in increasing order of the primes, as a string.
- factorial can be a very big number (`4000! has 12674 digits`, n will go from 300 to 4000).
- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use `dynamically allocated character strings`.
Write your solution by modifying this code:
```python
def decomp(n):
```
Your solution should implemented in the function "decomp". 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.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $(i,j)$ is considered the same as the pair $(j,i)$.
-----Input-----
The first line contains a positive integer $N$ ($1 \le N \le 100\,000$), representing the length of the input array.
Eacg of the next $N$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array.
The total number of characters in the input array will be less than $1\,000\,000$.
-----Output-----
Output one number, representing how many palindrome pairs there are in the array.
-----Examples-----
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
-----Note-----
The first example: aa $+$ bb $\to$ abba.
The second example: aab $+$ abcac $=$ aababcac $\to$ aabccbaa aab $+$ aa $=$ aabaa abcac $+$ aa $=$ abcacaa $\to$ aacbcaa dffe $+$ ed $=$ dffeed $\to$ fdeedf dffe $+$ aade $=$ dffeaade $\to$ adfaafde ed $+$ aade $=$ edaade $\to$ aeddea
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone — neither any other statues, nor Anna, nor Maria.
Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is — to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared.
At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner.
Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error.
Input
You are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one — for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S".
It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S".
Output
If Maria wins, print string "WIN". If the statues win, print string "LOSE".
Examples
Input
.......A
........
........
........
........
........
........
M.......
Output
WIN
Input
.......A
........
........
........
........
........
SS......
M.......
Output
LOSE
Input
.......A
........
........
........
........
.S......
S.......
MS......
Output
LOSE
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+
++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>+++++++
+++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>>>.<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<<<<<<<
<<<<<>>>>>>>>>>>>>+.-<<<<<<<<<<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<<>>>>>>>>>
>>>>>>----.++++<<<<<<<<<<<<<<<>>>>.<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<<>>>>
>>>>>>>>>>>---.+++<<<<<<<<<<<<<<<>>>>>>>>>>>>>>---.+++<<<<<<<<<<<<<<>>>>>>>>
>>>>++.--<<<<<<<<<<<<>>>>>>>>>>>>>---.+++<<<<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<
<<<<<<<<<<<.
DCBA:^!~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHdcbD`Y^]\UZYRv
9876543210/.-,+*)('&%$#"!~}|{zyxwvutsrqponm+*)('&%$#cya`=^]\[ZYXWVUTSRQPONML
KJfe^cba`_X]VzTYRv98TSRQ3ONMLEi,+*)('&%$#"!~}|{zyxwvutsrqponmlkjihgfedcba`_^
]\[ZYXWVUTSonPlkjchg`ed]#DCBA@?>=<;:9876543OHGLKDIHGFE>b%$#"!~}|{zyxwvutsrqp
onmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMibafedcba`_X|?>Z<XWVUTSRKo\
[Image]
v34*8+6+,78+9*3+,93+9*5+,28+9*1+,55+9*4+,23*6*2*,91,@,+7*9*25,*48,+3*9+38,+<
>62*9*2+,34*9*3+,66+9*8+,52*9*7+,75+9*8+,92+9*6+,48+9*3+,43*9*2+,84*,26*9*3^
-----Input-----
The input contains a single integer a (0 ≤ a ≤ 1 000 000).
-----Output-----
Output a single integer.
-----Example-----
Input
129
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.
Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".
The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:
some dwarf in one of the chosen lines is located in the rightmost cell of his row; some dwarf in the chosen lines is located in the cell with the candy.
The point of the game is to transport all the dwarves to the candy cells.
Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).
Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".
-----Output-----
In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.
-----Examples-----
Input
3 4
*G*S
G**S
*G*S
Output
2
Input
1 3
S*G
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
-----Input-----
The single line of the input contains a pair of integers m, s (1 ≤ m ≤ 100, 0 ≤ s ≤ 900) — the length and the sum of the digits of the required numbers.
-----Output-----
In the output print the pair of the required non-negative integer numbers — first the minimum possible number, then — the maximum possible number. If no numbers satisfying conditions required exist, print the pair of numbers "-1 -1" (without the quotes).
-----Examples-----
Input
2 15
Output
69 96
Input
3 0
Output
-1 -1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.
Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?
You can assume that initially Vanya had infinitely many cards with each integer number from - x to x.
-----Input-----
The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.
-----Output-----
Print a single number — the answer to the problem.
-----Examples-----
Input
3 2
-1 1 2
Output
1
Input
2 3
-2 -2
Output
2
-----Note-----
In the first sample, Vanya needs to find a single card with number -2.
In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider the infinite sequence $s$ of positive integers, created by repeating the following steps:
Find the lexicographically smallest triple of positive integers $(a, b, c)$ such that $a \oplus b \oplus c = 0$, where $\oplus$ denotes the bitwise XOR operation. $a$, $b$, $c$ are not in $s$. Here triple of integers $(a_1, b_1, c_1)$ is considered to be lexicographically smaller than triple $(a_2, b_2, c_2)$ if sequence $[a_1, b_1, c_1]$ is lexicographically smaller than sequence $[a_2, b_2, c_2]$. Append $a$, $b$, $c$ to $s$ in this order. Go back to the first step.
You have integer $n$. Find the $n$-th element of $s$.
You have to answer $t$ independent test cases.
A sequence $a$ is lexicographically smaller than a sequence $b$ if in the first position where $a$ and $b$ differ, the sequence $a$ has a smaller element than the corresponding element in $b$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases.
Each of the next $t$ lines contains a single integer $n$ ($1\le n \le 10^{16}$) — the position of the element you want to know.
-----Output-----
In each of the $t$ lines, output the answer to the corresponding test case.
-----Example-----
Input
9
1
2
3
4
5
6
7
8
9
Output
1
2
3
4
8
12
5
10
15
-----Note-----
The first elements of $s$ are $1, 2, 3, 4, 8, 12, 5, 10, 15, \dots $
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array of N elements, check if it is possible to obtain a sum of S, by choosing some (or none) elements of the array and adding them.
Input:
First line of the input contains number of test cases T. Each test case has three lines.
First line has N, the number of elements in array.
Second line contains N space separated integers denoting the elements of the array.
Third line contains a single integer denoting S.
Output:
For each test case, print "YES" if S can be obtained by choosing some(or none) elements of the array and adding them. Otherwise Print "NO".
Note that 0 can always be obtained by choosing none.
Constraints
1 ≤ T ≤10
1 ≤ N ≤ 15
-10^6 ≤ A[i] ≤ 10^6 for 0 ≤ i < N
SAMPLE INPUT
3
5
3 2 0 7 -1
8
3
-1 3 3
4
3
4 -5 1
5
SAMPLE OUTPUT
YES
NO
YES
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a permutation P of \{1, 2, \ldots, N\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
-----Constraints-----
- 2 \le N \le 10^5
- 1 \le P_i \le N
- P_i \neq P_j (i \neq j)
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
-----Output-----
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
-----Sample Input-----
3
2 3 1
-----Sample Output-----
5
X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are provided with array of positive non-zero ints and int n representing n-th power (n >= 2).
For the given array, calculate the sum of each value to the n-th power. Then subtract the sum of the original array.
Example 1: Input: {1, 2, 3}, 3 --> (1 ^ 3 + 2 ^ 3 + 3 ^ 3 ) - (1 + 2 + 3) --> 36 - 6 --> Output: 30
Example 2: Input: {1, 2}, 5 --> (1 ^ 5 + 2 ^ 5) - (1 + 2) --> 33 - 3 --> Output: 30
Write your solution by modifying this code:
```python
def modified_sum(a, n):
```
Your solution should implemented in the function "modified_sum". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor — a square tile that is diagonally split into white and black part as depicted in the figure below. [Image]
The dimension of this tile is perfect for this kitchen, as he will need exactly $w \times h$ tiles without any scraps. That is, the width of the kitchen is $w$ tiles, and the height is $h$ tiles. As each tile can be rotated in one of four ways, he still needs to decide on how exactly he will tile the floor. There is a single aesthetic criterion that he wants to fulfil: two adjacent tiles must not share a colour on the edge — i.e. one of the tiles must have a white colour on the shared border, and the second one must be black. [Image] The picture on the left shows one valid tiling of a $3 \times 2$ kitchen. The picture on the right shows an invalid arrangement, as the bottom two tiles touch with their white parts.
Find the number of possible tilings. As this number may be large, output its remainder when divided by $998244353$ (a prime number).
-----Input-----
The only line contains two space separated integers $w$, $h$ ($1 \leq w,h \leq 1\,000$) — the width and height of the kitchen, measured in tiles.
-----Output-----
Output a single integer $n$ — the remainder of the number of tilings when divided by $998244353$.
-----Examples-----
Input
2 2
Output
16
Input
2 4
Output
64
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 angle $\text{ang}$.
The Jury asks You to find such regular $n$-gon (regular polygon with $n$ vertices) that it has three vertices $a$, $b$ and $c$ (they can be non-consecutive) with $\angle{abc} = \text{ang}$ or report that there is no such $n$-gon. [Image]
If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $998244353$.
-----Input-----
The first line contains single integer $T$ ($1 \le T \le 180$) — the number of queries.
Each of the next $T$ lines contains one integer $\text{ang}$ ($1 \le \text{ang} < 180$) — the angle measured in degrees.
-----Output-----
For each query print single integer $n$ ($3 \le n \le 998244353$) — minimal possible number of vertices in the regular $n$-gon or $-1$ if there is no such $n$.
-----Example-----
Input
4
54
50
2
178
Output
10
18
90
180
-----Note-----
The answer for the first query is on the picture above.
The answer for the second query is reached on a regular $18$-gon. For example, $\angle{v_2 v_1 v_6} = 50^{\circ}$.
The example angle for the third query is $\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$.
In the fourth query, minimal possible $n$ is $180$ (not $90$).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$ of even length $n$. String $s$ is binary, in other words, consists only of 0's and 1's.
String $s$ has exactly $\frac{n}{2}$ zeroes and $\frac{n}{2}$ ones ($n$ is even).
In one operation you can reverse any substring of $s$. A substring of a string is a contiguous subsequence of that string.
What is the minimum number of operations you need to make string $s$ alternating? A string is alternating if $s_i \neq s_{i + 1}$ for all $i$. There are two types of alternating strings in general: 01010101... or 10101010...
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains a single integer $n$ ($2 \le n \le 10^5$; $n$ is even) — the length of string $s$.
The second line of each test case contains a binary string $s$ of length $n$ ($s_i \in$ {0, 1}). String $s$ has exactly $\frac{n}{2}$ zeroes and $\frac{n}{2}$ ones.
It's guaranteed that the total sum of $n$ over test cases doesn't exceed $10^5$.
-----Output-----
For each test case, print the minimum number of operations to make $s$ alternating.
-----Example-----
Input
3
2
10
4
0110
8
11101000
Output
0
1
2
-----Note-----
In the first test case, string 10 is already alternating.
In the second test case, we can, for example, reverse the last two elements of $s$ and get: 0110 $\rightarrow$ 0101.
In the third test case, we can, for example, make the following two operations: 11101000 $\rightarrow$ 10101100; 10101100 $\rightarrow$ 10101010.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two positive integers A and B. Compare the magnitudes of these numbers.
-----Constraints-----
- 1 ≤ A, B ≤ 10^{100}
- Neither A nor B begins with a 0.
-----Input-----
Input is given from Standard Input in the following format:
A
B
-----Output-----
Print GREATER if A>B, LESS if A<B and EQUAL if A=B.
-----Sample Input-----
36
24
-----Sample Output-----
GREATER
Since 36>24, print GREATER.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function that finds the [integral](https://en.wikipedia.org/wiki/Integral) of the expression passed.
In order to find the integral all you need to do is add one to the `exponent` (the second argument), and divide the `coefficient` (the first argument) by that new number.
For example for `3x^2`, the integral would be `1x^3`: we added 1 to the exponent, and divided the coefficient by that new number).
Notes:
* The output should be a string.
* The coefficient and exponent is always a positive integer.
## Examples
```
3, 2 --> "1x^3"
12, 5 --> "2x^6"
20, 1 --> "10x^2"
40, 3 --> "10x^4"
90, 2 --> "30x^3"
```
Write your solution by modifying this code:
```python
def integrate(coefficient, exponent):
```
Your solution should implemented in the function "integrate". 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.
Create a function that takes a number as an argument and returns a grade based on that number.
Score | Grade
-----------------------------------------|-----
Anything greater than 1 or less than 0.6 | "F"
0.9 or greater | "A"
0.8 or greater | "B"
0.7 or greater | "C"
0.6 or greater | "D"
Examples:
```
grader(0) should be "F"
grader(1.1) should be "F"
grader(0.9) should be "A"
grader(0.8) should be "B"
grader(0.7) should be "C"
grader(0.6) should be "D"
```
Write your solution by modifying this code:
```python
def grader(score):
```
Your solution should implemented in the function "grader". 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.
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.
According to the borscht recipe it consists of n ingredients that have to be mixed in proportion <image> litres (thus, there should be a1 ·x, ..., an ·x litres of corresponding ingredients mixed for some non-negative x). In the kitchen Volodya found out that he has b1, ..., bn litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a V litres volume pan (which means the amount of soup cooked can be between 0 and V litres). What is the volume of borscht Volodya will cook ultimately?
Input
The first line of the input contains two space-separated integers n and V (1 ≤ n ≤ 20, 1 ≤ V ≤ 10000). The next line contains n space-separated integers ai (1 ≤ ai ≤ 100). Finally, the last line contains n space-separated integers bi (0 ≤ bi ≤ 100).
Output
Your program should output just one real number — the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10 - 4.
Examples
Input
1 100
1
40
Output
40.0
Input
2 100
1 1
25 30
Output
50.0
Input
2 100
1 1
60 60
Output
100.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.
Jeff got 2n real numbers a_1, a_2, ..., a_2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: choose indexes i and j (i ≠ j) that haven't been chosen yet; round element a_{i} to the nearest integer that isn't more than a_{i} (assign to a_{i}: ⌊ a_{i} ⌋); round element a_{j} to the nearest integer that isn't less than a_{j} (assign to a_{j}: ⌈ a_{j} ⌉).
Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 2000). The next line contains 2n real numbers a_1, a_2, ..., a_2n (0 ≤ a_{i} ≤ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
-----Output-----
In a single line print a single real number — the required difference with exactly three digits after the decimal point.
-----Examples-----
Input
3
0.000 0.500 0.750 1.000 2.000 3.000
Output
0.250
Input
3
4469.000 6526.000 4864.000 9356.383 7490.000 995.896
Output
0.279
-----Note-----
In the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
-----Input-----
The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows: each of the R lines contains a string of length C, the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise. The input will contain at least one character B and it will be valid.
-----Output-----
The number of wall segments in the input configuration.
-----Examples-----
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
-----Note-----
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Complete the function that returns an array of length `n`, starting with the given number `x` and the squares of the previous number. If `n` is negative or zero, return an empty array/list.
## Examples
```
2, 5 --> [2, 4, 16, 256, 65536]
3, 3 --> [3, 9, 81]
```
Write your solution by modifying this code:
```python
def squares(x, n):
```
Your solution should implemented in the function "squares". 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.
Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric.
The piece of the multicolored fabric consists of $n \times m$ separate square scraps. Since Rarity likes dresses in style, a dress pattern must only include scraps sharing the same color. A dress pattern must be the square, and since Rarity is fond of rhombuses, the sides of a pattern must form a $45^{\circ}$ angle with sides of a piece of fabric (that way it will be resembling the traditional picture of a rhombus).
Examples of proper dress patterns: [Image] Examples of improper dress patterns: [Image] The first one consists of multi-colored scraps, the second one goes beyond the bounds of the piece of fabric, the third one is not a square with sides forming a $45^{\circ}$ angle with sides of the piece of fabric.
Rarity wonders how many ways to cut out a dress pattern that satisfies all the conditions that do exist. Please help her and satisfy her curiosity so she can continue working on her new masterpiece!
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2000$). Each of the next $n$ lines contains $m$ characters: lowercase English letters, the $j$-th of which corresponds to scrap in the current line and in the $j$-th column. Scraps having the same letter share the same color, scraps having different letters have different colors.
-----Output-----
Print a single integer: the number of ways to cut out a dress pattern to satisfy all of Rarity's conditions.
-----Examples-----
Input
3 3
aaa
aaa
aaa
Output
10
Input
3 4
abab
baba
abab
Output
12
Input
5 5
zbacg
baaac
aaaaa
eaaad
weadd
Output
31
-----Note-----
In the first example, all the dress patterns of size $1$ and one of size $2$ are satisfactory.
In the second example, only the dress patterns of size $1$ are satisfactory.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.
The classroom contains $n$ rows of seats and there are $m$ seats in each row. Then the classroom can be represented as an $n \times m$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $k$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
-----Input-----
The first line contains three positive integers $n,m,k$ ($1 \leq n, m, k \leq 2\,000$), where $n,m$ represent the sizes of the classroom and $k$ is the number of consecutive seats you need to find.
Each of the next $n$ lines contains $m$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
-----Output-----
A single number, denoting the number of ways to find $k$ empty seats in the same row or column.
-----Examples-----
Input
2 3 2
**.
...
Output
3
Input
1 2 2
..
Output
1
Input
3 3 4
.*.
*.*
.*.
Output
0
-----Note-----
In the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $(1,3)$, $(2,3)$ $(2,2)$, $(2,3)$ $(2,1)$, $(2,2)$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Central Company has an office with a sophisticated security system. There are $10^6$ employees, numbered from $1$ to $10^6$.
The security system logs entrances and departures. The entrance of the $i$-th employee is denoted by the integer $i$, while the departure of the $i$-th employee is denoted by the integer $-i$.
The company has some strict rules about access to its office:
An employee can enter the office at most once per day. He obviously can't leave the office if he didn't enter it earlier that day. In the beginning and at the end of every day, the office is empty (employees can't stay at night). It may also be empty at any moment of the day.
Any array of events satisfying these conditions is called a valid day.
Some examples of valid or invalid days:
$[1, 7, -7, 3, -1, -3]$ is a valid day ($1$ enters, $7$ enters, $7$ leaves, $3$ enters, $1$ leaves, $3$ leaves). $[2, -2, 3, -3]$ is also a valid day. $[2, 5, -5, 5, -5, -2]$ is not a valid day, because $5$ entered the office twice during the same day. $[-4, 4]$ is not a valid day, because $4$ left the office without being in it. $[4]$ is not a valid day, because $4$ entered the office and didn't leave it before the end of the day.
There are $n$ events $a_1, a_2, \ldots, a_n$, in the order they occurred. This array corresponds to one or more consecutive days. The system administrator erased the dates of events by mistake, but he didn't change the order of the events.
You must partition (to cut) the array $a$ of events into contiguous subarrays, which must represent non-empty valid days (or say that it's impossible). Each array element should belong to exactly one contiguous subarray of a partition. Each contiguous subarray of a partition should be a valid day.
For example, if $n=8$ and $a=[1, -1, 1, 2, -1, -2, 3, -3]$ then he can partition it into two contiguous subarrays which are valid days: $a = [1, -1~ \boldsymbol{|}~ 1, 2, -1, -2, 3, -3]$.
Help the administrator to partition the given array $a$ in the required way or report that it is impossible to do. Find any required partition, you should not minimize or maximize the number of parts.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-10^6 \le a_i \le 10^6$ and $a_i \neq 0$).
-----Output-----
If there is no valid partition, print $-1$. Otherwise, print any valid partition in the following format:
On the first line print the number $d$ of days ($1 \le d \le n$). On the second line, print $d$ integers $c_1, c_2, \ldots, c_d$ ($1 \le c_i \le n$ and $c_1 + c_2 + \ldots + c_d = n$), where $c_i$ is the number of events in the $i$-th day.
If there are many valid solutions, you can print any of them. You don't have to minimize nor maximize the number of days.
-----Examples-----
Input
6
1 7 -7 3 -1 -3
Output
1
6
Input
8
1 -1 1 2 -1 -2 3 -3
Output
2
2 6
Input
6
2 5 -5 5 -5 -2
Output
-1
Input
3
-8 1 1
Output
-1
-----Note-----
In the first example, the whole array is a valid day.
In the second example, one possible valid solution is to split the array into $[1, -1]$ and $[1, 2, -1, -2, 3, -3]$ ($d = 2$ and $c = [2, 6]$). The only other valid solution would be to split the array into $[1, -1]$, $[1, 2, -1, -2]$ and $[3, -3]$ ($d = 3$ and $c = [2, 4, 2]$). Both solutions are accepted.
In the third and fourth examples, we can prove that there exists no valid solution. Please note that the array given in input is not guaranteed to represent a coherent set of events.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Books are indexed. Write a program which reads a list of pairs of a word and a page number, and prints the word and a list of the corresponding page numbers.
You can assume that a word consists of at most 30 characters, and the page number is less than or equal to 1000. The number of pairs of a word and a page number is less than or equal to 100. A word never appear in a page more than once.
The words should be printed in alphabetical order and the page numbers should be printed in ascending order.
Input
word page_number
::
::
Output
word
a_list_of_the_page_number
word
a_list_of_the_Page_number
::
::
Example
Input
style 12
even 25
introduction 3
easy 9
style 7
document 13
style 21
even 18
Output
document
13
easy
9
even
18 25
introduction
3
style
7 12 21
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Barney is standing in a bar and starring at a pretty girl. He wants to shoot her with his heart arrow but he needs to know the distance between him and the girl to make his shot accurate. [Image]
Barney asked the bar tender Carl about this distance value, but Carl was so busy talking to the customers so he wrote the distance value (it's a real number) on a napkin. The problem is that he wrote it in scientific notation. The scientific notation of some real number x is the notation of form AeB, where A is a real number and B is an integer and x = A × 10^{B} is true. In our case A is between 0 and 9 and B is non-negative.
Barney doesn't know anything about scientific notation (as well as anything scientific at all). So he asked you to tell him the distance value in usual decimal representation with minimal number of digits after the decimal point (and no decimal point if it is an integer). See the output format for better understanding.
-----Input-----
The first and only line of input contains a single string of form a.deb where a, d and b are integers and e is usual character 'e' (0 ≤ a ≤ 9, 0 ≤ d < 10^100, 0 ≤ b ≤ 100) — the scientific notation of the desired distance value.
a and b contain no leading zeros and d contains no trailing zeros (but may be equal to 0). Also, b can not be non-zero if a is zero.
-----Output-----
Print the only real number x (the desired distance value) in the only line in its decimal notation.
Thus if x is an integer, print it's integer value without decimal part and decimal point and without leading zeroes.
Otherwise print x in a form of p.q such that p is an integer that have no leading zeroes (but may be equal to zero), and q is an integer that have no trailing zeroes (and may not be equal to zero).
-----Examples-----
Input
8.549e2
Output
854.9
Input
8.549e3
Output
8549
Input
0.33e0
Output
0.33
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a square of size $10^6 \times 10^6$ on the coordinate plane with four points $(0, 0)$, $(0, 10^6)$, $(10^6, 0)$, and $(10^6, 10^6)$ as its vertices.
You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.
Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.
-----Input-----
The first line contains two integers $n$ and $m$ ($0 \le n, m \le 10^5$) — the number of horizontal segments and the number of vertical segments.
The next $n$ lines contain descriptions of the horizontal segments. The $i$-th line contains three integers $y_i$, $lx_i$ and $rx_i$ ($0 < y_i < 10^6$; $0 \le lx_i < rx_i \le 10^6$), which means the segment connects $(lx_i, y_i)$ and $(rx_i, y_i)$.
The next $m$ lines contain descriptions of the vertical segments. The $i$-th line contains three integers $x_i$, $ly_i$ and $ry_i$ ($0 < x_i < 10^6$; $0 \le ly_i < ry_i \le 10^6$), which means the segment connects $(x_i, ly_i)$ and $(x_i, ry_i)$.
It's guaranteed that there are no two segments on the same line, and each segment intersects with at least one of square's sides.
-----Output-----
Print the number of pieces the square is divided into after drawing all the segments.
-----Example-----
Input
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
Output
7
-----Note-----
The sample is like this: [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
-----Constraints-----
- 100 \leq N \leq 999
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
If the earliest ABC where Kurohashi can make his debut is ABC n, print n.
-----Sample Input-----
111
-----Sample Output-----
111
The next ABC to be held is ABC 111, where Kurohashi can make his debut.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
-----Input-----
The first line contains single positive integer n (1 ≤ n ≤ 10^5) — the number of integers.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print the maximum length of an increasing subarray of the given array.
-----Examples-----
Input
5
1 7 2 11 15
Output
3
Input
6
100 100 100 100 100 100
Output
1
Input
3
1 2 3
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.
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.
This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).
As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.
-----Input-----
The first line contains two integers n and k (2 ≤ n ≤ 2·10^5, 0 < 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x_1, x_2, ..., x_{n} — the absurdity of each law (1 ≤ x_{i} ≤ 10^9).
-----Output-----
Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.
-----Examples-----
Input
5 2
3 6 1 1 6
Output
1 4
Input
6 2
1 1 1 1 1 1
Output
1 3
-----Note-----
In the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.
In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on.
Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth n and a duration for each level of recursion t_1, t_2, ..., t_{n}. Once Limak launches the firework in some cell, the firework starts moving upward. After covering t_1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering t_2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the n-th level of recursion, when all 2^{n} - 1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time — it is allowed and such parts do not crash.
Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells?
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 30) — the total depth of the recursion.
The second line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 5). On the i-th level each of 2^{i} - 1 parts will cover t_{i} cells before exploding.
-----Output-----
Print one integer, denoting the number of cells which will be visited at least once by any part of the firework.
-----Examples-----
Input
4
4 2 2 3
Output
39
Input
6
1 1 1 1 1 3
Output
85
Input
1
3
Output
3
-----Note-----
For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered t_1 = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39.
[Image]
For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level.
[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.
### Task:
You have to write a function `pattern` which creates the following pattern (See Examples) upto desired number of rows.
If the Argument is `0` or a Negative Integer then it should return `""` i.e. empty string.
### Examples:
`pattern(9)`:
123456789
234567891
345678912
456789123
567891234
678912345
789123456
891234567
912345678
`pattern(5)`:
12345
23451
34512
45123
51234
Note: There are no spaces in the pattern
Hint: Use `\n` in string to jump to next line
Write your solution by modifying this code:
```python
def pattern(n):
```
Your solution should implemented in the function "pattern". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single `100`, `50` or `25` dollar bill. An "Avengers" ticket costs `25 dollars`.
Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.
Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue?
Return `YES`, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return `NO`.
### Examples:
```csharp
Line.Tickets(new int[] {25, 25, 50}) // => YES
Line.Tickets(new int[] {25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
Line.Tickets(new int[] {25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```python
tickets([25, 25, 50]) # => YES
tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```cpp
tickets({25, 25, 50}) // => YES
tickets({25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
tickets({25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
Write your solution by modifying this code:
```python
def tickets(people):
```
Your solution should implemented in the function "tickets". 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.
Flash has invited his nemesis The Turtle (He actually was a real villain! ) to play his favourite card game, SNAP. In this game a 52 card deck is dealt out so both Flash and the Turtle get 26 random cards.
Each players cards will be represented by an array like below
Flash’s pile:
```[ 'A', '5', 'Q', 'Q', '6', '2', 'A', '9', '10', '6', '4', '3', '10', '9', '3', '8', 'K', 'J', 'J', 'K', '7', '9', '5', 'J', '7', '2' ]```
Turtle’s pile:
```[ '8', 'A', '2', 'Q', 'K', '8', 'J', '6', '4', '8', '7', 'A', '5', 'K', '3', 'Q', '6', '9', '4', '3', '4', '10', '2', '7', '10', '5' ]```
The players take it in turn to take the top card from their deck (the first element in their array) and place it in a face up pile in the middle. Flash goes first.
When a card is placed on the face up pile that matches the card it is placed on top of the first player to shout ‘SNAP!’ wins that round. Due to Flash's speed he wins every round.
Face up pile in the middle:
```[ 'A', '8', '5', 'A', 'Q', '2', 'Q', 'Q',``` => SNAP!
The face up pile of cards in the middle are added to the bottom of Flash's pile.
Flash’s pile after one round:
```['6', '2', 'A', '9', '10', '6', '4', '3', '10', '9', '3', '8', 'K', 'J', 'J', 'K', '7', '9', '5', 'J', '7', '2', 'A', '8', '5', 'A', 'Q', '2', 'Q', 'Q' ]```
Flash then starts the next round by putting down the next card.
When Turtle runs out of cards the game is over.
How many times does Flash get to call Snap before Turtle runs out of cards?
If both the player put down all their cards into the middle without any matches then the game ends a draw and Flash calls SNAP 0 times.
Write your solution by modifying this code:
```python
def snap(flash_pile, turtle_pile):
```
Your solution should implemented in the function "snap". 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.
$n$ players are playing a game.
There are two different maps in the game. For each player, we know his strength on each map. When two players fight on a specific map, the player with higher strength on that map always wins. No two players have the same strength on the same map.
You are the game master and want to organize a tournament. There will be a total of $n-1$ battles. While there is more than one player in the tournament, choose any map and any two remaining players to fight on it. The player who loses will be eliminated from the tournament.
In the end, exactly one player will remain, and he is declared the winner of the tournament. For each player determine if he can win the tournament.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer $n$ ($1 \leq n \leq 10^5$) — the number of players.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq 10^9$, $a_i \neq a_j$ for $i \neq j$), where $a_i$ is the strength of the $i$-th player on the first map.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \leq b_i \leq 10^9$, $b_i \neq b_j$ for $i \neq j$), where $b_i$ is the strength of the $i$-th player on the second map.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case print a string of length $n$. $i$-th character should be "1" if the $i$-th player can win the tournament, or "0" otherwise.
-----Examples-----
Input
3
4
1 2 3 4
1 2 3 4
4
11 12 20 21
44 22 11 30
1
1000000000
1000000000
Output
0001
1111
1
-----Note-----
In the first test case, the $4$-th player will beat any other player on any game, so he will definitely win the tournament.
In the second test case, everyone can be a winner.
In the third test case, there is only one player. Clearly, he will win the tournament.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke loves working out. He is now exercising N times.
Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.
Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.
-----Constraints-----
- 1 ≤ N ≤ 10^{5}
-----Input-----
The input is given from Standard Input in the following format:
N
-----Output-----
Print the answer modulo 10^{9}+7.
-----Sample Input-----
3
-----Sample Output-----
6
- After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.
- After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.
- After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor $x$, Egor on the floor $y$ (not on the same floor with Masha).
The house has a staircase and an elevator. If Masha uses the stairs, it takes $t_1$ seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in $t_2$ seconds. The elevator moves with doors closed. The elevator spends $t_3$ seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor.
Coming out of the apartment on her floor, Masha noticed that the elevator is now on the floor $z$ and has closed doors. Now she has to choose whether to use the stairs or use the elevator.
If the time that Masha needs to get to the Egor's floor by the stairs is strictly less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator.
Help Mary to understand whether to use the elevator or the stairs.
-----Input-----
The only line contains six integers $x$, $y$, $z$, $t_1$, $t_2$, $t_3$ ($1 \leq x, y, z, t_1, t_2, t_3 \leq 1000$) — the floor Masha is at, the floor Masha wants to get to, the floor the elevator is located on, the time it takes Masha to pass between two floors by stairs, the time it takes the elevator to pass between two floors and the time it takes for the elevator to close or open the doors.
It is guaranteed that $x \ne y$.
-----Output-----
If the time it will take to use the elevator is not greater than the time it will take to use the stairs, print «YES» (without quotes), otherwise print «NO> (without quotes).
You can print each letter in any case (upper or lower).
-----Examples-----
Input
5 1 4 4 2 1
Output
YES
Input
1 6 6 2 1 1
Output
NO
Input
4 1 7 4 1 2
Output
YES
-----Note-----
In the first example:
If Masha goes by the stairs, the time she spends is $4 \cdot 4 = 16$, because she has to go $4$ times between adjacent floors and each time she spends $4$ seconds.
If she chooses the elevator, she will have to wait $2$ seconds while the elevator leaves the $4$-th floor and goes to the $5$-th. After that the doors will be opening for another $1$ second. Then Masha will enter the elevator, and she will have to wait for $1$ second for the doors closing. Next, the elevator will spend $4 \cdot 2 = 8$ seconds going from the $5$-th floor to the $1$-st, because the elevator has to pass $4$ times between adjacent floors and spends $2$ seconds each time. And finally, it will take another $1$ second before the doors are open and Masha can come out.
Thus, all the way by elevator will take $2 + 1 + 1 + 8 + 1 = 13$ seconds, which is less than $16$ seconds, so Masha has to choose the elevator.
In the second example, it is more profitable for Masha to use the stairs, because it will take $13$ seconds to use the elevator, that is more than the $10$ seconds it will takes to go by foot.
In the third example, the time it takes to use the elevator is equal to the time it takes to walk up by the stairs, and is equal to $12$ seconds. That means Masha will take the elevator.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.
There are $n$ positive integers $a_1, a_2, \ldots, a_n$ on Bob's homework paper, where $n$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $2$ numbers. Suppose the numbers are divided into $m$ groups, and the sum of the numbers in the $j$-th group is $s_j$. Bob's aim is to minimize the sum of the square of $s_j$, that is $$\sum_{j = 1}^{m} s_j^2.$$
Bob is puzzled by this hard problem. Could you please help him solve it?
-----Input-----
The first line contains an even integer $n$ ($2 \leq n \leq 3 \cdot 10^5$), denoting that there are $n$ integers on Bob's homework paper.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^4$), describing the numbers you need to deal with.
-----Output-----
A single line containing one integer, denoting the minimum of the sum of the square of $s_j$, which is $$\sum_{i = j}^{m} s_j^2,$$ where $m$ is the number of groups.
-----Examples-----
Input
4
8 5 2 3
Output
164
Input
6
1 1 1 2 2 2
Output
27
-----Note-----
In the first sample, one of the optimal solutions is to divide those $4$ numbers into $2$ groups $\{2, 8\}, \{5, 3\}$. Thus the answer is $(2 + 8)^2 + (5 + 3)^2 = 164$.
In the second sample, one of the optimal solutions is to divide those $6$ numbers into $3$ groups $\{1, 2\}, \{1, 2\}, \{1, 2\}$. Thus the answer is $(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.
Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — 50 millimeters per second.
Scrooge signed exactly k papers throughout his life and all those signatures look the same.
Find the total time Scrooge wasted signing the papers.
Input
The first line contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai — integers xi and yi, separated by a space.
All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.
Output
Print one real number — the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6.
Examples
Input
2 1
0 0
10 0
Output
0.200000000
Input
5 10
3 1
-5 6
-2 -1
3 2
10 0
Output
6.032163204
Input
6 10
5 0
4 0
6 0
3 0
7 0
2 0
Output
3.000000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if: the Euclidean distance between A and B is one unit and neither A nor B is blocked; or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B.
Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
-----Input-----
The first line contains an integer n (0 ≤ n ≤ 4·10^7).
-----Output-----
Print a single integer — the minimum number of points that should be blocked.
-----Examples-----
Input
1
Output
4
Input
2
Output
8
Input
3
Output
16
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.
The game is played on the following field. [Image]
Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (x_{l}, y_{l}) in some small field, the next move should be done in one of the cells of the small field with coordinates (x_{l}, y_{l}). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.
You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.
A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.
-----Input-----
First 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell.
The line after the table contains two integers x and y (1 ≤ x, y ≤ 9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right.
It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable.
-----Output-----
Output the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified.
-----Examples-----
Input
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... x.. ...
... ... ...
... ... ...
... ... ...
6 4
Output
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... x.. ...
!!! ... ...
!!! ... ...
!!! ... ...
Input
xoo x.. x..
ooo ... ...
ooo ... ...
x.. x.. x..
... ... ...
... ... ...
x.. x.. x..
... ... ...
... ... ...
7 4
Output
xoo x!! x!!
ooo !!! !!!
ooo !!! !!!
x!! x!! x!!
!!! !!! !!!
!!! !!! !!!
x!! x!! x!!
!!! !!! !!!
!!! !!! !!!
Input
o.. ... ...
... ... ...
... ... ...
... xxx ...
... xox ...
... ooo ...
... ... ...
... ... ...
... ... ...
5 5
Output
o!! !!! !!!
!!! !!! !!!
!!! !!! !!!
!!! xxx !!!
!!! xox !!!
!!! ooo !!!
!!! !!! !!!
!!! !!! !!!
!!! !!! !!!
-----Note-----
In the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.
In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.
In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 `S` and a character `C`, return an array of integers representing the shortest distance from the current character in `S` to `C`.
### Notes
* All letters will be lowercase.
* If the string is empty, return an empty array.
* If the character is not present, return an empty array.
## Examples
```python
shortest_to_char("lovecodewars", "e") == [3, 2, 1, 0, 1, 2, 1, 0, 1, 2, 3, 4]
shortest_to_char("aaaabbbb", "b") == [4, 3, 2, 1, 0, 0, 0, 0]
shortest_to_char("", "b") == []
shortest_to_char("abcde", "") == []
```
___
If you liked it, please rate :D
Write your solution by modifying this code:
```python
def shortest_to_char(s, c):
```
Your solution should implemented in the function "shortest_to_char". 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.
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings s_1, s_2 and another string called virus. Your task is to find the longest common subsequence of s_1 and s_2, such that it doesn't contain virus as a substring.
-----Input-----
The input contains three strings in three separate lines: s_1, s_2 and virus (1 ≤ |s_1|, |s_2|, |virus| ≤ 100). Each string consists only of uppercase English letters.
-----Output-----
Output the longest common subsequence of s_1 and s_2 without virus as a substring. If there are multiple answers, any of them will be accepted.
If there is no valid common subsequence, output 0.
-----Examples-----
Input
AJKEQSLOBSROFGZ
OVGURWZLWVLUXTH
OZ
Output
ORZ
Input
AA
A
A
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.
We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.
-----Constraints-----
- All values in input are integers.
- 1 \leq A_{i, j} \leq 100
- A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))
- 1 \leq N \leq 10
- 1 \leq b_i \leq 100
- b_i \neq b_j (i \neq j)
-----Input-----
Input is given from Standard Input in the following format:
A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N
-----Output-----
If we will have a bingo, print Yes; otherwise, print No.
-----Sample Input-----
84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30
-----Sample Output-----
Yes
We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.
She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).
However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.
Find the amount of money that she will hand to the cashier.
Constraints
* 1 ≦ N < 10000
* 1 ≦ K < 10
* 0 ≦ D_1 < D_2 < … < D_K≦9
* \\{D_1,D_2,...,D_K\\} ≠ \\{1,2,3,4,5,6,7,8,9\\}
Input
The input is given from Standard Input in the following format:
N K
D_1 D_2 … D_K
Output
Print the amount of money that Iroha will hand to the cashier.
Examples
Input
1000 8
1 3 4 5 6 7 8 9
Output
2000
Input
9999 1
0
Output
9999
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.
In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.
An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
Input
The first line of the input data contains an integer number n (3 ≤ n ≤ 106), n — the amount of hills around the capital. The second line contains n numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Output
Print the required amount of pairs.
Examples
Input
5
1 2 4 5 3
Output
7
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n.
Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing.
There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold.
For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey:
* c = [1, 2, 4];
* c = [3, 5, 6, 8];
* c = [7] (a journey consisting of one city is also valid).
There are some additional ways to plan a journey that are not listed above.
Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?
Input
The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of cities in Berland.
The second line contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 4 ⋅ 10^5), where b_i is the beauty value of the i-th city.
Output
Print one integer — the maximum beauty of a journey Tanya can choose.
Examples
Input
6
10 7 1 9 10 15
Output
26
Input
1
400000
Output
400000
Input
7
8 9 26 11 12 29 14
Output
55
Note
The optimal journey plan in the first example is c = [2, 4, 5].
The optimal journey plan in the second example is c = [1].
The optimal journey plan in the third example is c = [3, 6].
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
JOI Pizza sells pizza home delivery along the d-meter-long ring road that runs through the city center.
JOI Pizza has n stores S1, ..., Sn on the loop line. The head office is S1. The distance from S1 to Si when moving the loop line clockwise is set to di meters. D2 , ..., dn is an integer greater than or equal to 1 and less than or equal to d -1. D2, ..., dn are all different. Bake and deliver pizza at the shortest store.
The location of the delivery destination is represented by an integer k that is greater than or equal to 0 and less than or equal to d -1. This means that the distance from the head office S1 to the delivery destination in the clockwise direction is k meters. Pizza delivery is done along the loop line and no other road is allowed. However, the loop line may move clockwise or counterclockwise.
For example, if the location of the store and the location of the delivery destination are as shown in the figure below (this example corresponds to Example 1 of "I / O example").
<image>
The store closest to the delivery destination 1 is S2, so the delivery is from store S2. At this time, the distance traveled from the store is 1. Also, the store closest to delivery destination 2 is S1 (main store), so store S1 (main store). ) To deliver to home. At this time, the distance traveled from the store is 2.
Total length of the loop line d, Number of JOI pizza stores n, Number of orders m, N --1 integer representing a location other than the main store d2, ..., dn, Integer k1, .. representing the location of the delivery destination Given ., km, create a program to find the sum of all orders for each order by the distance traveled during delivery (ie, the distance from the nearest store to the delivery destination).
input
The input consists of multiple datasets. Each dataset is given in the following format.
The first line is a positive integer d (2 ≤ d ≤ 1000000000 = 109) that represents the total length of the loop line, the second line is a positive integer n (2 ≤ n ≤ 100000) that represents the number of stores, and the third line is A positive integer m (1 ≤ m ≤ 10000) is written to represent the number of orders. The n --1 lines after the 4th line are integers d2, d3, ..., dn that represent the location of stores other than the main store. (1 ≤ di ≤ d -1) is written in this order, and the integers k1, k2, ..., km (0 ≤ ki ≤ d) representing the delivery destination location are in the m lines after the n + 3rd line. --1) are written in this order.
Of the scoring data, for 40% of the points, n ≤ 10000 is satisfied. For 40% of the points, the total distance traveled and the value of d are both 1000000 or less. In the scoring data, the total distance traveled is 1000000000 = 109 or less.
When d is 0, it indicates the end of input. The number of data sets does not exceed 10.
output
For each data set, one integer representing the total distance traveled during delivery is output on one line.
Examples
Input
8
3
2
3
1
4
6
20
4
4
12
8
16
7
7
11
8
0
Output
3
3
Input
None
Output
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.
Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly $\frac{n}{k}$ times consecutively. In other words, array a is k-periodic, if it has period of length k.
For example, any array is n-periodic, where n is the array length. Array [2, 1, 2, 1, 2, 1] is at the same time 2-periodic and 6-periodic and array [1, 2, 1, 1, 2, 1, 1, 2, 1] is at the same time 3-periodic and 9-periodic.
For the given array a, consisting only of numbers one and two, find the minimum number of elements to change to make the array k-periodic. If the array already is k-periodic, then the required value equals 0.
-----Input-----
The first line of the input contains a pair of integers n, k (1 ≤ k ≤ n ≤ 100), where n is the length of the array and the value n is divisible by k. The second line contains the sequence of elements of the given array a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 2), a_{i} is the i-th element of the array.
-----Output-----
Print the minimum number of array elements we need to change to make the array k-periodic. If the array already is k-periodic, then print 0.
-----Examples-----
Input
6 2
2 1 2 2 2 1
Output
1
Input
8 4
1 1 2 1 1 1 2 1
Output
0
Input
9 3
2 1 1 1 2 1 1 1 2
Output
3
-----Note-----
In the first sample it is enough to change the fourth element from 2 to 1, then the array changes to [2, 1, 2, 1, 2, 1].
In the second sample, the given array already is 4-periodic.
In the third sample it is enough to replace each occurrence of number two by number one. In this case the array will look as [1, 1, 1, 1, 1, 1, 1, 1, 1] — this array is simultaneously 1-, 3- and 9-periodic.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
N hotels are located on a straight line. The coordinate of the i-th hotel (1 \leq i \leq N) is x_i.
Tak the traveler has the following two personal principles:
- He never travels a distance of more than L in a single day.
- He never sleeps in the open. That is, he must stay at a hotel at the end of a day.
You are given Q queries. The j-th (1 \leq j \leq Q) query is described by two distinct integers a_j and b_j.
For each query, find the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel following his principles.
It is guaranteed that he can always travel from the a_j-th hotel to the b_j-th hotel, in any given input.
-----Constraints-----
- 2 \leq N \leq 10^5
- 1 \leq L \leq 10^9
- 1 \leq Q \leq 10^5
- 1 \leq x_i < x_2 < ... < x_N \leq 10^9
- x_{i+1} - x_i \leq L
- 1 \leq a_j,b_j \leq N
- a_j \neq b_j
- N,\,L,\,Q,\,x_i,\,a_j,\,b_j are integers.
-----Partial Score-----
- 200 points will be awarded for passing the test set satisfying N \leq 10^3 and Q \leq 10^3.
-----Input-----
The input is given from Standard Input in the following format:
N
x_1 x_2 ... x_N
L
Q
a_1 b_1
a_2 b_2
:
a_Q b_Q
-----Output-----
Print Q lines.
The j-th line (1 \leq j \leq Q) should contain the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel.
-----Sample Input-----
9
1 3 6 13 15 18 19 29 31
10
4
1 8
7 3
6 7
8 5
-----Sample Output-----
4
2
1
2
For the 1-st query, he can travel from the 1-st hotel to the 8-th hotel in 4 days, as follows:
- Day 1: Travel from the 1-st hotel to the 2-nd hotel. The distance traveled is 2.
- Day 2: Travel from the 2-nd hotel to the 4-th hotel. The distance traveled is 10.
- Day 3: Travel from the 4-th hotel to the 7-th hotel. The distance traveled is 6.
- Day 4: Travel from the 7-th hotel to the 8-th hotel. The distance traveled is 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.
PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $6$ slices, medium ones consist of $8$ slices, and large pizzas consist of $10$ slices each. Baking them takes $15$, $20$ and $25$ minutes, respectively.
Petya's birthday is today, and $n$ of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.
Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least $n$ slices in total. For example:
if $12$ friends come to Petya's birthday, he has to order pizzas containing at least $12$ slices in total. He can order two small pizzas, containing exactly $12$ slices, and the time to bake them is $30$ minutes;
if $15$ friends come to Petya's birthday, he has to order pizzas containing at least $15$ slices in total. He can order a small pizza and a large pizza, containing $16$ slices, and the time to bake them is $40$ minutes;
if $300$ friends come to Petya's birthday, he has to order pizzas containing at least $300$ slices in total. He can order $15$ small pizzas, $10$ medium pizzas and $13$ large pizzas, in total they contain $15 \cdot 6 + 10 \cdot 8 + 13 \cdot 10 = 300$ slices, and the total time to bake them is $15 \cdot 15 + 10 \cdot 20 + 13 \cdot 25 = 750$ minutes;
if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is $15$ minutes.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases.
Each testcase consists of a single line that contains a single integer $n$ ($1 \le n \le 10^{16}$) — the number of Petya's friends.
-----Output-----
For each testcase, print one integer — the minimum number of minutes that is needed to bake pizzas containing at least $n$ slices in total.
-----Examples-----
Input
6
12
15
300
1
9999999999999999
3
Output
30
40
750
15
25000000000000000
15
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Chef and his girlfriend are going to have a promenade. They are walking along the straight road which consists of segments placed one by one. Before walking Chef and his girlfriend stay at the beginning of the first segment, they want to achieve the end of the last segment.
There are few problems:
- At the beginning Chef should choose constant integer - the velocity of mooving. It can't be changed inside one segment.
- The velocity should be decreased by at least 1 after achieving the end of some segment.
- There is exactly one shop on each segment. Each shop has an attractiveness. If it's attractiveness is W and Chef and his girlfriend move with velocity V then if V < W girlfriend will run away into the shop and the promenade will become ruined.
Chef doesn't want to lose her girl in such a way, but he is an old one, so you should find the minimal possible velocity at the first segment to satisfy all conditions.
-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N denoting the number of segments. The second line contains N space-separated integers W1, W2, ..., WN denoting the attractiveness of shops.
-----Output-----
- For each test case, output a single line containing the minimal possible velocity at the beginning.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10^5
- 1 ≤ Wi ≤ 10^6
-----Example-----
Input:
2
5
6 5 4 3 2
5
3 4 3 1 1
Output:
6
5
-----Explanation-----
Example case 1.
If we choose velocity 6, on the first step we have 6 >= 6 everything is OK, then we should decrease the velocity to 5 and on the 2nd segment we'll receive 5 >= 5, again OK, and so on.
Example case 2.
If we choose velocity 4, the promanade will be ruined on the 2nd step (we sould decrease our velocity, so the maximal possible will be 3 which is less than 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.
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?
Input
The first line contains the only integer n (0 ≤ n ≤ 10100000). It is guaranteed that n doesn't contain any leading zeroes.
Output
Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.
Examples
Input
0
Output
0
Input
10
Output
1
Input
991
Output
3
Note
In the first sample the number already is one-digit — Herald can't cast a spell.
The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.
The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
-----Input-----
The input contains a single integer a (10 ≤ a ≤ 999).
-----Output-----
Output 0 or 1.
-----Examples-----
Input
13
Output
1
Input
927
Output
1
Input
48
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.
In the board game Talisman, when two players enter combat the outcome is decided by a combat score, equal to the players power plus any modifiers plus the roll of a standard 1-6 dice. The player with the highest combat score wins and the opposing player loses a life. In the case of a tie combat ends with neither player losing a life.
For example:
```
Player 1: 5 Power, 0 Modifier
Player 2: 3 Power, 2 Modifier
Player 1 rolls a 4, Player 2 rolls a 2.
(5 + 0 + 4) -> (3 + 2 + 2)
Player 1 wins (9 > 7)
```
Your task is to write a method that calculates the required roll for the player to win.
The player and enemy stats are given as an array in the format:
```python
[power, modifier]
```
For example for the examples used above the stats would be given as:
```python
get_required([5, 0], [3, 2]) # returns 'Random'
```
If the player has at least 6 more power (including modifiers) than the enemy they automatically wins the fight, as the enemy's combat score couldn't possibly exceed the player's. In this instance the method should return "Auto-win".
For example:
```python
get_required([9, 0], [2, 1]) # returns 'Auto-win' as the enemy can't possibly win
```
If the enemy has at least 6 more power (including modifiers) than the player they automatically wins the fight, as the player's combat score couldn't possibly exceed the enemy's. In this instance the method should return "Auto-lose".
For example:
```python
get_required([2, 1], [9, 0]) # returns 'Auto-lose' as the player can't possibly win
```
If the player and enemy have the same power (including modifiers) the outcome is purely down to the dice roll, and hence would be considered completely random. In this instance the method should return "Random".
For example (as above):
```python
get_required([5, 0], [3, 2]) # returns 'Random' as it is purely down to the dice roll
```
If the player has greater power than the enemy (including modifiers) the player could guarantee a win by rolling a high enough number on the dice. In this instance the method should return a range equal to the numbers which would guarantee victory for the player.
```python
get_required([6, 0], [2, 2]) # returns '(5..6)' as rolling a 5 or 6 would mean the enemy could not win
get_required([7, 1], [2, 2]) # returns '(3..6)' as rolling anything 3 through 6 would mean the enemy could not win
```
If the player has less power than the enemy (including modifiers) the player can only win if the enemy rolls a low enough number, providing they then roll a high enough number. In this instance the method should return a range equal to the numbers which would allow the player a chance to win.
```python
get_required([4, 0], [6, 0]) # returns '(1..3)' as this would be the only outcome for which the player could still win
get_required([1, 1], [6, 0]) # returns '(1..1)' as this would be the only outcome for which the player could still win
```
If the better case scenario for the player is to hope for a tie, then return `"Pray for a tie!"`.
```python
get_required([7, 2], [6, 8]) # returns "Pray for a tie!"
```
Write your solution by modifying this code:
```python
def get_required(player,enemy):
```
Your solution should implemented in the function "get_required". 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.
No Story
No Description
Only by Thinking and Testing
Look at the results of the testcases, and guess the code!
---
## Series:
01. [A and B?](http://www.codewars.com/kata/56d904db9963e9cf5000037d)
02. [Incomplete string](http://www.codewars.com/kata/56d9292cc11bcc3629000533)
03. [True or False](http://www.codewars.com/kata/56d931ecc443d475d5000003)
04. [Something capitalized](http://www.codewars.com/kata/56d93f249c844788bc000002)
05. [Uniq or not Uniq](http://www.codewars.com/kata/56d949281b5fdc7666000004)
06. [Spatiotemporal index](http://www.codewars.com/kata/56d98b555492513acf00077d)
07. [Math of Primary School](http://www.codewars.com/kata/56d9b46113f38864b8000c5a)
08. [Math of Middle school](http://www.codewars.com/kata/56d9c274c550b4a5c2000d92)
09. [From nothingness To nothingness](http://www.codewars.com/kata/56d9cfd3f3928b4edd000021)
10. [Not perfect? Throw away!](http://www.codewars.com/kata/56dae2913cb6f5d428000f77)
11. [Welcome to take the bus](http://www.codewars.com/kata/56db19703cb6f5ec3e001393)
12. [A happy day will come](http://www.codewars.com/kata/56dc41173e5dd65179001167)
13. [Sum of 15(Hetu Luosliu)](http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356)
14. [Nebula or Vortex](http://www.codewars.com/kata/56dd3dd94c9055a413000b22)
15. [Sport Star](http://www.codewars.com/kata/56dd927e4c9055f8470013a5)
16. [Falsetto Rap Concert](http://www.codewars.com/kata/56de38c1c54a9248dd0006e4)
17. [Wind whispers](http://www.codewars.com/kata/56de4d58301c1156170008ff)
18. [Mobile phone simulator](http://www.codewars.com/kata/56de82fb9905a1c3e6000b52)
19. [Join but not join](http://www.codewars.com/kata/56dfce76b832927775000027)
20. [I hate big and small](http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7)
21. [I want to become diabetic ;-)](http://www.codewars.com/kata/56e0e065ef93568edb000731)
22. [How many blocks?](http://www.codewars.com/kata/56e0f1dc09eb083b07000028)
23. [Operator hidden in a string](http://www.codewars.com/kata/56e1161fef93568228000aad)
24. [Substring Magic](http://www.codewars.com/kata/56e127d4ef93568228000be2)
25. [Report about something](http://www.codewars.com/kata/56eccc08b9d9274c300019b9)
26. [Retention and discard I](http://www.codewars.com/kata/56ee0448588cbb60740013b9)
27. [Retention and discard II](http://www.codewars.com/kata/56eee006ff32e1b5b0000c32)
28. [How many "word"?](http://www.codewars.com/kata/56eff1e64794404a720002d2)
29. [Hail and Waterfall](http://www.codewars.com/kata/56f167455b913928a8000c49)
30. [Love Forever](http://www.codewars.com/kata/56f214580cd8bc66a5001a0f)
31. [Digital swimming pool](http://www.codewars.com/kata/56f25b17e40b7014170002bd)
32. [Archery contest](http://www.codewars.com/kata/56f4202199b3861b880013e0)
33. [The repair of parchment](http://www.codewars.com/kata/56f606236b88de2103000267)
34. [Who are you?](http://www.codewars.com/kata/56f6b4369400f51c8e000d64)
35. [Safe position](http://www.codewars.com/kata/56f7eb14f749ba513b0009c3)
---
## Special recommendation
Another series, innovative and interesting, medium difficulty. People who like challenges, can try these kata:
* [Play Tetris : Shape anastomosis](http://www.codewars.com/kata/56c85eebfd8fc02551000281)
* [Play FlappyBird : Advance Bravely](http://www.codewars.com/kata/56cd5d09aa4ac772e3000323)
Write your solution by modifying this code:
```python
def mystery(n):
```
Your solution should implemented in the function "mystery". 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.
Natasha travels around Mars in the Mars rover. But suddenly it broke down, namely — the logical scheme inside it. The scheme is an undirected tree (connected acyclic graph) with a root in the vertex $1$, in which every leaf (excluding root) is an input, and all other vertices are logical elements, including the root, which is output. One bit is fed to each input. One bit is returned at the output.
There are four types of logical elements: AND ($2$ inputs), OR ($2$ inputs), XOR ($2$ inputs), NOT ($1$ input). Logical elements take values from their direct descendants (inputs) and return the result of the function they perform. Natasha knows the logical scheme of the Mars rover, as well as the fact that only one input is broken. In order to fix the Mars rover, she needs to change the value on this input.
For each input, determine what the output will be if Natasha changes this input.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 10^6$) — the number of vertices in the graph (both inputs and elements).
The $i$-th of the next $n$ lines contains a description of $i$-th vertex: the first word "AND", "OR", "XOR", "NOT" or "IN" (means the input of the scheme) is the vertex type. If this vertex is "IN", then the value of this input follows ($0$ or $1$), otherwise follow the indices of input vertices of this element: "AND", "OR", "XOR" have $2$ inputs, whereas "NOT" has $1$ input. The vertices are numbered from one.
It is guaranteed that input data contains a correct logical scheme with an output produced by the vertex $1$.
-----Output-----
Print a string of characters '0' and '1' (without quotes) — answers to the problem for each input in the ascending order of their vertex indices.
-----Example-----
Input
10
AND 9 4
IN 1
IN 1
XOR 6 5
AND 3 7
IN 0
NOT 10
IN 1
IN 1
AND 2 8
Output
10110
-----Note-----
The original scheme from the example (before the input is changed):
[Image]
Green indicates bits '1', yellow indicates bits '0'.
If Natasha changes the input bit $2$ to $0$, then the output will be $1$.
If Natasha changes the input bit $3$ to $0$, then the output will be $0$.
If Natasha changes the input bit $6$ to $1$, then the output will be $1$.
If Natasha changes the input bit $8$ to $0$, then the output will be $1$.
If Natasha changes the input bit $9$ to $0$, then the output will be $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.
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
Write your solution by modifying this code:
```python
def find_it(seq):
```
Your solution should implemented in the function "find_it". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It is known that passages in Singer house are complex and intertwined. Let's define a Singer k-house as a graph built by the following process: take complete binary tree of height k and add edges from each vertex to all its successors, if they are not yet present.
<image> Singer 4-house
Count the number of non-empty paths in Singer k-house which do not pass the same vertex twice. Two paths are distinct if the sets or the orders of visited vertices are different. Since the answer can be large, output it modulo 109 + 7.
Input
The only line contains single integer k (1 ≤ k ≤ 400).
Output
Print single integer — the answer for the task modulo 109 + 7.
Examples
Input
2
Output
9
Input
3
Output
245
Input
20
Output
550384565
Note
There are 9 paths in the first example (the vertices are numbered on the picture below): 1, 2, 3, 1-2, 2-1, 1-3, 3-1, 2-1-3, 3-1-2.
<image> Singer 2-house
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This morning, Roman woke up and opened the browser with $n$ opened tabs numbered from $1$ to $n$. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this by closing every $k$-th ($2 \leq k \leq n - 1$) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be $b$) and then close all tabs with numbers $c = b + i \cdot k$ that satisfy the following condition: $1 \leq c \leq n$ and $i$ is an integer (it may be positive, negative or zero).
For example, if $k = 3$, $n = 14$ and Roman chooses $b = 8$, then he will close tabs with numbers $2$, $5$, $8$, $11$ and $14$.
After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it $e$) and the amount of remaining social network tabs ($s$). Help Roman to calculate the maximal absolute value of the difference of those values $|e - s|$ so that it would be easy to decide what to do next.
-----Input-----
The first line contains two integers $n$ and $k$ ($2 \leq k < n \leq 100$) — the amount of tabs opened currently and the distance between the tabs closed.
The second line consists of $n$ integers, each of them equal either to $1$ or to $-1$. The $i$-th integer denotes the type of the $i$-th tab: if it is equal to $1$, this tab contains information for the test, and if it is equal to $-1$, it's a social network tab.
-----Output-----
Output a single integer — the maximum absolute difference between the amounts of remaining tabs of different types $|e - s|$.
-----Examples-----
Input
4 2
1 1 -1 1
Output
2
Input
14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1
Output
9
-----Note-----
In the first example we can choose $b = 1$ or $b = 3$. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, $e = 2$ and $s = 0$ and $|e - s| = 2$.
In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly: It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains). There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false.
If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.
-----Input-----
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n, a ≠ b).
-----Output-----
The output consists of one line, containing either yes or no depending on whether the nervous system is valid.
-----Examples-----
Input
4 4
1 2
2 3
3 1
4 1
Output
no
Input
6 5
1 2
2 3
3 4
4 5
3 6
Output
yes
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
* There are n knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to n.
* The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament.
* After the i-th fight among all participants of the fight only one knight won — the knight number xi, he continued participating in the tournament. Other knights left the tournament.
* The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.
Write the code that calculates for each knight, the name of the knight that beat him.
Input
The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ 3·105) — the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≤ li < ri ≤ n; li ≤ xi ≤ ri) — the description of the i-th fight.
It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.
Output
Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.
Examples
Input
4 3
1 2 1
1 3 3
1 4 4
Output
3 1 4 0
Input
8 4
3 5 4
3 7 6
2 8 8
1 8 1
Output
0 8 4 6 4 8 6 1
Note
Consider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to use the Amidakuji to improve luck by gaining the ability to read the future. Of course, not only relying on intuition, but also detailed probability calculation is indispensable.
The Amidakuji we consider this time consists of N vertical bars with a length of H + 1 cm. The rabbit looks at the top of the stick and chooses one of the N. At the bottom of the bar, "hit" is written only at the location of the Pth bar from the left. The Amidakuji contains several horizontal bars. Consider the following conditions regarding the arrangement of horizontal bars.
* Each horizontal bar is at a height of a centimeter from the top of the vertical bar, where a is an integer greater than or equal to 1 and less than or equal to H.
* Each horizontal bar connects only two adjacent vertical bars.
* There are no multiple horizontal bars at the same height.
The rabbit drew M horizontal bars to satisfy these conditions. Unfortunately, the rabbit has a good memory, so I remember all the hit positions and the positions of the horizontal bars, so I can't enjoy the Amidakuji. So I decided to have my friend's cat add more horizontal bars.
First, the rabbit chooses one of the N sticks, aiming for a hit. After that, the cat performs the following operations exactly K times.
* Randomly select one of the locations that meet the conditions specified above even if a horizontal bar is added. Here, it is assumed that every place is selected with equal probability. Add a horizontal bar at the selected location.
Then, it is determined whether the stick selected by the rabbit was a hit. The way to follow the bars is the same as the normal Amidakuji (every time you meet a horizontal bar, you move to the next vertical bar). Rabbits want to have a high probability of winning as much as possible.
Input
H N P M K
A1 B1
...
AM BM
In Ai, Bi (1 ≤ i ≤ M), the i-th horizontal bar drawn by the rabbit is at a height of Ai centimeters from the top of the vertical bar, and the second vertical bar from the left and Bi from the left. + An integer that represents connecting the first vertical bar.
2 ≤ H ≤ 500, 2 ≤ N ≤ 100, 1 ≤ P ≤ N, 1 ≤ M ≤ 100, 1 ≤ K ≤ 100, M + K ≤ H, 1 ≤ A1 <A2 <... <AM ≤ H, Satisfy 1 ≤ Bi ≤ N-1.
Output
Output the probability of winning in one line when the rabbit chooses a stick so that the probability of winning is maximized. Absolute errors of 10-6 or less are allowed.
Examples
Input
9 4 3 2 1
2 1
7 3
Output
0.571428571
Input
9 4 3 2 3
2 1
7 3
Output
0.375661376
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a_1, a_2, ..., a_{n} - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ a_{i} ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + a_{i}), and one can travel from cell i to cell (i + a_{i}) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + a_{i}) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ a_{i} ≤ n - i one can't leave the Line World using portals.
Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
-----Input-----
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 10^4) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to.
The second line contains n - 1 space-separated integers a_1, a_2, ..., a_{n} - 1 (1 ≤ a_{i} ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
-----Output-----
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
-----Examples-----
Input
8 4
1 2 1 2 1 2 1
Output
YES
Input
8 5
1 2 1 2 1 1 1
Output
NO
-----Note-----
In the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.
In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!
Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles — one bottle of each kind. We know that the volume of milk in each bottle equals w.
When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it?
Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!
Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.
Input
The only input data file contains three integers n, w and m (1 ≤ n ≤ 50, 100 ≤ w ≤ 1000, 2 ≤ m ≤ 50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company.
Output
Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO".
If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (v > 0) units of milk were poured into the i-th cup from bottle b (1 ≤ b ≤ n). All numbers b on each line should be different.
If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.
Examples
Input
2 500 3
Output
YES
1 333.333333
2 333.333333
2 166.666667 1 166.666667
Input
4 100 5
Output
YES
3 20.000000 4 60.000000
1 80.000000
4 40.000000 2 40.000000
3 80.000000
2 60.000000 1 20.000000
Input
4 100 7
Output
NO
Input
5 500 2
Output
YES
4 250.000000 5 500.000000 2 500.000000
3 500.000000 1 500.000000 4 250.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.
Americans are odd people: in their buildings, the first floor is actually the ground floor and there is no 13th floor (due to superstition).
Write a function that given a floor in the american system returns the floor in the european system.
With the 1st floor being replaced by the ground floor and the 13th floor being removed, the numbers move down to take their place. In case of above 13, they move down by two because there are two omitted numbers below them.
Basements (negatives) stay the same as the universal level.
[More information here](https://en.wikipedia.org/wiki/Storey#European_scheme)
## Examples
```
1 => 0
0 => 0
5 => 4
15 => 13
-3 => -3
```
Write your solution by modifying this code:
```python
def get_real_floor(n):
```
Your solution should implemented in the function "get_real_floor". 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.
Example
Input
5
Output
5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. [Image]
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x_1 < x_2 < ... < x_{k} where p matches s. More formally, for each x_{i} (1 ≤ i ≤ k) he condition s_{x}_{i}s_{x}_{i} + 1... s_{x}_{i} + |p| - 1 = p is fullfilled.
Then Malekas wrote down one of subsequences of x_1, x_2, ... x_{k} (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).
After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.
Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.
Answer can be very large, so Tavas wants you to print the answer modulo 10^9 + 7.
-----Input-----
The first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1 ≤ n ≤ 10^6 and 0 ≤ m ≤ n - |p| + 1).
The second line contains string p (1 ≤ |p| ≤ n).
The next line contains m space separated integers y_1, y_2, ..., y_{m}, Malekas' subsequence (1 ≤ y_1 < y_2 < ... < y_{m} ≤ n - |p| + 1).
-----Output-----
In a single line print the answer modulo 1000 000 007.
-----Examples-----
Input
6 2
ioi
1 3
Output
26
Input
5 2
ioi
1 2
Output
0
-----Note-----
In the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy.
Here |x| denotes the length of string x.
Please note that it's possible that there is no such string (answer is 0).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer sequence of length N, a = {a_1, a_2, …, a_N}, and an integer K.
a has N(N+1)/2 non-empty contiguous subsequences, {a_l, a_{l+1}, …, a_r} (1 ≤ l ≤ r ≤ N). Among them, how many have an arithmetic mean that is greater than or equal to K?
Constraints
* All input values are integers.
* 1 ≤ N ≤ 2 \times 10^5
* 1 ≤ K ≤ 10^9
* 1 ≤ a_i ≤ 10^9
Input
Input is given from Standard Input in the following format:
N K
a_1
a_2
:
a_N
Output
Print the number of the non-empty contiguous subsequences with an arithmetic mean that is greater than or equal to K.
Examples
Input
3 6
7
5
7
Output
5
Input
1 2
1
Output
0
Input
7 26
10
20
30
40
30
20
10
Output
13
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp loves ciphers. He has invented his own cipher called Right-Left.
Right-Left cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \dots s_{n}$ Polycarp uses the following algorithm: he writes down $s_1$, he appends the current word with $s_2$ (i.e. writes down $s_2$ to the right of the current result), he prepends the current word with $s_3$ (i.e. writes down $s_3$ to the left of the current result), he appends the current word with $s_4$ (i.e. writes down $s_4$ to the right of the current result), he prepends the current word with $s_5$ (i.e. writes down $s_5$ to the left of the current result), and so on for each position until the end of $s$.
For example, if $s$="techno" the process is: "t" $\to$ "te" $\to$ "cte" $\to$ "cteh" $\to$ "ncteh" $\to$ "ncteho". So the encrypted $s$="techno" is "ncteho".
Given string $t$ — the result of encryption of some string $s$. Your task is to decrypt it, i.e. find the string $s$.
-----Input-----
The only line of the input contains $t$ — the result of encryption of some string $s$. It contains only lowercase Latin letters. The length of $t$ is between $1$ and $50$, inclusive.
-----Output-----
Print such string $s$ that after encryption it equals $t$.
-----Examples-----
Input
ncteho
Output
techno
Input
erfdcoeocs
Output
codeforces
Input
z
Output
z
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this Kata you need to write the method SharedBits that returns true if 2 integers share at least two '1' bits. For simplicity assume that all numbers are positive
For example
int seven = 7; //0111
int ten = 10; //1010
int fifteen = 15; //1111
SharedBits(seven, ten); //false
SharedBits(seven, fifteen); //true
SharedBits(ten, fifteen); //true
- seven and ten share only a single '1' (at index 3)
- seven and fifteen share 3 bits (at indexes 1, 2, and 3)
- ten and fifteen share 2 bits (at indexes 0 and 2)
Hint: you can do this with just string manipulation, but binary operators will make your life much easier.
Write your solution by modifying this code:
```python
def shared_bits(a, b):
```
Your solution should implemented in the function "shared_bits". 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 is an integer N. Snuke will choose integers s_1, s_2, n_1, n_2, u_1, u_2, k_1, k_2, e_1, and e_2 so that all of the following six conditions will be satisfied:
* 0 \leq s_1 < s_2
* 0 \leq n_1 < n_2
* 0 \leq u_1 < u_2
* 0 \leq k_1 < k_2
* 0 \leq e_1 < e_2
* s_1 + s_2 + n_1 + n_2 + u_1 + u_2 + k_1 + k_2 + e_1 + e_2 \leq N
For every possible choice (s_1,s_2,n_1,n_2,u_1,u_2,k_1,k_2,e_1,e_2), compute (s_2 − s_1)(n_2 − n_1)(u_2 − u_1)(k_2 - k_1)(e_2 - e_1), and find the sum of all computed values, modulo (10^{9} +7).
Solve this problem for each of the T test cases given.
Constraints
* All values in input are integers.
* 1 \leq T \leq 100
* 1 \leq N \leq 10^{9}
Input
Input is given from Standard Input in the following format:
T
\mathrm{case}_1
\vdots
\mathrm{case}_T
Each case is given in the following format:
N
Output
Print T lines. The i-th line should contain the answer to the i-th test case.
Example
Input
4
4
6
10
1000000000
Output
0
11
4598
257255556
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr Leicester's cheese factory is the pride of the East Midlands, but he's feeling a little blue. It's the time of the year when **the taxman is coming round to take a slice of his cheddar** - and the final thing he has to work out is how much money he's spending on his staff. Poor Mr Leicester can barely sleep he's so stressed. Can you help?
- Mr Leicester **employs 4 staff**, who together make **10 wheels of cheese every 6 minutes**.
- Worker pay is calculated on **how many wheels of cheese they produce in a day**.
- Mr Leicester pays his staff according to the UK living wage, which is currently **£8.75p an hour**. There are **100 pence (p) to the UK pound (£)**.
The input for function payCheese will be provided as an array of five integers, one for each amount of cheese wheels produced each day.
When the workforce don't work a nice integer number of minutes - much to the chagrin of the company accountant - Mr Leicester very generously **rounds up to the nearest hour** at the end of the week (*not the end of each day*). Which means if the workers make 574 wheels on each day of the week, they're each paid 29 hours for the week (28.699 hours rounded up) and not 30 (6 hours a day rounded up * 5).
The return value should be a string (with the £ included) of the **total £ of staff wages for that week.**
Write your solution by modifying this code:
```python
def pay_cheese(arr):
```
Your solution should implemented in the function "pay_cheese". 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.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
The following are examples of expected output values:
```python
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3
```
```if:nasm
char \*rgb(int r, int g, int b, char \*outp)
```
Write your solution by modifying this code:
```python
def rgb(r, g, b):
```
Your solution should implemented in the function "rgb". 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.
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.
Polycarp decided to store the hash of the password, generated by the following algorithm: take the password $p$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $p'$ ($p'$ can still be equal to $p$); generate two random strings, consisting of lowercase Latin letters, $s_1$ and $s_2$ (any of these strings can be empty); the resulting hash $h = s_1 + p' + s_2$, where addition is string concatenation.
For example, let the password $p =$ "abacaba". Then $p'$ can be equal to "aabcaab". Random strings $s1 =$ "zyx" and $s2 =$ "kjh". Then $h =$ "zyxaabcaabkjh".
Note that no letters could be deleted or added to $p$ to obtain $p'$, only the order could be changed.
Now Polycarp asks you to help him to implement the password check module. Given the password $p$ and the hash $h$, check that $h$ can be the hash for the password $p$.
Your program should answer $t$ independent test cases.
-----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 a non-empty string $p$, consisting of lowercase Latin letters. The length of $p$ does not exceed $100$.
The second line of each test case contains a non-empty string $h$, consisting of lowercase Latin letters. The length of $h$ does not exceed $100$.
-----Output-----
For each test case print the answer to it — "YES" if the given hash $h$ could be obtained from the given password $p$ or "NO" otherwise.
-----Example-----
Input
5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten
Output
YES
YES
NO
YES
NO
-----Note-----
The first test case is explained in the statement.
In the second test case both $s_1$ and $s_2$ are empty and $p'=$ "threetwoone" is $p$ shuffled.
In the third test case the hash could not be obtained from the password.
In the fourth test case $s_1=$ "n", $s_2$ is empty and $p'=$ "one" is $p$ shuffled (even thought it stayed the same).
In the fifth test case the hash could not be obtained from the password.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.
Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins.
After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.
Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.
Help Roma find the maximum profit of the grind.
Input
The first line contains three integers n, m, and p (1 ≤ n, m, p ≤ 2 ⋅ 10^5) — the number of available weapons, armor sets and monsters respectively.
The following n lines describe available weapons. The i-th of these lines contains two integers a_i and ca_i (1 ≤ a_i ≤ 10^6, 1 ≤ ca_i ≤ 10^9) — the attack modifier and the cost of the weapon i.
The following m lines describe available armor sets. The j-th of these lines contains two integers b_j and cb_j (1 ≤ b_j ≤ 10^6, 1 ≤ cb_j ≤ 10^9) — the defense modifier and the cost of the armor set j.
The following p lines describe monsters. The k-th of these lines contains three integers x_k, y_k, z_k (1 ≤ x_k, y_k ≤ 10^6, 1 ≤ z_k ≤ 10^3) — defense, attack and the number of coins of the monster k.
Output
Print a single integer — the maximum profit of the grind.
Example
Input
2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.