question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
It is September 9 in Japan now.
You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?
-----Constraints-----
- 10≤N≤99
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
If 9 is contained in the decimal notation of N, print Yes; if not, print No.
-----Sample Input-----
29
-----Sample Output-----
Yes
The one's digit of 29 is 9.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two binary strings $a$ and $b$ of the same length. You can perform the following two operations on the string $a$:
Swap any two bits at indices $i$ and $j$ respectively ($1 \le i, j \le n$), the cost of this operation is $|i - j|$, that is, the absolute difference between $i$ and $j$. Select any arbitrary index $i$ ($1 \le i \le n$) and flip (change $0$ to $1$ or $1$ to $0$) the bit at this index. The cost of this operation is $1$.
Find the minimum cost to make the string $a$ equal to $b$. It is not allowed to modify string $b$.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the length of the strings $a$ and $b$.
The second and third lines contain strings $a$ and $b$ respectively.
Both strings $a$ and $b$ have length $n$ and contain only '0' and '1'.
-----Output-----
Output the minimum cost to make the string $a$ equal to $b$.
-----Examples-----
Input
3
100
001
Output
2
Input
4
0101
0011
Output
1
-----Note-----
In the first example, one of the optimal solutions is to flip index $1$ and index $3$, the string $a$ changes in the following way: "100" $\to$ "000" $\to$ "001". The cost is $1 + 1 = 2$.
The other optimal solution is to swap bits and indices $1$ and $3$, the string $a$ changes then "100" $\to$ "001", the cost is also $|1 - 3| = 2$.
In the second example, the optimal solution is to swap bits at indices $2$ and $3$, the string $a$ changes as "0101" $\to$ "0011". The cost is $|2 - 3| = 1$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.
You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.
-----Input-----
The first line contains a single integer n — the number of items (1 ≤ n ≤ 10^5).
The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5) — the initial inventory numbers of the items.
-----Output-----
Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.
-----Examples-----
Input
3
1 3 2
Output
1 3 2
Input
4
2 2 3 3
Output
2 1 3 4
Input
1
2
Output
1
-----Note-----
In the first test the numeration is already a permutation, so there is no need to change anything.
In the second test there are two pairs of equal numbers, in each pair you need to replace one number.
In the third test you need to replace 2 by 1, as the numbering should start from one.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Santosh has a farm at Byteland. He has a very big family to look after. His life takes a sudden turn and he runs into a financial crisis. After giving all the money he has in his hand, he decides to sell his plots. The speciality of his land is that it is rectangular in nature. Santosh comes to know that he will get more money if he sells square shaped plots. So keeping this in mind, he decides to divide his land into minimum possible number of square plots, such that each plot has the same area, and the plots divide the land perfectly. He does this in order to get the maximum profit out of this.
So your task is to find the minimum number of square plots with the same area, that can be formed out of the rectangular land, such that they divide it perfectly.
-----Input-----
- The first line of the input contains $T$, the number of test cases. Then $T$ lines follow.
- The first and only line of each test case contains two space-separated integers, $N$ and $M$, the length and the breadth of the land, respectively.
-----Output-----
For each test case, print the minimum number of square plots with equal area, such that they divide the farm land perfectly, in a new line.
-----Constraints-----
$1 \le T \le 20$
$1 \le M \le 10000$
$1 \le N \le 10000$
-----Sample Input:-----
2
10 15
4 6
-----SampleOutput:-----
6
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.
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.
For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.
Write a program that will print the name of a man who will drink the n-th can.
Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.
Input
The input data consist of a single integer n (1 ≤ n ≤ 109).
It is guaranteed that the pretests check the spelling of all the five names, that is, that they contain all the five possible answers.
Output
Print the single line — the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1. Please note that you should spell the names like this: "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" (without the quotes). In that order precisely the friends are in the queue initially.
Examples
Input
1
Output
Sheldon
Input
6
Output
Sheldon
Input
1802
Output
Penny
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alperen has two strings, $s$ and $t$ which are both initially equal to "a".
He will perform $q$ operations of two types on the given strings:
$1 \;\; k \;\; x$ — Append the string $x$ exactly $k$ times at the end of string $s$. In other words, $s := s + \underbrace{x + \dots + x}_{k \text{ times}}$.
$2 \;\; k \;\; x$ — Append the string $x$ exactly $k$ times at the end of string $t$. In other words, $t := t + \underbrace{x + \dots + x}_{k \text{ times}}$.
After each operation, determine if it is possible to rearrange the characters of $s$ and $t$ such that $s$ is lexicographically smaller$^{\dagger}$ than $t$.
Note that the strings change after performing each operation and don't go back to their initial states.
$^{\dagger}$ Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string $p$ is lexicographically smaller than string $q$ if there exists a position $i$ such that $p_i < q_i$, and for all $j < i$, $p_j = q_j$. If no such $i$ exists, then $p$ is lexicographically smaller than $q$ if the length of $p$ is less than the length of $q$. For example, ${abdc} < {abe}$ and ${abc} < {abcd}$, where we write $p < q$ if $p$ is lexicographically smaller than $q$.
-----Input-----
The first line of the input contains an integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases.
The first line of each test case contains an integer $q$ $(1 \leq q \leq 10^5)$ — the number of operations Alperen will perform.
Then $q$ lines follow, each containing two positive integers $d$ and $k$ ($1 \leq d \leq 2$; $1 \leq k \leq 10^5$) and a non-empty string $x$ consisting of lowercase English letters — the type of the operation, the number of times we will append string $x$ and the string we need to append respectively.
It is guaranteed that the sum of $q$ over all test cases doesn't exceed $10^5$ and that the sum of lengths of all strings $x$ in the input doesn't exceed $5 \cdot 10^5$.
-----Output-----
For each operation, output "YES", if it is possible to arrange the elements in both strings in such a way that $s$ is lexicographically smaller than $t$ and "NO" otherwise.
-----Examples-----
Input
3
5
2 1 aa
1 2 a
2 3 a
1 2 b
2 3 abca
2
1 5 mihai
2 2 buiucani
3
1 5 b
2 3 a
2 4 paiu
Output
YES
NO
YES
NO
YES
NO
YES
NO
NO
YES
-----Note-----
In the first test case, the strings are initially $s = $ "a" and $t = $ "a".
After the first operation the string $t$ becomes "aaa". Since "a" is already lexicographically smaller than "aaa", the answer for this operation should be "YES".
After the second operation string $s$ becomes "aaa", and since $t$ is also equal to "aaa", we can't arrange $s$ in any way such that it is lexicographically smaller than $t$, so the answer is "NO".
After the third operation string $t$ becomes "aaaaaa" and $s$ is already lexicographically smaller than it so the answer is "YES".
After the fourth operation $s$ becomes "aaabb" and there is no way to make it lexicographically smaller than "aaaaaa" so the answer is "NO".
After the fifth operation the string $t$ becomes "aaaaaaabcaabcaabca", and we can rearrange the strings to: "bbaaa" and "caaaaaabcaabcaabaa" so that $s$ is lexicographically smaller than $t$, so we should answer "YES".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
-----Input-----
The first line contains two integers n_{A}, n_{B} (1 ≤ n_{A}, n_{B} ≤ 10^5), separated by a space — the sizes of arrays A and B, correspondingly.
The second line contains two integers k and m (1 ≤ k ≤ n_{A}, 1 ≤ m ≤ n_{B}), separated by a space.
The third line contains n_{A} numbers a_1, a_2, ... a_{n}_{A} ( - 10^9 ≤ a_1 ≤ a_2 ≤ ... ≤ a_{n}_{A} ≤ 10^9), separated by spaces — elements of array A.
The fourth line contains n_{B} integers b_1, b_2, ... b_{n}_{B} ( - 10^9 ≤ b_1 ≤ b_2 ≤ ... ≤ b_{n}_{B} ≤ 10^9), separated by spaces — elements of array B.
-----Output-----
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
-----Examples-----
Input
3 3
2 1
1 2 3
3 4 5
Output
YES
Input
3 3
3 3
1 2 3
3 4 5
Output
NO
Input
5 2
3 1
1 1 1 1 1
2 2
Output
YES
-----Note-----
In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).
In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: $3 < 3$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.
You can rearrange these children just one time in any order you like.
When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.
Find the maximum total happiness points the children can earn.
-----Constraints-----
- 2 \leq N \leq 2000
- 1 \leq A_i \leq 10^9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
-----Output-----
Print the maximum total happiness points the children can earn.
-----Sample Input-----
4
1 3 4 2
-----Sample Output-----
20
If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement.
We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct.
* binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$
* heap property. If $v$ is a child of $u$, then $v.priority < u.priority$
This combination of properties is why the tree is called Treap (tree + heap).
An example of Treap is shown in the following figure.
<image>
Insert
To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted.
<image>
It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property.
<image>
The rotate operations can be implemented as follows.
rightRotate(Node t)
Node s = t.left
t.left = s.right
s.right = t
return s // the new root of subtree
|
leftRotate(Node t)
Node s = t.right
t.right = s.left
s.left = t
return s // the new root of subtree
---|---
The following figure shows processes of the rotate operations after the insert operation to maintain the properties.
<image>
The insert operation with rotate operations can be implemented as follows.
insert(Node t, int key, int priority) // search the corresponding place recursively
if t == NIL
return Node(key, priority) // create a new node when you reach a leaf
if key == t.key
return t // ignore duplicated keys
if key < t.key // move to the left child
t.left = insert(t.left, key, priority) // update the pointer to the left child
if t.priority < t.left.priority // rotate right if the left child has higher priority
t = rightRotate(t)
else // move to the right child
t.right = insert(t.right, key, priority) // update the pointer to the right child
if t.priority < t.right.priority // rotate left if the right child has higher priority
t = leftRotate(t)
return t
Delete
To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows.
delete(Node t, int key) // seach the target recursively
if t == NIL
return NIL
if key < t.key // search the target recursively
t.left = delete(t.left, key)
else if key > t.key
t.right = delete(t.right, key)
else
return _delete(t, key)
return t
_delete(Node t, int key) // if t is the target node
if t.left == NIL && t.right == NIL // if t is a leaf
return NIL
else if t.left == NIL // if t has only the right child, then perform left rotate
t = leftRotate(t)
else if t.right == NIL // if t has only the left child, then perform right rotate
t = rightRotate(t)
else // if t has both the left and right child
if t.left.priority > t.right.priority // pull up the child with higher priority
t = rightRotate(t)
else
t = leftRotate(t)
return delete(t, key)
Write a program which performs the following operations to a Treap $T$ based on the above described algorithm.
* insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$.
* find ($k$): Report whether $T$ has a node containing $k$.
* delete ($k$): Delete a node containing $k$.
* print(): Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.
Constraints
* The number of operations $ \leq 200,000$
* $0 \leq k, p \leq 2,000,000,000$
* The height of the binary tree does not exceed 50 if you employ the above algorithm
* The keys in the binary search tree are all different.
* The priorities in the binary search tree are all different.
* The size of output $\leq 10$ MB
Input
In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $k$ or print are given.
Output
For each find($k$) operation, print "yes" if $T$ has a node containing $k$, "no" if not.
In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.
Example
Input
16
insert 35 99
insert 3 80
insert 1 53
insert 14 25
insert 80 76
insert 42 3
insert 86 47
insert 21 12
insert 7 10
insert 6 90
print
find 21
find 22
delete 35
delete 99
print
Output
1 3 6 7 14 21 35 42 80 86
35 6 3 1 14 7 21 80 42 86
yes
no
1 3 6 7 14 21 42 80 86
6 3 1 80 14 7 21 42 86
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers.
If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} K ⌉ bits to store each value. It then takes nk bits to store the whole file.
To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers l ≤ r, and after that all intensity values are changed in the following way: if the intensity value is within the range [l;r], we don't change it. If it is less than l, we change it to l; if it is greater than r, we change it to r. You can see that we lose some low and some high intensities.
Your task is to apply this compression in such a way that the file fits onto a disk of size I bytes, and the number of changed elements in the array is minimal possible.
We remind you that 1 byte contains 8 bits.
k = ⌈ log_{2} K ⌉ is the smallest integer such that K ≤ 2^{k}. In particular, if K = 1, then k = 0.
Input
The first line contains two integers n and I (1 ≤ n ≤ 4 ⋅ 10^{5}, 1 ≤ I ≤ 10^{8}) — the length of the array and the size of the disk in bytes, respectively.
The next line contains n integers a_{i} (0 ≤ a_{i} ≤ 10^{9}) — the array denoting the sound file.
Output
Print a single integer — the minimal possible number of changed elements.
Examples
Input
6 1
2 1 2 3 4 3
Output
2
Input
6 2
2 1 2 3 4 3
Output
0
Input
6 1
1 1 2 2 3 3
Output
2
Note
In the first example we can choose l=2, r=3. The array becomes 2 2 2 3 3 3, the number of distinct elements is K=2, and the sound file fits onto the disk. Only two values are changed.
In the second example the disk is larger, so the initial file fits it and no changes are required.
In the third example we have to change both 1s or both 3s.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N squares aligned in a row. The i-th square from the left contains an integer a_i.
Initially, all the squares are white. Snuke will perform the following operation some number of times:
* Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares are overwritten.
After Snuke finishes performing the operation, the score will be calculated as the sum of the integers contained in the black squares. Find the maximum possible score.
Constraints
* 1≤N≤10^5
* 1≤K≤N
* a_i is an integer.
* |a_i|≤10^9
Input
The input is given from Standard Input in the following format:
N K
a_1 a_2 ... a_N
Output
Print the maximum possible score.
Examples
Input
5 3
-10 10 -10 10 -10
Output
10
Input
4 2
10 -10 -10 10
Output
20
Input
1 1
-10
Output
0
Input
10 5
5 -4 -5 -8 -4 7 2 -4 0 7
Output
17
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $n$ non-negative integers.
If there are exactly $K$ distinct values in the array, then we need $k = \lceil \log_{2} K \rceil$ bits to store each value. It then takes $nk$ bits to store the whole file.
To reduce the memory consumption we need to apply some compression. One common way is to reduce the number of possible intensity values. We choose two integers $l \le r$, and after that all intensity values are changed in the following way: if the intensity value is within the range $[l;r]$, we don't change it. If it is less than $l$, we change it to $l$; if it is greater than $r$, we change it to $r$. You can see that we lose some low and some high intensities.
Your task is to apply this compression in such a way that the file fits onto a disk of size $I$ bytes, and the number of changed elements in the array is minimal possible.
We remind you that $1$ byte contains $8$ bits.
$k = \lceil log_{2} K \rceil$ is the smallest integer such that $K \le 2^{k}$. In particular, if $K = 1$, then $k = 0$.
-----Input-----
The first line contains two integers $n$ and $I$ ($1 \le n \le 4 \cdot 10^{5}$, $1 \le I \le 10^{8}$) — the length of the array and the size of the disk in bytes, respectively.
The next line contains $n$ integers $a_{i}$ ($0 \le a_{i} \le 10^{9}$) — the array denoting the sound file.
-----Output-----
Print a single integer — the minimal possible number of changed elements.
-----Examples-----
Input
6 1
2 1 2 3 4 3
Output
2
Input
6 2
2 1 2 3 4 3
Output
0
Input
6 1
1 1 2 2 3 3
Output
2
-----Note-----
In the first example we can choose $l=2, r=3$. The array becomes 2 2 2 3 3 3, the number of distinct elements is $K=2$, and the sound file fits onto the disk. Only two values are changed.
In the second example the disk is larger, so the initial file fits it and no changes are required.
In the third example we have to change both 1s or both 3s.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integers 14 and 15, are contiguous (1 the difference between them, obvious) and have the same number of divisors.
```python
14 ----> 1, 2, 7, 14 (4 divisors)
15 ----> 1, 3, 5, 15 (4 divisors)
```
The next pair of contiguous integers with this property is 21 and 22.
```python
21 -----> 1, 3, 7, 21 (4 divisors)
22 -----> 1, 2, 11, 22 (4 divisors)
```
We have 8 pairs of integers below 50 having this property, they are:
```python
[[2, 3], [14, 15], [21, 22], [26, 27], [33, 34], [34, 35], [38, 39], [44, 45]]
```
Let's see now the integers that have a difference of 3 between them. There are seven pairs below 100:
```python
[[2, 5], [35, 38], [55, 58], [62, 65], [74, 77], [82, 85], [91, 94]]
```
Let's name, diff, the difference between two integers, next and prev, (diff = next - prev) and nMax, an upper bound of the range.
We need a special function, count_pairsInt(), that receives two arguments, diff and nMax and outputs the amount of pairs of integers that fulfill this property, all of them being smaller (not smaller or equal) than nMax.
Let's see it more clearly with examples.
```python
count_pairsInt(1, 50) -----> 8 (See case above)
count_pairsInt(3, 100) -----> 7 (See case above)
```
Happy coding!!!
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 graph of $n$ rows and $10^6 + 2$ columns, where rows are numbered from $1$ to $n$ and columns from $0$ to $10^6 + 1$:
Let's denote the node in the row $i$ and column $j$ by $(i, j)$.
Initially for each $i$ the $i$-th row has exactly one obstacle — at node $(i, a_i)$. You want to move some obstacles so that you can reach node $(n, 10^6+1)$ from node $(1, 0)$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $u$ or $v$ coins, as below:
If there is an obstacle in the node $(i, j)$, you can use $u$ coins to move it to $(i-1, j)$ or $(i+1, j)$, if such node exists and if there is no obstacle in that node currently.
If there is an obstacle in the node $(i, j)$, you can use $v$ coins to move it to $(i, j-1)$ or $(i, j+1)$, if such node exists and if there is no obstacle in that node currently.
Note that you can't move obstacles outside the grid. For example, you can't move an obstacle from $(1,1)$ to $(0,1)$.
Refer to the picture above for a better understanding.
Now you need to calculate the minimal number of coins you need to spend to be able to reach node $(n, 10^6+1)$ from node $(1, 0)$ by moving through edges of this graph without passing through obstacles.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.
The first line of each test case contains three integers $n$, $u$ and $v$ ($2 \le n \le 100$, $1 \le u, v \le 10^9$) — the number of rows in the graph and the numbers of coins needed to move vertically and horizontally respectively.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — where $a_i$ represents that the obstacle in the $i$-th row is in node $(i, a_i)$.
It's guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^4$.
-----Output-----
For each test case, output a single integer — the minimal number of coins you need to spend to be able to reach node $(n, 10^6+1)$ from node $(1, 0)$ by moving through edges of this graph without passing through obstacles.
It can be shown that under the constraints of the problem there is always a way to make such a trip possible.
-----Examples-----
Input
3
2 3 4
2 2
2 3 4
3 2
2 4 3
3 2
Output
7
3
3
-----Note-----
In the first sample, two obstacles are at $(1, 2)$ and $(2,2)$. You can move the obstacle on $(2, 2)$ to $(2, 3)$, then to $(1, 3)$. The total cost is $u+v = 7$ coins.
In the second sample, two obstacles are at $(1, 3)$ and $(2,2)$. You can move the obstacle on $(1, 3)$ to $(2, 3)$. The cost is $u = 3$ coins.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC.
For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers t_{i} and c_{i} — the receiving time (the second) and the number of the text messages, correspondingly.
Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:
If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue.
Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^3) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers t_{i} and c_{i} (1 ≤ t_{i}, c_{i} ≤ 10^6) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly.
It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, t_{i} < t_{i} + 1 for all integer i (1 ≤ i < n).
-----Output-----
In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.
-----Examples-----
Input
2
1 1
2 1
Output
3 1
Input
1
1000000 10
Output
1000010 10
Input
3
3 3
4 3
5 3
Output
12 7
-----Note-----
In the first test sample:
second 1: the first message has appeared in the queue, the queue's size is 1; second 2: the first message is sent, the second message has been received, the queue's size is 1; second 3: the second message is sent, the queue's size is 0,
Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's denote a function
$d(x, y) = \left\{\begin{array}{ll}{y - x,} & {\text{if}|x - y|> 1} \\{0,} & {\text{if}|x - y|\leq 1} \end{array} \right.$
You are given an array a consisting of n integers. You have to calculate the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — elements of the array.
-----Output-----
Print one integer — the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
-----Examples-----
Input
5
1 2 3 1 3
Output
4
Input
4
6 6 5 5
Output
0
Input
4
6 6 4 4
Output
-8
-----Note-----
In the first example:
d(a_1, a_2) = 0; d(a_1, a_3) = 2; d(a_1, a_4) = 0; d(a_1, a_5) = 2; d(a_2, a_3) = 0; d(a_2, a_4) = 0; d(a_2, a_5) = 0; d(a_3, a_4) = - 2; d(a_3, a_5) = 0; d(a_4, a_5) = 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 Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.
The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti — the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.
When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:
* the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n),
* the sum of the ti values of the remaining sculptures is maximized.
Help the Vice Rector to analyze the criticism — find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.
Input
The first input line contains an integer n (3 ≤ n ≤ 20000) — the initial number of sculptures. The second line contains a sequence of integers t1, t2, ..., tn, ti — the degree of the i-th sculpture's attractiveness ( - 1000 ≤ ti ≤ 1000). The numbers on the line are separated by spaces.
Output
Print the required maximum sum of the sculptures' attractiveness.
Examples
Input
8
1 2 -3 4 -5 5 2 3
Output
14
Input
6
1 -2 3 -4 5 -6
Output
9
Input
6
1 2 3 4 5 6
Output
21
Note
In the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 и 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.
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a_1, a_2, ..., a_{n}. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values a_{k} for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.
The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a_1, a_2, ..., a_{n}. It is guaranteed that each of those n values is either 0 or 1.
-----Output-----
Print an integer — the maximal number of 1s that can be obtained after exactly one move.
-----Examples-----
Input
5
1 0 0 1 0
Output
4
Input
4
1 0 0 1
Output
4
-----Note-----
In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1].
In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 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.
Takahashi is drawing a segment on grid paper.
From a certain square, a square that is x squares to the right and y squares above, is denoted as square (x, y).
When Takahashi draws a segment connecting the lower left corner of square (A, B) and the lower left corner of square (C, D), find the number of the squares crossed by the segment.
Here, the segment is said to cross a square if the segment has non-empty intersection with the region within the square, excluding the boundary.
Constraints
* 1 \leq A, B, C, D \leq 10^9
* At least one of A \neq C and B \neq D holds.
Input
The input is given from Standard Input in the following format:
A B C D
Output
Print the number of the squares crossed by the segment.
Examples
Input
1 1 3 4
Output
4
Input
2 3 10 7
Output
8
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins.
In a single strand of DNA you find 3 Reading frames, for example the following sequence:
```
AGGTGACACCGCAAGCCTTATATTAGC
```
will be decompose in:
```
Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC
Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC
Frame 3: AG·GTG·ACA·CCG·CAA·GCC·TTA·TAT·TAG·C
```
In a double strand DNA you find 3 more Reading frames base on the reverse complement-strand, given the previous DNA sequence, in the reverse complement ( A-->T, G-->C, T-->A, C-->G).
Due to the splicing of DNA strands and the fixed reading direction of a nucleotide strand, the reverse complement gets read from right to left
```
AGGTGACACCGCAAGCCTTATATTAGC
Reverse complement: TCCACTGTGGCGTTCGGAATATAATCG
reversed reverse frame: GCTAATATAAGGCTTGCGGTGTCACCT
```
You have:
```
Reverse Frame 1: GCT AAT ATA AGG CTT GCG GTG TCA CCT
reverse Frame 2: G CTA ATA TAA GGC TTG CGG TGT CAC CT
reverse Frame 3: GC TAA TAT AAG GCT TGC GGT GTC ACC T
```
You can find more information about the Open Reading frame in wikipedia just [here] (https://en.wikipedia.org/wiki/Reading_frame)
Given the [standard table of genetic code](http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi#SG1):
```
AAs = FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG
Base1 = TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
Base2 = TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
Base3 = TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
```
The tri-nucleotide TTT = F, TTC = F, TTA = L...
So our 6 frames will be translate as:
```
Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC
R * H R K P Y I S
Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC
G D T A S L I L
Frame 3: AG·GTG·ACA·CCG·CAA·GCC·TTA·TAT·TAG·C
V T P Q A L Y *
Reverse Frame 1: GCT AAT ATA AGG CTT GCG GTG TCA CCT
A N I R L A V S P
Reverse Frame 2: G CTA ATA TAA GGC TTG CGG TGT CAC CT
L I * G L R C H
Reverse Frame 3: GC TAA TAT AAG GCT TGC GGT GTC ACC T
* Y K A C G V T
```
In this kata you should create a function that translates DNA on all 6 frames, this function takes 2 arguments.
The first one is the DNA sequence the second one is an array of frame number for example if we want to translate in Frame 1 and Reverse 1 this array will be [1,-1]. Valid frames are 1, 2, 3 and -1, -2, -3.
The translation hash is available for you under a translation hash `$codons` [Ruby] or `codon` [other languages] (for example to access value of 'TTT' you should call $codons['TTT'] => 'F').
The function should return an array with all translation asked for, by default the function do the translation on all 6 frames.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya was delivered a string s, containing only digits. He needs to find a string that
* represents a lucky number without leading zeroes,
* is not empty,
* is contained in s as a substring the maximum number of times.
Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.
Input
The single line contains a non-empty string s whose length can range from 1 to 50, inclusive. The string only contains digits. The string can contain leading zeroes.
Output
In the only line print the answer to Petya's problem. If the sought string does not exist, print "-1" (without quotes).
Examples
Input
047
Output
4
Input
16
Output
-1
Input
472747
Output
7
Note
The lexicographical comparison of strings is performed by the < operator in the modern programming languages. String x is lexicographically less than string y either if x is a prefix of y, or exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of string a.
In the first sample three conditions are fulfilled for strings "4", "7" and "47". The lexicographically minimum one is "4".
In the second sample s has no substrings which are lucky numbers.
In the third sample the three conditions are only fulfilled for string "7".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ students in a university. The number of students is even. The $i$-th student has programming skill equal to $a_i$.
The coach wants to form $\frac{n}{2}$ teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal (otherwise they cannot understand each other and cannot form a team).
Students can solve problems to increase their skill. One solved problem increases the skill by one.
The coach wants to know the minimum total number of problems students should solve to form exactly $\frac{n}{2}$ teams (i.e. each pair of students should form a team). Your task is to find this number.
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 100$) — the number of students. It is guaranteed that $n$ is even.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the skill of the $i$-th student.
-----Output-----
Print one number — the minimum total number of problems students should solve to form exactly $\frac{n}{2}$ teams.
-----Examples-----
Input
6
5 10 2 3 14 5
Output
5
Input
2
1 100
Output
99
-----Note-----
In the first example the optimal teams will be: $(3, 4)$, $(1, 6)$ and $(2, 5)$, where numbers in brackets are indices of students. Then, to form the first team the third student should solve $1$ problem, to form the second team nobody needs to solve problems and to form the third team the second student should solve $4$ problems so the answer is $1 + 4 = 5$.
In the second example the first student should solve $99$ problems to form a team with the second one.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Inaka has a disc, the circumference of which is $n$ units. The circumference is equally divided by $n$ points numbered clockwise from $1$ to $n$, such that points $i$ and $i + 1$ ($1 \leq i < n$) are adjacent, and so are points $n$ and $1$.
There are $m$ straight segments on the disc, the endpoints of which are all among the aforementioned $n$ points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $k$ ($1 \leq k < n$), such that if all segments are rotated clockwise around the center of the circle by $k$ units, the new image will be the same as the original one.
-----Input-----
The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100\,000$, $1 \leq m \leq 200\,000$) — the number of points and the number of segments, respectively.
The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) that describe a segment connecting points $a_i$ and $b_i$.
It is guaranteed that no segments coincide.
-----Output-----
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
-----Examples-----
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
-----Note-----
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $120$ degrees around the center.
[Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.
You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display.
The second line contains n digits — the initial state of the display.
-----Output-----
Print a single line containing n digits — the desired state of the display containing the smallest possible number.
-----Examples-----
Input
3
579
Output
024
Input
4
2014
Output
0142
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A histogram is made of a number of contiguous bars, which have same width.
For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area.
Constraints
* $1 \leq N \leq 10^5$
* $0 \leq h_i \leq 10^9$
Input
The input is given in the following format.
$N$
$h_1$ $h_2$ ... $h_N$
Output
Print the area of the largest rectangle.
Examples
Input
8
2 1 3 5 3 4 2 1
Output
12
Input
3
2 0 1
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.
But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 100) — the number of apples. The second line contains n integers w_1, w_2, ..., w_{n} (w_{i} = 100 or w_{i} = 200), where w_{i} is the weight of the i-th apple.
-----Output-----
In a single line print "YES" (without the quotes) if it is possible to divide all the apples between his friends. Otherwise print "NO" (without the quotes).
-----Examples-----
Input
3
100 200 100
Output
YES
Input
4
100 100 100 200
Output
NO
-----Note-----
In the first test sample Kitahara Haruki can give the first and the last apple to Ogiso Setsuna and the middle apple to Touma Kazusa.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Introduction
Digital Cypher assigns a unique number to each letter of the alphabet:
```
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
```
In the encrypted word we write the corresponding numbers instead of the letters. For example, the word `scout` becomes:
```
s c o u t
19 3 15 21 20
```
Then we add to each number a digit from the key (repeated if necessary). For example if the key is `1939`:
```
s c o u t
19 3 15 21 20
+ 1 9 3 9 1
---------------
20 12 18 30 21
m a s t e r p i e c e
13 1 19 20 5 18 16 9 5 3 5
+ 1 9 3 9 1 9 3 9 1 9 3
--------------------------------
14 10 22 29 6 27 19 18 6 12 8
```
# Task
Write a function that accepts a `message` string and an array of integers `code`. As the result, return the `key` that was used to encrypt the `message`. The `key` has to be shortest of all possible keys that can be used to code the `message`: i.e. when the possible keys are `12` , `1212`, `121212`, your solution should return `12`.
#### Input / Output:
* The `message` is a string containing only lowercase letters.
* The `code` is an array of positive integers.
* The `key` output is a positive integer.
# Examples
```python
find_the_key("scout", [20, 12, 18, 30, 21]) # --> 1939
find_the_key("masterpiece", [14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8]) # --> 1939
find_the_key("nomoretears", [15, 17, 14, 17, 19, 7, 21, 7, 2, 20, 20]) # --> 12
```
# Digital cypher series
- [Digital cypher vol 1](https://www.codewars.com/kata/592e830e043b99888600002d)
- [Digital cypher vol 2](https://www.codewars.com/kata/592edfda5be407b9640000b2)
- [Digital cypher vol 3 - missing key](https://www.codewars.com/kata/5930d8a4b8c2d9e11500002a)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.
Input
The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly.
Output
Print the number of chips the presenter ended up with.
Examples
Input
4 11
Output
0
Input
17 107
Output
2
Input
3 8
Output
1
Note
In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.
In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 statement
Cards with ranks of $ 2 $ and $ 8 $ are powerful in card game millionaires. Therefore, we call an integer consisting of only the numbers $ 2 $ and $ 8 $ in $ 10 $ decimal notation a good integer. The best integers are listed from the smallest to $ 2, 8, 22, 28, 82, 88, \ cdots $.
Let $ n $ be a positive integer. When $ n $ can be expressed in the form of a product of good integers, find the maximum product. If you can't, output $ -1 $.
Constraint
$ 1 \ leq n \ leq 10 ^ {18} $
sample
Sample input 1
1
Sample output 1
-1
Sample input 2
2
Sample output 2
1
Sample input 3
88
Sample output 3
3
It can be expressed as $ 2 \ times 2 \ times 22 $.
Sample input 4
100
Sample output 4
-1
Sample input 5
173553147234869248
Sample output 5
11
It can be expressed as $ 2 ^ 6 \ times 28 \ times 2222 ^ 3 \ times 8828 $.
input
$ n $
output
Print the answer on the $ 1 $ line.
Example
Input
1
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array $A_1, A_2, ..., A_N$, count the number of subarrays of array $A$ which are non-decreasing.
A subarray $A[i, j]$, where $1 ≤ i ≤ j ≤ N$ is a sequence of integers $A_i, A_i+1, ..., A_j$.
A subarray $A[i, j]$ is non-decreasing if $A_i ≤ A_i+1 ≤ A_i+2 ≤ ... ≤ A_j$. You have to count the total number of such subarrays.
-----Input-----
-
The first line of 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 size of array.
-
The second line contains $N$ space-separated integers $A_1$, $A_2$, …, $A_N$ denoting the elements of the array.
-----Output-----
For each test case, output in a single line the required answer.
-----Constraints-----
- $1 ≤ T ≤ 5$
- $1 ≤ N ≤ 10^5$
- $1 ≤ A_i ≤ 10^9$
-----Subtasks-----
- Subtask 1 (20 points) : $1 ≤ N ≤ 100$
- Subtask 2 (30 points) : $1 ≤ N ≤ 1000$
- Subtask 3 (50 points) : Original constraints
-----Sample Input:-----
2
4
1 4 2 3
1
5
-----Sample Output:-----
6
1
-----Explanation-----
Example case 1.
All valid subarrays are $A[1, 1], A[1, 2], A[2, 2], A[3, 3], A[3, 4], A[4, 4]$.
Note that singleton subarrays are identically non-decreasing.
Example case 2.
Only single subarray $A[1, 1]$ is non-decreasing.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has $n$ cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has $m$ points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most $1$ to this city. Next turn, the Monument controls all points at distance at most $2$, the turn after — at distance at most $3$, and so on. Monocarp will build $n$ Monuments in $n$ turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among $m$ of them) he will conquer at the end of turn number $n$. Help him to calculate the expected number of conquered points!
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 20$; $1 \le m \le 5 \cdot 10^4$) — the number of cities and the number of points.
Next $n$ lines contains $m$ integers each: the $j$-th integer of the $i$-th line $d_{i, j}$ ($1 \le d_{i, j} \le n + 1$) is the distance between the $i$-th city and the $j$-th point.
-----Output-----
It can be shown that the expected number of points Monocarp conquers at the end of the $n$-th turn can be represented as an irreducible fraction $\frac{x}{y}$. Print this fraction modulo $998\,244\,353$, i. e. value $x \cdot y^{-1} mod 998244353$ where $y^{-1}$ is such number that $y \cdot y^{-1} mod 998244353 = 1$.
-----Examples-----
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
-----Note-----
Let's look at all possible orders of cities Monuments will be build in:
$[1, 2, 3]$:
the first city controls all points at distance at most $3$, in other words, points $1$ and $4$;
the second city controls all points at distance at most $2$, or points $1$, $3$ and $5$;
the third city controls all points at distance at most $1$, or point $1$.
In total, $4$ points are controlled.
$[1, 3, 2]$: the first city controls points $1$ and $4$; the second city — points $1$ and $3$; the third city — point $1$. In total, $3$ points.
$[2, 1, 3]$: the first city controls point $1$; the second city — points $1$, $3$ and $5$; the third city — point $1$. In total, $3$ points.
$[2, 3, 1]$: the first city controls point $1$; the second city — points $1$, $3$ and $5$; the third city — point $1$. In total, $3$ points.
$[3, 1, 2]$: the first city controls point $1$; the second city — points $1$ and $3$; the third city — points $1$ and $5$. In total, $3$ points.
$[3, 2, 1]$: the first city controls point $1$; the second city — points $1$, $3$ and $5$; the third city — points $1$ and $5$. In total, $3$ points.
The expected number of controlled points is $\frac{4 + 3 + 3 + 3 + 3 + 3}{6}$ $=$ $\frac{19}{6}$ or $19 \cdot 6^{-1}$ $\equiv$ $19 \cdot 166374059$ $\equiv$ $166374062$ $\pmod{998244353}$
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0.
Write the program which finds the number of points in the intersection of two given sets.
Input
The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive.
Output
Print the number of points in the intersection or -1 if there are infinite number of points.
Examples
Input
1 1 0
2 2 0
Output
-1
Input
1 1 0
2 -2 0
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!
There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad.
Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.
-----Input-----
The first line contains integers $n$ and $k$ ($2 \le n \le 10^5$, $1 \le k \le 10^5$), the number of snacks and the number of guests.
The $i$-th of the following $k$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), favorite snack flavors of the $i$-th guest.
-----Output-----
Output one integer, the smallest possible number of sad guests.
-----Examples-----
Input
5 4
1 2
4 3
1 4
3 4
Output
1
Input
6 5
2 3
2 1
3 4
6 5
4 5
Output
0
-----Note-----
In the first example, Bessie can order the guests like this: $3, 1, 2, 4$. Guest $3$ goes first and eats snacks $1$ and $4$. Then the guest $1$ goes and eats the snack $2$ only, because the snack $1$ has already been eaten. Similarly, the guest $2$ goes up and eats the snack $3$ only. All the snacks are gone, so the guest $4$ will be sad.
In the second example, one optimal ordering is $2, 1, 3, 5, 4$. All the guests will be satisfied.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
AOR Ika is at the $ S $ th bus stop at time $ 0 $ and wants to go from there to the $ G $ th bus stop. The number of bus stops $ N $ and $ M $ routes (*) connecting different bus stops are given. The bus stops are numbered $ 1, \ dots, and N $, respectively. Each route consists of $ 4 $ values: origin $ u $, destination $ v $, departure time $ t $, and travel time $ c $. You can catch the bus if you are at the departure $ u $ at the time $ t $ and arrive at the destination $ v $ at the time $ t + c $. While not on the bus, AOR Ika gets wet in the rain. When heading to the $ G $ th bus stop through the route that minimizes the time of getting wet in the rain, output the total time of getting wet in the rain from the time $ 0 $ to the arrival at the $ G $ th bus stop.
(*) In graph theory terms, a path is a sequence of vertices and edges, but please note that it is used here to mean edges.
input
Input is given from standard input in the following format.
$ N \ M \ S \ G $
$ u_1 \ v_1 \ t_1 \ c_1 $
$ \ vdots $
$ u_M \ v_M \ t_M \ c_M $
output
Print the minimum amount of time you get wet in one line. Also, output a line break at the end.
Example
Input
2 2 1 2
1 2 10 100
1 2 5 500
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.
A fraction whose numerator is 1 and whose denominator is a positive integer is called a unit fraction. A representation of a positive rational number p/q as the sum of finitely many unit fractions is called a partition of p/q into unit fractions. For example, 1/2 + 1/6 is a partition of 2/3 into unit fractions. The difference in the order of addition is disregarded. For example, we do not distinguish 1/6 + 1/2 from 1/2 + 1/6.
For given four positive integers p, q, a, and n, count the number of partitions of p/q into unit fractions satisfying the following two conditions.
* The partition is the sum of at most n many unit fractions.
* The product of the denominators of the unit fractions in the partition is less than or equal to a.
For example, if (p,q,a,n) = (2,3,120,3), you should report 4 since
2/3 = 1/3 + 1/3 = 1/2 + 1/6 = 1/4 + 1/4 + 1/6 = 1/3 + 1/6 + 1/6
enumerates all of the valid partitions.
Input
The input is a sequence of at most 1000 data sets followed by a terminator.
A data set is a line containing four positive integers p, q, a, and n satisfying p,q <= 800, a <= 12000 and n <= 7. The integers are separated by a space.
The terminator is composed of just one line which contains four zeros separated by a space. It is not a part of the input data but a mark for the end of the input.
Output
The output should be composed of lines each of which contains a single integer. No other characters should appear in the output.
The output integer corresponding to a data set p, q, a, n should be the number of all partitions of p/q into at most n many unit fractions such that the product of the denominators of the unit fractions is less than or equal to a.
Example
Input
2 3 120 3
2 3 300 3
2 3 299 3
2 3 12 3
2 3 12000 7
54 795 12000 7
2 3 300 1
2 1 200 5
2 4 54 2
0 0 0 0
Output
4
7
6
2
42
1
0
9
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if that square is white.
We will repeatedly perform the following operation until all the squares are black:
* Every white square that shares a side with a black square, becomes black.
Find the number of operations that will be performed. The initial grid has at least one black square.
Constraints
* 1 \leq H,W \leq 1000
* A_{ij} is `#` or `.`.
* The given grid has at least one black square.
Input
Input is given from Standard Input in the following format:
H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}
Output
Print the number of operations that will be performed.
Examples
Input
3 3
...
.#.
...
Output
2
Input
6 6
..#..#
......
..#..
......
.#....
....#.
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).
Alice makes the first move. During the first move, she will eat $1$ candy (its size is $a_1$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.
On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.
For example, if $n=11$ and $a=[3,1,4,1,5,9,2,6,5,3,5]$, then: move 1: Alice eats one candy of size $3$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3,5]$. move 2: Alice ate $3$ on the previous move, which means Bob must eat $4$ or more. Bob eats one candy of size $5$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3]$. move 3: Bob ate $5$ on the previous move, which means Alice must eat $6$ or more. Alice eats three candies with the total size of $1+4+1=6$ and the sequence of candies becomes $[5,9,2,6,5,3]$. move 4: Alice ate $6$ on the previous move, which means Bob must eat $7$ or more. Bob eats two candies with the total size of $3+5=8$ and the sequence of candies becomes $[5,9,2,6]$. move 5: Bob ate $8$ on the previous move, which means Alice must eat $9$ or more. Alice eats two candies with the total size of $5+9=14$ and the sequence of candies becomes $[2,6]$. move 6 (the last): Alice ate $14$ on the previous move, which means Bob must eat $15$ or more. It is impossible, so Bob eats the two remaining candies and the game ends.
Print the number of moves in the game and two numbers: $a$ — the total size of all sweets eaten by Alice during the game; $b$ — the total size of all sweets eaten by Bob during the game.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 5000$) — the number of test cases in the input. The following are descriptions of the $t$ test cases.
Each test case consists of two lines. The first line contains an integer $n$ ($1 \le n \le 1000$) — the number of candies. The second line contains a sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) — the sizes of candies in the order they are arranged from left to right.
It is guaranteed that the sum of the values of $n$ for all sets of input data in a test does not exceed $2\cdot10^5$.
-----Output-----
For each set of input data print three integers — the number of moves in the game and the required values $a$ and $b$.
-----Example-----
Input
7
11
3 1 4 1 5 9 2 6 5 3 5
1
1000
3
1 1 1
13
1 2 3 4 5 6 7 8 9 10 11 12 13
2
2 1
6
1 1 1 1 1 1
7
1 1 1 1 1 1 1
Output
6 23 21
1 1000 0
2 1 2
6 45 46
2 2 1
3 4 2
4 4 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Alice visited Byteland to purchase jewels for her upcoming wedding anniversary.
In Byteland, every Jewelry shop has their own discount methods to attract the customers. One discount method called Buy1-Get1 caught Alice's attention. That is, Alice buys one jewel, then she can get one additional jewel with the same color without charge by Buy1-Get1.
Alice lists the needed jewels as a string S, each letter denotes one jewel, and the same letters denote the same colors of jewels, and the different letters denote the different colors of jewels. The cost of each jewel is 1. Your task is to calculate the minimum cost for getting all the jewels Alice listed.
------ Input ------
The first line of input contains a single line T, which represents the number of test cases. Then T lines will follow, and each contains a string S, which represents the jewels Alice needed.
------ Output ------
Output the minimum cost for each test case.
------ Constraints ------
1 ≤ T ≤ 100
1 ≤ |S| ≤ 200, where |S| represents the length of the string S.
The string S is case sensitive, and will contain only English characters in the range [a-z], [A-Z].
----- Sample Input 1 ------
4
ssss
ssas
sa
s
----- Sample Output 1 ------
2
3
2
1
----- explanation 1 ------
In the first sample case, Alice needs 4 jewel of color s. One of the optimal way is the following: Buy the first s with cost 1, and she can get the second s without charge. Then buy the third s with cost 1, and she can get the last s without charge. In this case, she get 4 jewels with only cost 2.
In the second sample case, Alice needs 3 jewels of color s and 1 jewel of color a. One of the optimal way is the following: Buy the second s with cost 1, and she can get the last s without charge. Then buy the a and the first s with cost 2. In this case, she get 4 jewels with only cost 3.
In the third and fourth sample cases, she cannot save her money by using Buy1-Get1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ivan has got an array of n non-negative integers a_1, a_2, ..., a_{n}. Ivan knows that the array is sorted in the non-decreasing order.
Ivan wrote out integers 2^{a}_1, 2^{a}_2, ..., 2^{a}_{n} on a piece of paper. Now he wonders, what minimum number of integers of form 2^{b} (b ≥ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2^{v} - 1 for some integer v (v ≥ 0).
Help Ivan, find the required quantity of numbers.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5). The second input line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 2·10^9). It is guaranteed that a_1 ≤ a_2 ≤ ... ≤ a_{n}.
-----Output-----
Print a single integer — the answer to the problem.
-----Examples-----
Input
4
0 1 1 1
Output
0
Input
1
3
Output
3
-----Note-----
In the first sample you do not need to add anything, the sum of numbers already equals 2^3 - 1 = 7.
In the second sample you need to add numbers 2^0, 2^1, 2^2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two integers K and S.
Three variable X, Y and Z takes integer values satisfying 0≤X,Y,Z≤K.
How many different assignments of values to X, Y and Z are there such that X + Y + Z = S?
Constraints
* 2≤K≤2500
* 0≤S≤3K
* K and S are integers.
Input
The input is given from Standard Input in the following format:
K S
Output
Print the number of the triples of X, Y and Z that satisfy the condition.
Examples
Input
2 2
Output
6
Input
5 15
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have two integers $l$ and $r$. Find an integer $x$ which satisfies the conditions below:
$l \le x \le r$. All digits of $x$ are different.
If there are multiple answers, print any of them.
-----Input-----
The first line contains two integers $l$ and $r$ ($1 \le l \le r \le 10^{5}$).
-----Output-----
If an answer exists, print any of them. Otherwise, print $-1$.
-----Examples-----
Input
121 130
Output
123
Input
98766 100000
Output
-1
-----Note-----
In the first example, $123$ is one of the possible answers. However, $121$ can't be the answer, because there are multiple $1$s on different digits.
In the second example, there is no valid 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.
Hierarchical Democracy
The presidential election in Republic of Democratia is carried out through multiple stages as follows.
1. There are exactly two presidential candidates.
2. At the first stage, eligible voters go to the polls of his/her electoral district. The winner of the district is the candidate who takes a majority of the votes. Voters cast their ballots only at this first stage.
3. A district of the k-th stage (k > 1) consists of multiple districts of the (k − 1)-th stage. In contrast, a district of the (k − 1)-th stage is a sub-district of one and only one district of the k-th stage. The winner of a district of the k-th stage is the candidate who wins in a majority of its sub-districts of the (k − 1)-th stage.
4. The final stage has just one nation-wide district. The winner of the final stage is chosen as the president.
You can assume the following about the presidential election of this country.
* Every eligible voter casts a vote.
* The number of the eligible voters of each electoral district of the first stage is odd.
* The number of the sub-districts of the (k − 1)-th stage that constitute a district of the k-th stage (k > 1) is also odd.
This means that each district of every stage has its winner (there is no tie).
Your mission is to write a program that finds a way to win the presidential election with the minimum number of votes. Suppose, for instance, that the district of the final stage has three sub-districts of the first stage and that the numbers of the eligible voters of the sub-districts are 123, 4567, and 89, respectively. The minimum number of votes required to be the winner is 107, that is, 62 from the first district and 45 from the third. In this case, even if the other candidate were given all the 4567 votes in the second district, s/he would inevitably be the loser. Although you might consider this election system unfair, you should accept it as a reality.
Input
The entire input looks like:
> the number of datasets (=n)
> 1st dataset
> 2nd dataset
> …
> n-th dataset
>
The number of datasets, n, is no more than 100.
The number of the eligible voters of each district and the part-whole relations among districts are denoted as follows.
* An electoral district of the first stage is denoted as [c], where c is the number of the eligible voters of the district.
* A district of the k-th stage (k > 1) is denoted as [d1d2…dm], where d1, d2, …, dm denote its sub-districts of the (k − 1)-th stage in this notation.
For instance, an electoral district of the first stage that has 123 eligible voters is denoted as [123]. A district of the second stage consisting of three sub-districts of the first stage that have 123, 4567, and 89 eligible voters, respectively, is denoted as [[123][4567][89]].
Each dataset is a line that contains the character string denoting the district of the final stage in the aforementioned notation. You can assume the following.
* The character string in each dataset does not include any characters except digits ('0', '1', …, '9') and square brackets ('[', ']'), and its length is between 11 and 10000, inclusive.
* The number of the eligible voters of each electoral district of the first stage is between 3 and 9999, inclusive.
The number of stages is a nation-wide constant. So, for instance, [[[9][9][9]][9][9]] never appears in the input. [[[[9]]]] may not appear either since each district of the second or later stage must have multiple sub-districts of the previous stage.
Output
For each dataset, print the minimum number of votes required to be the winner of the presidential election in a line. No output line may include any characters except the digits with which the number is written.
Sample Input
6
[[123][4567][89]]
[[5][3][7][3][9]]
[[[99][59][63][85][51]][[1539][7995][467]][[51][57][79][99][3][91][59]]]
[[[37][95][31][77][15]][[43][5][5][5][85]][[71][3][51][89][29]][[57][95][5][69][31]][[99][59][65][73][31]]]
[[[[9][7][3]][[3][5][7]][[7][9][5]]][[[9][9][3]][[5][9][9]][[7][7][3]]][[[5][9][7]][[3][9][3]][[9][5][5]]]]
[[8231][3721][203][3271][8843]]
Output for the Sample Input
107
7
175
95
21
3599
Example
Input
6
[[123][4567][89]]
[[5][3][7][3][9]]
[[[99][59][63][85][51]][[1539][7995][467]][[51][57][79][99][3][91][59]]]
[[[37][95][31][77][15]][[43][5][5][5][85]][[71][3][51][89][29]][[57][95][5][69][31]][[99][59][65][73][31]]]
[[[[9][7][3]][[3][5][7]][[7][9][5]]][[[9][9][3]][[5][9][9]][[7][7][3]]][[[5][9][7]][[3][9][3]][[9][5][5]]]]
[[8231][3721][203][3271][8843]]
Output
107
7
175
95
21
3599
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One important contest will take place on the most famous programming platform (Topforces) very soon!
The authors have a pool of $n$ problems and should choose at most three of them into this contest. The prettiness of the $i$-th problem is $a_i$. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be maximum possible).
But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are $x, y, z$, then $x$ should be divisible by neither $y$, nor $z$, $y$ should be divisible by neither $x$, nor $z$ and $z$ should be divisible by neither $x$, nor $y$. If the prettinesses of chosen problems are $x$ and $y$ then neither $x$ should be divisible by $y$ nor $y$ should be divisible by $x$. Any contest composed from one problem is considered good.
Your task is to find out the maximum possible total prettiness of the contest composed of at most three problems from the given pool.
You have to answer $q$ independent queries.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
-----Input-----
The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries.
The first line of the query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of problems.
The second line of the query contains $n$ integers $a_1, a_2, \dots, a_n$ ($2 \le a_i \le 2 \cdot 10^5$), where $a_i$ is the prettiness of the $i$-th problem.
It is guaranteed that the sum of $n$ over all queries does not exceed $2 \cdot 10^5$.
-----Output-----
For each query print one integer — the maximum possible cumulative prettiness of the contest composed of at most three problems from the given pool of problems in the query.
-----Example-----
Input
3
4
5 6 15 30
4
10 6 30 15
3
3 4 6
Output
30
31
10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to $120^{\circ}$. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.
-----Input-----
The first and the single line of the input contains 6 space-separated integers a_1, a_2, a_3, a_4, a_5 and a_6 (1 ≤ a_{i} ≤ 1000) — the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.
-----Output-----
Print a single integer — the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.
-----Examples-----
Input
1 1 1 1 1 1
Output
6
Input
1 2 1 2 1 2
Output
13
-----Note-----
This is what Gerald's hexagon looks like in the first sample:
$\theta$
And that's what it looks like in the second sample:
$A$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
There are n islands in JOI, and each island is numbered from 1 to n. Currently, the JOI country is developing a route network connecting each island.
You work at a ticket center that handles ship tickets. There are many people in JOI who want to travel between islands by boat, as cheaply as possible, and they fill out the order form with their origin and destination, and they are at your place. Will be sent to.
Your job is to transfer several vessels as soon as you receive the order form from the customer, calculate the cheapest fare on the route connecting the departure point and the destination, and tell the customer. However, depending on the itinerary, it may not be possible to travel by ship. At that time, it is necessary to tell the customer that "I cannot travel by ship". Also, in JOI, new vessels connecting the islands are starting to operate one after another, and you will be informed of this information from time to time. When replying to customers, you must keep in mind the latest information.
Create a program that asks for a reply to the customer when the customer's order form or operation information of the newly started vessel is given as input.
The execution status of Input Example 1 and Output Example 1 is shown in Fig. 1.
input
The input consists of multiple datasets. Each dataset is given in the following format.
Two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ 5000) are written on the first line of the input. This means that the number of islands is n and the input consists of k + 1 lines. On the first line of i + (1 ≤ i ≤ k), three or four integers are written separated by blanks.
* When the first number is 0, this line represents the customer's order form.
Three integers 0, a, b (1 ≤ a ≤ n, 1 ≤ b ≤ n, a ≠ b) are written on this line, separated by blanks. This means that the customer has sent an order form with island a as the starting point and island b as the destination.
* When the first number is 1, this line represents the operation information of the newly started vessel.
This line contains four integers 1, c, d, e (1 ≤ c ≤ n, 1 ≤ d ≤ n, c ≠ d, 1 ≤ e ≤ 1000000).
This means that a vessel that goes back and forth between island c and island d has newly started operation, and the fare from island c to island d and the fare from island d to island c are both e.
The order form after this line must be answered in consideration of this vessel.
At the first stage, it is assumed that no vessel is in operation. Of the inputs, the number of lines representing ship operation information is 1000 or less. Also note that multiple vessels may operate between islands.
When both n and k are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output in the following format for each data set.
Let m be the number of lines representing the order form in the input. The output of each dataset consists of m lines, and on the i-th line (1 ≤ i ≤ m), an integer representing the reply to the i-th order form is written. That is, if it is possible to travel between the departure point and the destination of the i-th order form by connecting several vessels, write the minimum value of the total fare. If it is impossible to travel, output -1.
Examples
Input
3 8
1 3 1 10
0 2 3
1 2 3 20
1 1 2 5
0 3 2
1 1 3 7
1 2 1 9
0 2 3
5 16
1 1 2 343750
1 1 3 3343
1 1 4 347392
1 1 5 5497
1 2 3 123394
1 2 4 545492
1 2 5 458
1 3 4 343983
1 3 5 843468
1 4 5 15934
0 2 1
0 4 1
0 3 2
0 4 2
0 4 3
0 5 3
0 0
Output
-1
15
12
5955
21431
9298
16392
24774
8840
Input
None
Output
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq h_i \leq 10^4
Input
Input is given from Standard Input in the following format:
N
h_1 h_2 \ldots h_N
Output
Print the minimum possible total cost incurred.
Examples
Input
4
10 30 40 20
Output
30
Input
2
10 10
Output
0
Input
6
30 10 60 10 60 50
Output
40
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.
He has a special interest to create difficult problems for others to solve. This time, with many $1 \times 1 \times 1$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $n \times m$ matrix, such that in each cell $(i,j)$, there are $h_{i,j}$ bricks standing on the top of each other.
However, Serval doesn't give you any $h_{i,j}$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $m$ columns, and in the $i$-th of them, the height is the maximum of $h_{1,i},h_{2,i},\dots,h_{n,i}$. It is similar for the left view, where there are $n$ columns. And in the top view, there is an $n \times m$ matrix $t_{i,j}$, where $t_{i,j}$ is $0$ or $1$. If $t_{i,j}$ equals $1$, that means $h_{i,j}>0$, otherwise, $h_{i,j}=0$.
However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?
-----Input-----
The first line contains three positive space-separated integers $n, m, h$ ($1\leq n, m, h \leq 100$) — the length, width and height.
The second line contains $m$ non-negative space-separated integers $a_1,a_2,\dots,a_m$, where $a_i$ is the height in the $i$-th column from left to right of the front view ($0\leq a_i \leq h$).
The third line contains $n$ non-negative space-separated integers $b_1,b_2,\dots,b_n$ ($0\leq b_j \leq h$), where $b_j$ is the height in the $j$-th column from left to right of the left view.
Each of the following $n$ lines contains $m$ numbers, each is $0$ or $1$, representing the top view, where $j$-th number of $i$-th row is $1$ if $h_{i, j}>0$, and $0$ otherwise.
It is guaranteed that there is at least one structure satisfying the input.
-----Output-----
Output $n$ lines, each of them contains $m$ integers, the $j$-th number in the $i$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.
-----Examples-----
Input
3 7 3
2 3 0 0 2 0 1
2 1 3
1 0 0 0 1 0 0
0 0 0 0 0 0 1
1 1 0 0 0 0 0
Output
1 0 0 0 2 0 0
0 0 0 0 0 0 1
2 3 0 0 0 0 0
Input
4 5 5
3 5 2 0 4
4 2 5 4
0 0 0 0 1
1 0 1 0 0
0 1 0 0 0
1 1 1 0 0
Output
0 0 0 0 4
1 0 2 0 0
0 5 0 0 0
3 4 1 0 0
-----Note-----
[Image]
The graph above illustrates the object in the first example.
[Image]
[Image]
The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.
Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.
Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.
-----Output-----
On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.
-----Examples-----
Input
4
4 1 2 10
Output
12 5
Input
7
1 2 3 4 5 6 7
Output
16 12
-----Note-----
In the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is an easier version of the problem with smaller constraints.
Korney Korneevich dag up an array $a$ of length $n$. Korney Korneevich has recently read about the operation bitwise XOR , so he wished to experiment with it. For this purpose, he decided to find all integers $x \ge 0$ such that there exists an increasing subsequence of the array $a$, in which the bitwise XOR of numbers is equal to $x$.
It didn't take a long time for Korney Korneevich to find all such $x$, and he wants to check his result. That's why he asked you to solve this problem!
A sequence $s$ is a subsequence of a sequence $b$ if $s$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.
A sequence $s_1, s_2, \ldots , s_m$ is called increasing if $s_1 < s_2 < \ldots < s_m$.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 500$) — the elements of the array $a$.
-----Output-----
In the first line print a single integer $k$ — the number of found $x$ values.
In the second line print $k$ integers in increasing order $x_1, x_2, \ldots x_k$ ($0 \le x_1 < \ldots < x_k$) — found $x$ values.
-----Examples-----
Input
4
4 2 2 4
Output
4
0 2 4 6
Input
8
1 0 1 7 12 5 3 2
Output
12
0 1 2 3 4 5 6 7 10 11 12 13
-----Note-----
In the first test case:
To get value $x = 0$ it is possible to choose and empty subsequence
To get value $x = 2$ it is possible to choose a subsequence $[2]$
To get value $x = 4$ it is possible to choose a subsequence $[4]$
To get value $x = 6$ it is possible to choose a subsequence $[2, 4]$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice became interested in periods of integer numbers. We say positive $X$ integer number is periodic with length $L$ if there exists positive integer number $P$ with $L$ digits such that $X$ can be written as $PPPP…P$. For example:
$X = 123123123$ is periodic number with length $L = 3$ and $L = 9$
$X = 42424242$ is periodic number with length $L = 2,L = 4$ and $L = 8$
$X = 12345$ is periodic number with length $L = 5$
For given positive period length $L$ and positive integer number $A$, Alice wants to find smallest integer number $X$ strictly greater than $A$ that is periodic with length L.
-----Input-----
First line contains one positive integer number $L \ (1 \leq L \leq 10^5)$ representing length of the period. Second line contains one positive integer number $A \ (1 \leq A \leq 10^{100 000})$.
-----Output-----
One positive integer number representing smallest positive number that is periodic with length $L$ and is greater than $A$.
-----Examples-----
Input
3
123456
Output
124124
Input
3
12345
Output
100100
-----Note-----
In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).
In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Introduction
The first century spans from the **year 1** *up to* and **including the year 100**, **The second** - *from the year 101 up to and including the year 200*, etc.
# Task :
Given a year, return the century it is in.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given some positive integers, I wish to print the integers such that all take up the same width by adding a minimum number of leading zeroes. No leading zeroes shall be added to the largest integer.
For example, given `1, 23, 2, 17, 102`, I wish to print out these numbers as follows:
```python
001
023
002
017
102
```
Write a function `print_nums(n1, n2, n3, ...)` that takes a variable number of arguments and returns the string to be printed out.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many participants will advance to the next round.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 50) separated by a single space.
The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 100), where ai is the score earned by the participant who got the i-th place. The given sequence is non-increasing (that is, for all i from 1 to n - 1 the following condition is fulfilled: ai ≥ ai + 1).
Output
Output the number of participants who advance to the next round.
Examples
Input
8 5
10 9 8 7 7 7 5 5
Output
6
Input
4 2
0 0 0 0
Output
0
Note
In the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.
In the second example nobody got a positive score.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.
Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.
On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.
The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct:
* n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"),
* p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ min(n, m)), here characters in strings are numbered starting from 1.
Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum.
Input
The first line contains a non-empty string s (1 ≤ |s| ≤ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≤ |t| ≤ 5000), where |t| is its length. Both strings consist of lowercase Latin letters.
Output
Print the sought name or -1 if it doesn't exist.
Examples
Input
aad
aac
Output
aad
Input
abad
bob
Output
daab
Input
abc
defg
Output
-1
Input
czaaab
abcdef
Output
abczaa
Note
In the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How many people did you split into? However, all members of the PA Lab shall honestly answer their names.
input
Input is given from standard input in the following format.
$ N $
$ S_1 $
$ S_2 $
$ S_3 $
$ \ ldots $
$ S_N $
output
E869120 Please output the number of people you were split into. However, if you do not have E869120, please output "0".
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 1000 $
* $ 1 \ leq (length of S_i $ $) \ leq 100 $
* $ N $ is an integer.
* $ S_i $ is a string consisting of numbers and uppercase letters.
Input example 1
Five
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output example 1
2
E869120 You are split into two.
Input example 2
3
SQUARE1001
MENCOTTON
B2563125
Output example 2
0
E869120 Please output 0 when you are not there.
Input example 3
6
E8691200
E869121
E869122
E869123
E869124
E869125
Output example 3
0
Beware of impostors.
Example
Input
5
E869120
TMJN
E869120
TAISA
YNYMXIAOLONGBAO
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
JOI City will hold a large-scale exposition.
There are two themes for this exposition, and each of the N exhibition facilities in JOI City will exhibit on one of the two themes.
The location of the facility is represented by plane coordinates (x, y). To move from the facility at position (x, y) to the facility at (x ′, y ′), | x − x ′ | + It takes only | y − y ′ | (for the integer a, | a | represents the absolute value of a). To create a sense of unity within the same theme, and to be interested in only one theme. In order not to make people feel inconvenience, I would like to assign the theme so that the travel time between two facilities exhibiting on the same theme is as short as possible. Unless the same theme is assigned to all exhibition facilities. , How can you divide the theme.
Let M be the maximum travel time between two facilities exhibiting on the same theme. Create a program to find the minimum value of M given the locations of N exhibition facilities.
output
The output consists of only one line. Output the maximum value M of the maximum travel time between two facilities exhibiting on the same theme.
Input / output example
Input example 1
Five
0 0
Ten
-1 -2
0 1
-1 1
Output example 1
3
In this case, for example, one theme for the facility at coordinates (0, 0), (1, 0), (0, 1), and another theme for the facility at (−1, −2), (−1, 1). When one theme is assigned, the travel time between two facilities exhibiting on the same theme is all 3 or less. Since the travel time cannot be all 2 or less, 3 is output.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The first line of input contains the number of facilities N (3 ≤ N ≤ 100000 = 105). The first line of input i + 1 (1 ≤ i ≤ N) represents the coordinates of each facility. The two integers xi, yi (| xi | ≤ 100000 = 105, | yi | ≤ 100000 = 105) are separated by blanks. This is where the coordinates of the i-th facility are (xi, yi). It means that there can be no more than one facility at the same coordinates.
Of the scoring data, 40% of the points are N ≤ 2000.
Example
Input
5
0 0
1 0
-1 -2
0 1
-1 1
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In mathematics, a [Diophantine equation](https://en.wikipedia.org/wiki/Diophantine_equation) is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied.
In this kata we want to find all integers `x, y` (`x >= 0, y >= 0`) solutions of a diophantine equation of the form:
#### x^(2) - 4 \* y^(2) = n
(where the unknowns are `x` and `y`, and `n` is a given positive number)
in decreasing order of the positive xi.
If there is no solution return `[]` or `"[]" or ""`. (See "RUN SAMPLE TESTS" for examples of returns).
## Examples:
```
solEquaStr(90005) --> "[[45003, 22501], [9003, 4499], [981, 467], [309, 37]]"
solEquaStr(90002) --> "[]"
```
## Hint:
x^(2) - 4 \* y^(2) = (x - 2\*y) \* (x + 2\*y)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
Today is Chef's birthday. His mom gifted him a truly lovable gift, a permutation of first N positive integers.
She placed the permutation on a very long table in front of Chef and left it for him to play with it. But as there was a lot of people coming and wishing him. It was interfering with his game which made him very angry and he banged the table very hard due to which K numbers from the permutation fell down and went missing.
Seeing her son's gift being spoilt, his mom became very sad. Chef didn't want his mom to be sad as he loves her the most. So to make her happy, he decided to play a game with her with the remaining N - K numbers on the table. Chef wants his mom to win all the games.
Chef and his mom play alternatively and optimally. In Xth move, a player can choose some numbers out of all the numbers available on the table such that chosen numbers sum up to X. After the move, Chosen numbers are placed back on the table.The player who is not able to make a move loses.
Now, Chef has to decide who should move first so that his Mom wins the game.
As Chef is a small child, he needs your help to decide who should move first. Please help him, he has promised to share his birthday cake with you :)
------ Input ------
First Line of input contains a single integer T denoting the number of test cases.
First line of each test case contains two space separated integers N and K denoting the size of
permutation and number of numbers fall down from the table.
Next line of each test case contains K space separated integers denoting the values of missing numbers.
------ Output ------
For each test case, print "Chef" if chef should move first otherwise print "Mom" (without quotes).
------ Constraints ------
1 ≤ T ≤ 10^{5}, 1 ≤ N ≤ 10^{9}
0 ≤ K ≤ min(10^{5}, N)
All K numbers are distinct.
Value of each of K number belongs to [1,N].
Sum of K over all the test cases does not exceed 5*10^{5}.
------ Scoring ------
Subtask 1 (13 pts): 1 ≤ T ≤ 100, 1 ≤ N ≤ 10^{2}, 1 ≤ K < N.
Subtask 2 (17 pts): 1 ≤ T ≤ 100, 1 ≤ N ≤ 10^{5}, K = 0.
Subtask 3 (70 pts): Original Constraints.
----- Sample Input 1 ------
2
5 2
3 5
5 1
1
----- Sample Output 1 ------
Mom
Chef
----- explanation 1 ------
For test case 1.
Mom can choose {1} to make 1.
Chef can choose {2} to make 2.
Mom can choose {1,2} to make 3.
Chef can choose {4} to make 4.
Mom can choose {1,4} to make 5.
Chef can choose {2,4} to make 6.
Mom can choose {1,2,4} to make 7.
Chef cannot make 8 out of the numbers on the table.
So,Chef loses and Mom wins.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.
-----Constraints-----
- 1 \leq N \leq 10^9
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the largest square number not exceeding N.
-----Sample Input-----
10
-----Sample Output-----
9
10 is not square, but 9 = 3 × 3 is. Thus, we print 9.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$ of length $n$ consisting of characters a and/or b.
Let $\operatorname{AB}(s)$ be the number of occurrences of string ab in $s$ as a substring. Analogically, $\operatorname{BA}(s)$ is the number of occurrences of ba in $s$ as a substring.
In one step, you can choose any index $i$ and replace $s_i$ with character a or b.
What is the minimum number of steps you need to make to achieve $\operatorname{AB}(s) = \operatorname{BA}(s)$?
Reminder:
The number of occurrences of string $d$ in $s$ as substring is the number of indices $i$ ($1 \le i \le |s| - |d| + 1$) such that substring $s_i s_{i + 1} \dots s_{i + |d| - 1}$ is equal to $d$. For example, $\operatorname{AB}($aabbbabaa$) = 2$ since there are two indices $i$: $i = 2$ where aabbbabaa and $i = 6$ where aabbbabaa.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 1000$). Description of the test cases follows.
The first and only line of each test case contains a single string $s$ ($1 \le |s| \le 100$, where $|s|$ is the length of the string $s$), consisting only of characters a and/or b.
-----Output-----
For each test case, print the resulting string $s$ with $\operatorname{AB}(s) = \operatorname{BA}(s)$ you'll get making the minimum number of steps.
If there are multiple answers, print any of them.
-----Examples-----
Input
4
b
aabbbabaa
abbb
abbaab
Output
b
aabbbabaa
bbbb
abbaaa
-----Note-----
In the first test case, both $\operatorname{AB}(s) = 0$ and $\operatorname{BA}(s) = 0$ (there are no occurrences of ab (ba) in b), so can leave $s$ untouched.
In the second test case, $\operatorname{AB}(s) = 2$ and $\operatorname{BA}(s) = 2$, so you can leave $s$ untouched.
In the third test case, $\operatorname{AB}(s) = 1$ and $\operatorname{BA}(s) = 0$. For example, we can change $s_1$ to b and make both values zero.
In the fourth test case, $\operatorname{AB}(s) = 2$ and $\operatorname{BA}(s) = 1$. For example, we can change $s_6$ to a and make both values equal to $1$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he scores $1$ point, in the second game he scores $2$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up!
Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $[1,2,3]$ can yield $[3,1,2]$ but it cannot yield $[3,2,1]$ since the $2$ is in the same position.
Given a permutation of $n$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $10^{18}$.
An array $a$ is a subarray of an array $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of the test cases follows.
The first line of each test case contains integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the length of the given permutation.
The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ ($1 \leq a_{i} \leq n$) — the initial permutation.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output one integer: the minimum number of special exchanges needed to sort the permutation.
-----Example-----
Input
2
5
1 2 3 4 5
7
3 2 4 5 1 6 7
Output
0
2
-----Note-----
In the first permutation, it is already sorted so no exchanges are needed.
It can be shown that you need at least $2$ exchanges to sort the second permutation.
$[3, 2, 4, 5, 1, 6, 7]$
Perform special exchange on range ($1, 5$)
$[4, 1, 2, 3, 5, 6, 7]$
Perform special exchange on range ($1, 4$)
$[1, 2, 3, 4, 5, 6, 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.
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $n$ machines, and the power of the $i$-th machine is $a_i$.
This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $x$, then choose one machine and reduce the power of its machine by $x$ times, and at the same time increase the power of one another machine by $x$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $i$ and $j$, and one integer $x$ such that $x$ is a divisor of $a_i$, and change powers as following: $a_i = \frac{a_i}{x}$, $a_j = a_j \cdot x$
Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 5 \cdot 10^4$) — the number of machines.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$) — the powers of the machines.
-----Output-----
Print one integer — minimum total power.
-----Examples-----
Input
5
1 2 3 4 5
Output
14
Input
4
4 2 4 4
Output
14
Input
5
2 4 2 3 7
Output
18
-----Note-----
In the first example, the farmer can reduce the power of the $4$-th machine by $2$ times, and increase the power of the $1$-st machine by $2$ times, then the powers will be: $[2, 2, 3, 2, 5]$.
In the second example, the farmer can reduce the power of the $3$-rd machine by $2$ times, and increase the power of the $2$-nd machine by $2$ times. At the same time, the farmer can leave is be as it is and the total power won't change.
In the third example, it is optimal to leave it be as it is.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It is raining heavily. But this is the first day for Serval, who just became 3 years old, to go to the kindergarten. Unfortunately, he lives far from kindergarten, and his father is too busy to drive him there. The only choice for this poor little boy is to wait for a bus on this rainy day. Under such circumstances, the poor boy will use the first bus he sees no matter where it goes. If several buses come at the same time, he will choose one randomly.
Serval will go to the bus station at time $t$, and there are $n$ bus routes which stop at this station. For the $i$-th bus route, the first bus arrives at time $s_i$ minutes, and each bus of this route comes $d_i$ minutes later than the previous one.
As Serval's best friend, you wonder which bus route will he get on. If several buses arrive at the same time, you can print any of them.
-----Input-----
The first line contains two space-separated integers $n$ and $t$ ($1\leq n\leq 100$, $1\leq t\leq 10^5$) — the number of bus routes and the time Serval goes to the station.
Each of the next $n$ lines contains two space-separated integers $s_i$ and $d_i$ ($1\leq s_i,d_i\leq 10^5$) — the time when the first bus of this route arrives and the interval between two buses of this route.
-----Output-----
Print one number — what bus route Serval will use. If there are several possible answers, you can print any of them.
-----Examples-----
Input
2 2
6 4
9 5
Output
1
Input
5 5
3 3
2 5
5 6
4 9
6 1
Output
3
Input
3 7
2 2
2 3
2 4
Output
1
-----Note-----
In the first example, the first bus of the first route arrives at time $6$, and the first bus of the second route arrives at time $9$, so the first route is the answer.
In the second example, a bus of the third route arrives at time $5$, so it is the answer.
In the third example, buses of the first route come at times $2$, $4$, $6$, $8$, and so fourth, buses of the second route come at times $2$, $5$, $8$, and so fourth and buses of the third route come at times $2$, $6$, $10$, and so on, so $1$ and $2$ are both acceptable answers while $3$ is not.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.
Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.
Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.
Next line describe the second permutation in the same format.
Output
Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.
Examples
Input
3
3 2 1
1 2 3
Output
2
Input
5
1 2 3 4 5
1 5 2 3 4
Output
1
Input
5
1 5 2 3 4
1 2 3 4 5
Output
3
Note
In the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.
In the second sample, he removes number 5 and inserts it after 1.
In the third sample, the sequence of changes are like this:
* 1 5 2 3 4
* 1 4 5 2 3
* 1 3 4 5 2
* 1 2 3 4 5
So he needs three moves.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It’s still hot every day, but September has already come. It’s autumn according to the calendar. Looking around, I see two red dragonflies at rest on the wall in front of me. It’s autumn indeed.
When two red dragonflies’ positional information as measured from the end of the wall is given, make a program to calculate the distance between their heads.
Input
The input is given in the following format.
$x_1$ $x_2$
The input line provides dragonflies’ head positions $x_1$ and $x_2$ ($0 \leq x_1, x_2 \leq 100$) as integers.
Output
Output the distance between the two red dragonflies in a line.
Examples
Input
20 30
Output
10
Input
50 25
Output
25
Input
25 25
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.
Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day k_{i} products will be put up for sale and exactly l_{i} clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.
For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale k_{i} products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·k_{i} products. Consequently, there is an opportunity to sell two times more products on days of sell-out.
Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.
-----Input-----
The first line contains two integers n and f (1 ≤ n ≤ 10^5, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.
Each line of the following n subsequent lines contains two integers k_{i}, l_{i} (0 ≤ k_{i}, l_{i} ≤ 10^9) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.
-----Output-----
Print a single integer denoting the maximal number of products that shop can sell.
-----Examples-----
Input
4 2
2 1
3 5
2 3
1 5
Output
10
Input
4 1
0 2
0 3
3 5
0 6
Output
5
-----Note-----
In the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.
In the second example it is possible to sell 5 products, if you choose third day for sell-out.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Iahub helps his grandfather at the farm. Today he must milk the cows. There are n cows sitting in a row, numbered from 1 to n from left to right. Each cow is either facing to the left or facing to the right. When Iahub milks a cow, all the cows that see the current cow get scared and lose one unit of the quantity of milk that they can give. A cow facing left sees all the cows with lower indices than her index, and a cow facing right sees all the cows with higher indices than her index. A cow that got scared once can get scared again (and lose one more unit of milk). A cow that has been milked once cannot get scared and lose any more milk. You can assume that a cow never loses all the milk she can give (a cow gives an infinitely amount of milk).
Iahub can decide the order in which he milks the cows. But he must milk each cow exactly once. Iahub wants to lose as little milk as possible. Print the minimum amount of milk that is lost.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 200000). The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} is 0 if the cow number i is facing left, and 1 if it is facing right.
-----Output-----
Print a single integer, the minimum amount of lost milk.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
4
0 0 1 0
Output
1
Input
5
1 0 1 0 1
Output
3
-----Note-----
In the first sample Iahub milks the cows in the following order: cow 3, cow 4, cow 2, cow 1. When he milks cow 3, cow 4 loses 1 unit of milk. After that, no more milk is lost.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.
Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?
-----Constraints-----
- 1 ≤ X ≤ 9
- X is an integer.
-----Input-----
Input is given from Standard Input in the following format:
X
-----Output-----
If Takahashi's growth will be celebrated, print YES; if it will not, print NO.
-----Sample Input-----
5
-----Sample Output-----
YES
The growth of a five-year-old child will be celebrated.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two students of AtCoder Kindergarten are fighting over candy packs.
There are three candy packs, each of which contains a, b, and c candies, respectively.
Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.
Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.
-----Constraints-----
- 1 ≦ a, b, c ≦ 100
-----Input-----
The input is given from Standard Input in the following format:
a b c
-----Output-----
If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.
-----Sample Input-----
10 30 20
-----Sample Output-----
Yes
Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Карта звёздного неба представляет собой прямоугольное поле, состоящее из n строк по m символов в каждой строке. Каждый символ — это либо «.» (означает пустой участок неба), либо «*» (означает то, что в этом месте на небе есть звезда).
Новое издание карты звёздного неба будет напечатано на квадратных листах, поэтому требуется найти минимально возможную сторону квадрата, в который могут поместиться все звезды. Границы искомого квадрата должны быть параллельны сторонам заданного прямоугольного поля.
-----Входные данные-----
В первой строке входных данных записаны два числа n и m (1 ≤ n, m ≤ 1000) — количество строк и столбцов на карте звездного неба.
В следующих n строках задано по m символов. Каждый символ — это либо «.» (пустой участок неба), либо «*» (звезда).
Гарантируется, что на небе есть хотя бы одна звезда.
-----Выходные данные-----
Выведите одно число — минимально возможную сторону квадрата, которым можно накрыть все звезды.
-----Примеры-----
Входные данные
4 4
....
..*.
...*
..**
Выходные данные
3
Входные данные
1 3
*.*
Выходные данные
3
Входные данные
2 1
.
*
Выходные данные
1
-----Примечание-----
Один из возможных ответов на первый тестовый пример:
[Image]
Один из возможных ответов на второй тестовый пример (обратите внимание, что покрывающий квадрат выходит за пределы карты звездного неба):
[Image]
Ответ на третий тестовый пример:
[Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Complete the function which returns the weekday according to the input number:
* `1` returns `"Sunday"`
* `2` returns `"Monday"`
* `3` returns `"Tuesday"`
* `4` returns `"Wednesday"`
* `5` returns `"Thursday"`
* `6` returns `"Friday"`
* `7` returns `"Saturday"`
* Otherwise returns `"Wrong, please enter a number between 1 and 7"`
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**.
### Abundant Numbers
An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself.
The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).
### Deficient Numbers
A deficient number is a number for which the sum of its proper divisors is less than the number itself.
The first few deficient numbers are: 1, 2, 3, 4, 5, 7, 8, 9.
### Perfect Numbers
A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.
The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6.
### Amicable Numbers
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.)
For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, of which the sum is 220.
### The Function
For a given two numbers, derive function `deficientlyAbundantAmicableNumbers(num1, num2)` which returns a string with first and second word either abundant or deficient depending on whether `num1` or `num2` are abundant, deficient or perfect. The string should finish with either amicable or not amicable depending on the relationship between `num1` and `num2`.
e.g. `deficientlyAbundantAmicableNumbers(220, 284)` returns `"abundant deficient amicable"` as 220 is an abundant number, 284 is a deficient number and amicable because 220 and 284 are an amicable number pair.
See Part 1 - [Excessively Abundant Numbers](http://www.codewars.com/kata/56a75b91688b49ad94000015)
See Part 2 - [The Most Amicable of Numbers](http://www.codewars.com/kata/56b5ebaa26fd54188b000018)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers.
You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figured out most of the digits as well as a few operators, but he needs your help to figure out the rest.
The professor will give you a simple math expression, of the form
```
[number][op][number]=[number]
```
He has converted all of the runes he knows into digits. The only operators he knows are addition (`+`),subtraction(`-`), and multiplication (`*`), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is 0, therefore 00 would not be a valid number.
Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case.
Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists.
~~~if:php
**Most of the time, the professor will be able to figure out most of the runes himself, but sometimes, there may be exactly 1 rune present in the expression that the professor cannot figure out (resulting in all question marks where the digits are in the expression) so be careful ;)**
~~~
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Obesity is cited as the cause of many adult diseases. In the past, with a few exceptions, it was unrelated to high school students. However, it is no longer unrealistic to suffer from lack of exercise due to excessive studying for entrance exams, or to become bulimia nervosa due to stress. It may be a problem that high school students should be fully interested in.
So you decided to work as an assistant to a teacher in the health room to create a program to find students suspected of being obese from student data.
The method is to calculate a numerical value called BMI (Body Mass Index). BMI is given by the following formula.
<image>
BMI = 22 is standard, and above 25 is suspected of being obese.
Create a program that calculates BMI from each student's weight and height information and outputs the student ID numbers of 25 or more students.
input
The input is given in the following format:
s1, w1, h1
s2, w2, h2
...
...
si (1 ≤ si ≤ 2,000), wi (1 ≤ wi ≤ 200), hi (1.0 ≤ hi ≤ 2.0) are the student ID numbers (integers), weight (real numbers), and height (real numbers) of the i-th student, respectively. Represents.
The number of students does not exceed 50.
output
The student ID numbers of students with a BMI of 25 or higher are output on one line in the order in which they were entered.
Example
Input
1001,50.0,1.60
1002,60.0,1.70
1003,70.0,1.80
1004,80.0,1.70
1005,90.0,1.60
Output
1004
1005
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
On her way to programming school tiger Dasha faced her first test — a huge staircase! [Image]
The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers.
You need to check whether there is an interval of steps from the l-th to the r-th (1 ≤ l ≤ r), for which values that Dasha has found are correct.
-----Input-----
In the only line you are given two integers a, b (0 ≤ a, b ≤ 100) — the number of even and odd steps, accordingly.
-----Output-----
In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise.
-----Examples-----
Input
2 3
Output
YES
Input
3 1
Output
NO
-----Note-----
In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps — 2 and 4, and three odd: 1, 3 and 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an integer `n`, find two integers `a` and `b` such that:
```Pearl
A) a >= 0 and b >= 0
B) a + b = n
C) DigitSum(a) + Digitsum(b) is maximum of all possibilities.
```
You will return the digitSum(a) + digitsum(b).
```
For example:
solve(29) = 11. If we take 15 + 14 = 29 and digitSum = 1 + 5 + 1 + 4 = 11. There is no larger outcome.
```
`n` will not exceed `10e10`.
More examples in test cases.
Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Takahashi is going to set a 3-character password.
How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?
-----Constraints-----
- 1 \leq N \leq 9
- N is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the number of possible passwords.
-----Sample Input-----
2
-----Sample Output-----
8
There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range.
You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query.
Input
The first line contains two integers a and b, the two integers as described above (1 ≤ a, b ≤ 109). The second line contains one integer n, the number of queries (1 ≤ n ≤ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≤ low ≤ high ≤ 109).
Output
Print n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query.
Examples
Input
9 27
3
1 5
10 11
9 11
Output
3
-1
9
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence.
Input
The input consists of multiple datasets. Each data set consists of:
n
a1
a2
.
.
an
You can assume that 1 ≤ n ≤ 5000 and -100000 ≤ ai ≤ 100000.
The input end with a line consisting of a single 0.
Output
For each dataset, print the maximum sum in a line.
Example
Input
7
-5
-1
6
4
9
-6
-7
13
1
2
3
2
-2
-1
1
2
3
2
1
-2
1
3
1000
-200
201
0
Output
19
14
1001
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.
Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined, there were n contestants in the tournament, numbered from 1 to n. Each of them had already obtained some amount of tournament points, namely the i-th fighter had p_{i} points.
Manao is going to engage in a single fight against each contestant. Each of Manao's fights ends in either a win or a loss. A win grants Manao one point, and a loss grants Manao's opponent one point. For each i, Manao estimated the amount of effort e_{i} he needs to invest to win against the i-th contestant. Losing a fight costs no effort.
After Manao finishes all of his fights, the ranklist will be determined, with 1 being the best rank and n + 1 being the worst. The contestants will be ranked in descending order of their tournament points. The contestants with the same number of points as Manao will be ranked better than him if they won the match against him and worse otherwise. The exact mechanism of breaking ties for other fighters is not relevant here.
Manao's objective is to have rank k or better. Determine the minimum total amount of effort he needs to invest in order to fulfill this goal, if it is possible.
-----Input-----
The first line contains a pair of integers n and k (1 ≤ k ≤ n + 1). The i-th of the following n lines contains two integers separated by a single space — p_{i} and e_{i} (0 ≤ p_{i}, e_{i} ≤ 200000).
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
In subproblem C1 (4 points), the constraint 1 ≤ n ≤ 15 will hold. In subproblem C2 (4 points), the constraint 1 ≤ n ≤ 100 will hold. In subproblem C3 (8 points), the constraint 1 ≤ n ≤ 200000 will hold.
-----Output-----
Print a single number in a single line — the minimum amount of effort Manao needs to use to rank in the top k. If no amount of effort can earn Manao such a rank, output number -1.
-----Examples-----
Input
3 2
1 1
1 4
2 2
Output
3
Input
2 1
3 2
4 0
Output
-1
Input
5 2
2 10
2 10
1 1
3 1
3 1
Output
12
-----Note-----
Consider the first test case. At the time when Manao joins the tournament, there are three fighters. The first of them has 1 tournament point and the victory against him requires 1 unit of effort. The second contestant also has 1 tournament point, but Manao needs 4 units of effort to defeat him. The third contestant has 2 points and victory against him costs Manao 2 units of effort. Manao's goal is top be in top 2. The optimal decision is to win against fighters 1 and 3, after which Manao, fighter 2, and fighter 3 will all have 2 points. Manao will rank better than fighter 3 and worse than fighter 2, thus finishing in second place.
Consider the second test case. Even if Manao wins against both opponents, he will still rank third.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.
The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.
Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.
The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui, vi) < x < max(ui, vi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly k - 1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.
Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 80) — the number of crossroads (and offices) and the number of offices Oleg wants to visit.
The second line contains single integer m (0 ≤ m ≤ 2000) — the number of bicycle lanes in Bankopolis.
The next m lines contain information about the lanes.
The i-th of these lines contains three integers ui, vi and ci (1 ≤ ui, vi ≤ n, 1 ≤ ci ≤ 1000), denoting the crossroads connected by the i-th road and its difficulty.
Output
In the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.
Examples
Input
7 4
4
1 6 2
6 2 2
2 4 2
2 7 1
Output
6
Input
4 3
4
2 1 2
1 3 2
3 4 2
4 1 1
Output
3
Note
In the first example Oleg visiting banks by path 1 → 6 → 2 → 4.
Path 1 → 6 → 2 → 7 with smaller difficulity is incorrect because crossroad 2 → 7 passes near already visited office on the crossroad 6.
In the second example Oleg can visit banks by path 4 → 1 → 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya has an array $a$ consisting of $n$ integers. He wants to remove duplicate (equal) elements.
Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 50$) — the number of elements in Petya's array.
The following line contains a sequence $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1\,000$) — the Petya's array.
-----Output-----
In the first line print integer $x$ — the number of elements which will be left in Petya's array after he removed the duplicates.
In the second line print $x$ integers separated with a space — Petya's array after he removed the duplicates. For each unique element only the rightmost entry should be left.
-----Examples-----
Input
6
1 5 5 1 6 1
Output
3
5 6 1
Input
5
2 4 2 4 4
Output
2
2 4
Input
5
6 6 6 6 6
Output
1
6
-----Note-----
In the first example you should remove two integers $1$, which are in the positions $1$ and $4$. Also you should remove the integer $5$, which is in the position $2$.
In the second example you should remove integer $2$, which is in the position $1$, and two integers $4$, which are in the positions $2$ and $4$.
In the third example you should remove four integers $6$, which are in the positions $1$, $2$, $3$ and $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.
We have A balls with the string S written on each of them and B balls with the string T written on each of them.
From these balls, Takahashi chooses one with the string U written on it and throws it away.
Find the number of balls with the string S and balls with the string T that we have now.
-----Constraints-----
- S, T, and U are strings consisting of lowercase English letters.
- The lengths of S and T are each between 1 and 10 (inclusive).
- S \not= T
- S=U or T=U.
- 1 \leq A,B \leq 10
- A and B are integers.
-----Input-----
Input is given from Standard Input in the following format:
S T
A B
U
-----Output-----
Print the answer, with space in between.
-----Sample Input-----
red blue
3 4
red
-----Sample Output-----
2 4
Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example:
```
12 ==> 21
513 ==> 531
2017 ==> 2071
```
If the digits can't be rearranged to form a bigger number, return `-1` (or `nil` in Swift):
```
9 ==> -1
111 ==> -1
531 ==> -1
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob have participated to a Rock Off with their bands. A jury of true metalheads rates the two challenges, awarding points to the bands on a scale from 1 to 50 for three categories: Song Heaviness, Originality, and Members' outfits.
For each one of these 3 categories they are going to be awarded one point, should they get a better judgement from the jury. No point is awarded in case of an equal vote.
You are going to receive two arrays, containing first the score of Alice's band and then those of Bob's. Your task is to find their total score by comparing them in a single line.
Example:
Alice's band plays a Nirvana inspired grunge and has been rated
``20`` for Heaviness,
``32`` for Originality and only
``18`` for Outfits.
Bob listens to Slayer and has gotten a good
``48`` for Heaviness,
``25`` for Originality and a rather honest
``40`` for Outfits.
The total score should be followed by a colon ```:``` and by one of the following quotes:
if Alice's band wins: ```Alice made "Kurt" proud!```
if Bob's band wins: ```Bob made "Jeff" proud!```
if they end up with a draw: ```that looks like a "draw"! Rock on!```
The solution to the example above should therefore appear like
``'1, 2: Bob made "Jeff" proud!'``.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.
Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)
For example, when n=7, it becomes 0 after two operations, as follows:
* \mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.
* \mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.
You are given an integer X with N digits in binary. For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted. Find f(X_1), f(X_2), \ldots, f(X_N).
Constraints
* 1 \leq N \leq 2 \times 10^5
* X is an integer with N digits in binary, possibly with leading zeros.
Input
Input is given from Standard Input in the following format:
N
X
Output
Print N lines. The i-th line should contain the value f(X_i).
Examples
Input
3
011
Output
2
1
1
Input
23
00110111001011011001110
Output
2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.
In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 × 2 square, such that from the four letters of this square you can make word "face".
You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.
-----Input-----
The first line contains two space-separated integers, n and m (1 ≤ n, m ≤ 50) — the height and the width of the image, respectively.
Next n lines define the image. Each line contains m lowercase Latin letters.
-----Output-----
In the single line print the number of faces on the image.
-----Examples-----
Input
4 4
xxxx
xfax
xcex
xxxx
Output
1
Input
4 2
xx
cf
ae
xx
Output
1
Input
2 3
fac
cef
Output
2
Input
1 4
face
Output
0
-----Note-----
In the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column: [Image]
In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.
In the third sample two faces are shown: $\text{fac}$
In the fourth sample the image has no faces on it.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Russian also.
Chef likes playing with strings. The most interesting game are named "CHEF in string". The move of the game consists of the following: Chef takes a subsequence of string's letters that form the word "CHEF" and then he removes that symbols. The goal of the game is to make the maximal number of moves. Please, help Chef and tell him the maximal possible number of moves that he is able to make for the given string S.
------ Input ------
The first line of each test case contains a given string. This string consists of uppercase letters from the set {"C", "H", "E", "F"}.
------ Output ------
Output a single line containing the maximal possible number of moves.
------ Constraints ------
$1 ≤ |S| ≤ 100000$
------ Scoring ------
Subtask 1 (25 points): |S| ≤ 2000
Subtask 2 (75 points): See the constraints.
----- Sample Input 1 ------
CHEFCHEFFFF
----- Sample Output 1 ------
2
----- explanation 1 ------
- In the first move, Chef can pick the subsequence $[1, 2, 3, 4]$. Thus the characters at these indices are C, H, E, and F. Chef removes this subsequence. The remaining string is CHEFFFF.
- In the second move, Chef can pick the indices $[1, 2, 3, 4]$ of the remaining string CHEFFFF as the subsequence. The characters at these indices are C, H, E, and F. Chef removes this subsequence. The remaining string is FFF.
- Chef cannot make any more valid moves.
----- Sample Input 2 ------
CHHHEEEFFCC
----- Sample Output 2 ------
1
----- explanation 2 ------
- In the first move, Chef can pick the subsequence $[1, 2, 5, 8]$. Thus the characters at these indices are C, H, E, and F. Chef removes this subsequence. The remaining string is HHEEFCC.
- Chef cannot make any more valid moves.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
F: Grid number
problem
Ebi-chan is trying to write exactly one integer from 1 to 2 \ times n in a grid with n columns horizontally and 2 rows vertically.
Only one integer can be written to each cell in the grid.
It's not fun just to write normally, so I set the following rules.
* The absolute value of the difference between the integers written in two adjacent cells is less than or equal to k.
* When there is a cell to the right of a cell, the integer written to the cell is truly smaller than the integer written to the cell to the right.
* When there is a cell under a cell, the integer written in the cell is truly smaller than the integer written in the cell below.
Here, two adjacent squares represent squares that share the top, bottom, left, and right sides with a certain square.
How many ways to write this? The answer can be very large, so print the remainder after dividing by the prime number m.
Supplement
The second and third rules above require you to write an integer so that it doesn't violate the inequality sign, as shown in the figure below.
<image>
Input format
You will be given three integers as input.
n k m
Constraint
* 1 \ leq n \ leq 100
* 1 \ leq k \ leq 10
* 2 \ leq m \ leq 10 ^ 9 + 7
* m is a prime number
Output format
Please output the number on one line according to how to write the number. Also, be careful not to forget the trailing line break.
Input example 1
3 2 7
Output example 1
1
<image>
* The above writing method meets the conditions, and there is no other writing method that meets the conditions.
Input example 2
5 10 11
Output example 2
9
* Output the remainder divided by m.
Example
Input
3 2 7
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by a and after each fashion show decreases by b (designers do too many experiments nowadays). Moreover, sometimes top-models participates in talk shows. After participating in talk show model becomes more popular and increasing of her rating after photo shoots become c and decreasing of her rating after fashion show becomes d.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will never become negative. Help her to find a suitable moment for participating in the talk show.
Let's assume that model's career begins in moment 0. At that moment Izabella's rating was equal to start. If talk show happens in moment t if will affect all events in model's life in interval of time [t..t + len) (including t and not including t + len), where len is duration of influence.
Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will not become become negative before talk show or during period of influence of talk show. Help her to find a suitable moment for participating in the talk show.
Input
In first line there are 7 positive integers n, a, b, c, d, start, len (1 ≤ n ≤ 3·105, 0 ≤ start ≤ 109, 1 ≤ a, b, c, d, len ≤ 109), where n is a number of fashion shows and photo shoots, a, b, c and d are rating changes described above, start is an initial rating of model and len is a duration of influence of talk show.
In next n lines descriptions of events are given. Each of those lines contains two integers ti and qi (1 ≤ ti ≤ 109, 0 ≤ q ≤ 1) — moment, in which event happens and type of this event. Type 0 corresponds to the fashion show and type 1 — to photo shoot.
Events are given in order of increasing ti, all ti are different.
Output
Print one non-negative integer t — the moment of time in which talk show should happen to make Izabella's rating non-negative before talk show and during period of influence of talk show. If there are multiple answers print smallest of them. If there are no such moments, print - 1.
Examples
Input
5 1 1 1 4 0 5
1 1
2 1
3 1
4 0
5 0
Output
6
Input
1 1 2 1 2 1 2
1 0
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The goddess of programming is reviewing a thick logbook, which is a yearly record of visitors to her holy altar of programming. The logbook also records her visits at the altar.
The altar attracts programmers from all over the world because one visitor is chosen every year and endowed with a gift of miracle programming power by the goddess. The endowed programmer is chosen from those programmers who spent the longest time at the altar during the goddess's presence. There have been enthusiastic visitors who spent very long time at the altar but failed to receive the gift because the goddess was absent during their visits.
Now, your mission is to write a program that finds how long the programmer to be endowed stayed at the altar during the goddess's presence.
Input
The input is a sequence of datasets. The number of datasets is less than 100. Each dataset is formatted as follows.
n
M1/D1 h1:m1e1 p1
M2/D2 h2:m2e2 p2
.
.
.
Mn/Dn hn:mnen pn
The first line of a dataset contains a positive even integer, n ≤ 1000, which denotes the number of lines of the logbook. This line is followed by n lines of space-separated data, where Mi/Di identifies the month and the day of the visit, hi:mi represents the time of either the entrance to or exit from the altar, ei is either I for entrance, or O for exit, and pi identifies the visitor.
All the lines in the logbook are formatted in a fixed-column format. Both the month and the day in the month are represented by two digits. Therefore April 1 is represented by 04/01 and not by 4/1. The time is described in the 24-hour system, taking two digits for the hour, followed by a colon and two digits for minutes, 09:13 for instance and not like 9:13. A programmer is identified by an ID, a unique number using three digits. The same format is used to indicate entrance and exit of the goddess, whose ID is 000.
All the lines in the logbook are sorted in ascending order with respect to date and time. Because the altar is closed at midnight, the altar is emptied at 00:00. You may assume that each time in the input is between 00:01 and 23:59, inclusive.
A programmer may leave the altar just after entering it. In this case, the entrance and exit time are the same and the length of such a visit is considered 0 minute. You may assume for such entrance and exit records, the line that corresponds to the entrance appears earlier in the input than the line that corresponds to the exit. You may assume that at least one programmer appears in the logbook.
The end of the input is indicated by a line containing a single zero.
Output
For each dataset, output the total sum of the blessed time of the endowed programmer. The blessed time of a programmer is the length of his/her stay at the altar during the presence of the goddess. The endowed programmer is the one whose total blessed time is the longest among all the programmers. The output should be represented in minutes. Note that the goddess of programming is not a programmer.
Example
Input
14
04/21 09:00 I 000
04/21 09:00 I 001
04/21 09:15 I 002
04/21 09:30 O 001
04/21 09:45 O 000
04/21 10:00 O 002
04/28 09:00 I 003
04/28 09:15 I 000
04/28 09:30 I 004
04/28 09:45 O 004
04/28 10:00 O 000
04/28 10:15 O 003
04/29 20:00 I 002
04/29 21:30 O 002
20
06/01 09:00 I 001
06/01 09:15 I 002
06/01 09:15 I 003
06/01 09:30 O 002
06/01 10:00 I 000
06/01 10:15 O 001
06/01 10:30 I 002
06/01 10:45 O 002
06/01 11:00 I 001
06/01 11:15 O 000
06/01 11:30 I 002
06/01 11:45 O 001
06/01 12:00 O 002
06/01 12:15 I 000
06/01 12:30 I 002
06/01 12:45 O 000
06/01 13:00 I 000
06/01 13:15 O 000
06/01 13:30 O 002
06/01 13:45 O 003
0
Output
45
120
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.
Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on.
For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.
At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.
He asks you to help to find the initial arrangement of the balls in the boxes.
-----Input-----
The first line of the input contains two integers n and x (2 ≤ n ≤ 10^5, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n}, where integer a_{i} (0 ≤ a_{i} ≤ 10^9, a_{x} ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.
-----Examples-----
Input
4 4
4 3 1 6
Output
3 2 5 4
Input
5 2
3 2 0 2 7
Output
2 1 4 1 6
Input
3 3
2 3 1
Output
1 2 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers $1$, $5$, $10$ and $50$ respectively. The use of other roman digits is not allowed.
Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it.
For example, the number XXXV evaluates to $35$ and the number IXI — to $12$.
Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means $11$, not $9$.
One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by exactly $n$ roman digits I, V, X, L.
-----Input-----
The only line of the input file contains a single integer $n$ ($1 \le n \le 10^9$) — the number of roman digits to use.
-----Output-----
Output a single integer — the number of distinct integers which can be represented using $n$ roman digits exactly.
-----Examples-----
Input
1
Output
4
Input
2
Output
10
Input
10
Output
244
-----Note-----
In the first sample there are exactly $4$ integers which can be represented — I, V, X and L.
In the second sample it is possible to represent integers $2$ (II), $6$ (VI), $10$ (VV), $11$ (XI), $15$ (XV), $20$ (XX), $51$ (IL), $55$ (VL), $60$ (XL) and $100$ (LL).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a puzzle to complete by combining 14 numbers from 1 to 9. Complete by adding another number to the given 13 numbers.
The conditions for completing the puzzle are
* You must have one combination of the same numbers.
* The remaining 12 numbers are 4 combinations of 3 numbers.
The combination of three numbers is either three of the same numbers or three consecutive numbers. However, sequences such as 9 1 2 are not considered consecutive numbers.
* The same number can be used up to 4 times.
Create a program that reads a string of 13 numbers and outputs all the numbers that can complete the puzzle in ascending order. If you cannot complete the puzzle by adding any number from 1 to 9, output 0.
For example, if the given string is 3456666777999
If there is a "2", 234 567 666 77 999
If there is a "3", then 33 456 666 777 999
If there is a "5", then 345 567 666 77 999
If there is an "8", then 345 666 678 77 999
And so on, the puzzle is complete when one of the numbers 2 3 5 8 is added. Note that "6" is fine, but it will be used for the 5th time, so it cannot be used in this example.
Input
The input consists of multiple datasets. For each dataset, 13 numbers are given on one line. The number of datasets does not exceed 50.
Output
For each dataset, the numbers that can complete the puzzle are output on one line in ascending order, separated by blanks.
Example
Input
3649596966777
6358665788577
9118992346175
9643871425498
7755542764533
1133557799246
Output
2 3 5 8
3 4
1 2 3 4 5 6 7 8 9
7 8 9
1 2 3 4 6 7 8
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 a positive integer $m$ and two integer sequence: $a=[a_1, a_2, \ldots, a_n]$ and $b=[b_1, b_2, \ldots, b_n]$. Both of these sequence have a length $n$.
Permutation is a sequence of $n$ different positive integers from $1$ to $n$. For example, these sequences are permutations: $[1]$, $[1,2]$, $[2,1]$, $[6,7,3,4,1,2,5]$. These are not: $[0]$, $[1,1]$, $[2,3]$.
You need to find the non-negative integer $x$, and increase all elements of $a_i$ by $x$, modulo $m$ (i.e. you want to change $a_i$ to $(a_i + x) \bmod m$), so it would be possible to rearrange elements of $a$ to make it equal $b$, among them you need to find the smallest possible $x$.
In other words, you need to find the smallest non-negative integer $x$, for which it is possible to find some permutation $p=[p_1, p_2, \ldots, p_n]$, such that for all $1 \leq i \leq n$, $(a_i + x) \bmod m = b_{p_i}$, where $y \bmod m$ — remainder of division of $y$ by $m$.
For example, if $m=3$, $a = [0, 0, 2, 1], b = [2, 0, 1, 1]$, you can choose $x=1$, and $a$ will be equal to $[1, 1, 0, 2]$ and you can rearrange it to make it equal $[2, 0, 1, 1]$, which is equal to $b$.
-----Input-----
The first line contains two integers $n,m$ ($1 \leq n \leq 2000, 1 \leq m \leq 10^9$): number of elemens in arrays and $m$.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i < m$).
The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($0 \leq b_i < m$).
It is guaranteed that there exists some non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$.
-----Output-----
Print one integer, the smallest non-negative integer $x$, such that it would be possible to find some permutation $p_1, p_2, \ldots, p_n$ such that $(a_i + x) \bmod m = b_{p_i}$ for all $1 \leq i \leq n$.
-----Examples-----
Input
4 3
0 0 2 1
2 0 1 1
Output
1
Input
3 2
0 0 0
1 1 1
Output
1
Input
5 10
0 0 0 1 2
2 1 0 0 0
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if:
* the Euclidean distance between A and B is one unit and neither A nor B is blocked;
* or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B.
Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
Input
The first line contains an integer n (0 ≤ n ≤ 4·107).
Output
Print a single integer — the minimum number of points that should be blocked.
Examples
Input
1
Output
4
Input
2
Output
8
Input
3
Output
16
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum.
Assume that the input n will always be a positive integer.
Examples:
```python
sum_cubes(2)
> 9
# sum of the cubes of 1 and 2 is 1 + 8
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.
Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!
Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.
Help Polycarpus and find any suitable method to cut the public key.
-----Input-----
The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 10^6 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 10^8).
-----Output-----
In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them.
If there is no answer, print in a single line "NO" (without the quotes).
-----Examples-----
Input
116401024
97 1024
Output
YES
11640
1024
Input
284254589153928171911281811000
1009 1000
Output
YES
2842545891539
28171911281811000
Input
120
12 1
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.