question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.
Perform all calculations in the 64-bit type: long long for Π‘/Π‘++, int64 for Delphi and long for Java.
Input
The only line of the input data contains three integers n, m, t (4 β€ n β€ 30, 1 β€ m β€ 30, 5 β€ t β€ n + m).
Output
Find the required number of ways.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
Input
5 2 5
Output
10
Input
4 3 5
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a special offer in Vasya's favourite supermarket: if the customer buys $a$ chocolate bars, he or she may take $b$ additional bars for free. This special offer can be used any number of times.
Vasya currently has $s$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $c$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) β the number of testcases.
Each of the next $t$ lines contains four integers $s, a, b, c~(1 \le s, a, b, c \le 10^9)$ β the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.
-----Output-----
Print $t$ lines. $i$-th line should contain the maximum possible number of chocolate bars Vasya can get in $i$-th test.
-----Example-----
Input
2
10 3 1 1
1000000000 1 1000000000 1
Output
13
1000000001000000000
-----Note-----
In the first test of the example Vasya can buy $9$ bars, get $3$ for free, buy another bar, and so he will get $13$ bars.
In the second test Vasya buys $1000000000$ bars and gets $1000000000000000000$ for free. So he has $1000000001000000000$ bars.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Heading ##There are two integers A and B. You are required to compute the bitwise AND amongst all natural numbers lying between A and B, both inclusive.
Input Format
First line of the input contains T, the number of testcases to follow.
Each testcase in a newline contains A and B separated by a single space.
Constraints
1β€Tβ€200
0β€Aβ€B<232
Output Format
Output one line per test case with the required bitwise AND.
SAMPLE INPUT
3
12 15
2 3
8 13
SAMPLE OUTPUT
12
2
8
Explanation
1st Test Case : 12 & 13 & 14 & 15 = 12
2nd Test Case : 2 & 3 = 2
3rd Test Case : 8 & 9 & 10 & 11 & 12 & 13 = 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.
J: City
Santa decides to deliver a present to a city.
The city has a rectangular shape divided into north-south $ H $ parcels x east-west $ W $ parcels, with one house delivering gifts to each parcel.
The $ X $ th section from the north and the $ Y $ th section from the west are represented by $ (X, Y) $.
Santa moves under the following conditions.
* First, get off at block $ (S, T) $ and start from this place.
* You can move to the adjacent sections in the north, south, east, and west with one move, and you cannot move outside the city.
* You will never enter the area you visited once.
Determine if Santa can visit all the houses in the city.
input
$ H, W, S, T $ are given separated by blanks.
output
Output "Yes" if Santa can visit all the homes in the city, otherwise output "No".
Constraint
* $ H, W $ are integers greater than or equal to $ 2 $ and less than or equal to $ 1 \ 000 \ 000 \ 000 $
* $ S $ is an integer greater than or equal to $ 1 $ and less than or equal to $ H $
* $ T $ is an integer greater than or equal to $ 1 $ and less than or equal to $ W $
Input example 1
4 5 2 3
Output example 1
Yes
For example, you can go to the figure.
<image>
Input example 2
3 3 1 2
Output example 2
No
Example
Input
4 5 2 3
Output
Yes
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character.
Input
The first line contains character's name s and an integer number k (0 β€ k β€ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 β€ n β€ 676) β amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β lowercase Latin letters, - 1000 β€ c β€ 1000). It is guaranteed that no pair x y mentioned twice in the input data.
Output
Output the only number β maximum possible euphony ΠΎf the new character's name.
Examples
Input
winner 4
4
s e 7
o s 8
l o 13
o o 8
Output
36
Input
abcdef 1
5
a b -10
b c 5
c d 5
d e 5
e f 5
Output
20
Note
In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 smallest possible sum of the digits in the decimal notation of a positive multiple of K.
-----Constraints-----
- 2 \leq K \leq 10^5
- K is an integer.
-----Input-----
Input is given from Standard Input in the following format:
K
-----Output-----
Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
-----Sample Input-----
6
-----Sample Output-----
3
12=6Γ2 yields the smallest sum.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 positive integers written on a blackboard: A_1, ..., A_N.
Snuke can perform the following operation when all integers on the blackboard are even:
- Replace each integer X on the blackboard by X divided by 2.
Find the maximum possible number of operations that Snuke can perform.
-----Constraints-----
- 1 \leq N \leq 200
- 1 \leq A_i \leq 10^9
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
-----Output-----
Print the maximum possible number of operations that Snuke can perform.
-----Sample Input-----
3
8 12 40
-----Sample Output-----
2
Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.
After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.
After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.
Thus, Snuke can perform the operation at most twice.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integers b_1, b_2, ..., b_{n} written in a row. For all i from 1 to n, values a_{i} are defined by the crows performing the following procedure:
The crow sets a_{i} initially 0. The crow then adds b_{i} to a_{i}, subtracts b_{i} + 1, adds the b_{i} + 2 number, and so on until the n'th number. Thus, a_{i} = b_{i} - b_{i} + 1 + b_{i} + 2 - b_{i} + 3....
Memory gives you the values a_1, a_2, ..., a_{n}, and he now wants you to find the initial numbers b_1, b_2, ..., b_{n} written in the row? Can you do it?
-----Input-----
The first line of the input contains a single integer n (2 β€ n β€ 100 000)Β β the number of integers written in the row.
The next line contains n, the i'th of which is a_{i} ( - 10^9 β€ a_{i} β€ 10^9)Β β the value of the i'th number.
-----Output-----
Print n integers corresponding to the sequence b_1, b_2, ..., b_{n}. It's guaranteed that the answer is unique and fits in 32-bit integer type.
-----Examples-----
Input
5
6 -4 8 -2 3
Output
2 4 6 1 3
Input
5
3 -2 -1 5 6
Output
1 -3 4 11 6
-----Note-----
In the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and - 4 = 4 - 6 + 1 - 3.
In the second sample test, the sequence 1, - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 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.
Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.
You are given a string $s$, you have to delete minimum number of characters from this string so that it becomes good.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of characters in $s$.
The second line contains the string $s$, consisting of exactly $n$ lowercase Latin letters.
-----Output-----
In the first line, print one integer $k$ ($0 \le k \le n$) β the minimum number of characters you have to delete from $s$ to make it good.
In the second line, print the resulting string $s$. If it is empty, you may leave the second line blank, or not print it at all.
-----Examples-----
Input
4
good
Output
0
good
Input
4
aabc
Output
2
ab
Input
3
aaa
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a directed graph $G$ which can contain loops (edges from a vertex to itself). Multi-edges are absent in $G$ which means that for all ordered pairs $(u, v)$ exists at most one edge from $u$ to $v$. Vertices are numbered from $1$ to $n$.
A path from $u$ to $v$ is a sequence of edges such that:
vertex $u$ is the start of the first edge in the path;
vertex $v$ is the end of the last edge in the path;
for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on.
We will assume that the empty sequence of edges is a path from $u$ to $u$.
For each vertex $v$ output one of four values:
$0$, if there are no paths from $1$ to $v$;
$1$, if there is only one path from $1$ to $v$;
$2$, if there is more than one path from $1$ to $v$ and the number of paths is finite;
$-1$, if the number of paths from $1$ to $v$ is infinite.
Let's look at the example shown in the figure.
Then:
the answer for vertex $1$ is $1$: there is only one path from $1$ to $1$ (path with length $0$);
the answer for vertex $2$ is $0$: there are no paths from $1$ to $2$;
the answer for vertex $3$ is $1$: there is only one path from $1$ to $3$ (it is the edge $(1, 3)$);
the answer for vertex $4$ is $2$: there are more than one paths from $1$ to $4$ and the number of paths are finite (two paths: $[(1, 3), (3, 4)]$ and $[(1, 4)]$);
the answer for vertex $5$ is $-1$: the number of paths from $1$ to $5$ is infinite (the loop can be used in a path many times);
the answer for vertex $6$ is $-1$: the number of paths from $1$ to $6$ is infinite (the loop can be used in a path many times).
-----Input-----
The first contains an integer $t$ ($1 \le t \le 10^4$) β the number of test cases in the input. Then $t$ test cases follow. Before each test case, there is an empty line.
The first line of the test case contains two integers $n$ and $m$ ($1 \le n \le 4 \cdot 10^5, 0 \le m \le 4 \cdot 10^5$) β numbers of vertices and edges in graph respectively. The next $m$ lines contain edges descriptions. Each line contains two integers $a_i$, $b_i$ ($1 \le a_i, b_i \le n$) β the start and the end of the $i$-th edge. The vertices of the graph are numbered from $1$ to $n$. The given graph can contain loops (it is possible that $a_i = b_i$), but cannot contain multi-edges (it is not possible that $a_i = a_j$ and $b_i = b_j$ for $i \ne j$).
The sum of $n$ over all test cases does not exceed $4 \cdot 10^5$. Similarly, the sum of $m$ over all test cases does not exceed $4 \cdot 10^5$.
-----Output-----
Output $t$ lines. The $i$-th line should contain an answer for the $i$-th test case: a sequence of $n$ integers from $-1$ to $2$.
-----Examples-----
Input
5
6 7
1 4
1 3
3 4
4 5
2 1
5 5
5 6
1 0
3 3
1 2
2 3
3 1
5 0
4 4
1 2
2 3
1 4
4 3
Output
1 0 1 2 -1 -1
1
-1 -1 -1
1 0 0 0 0
1 1 2 1
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. If you repeat the process continuously for n, n will eventually reach 1.
For example, if n = 20, the resulting sequence will be:
[20, 10, 5, 16, 8, 4, 2, 1]
Write a program that will output the length of the Collatz Conjecture for any given n. In the example above, the output would be 8.
For more reading see: http://en.wikipedia.org/wiki/Collatz_conjecture
Write your solution by modifying this code:
```python
def collatz(n):
```
Your solution should implemented in the function "collatz". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
How many ways are there to place a black and a white knight on an N * M chessboard such that they do not attack each other? The knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically, or two squares vertically and one square horizontally. The knights attack each other if one can reach the other in one move.
------ Input : ------
The first line contains the number of test cases T. Each of the next T lines contains two integers N and M.
------ Output : ------
Output T lines, one for each test case, each containing the required answer for the corresponding test case.
------ Constraints : ------
1 β€ T β€ 10000
1 β€ N,M β€ 100000
----- Sample Input 1 ------
3
2 2
2 3
4 5
----- Sample Output 1 ------
12
26
312
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After learning a lot about space exploration, a little girl named Ana wants to change the subject.
Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:
You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa").
Two pairs are considered different if the strings are located on different indices. The pair of strings with indices (i,j) is considered the same as the pair (j,i).
Input
The first line contains a positive integer N (1 β€ N β€ 100 000), representing the length of the input array.
Eacg of the next N lines contains a string (consisting of lowercase English letters from 'a' to 'z') β an element of the input array.
The total number of characters in the input array will be less than 1 000 000.
Output
Output one number, representing how many palindrome pairs there are in the array.
Examples
Input
3
aa
bb
cd
Output
1
Input
6
aab
abcac
dffe
ed
aa
aade
Output
6
Note
The first example:
1. aa + bb β abba.
The second example:
1. aab + abcac = aababcac β aabccbaa
2. aab + aa = aabaa
3. abcac + aa = abcacaa β aacbcaa
4. dffe + ed = dffeed β fdeedf
5. dffe + aade = dffeaade β adfaafde
6. ed + aade = edaade β aeddea
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a String(only lower case letters) , check if any substring has occured Twice :
Example : iwsagoodboody
Here, substring "ood" occurs twice.
Output "YES" if there is any such substring else output "NO" .(without qoutes)
Input:
First line of input consists of an integer T (1 β€ T β€ 100) , indicating the number of test cases.
For each test case, there will be a string s (1 β€ |s| β€ 2000)
Output:
Print "YES" if there is any such substring else Print "NO" .(without quotes)
SAMPLE INPUT
3
abcdefghi
dogsbarkatdogs
howtheydo
SAMPLE OUTPUT
NO
YES
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.
n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.
Input
The first line contains integer n (1 β€ n β€ 18) β the amount of fish in the lake. Then there follow n lines with n real numbers each β matrix a. aij (0 β€ aij β€ 1) β the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.
Output
Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.
Examples
Input
2
0 0.5
0.5 0
Output
0.500000 0.500000
Input
5
0 1 1 1 1
0 0 0.5 0.5 0.5
0 0.5 0 0.5 0.5
0 0.5 0.5 0 0.5
0 0.5 0.5 0.5 0
Output
1.000000 0.000000 0.000000 0.000000 0.000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a binary string $s$ consisting of $n$ zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) β the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the length of $s$. The second line of the test case contains $n$ characters '0' and '1' β the string $s$.
It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer: in the first line print one integer $k$ ($1 \le k \le n$) β the minimum number of subsequences you can divide the string $s$ to. In the second line print $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le k$), where $a_i$ is the number of subsequence the $i$-th character of $s$ belongs to.
If there are several answers, you can print any.
-----Example-----
Input
4
4
0011
6
111111
5
10101
8
01010000
Output
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7.
The Little Elephant has K favorite lucky strings A_{1}, A_{2}, ..., A_{K}. He thinks that the lucky string S is good if either |S| β₯ 47 or for some j from 1 to K we have that A_{j} is a substring of S.
The Little Elephant has found N lucky strings B_{1}, B_{2}, ..., B_{N} under the pillow. Now he wants to know which of them are good. Help him and find for each i from 1 to N whether the string B_{i} is good or not.
Notes.
Let S be some lucky string. Then
|S| denotes the length of the string S;
S[i] (1 β€ i β€ |S|) denotes the i^{th} character of S (the numeration of characters starts from 1);
The string T of the length M is called a substring of S if for some k from 0 to |S| - M we have
T[1] = S[k + 1], T[2] = S[k + 2], ..., T[M] = S[k + M].
------ Input ------
The first line of the input file contains two integers K and N, the number of favorite lucky strings of the Little Elephant and the number of strings he has found under the pillow. Each of the following K lines contains one favorite lucky string. Namely, j^{th} line among these K lines contains the string A_{j}. Each of the following N lines contains one lucky string that was found under the pillow. Namely, i^{th} line among these N lines contains the string B_{i}. The input file does not contain any whitespaces.
------ Output ------
For each of the N strings that were found under the pillow print Good if it is good, and Bad otherwise.
------ Constraints ------
1 β€ K, N β€ 50
For each string S in the input file we have 1 β€ |S| β€ 50.
Each string in the input file consists only of the lucky digits 4 and 7.
----- Sample Input 1 ------
2 4
47
744
7444
447
7774
77777777777777777777777777777777777777777777774
----- Sample Output 1 ------
Good
Good
Bad
Good
----- explanation 1 ------
The string S = 7444 is good since the favorite string 744 is its substring.
The string S = 447 is good since the favorite string 47 is its substring.
The string S = 7774 is bad since none of the favorite strings 47 and 744 is a substring of S.
The string S = 77777777777777777777777777777777777777777777774 is good since its length is 47. Note, however, that S does not have favorite substrings at all.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
"Search" is an operation to obtain the desired information from a large amount of information. Familiar examples include "finding your own exam number from a large number of exam numbers" when announcing your success, or "finding Taro Aizu's phone number" from your phone book. This search operation is also widely used in the computer field.
<image>
There are many ways to search. Consider a search method that can be used when the data to be searched is arranged in ascending (or largest) order.
Using the magnitude relationship between the value located in the center of the data string arranged in ascending order (or in descending order) and the target value, the first half is set as the search range or the second half is searched from the value located in the center. There is a way to narrow down the search range by deciding whether to make it a range. The procedure is as follows.
1. The entire column of data is the scope of the search.
2. Examine the value located in the center of the search range.
3. If the desired value matches the centered value, the search ends.
4. If it is smaller than the target value and the value located in the center, the first half is the search range, and if it is larger, the second half is the search range and returns to 2.
The following is an example of the search method described above. The desired value in this example is 51. Each piece of data is numbered (index), which starts at 0.
Step 1: Initially, the search range is the entire number 0-6.
Step 2: Find the value in the center of the search range. However, the "centered value" is the value at the position of the number obtained by dividing (the number on the left side + the number on the right side) by 2. In other words, in this case, (0 + 6) Γ· 2 is calculated, and the value (36) at number 3 is the value located in the center.
Step 3: Compare the desired value (51) with the centrally located value (36).
Step 4: From the result of step 3, the target value is larger than the value located in the center, so the search range is from number 4 (next to the value located in the center) in the latter half. Use the same procedure to check the value located in the center of the search range, and if the target value is smaller than the value located in the center, the first half is the search range, and if it is larger, the second half is the search range. I will make it smaller. (Repeat of steps 2 to 4) The search ends when the target value matches the value located in the center or the search range is reached.
| <image>
--- | ---
Create a program that takes an array of n numbers as input and outputs the number of times the target value is compared with the value located in the center. However, if the number of the value located in the center is not divisible, the value rounded down to the nearest whole number will be used as the number. It is assumed that the given data columns are sorted in ascending order.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
a1
a2
::
an
k
The number of numbers n (1 β€ n β€ 100) is given on the first line, and the i-th number ai (1 β€ ai β€ 100000, integer) is given on the following n lines.
The following line is given the value k (1 β€ k β€ 100000) to search for.
Output
The number of comparisons until the search is completed for each data set is output on one line.
Example
Input
7
11
15
23
36
51
61
86
51
4
1
2
3
5
4
0
Output
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.
Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.
Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.
Since the answer can be enormous, print the count modulo 10^9+7.
-----Constraints-----
- S is a string consisting of digits (0, ..., 9) and ?.
- 1 \leq |S| \leq 10^5
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the number of integers satisfying the condition, modulo 10^9+7.
-----Sample Input-----
??2??5
-----Sample Output-----
768
For example, 482305, 002865, and 972665 satisfy the condition.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant.
In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not.
Help Vitya find out if a word $s$ is Berlanese.
-----Input-----
The first line of the input contains the string $s$ consisting of $|s|$ ($1\leq |s|\leq 100$) lowercase Latin letters.
-----Output-----
Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
sumimasen
Output
YES
Input
ninja
Output
YES
Input
codeforces
Output
NO
-----Note-----
In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese.
In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Bob is about to take a hot bath.
There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second.
If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be:
<image>
Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible.
Determine how much each tap should be opened so that Bob was pleased with the result in the end.
Input
You are given five integers t1, t2, x1, x2 and t0 (1 β€ t1 β€ t0 β€ t2 β€ 106, 1 β€ x1, x2 β€ 106).
Output
Print two space-separated integers y1 and y2 (0 β€ y1 β€ x1, 0 β€ y2 β€ x2).
Examples
Input
10 70 100 100 25
Output
99 33
Input
300 500 1000 1000 300
Output
1000 0
Input
143 456 110 117 273
Output
76 54
Note
In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 four integers $a$, $b$, $x$ and $y$. Initially, $a \ge x$ and $b \ge y$. You can do the following operation no more than $n$ times:
Choose either $a$ or $b$ and decrease it by one. However, as a result of this operation, value of $a$ cannot become less than $x$, and value of $b$ cannot become less than $y$.
Your task is to find the minimum possible product of $a$ and $b$ ($a \cdot b$) you can achieve by applying the given operation no more than $n$ times.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) β the number of test cases. Then $t$ test cases follow.
The only line of the test case contains five integers $a$, $b$, $x$, $y$ and $n$ ($1 \le a, b, x, y, n \le 10^9$). Additional constraint on the input: $a \ge x$ and $b \ge y$ always holds.
-----Output-----
For each test case, print one integer: the minimum possible product of $a$ and $b$ ($a \cdot b$) you can achieve by applying the given operation no more than $n$ times.
-----Example-----
Input
7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10
Output
70
77
177177
999999999000000000
999999999
55
10
-----Note-----
In the first test case of the example, you need to decrease $b$ three times and obtain $10 \cdot 7 = 70$.
In the second test case of the example, you need to decrease $a$ one time, $b$ one time and obtain $11 \cdot 7 = 77$.
In the sixth test case of the example, you need to decrease $a$ five times and obtain $5 \cdot 11 = 55$.
In the seventh test case of the example, you need to decrease $b$ ten times and obtain $10 \cdot 1 = 10$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The grasshopper is located on the numeric axis at the point with coordinate $x_0$.
Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $x$ with a distance $d$ to the left moves the grasshopper to a point with a coordinate $x - d$, while jumping to the right moves him to a point with a coordinate $x + d$.
The grasshopper is very fond of positive integers, so for each integer $i$ starting with $1$ the following holds: exactly $i$ minutes after the start he makes a jump with a distance of exactly $i$. So, in the first minutes he jumps by $1$, then by $2$, and so on.
The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.
For example, if after $18$ consecutive jumps he arrives at the point with a coordinate $7$, he will jump by a distance of $19$ to the right, since $7$ is an odd number, and will end up at a point $7 + 19 = 26$. Since $26$ is an even number, the next jump the grasshopper will make to the left by a distance of $20$, and it will move him to the point $26 - 20 = 6$.
Find exactly which point the grasshopper will be at after exactly $n$ jumps.
-----Input-----
The first line of input contains an integer $t$ ($1 \leq t \leq 10^4$) β the number of test cases.
Each of the following $t$ lines contains two integers $x_0$ ($-10^{14} \leq x_0 \leq 10^{14}$) and $n$ ($0 \leq n \leq 10^{14}$) β the coordinate of the grasshopper's initial position and the number of jumps.
-----Output-----
Print exactly $t$ lines. On the $i$-th line print one integer β the answer to the $i$-th test case β the coordinate of the point the grasshopper will be at after making $n$ jumps from the point $x_0$.
-----Examples-----
Input
9
0 1
0 2
10 10
10 99
177 13
10000000000 987654321
-433494437 87178291199
1 0
-1 1
Output
-1
1
11
110
190
9012345679
-87611785637
1
0
-----Note-----
The first two test cases in the example correspond to the first two jumps from the point $x_0 = 0$.
Since $0$ is an even number, the first jump of length $1$ is made to the left, and the grasshopper ends up at the point $0 - 1 = -1$.
Then, since $-1$ is an odd number, a jump of length $2$ is made to the right, bringing the grasshopper to the point with coordinate $-1 + 2 = 1$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.
That element can store information about the matrix of integers size n Γ m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.
Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.
Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.
Input
The first line of the input contains three integers n, m and q (1 β€ n, m β€ 100, 1 β€ q β€ 10 000) β dimensions of the matrix and the number of turns in the experiment, respectively.
Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 β€ ti β€ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 β€ ri β€ n) or ci (1 β€ ci β€ m) follows, while for the operations of the third type three integers ri, ci and xi (1 β€ ri β€ n, 1 β€ ci β€ m, - 109 β€ xi β€ 109) are given.
Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.
Output
Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value.
If there are multiple valid solutions, output any of them.
Examples
Input
2 2 6
2 1
2 2
3 1 1 1
3 2 2 2
3 1 2 8
3 2 1 8
Output
8 2
1 8
Input
3 3 2
1 2
3 2 2 5
Output
0 0 0
0 0 5
0 0 0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a string S of length N-1. Each character in S is `<` or `>`.
A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1):
* If S_i= `<`: a_i<a_{i+1}
* If S_i= `>`: a_i>a_{i+1}
Find the minimum possible sum of the elements of a good sequence of N non-negative integers.
Constraints
* 2 \leq N \leq 5 \times 10^5
* S is a string of length N-1 consisting of `<` and `>`.
Input
Input is given from Standard Input in the following format:
S
Output
Find the minimum possible sum of the elements of a good sequence of N non-negative integers.
Examples
Input
<>>
Output
3
Input
<>>><<><<<<<>>><
Output
28
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.
A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.
Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is 6 because all its substrings are palindromes, and the palindromic count of the string "abc" is 3 because only its substrings of length 1 are palindromes.
You are given a string s. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.
Input
The first line contains an integer n (1 β€ n β€ 100 000) β the length of string s.
The second line contains string s that consists of exactly n lowercase characters of Latin alphabet.
Output
Print string t, which consists of the same set of characters (and each characters appears exactly the same number of times) as string s. Moreover, t should have the maximum possible value of palindromic count among all such strings strings.
If there are multiple such strings, print any of them.
Examples
Input
5
oolol
Output
ololo
Input
16
gagadbcgghhchbdf
Output
abccbaghghghgdfd
Note
In the first example, string "ololo" has 9 palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.
In the second example, the palindromic count of string "abccbaghghghgdfd" is 29.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Nezzar's favorite digit among $1,\ldots,9$ is $d$. He calls a positive integer lucky if $d$ occurs at least once in its decimal representation.
Given $q$ integers $a_1,a_2,\ldots,a_q$, for each $1 \le i \le q$ Nezzar would like to know if $a_i$ can be equal to a sum of several (one or more) lucky numbers.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 9$) β the number of test cases.
The first line of each test case contains two integers $q$ and $d$ ($1 \le q \le 10^4$, $1 \le d \le 9$).
The second line of each test case contains $q$ integers $a_1,a_2,\ldots,a_q$ ($1 \le a_i \le 10^9$).
-----Output-----
For each integer in each test case, print "YES" in a single line if $a_i$ can be equal to a sum of lucky numbers. Otherwise, print "NO".
You can print letters in any case (upper or lower).
-----Examples-----
Input
2
3 7
24 25 27
10 7
51 52 53 54 55 56 57 58 59 60
Output
YES
NO
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
NO
-----Note-----
In the first test case, $24 = 17 + 7$, $27$ itself is a lucky number, $25$ cannot be equal to a sum of lucky numbers.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.
Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $2$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $2$, divide the base into $2$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $A$ amount of power, otherwise it takes his $B \cdot n_a \cdot l$ amount of power, where $n_a$ is the number of avengers and $l$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.
-----Input-----
The first line contains four integers $n$, $k$, $A$ and $B$ ($1 \leq n \leq 30$, $1 \leq k \leq 10^5$, $1 \leq A,B \leq 10^4$), where $2^n$ is the length of the base, $k$ is the number of avengers and $A$ and $B$ are the constants explained in the question.
The second line contains $k$ integers $a_{1}, a_{2}, a_{3}, \ldots, a_{k}$ ($1 \leq a_{i} \leq 2^n$), where $a_{i}$ represents the position of avenger in the base.
-----Output-----
Output one integer β the minimum power needed to destroy the avengers base.
-----Examples-----
Input
2 2 1 2
1 3
Output
6
Input
3 2 1 2
1 7
Output
8
-----Note-----
Consider the first example.
One option for Thanos is to burn the whole base $1-4$ with power $2 \cdot 2 \cdot 4 = 16$.
Otherwise he can divide the base into two parts $1-2$ and $3-4$.
For base $1-2$, he can either burn it with power $2 \cdot 1 \cdot 2 = 4$ or divide it into $2$ parts $1-1$ and $2-2$.
For base $1-1$, he can burn it with power $2 \cdot 1 \cdot 1 = 2$. For $2-2$, he can destroy it with power $1$, as there are no avengers. So, the total power for destroying $1-2$ is $2 + 1 = 3$, which is less than $4$.
Similarly, he needs $3$ power to destroy $3-4$. The total minimum power needed is $6$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $X[i]$ grams on day $i$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $A$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $C[i]$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $K$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $-1$.
-----Input-----
The first one contains two integer numbers, integers $N$ $(1 \leq N \leq 10^5)$ and $K$ $(1 \leq K \leq 10^5)$ β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $N$ integer numbers $X[i]$ $(1 \leq X[i] \leq 10^9)$ separated by a single space representing how many grams Alan wants to lift on day $i$. The third line contains one integer number $A$ $(1 \leq A \leq 10^9)$ representing permanent performance gains from a single drink. The last line contains $N$ integer numbers $C[i]$ $(1 \leq C[i] \leq 10^9)$ , representing cost of performance booster drink in the gym he visits on day $i$.
-----Output-----
One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1.
-----Examples-----
Input
5 10000
10000 30000 30000 40000 20000
20000
5 2 8 3 6
Output
5
Input
5 10000
10000 40000 30000 30000 20000
10000
5 2 8 3 6
Output
-1
-----Note-----
First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 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 dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance.
They take turns drawing a mouse from a bag which initially contains w white and b black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). Princess draws first. What is the probability of the princess winning?
If there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one.
Input
The only line of input data contains two integers w and b (0 β€ w, b β€ 1000).
Output
Output the probability of the princess winning. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.
Examples
Input
1 3
Output
0.500000000
Input
5 5
Output
0.658730159
Note
Let's go through the first sample. The probability of the princess drawing a white mouse on her first turn and winning right away is 1/4. The probability of the dragon drawing a black mouse and not winning on his first turn is 3/4 * 2/3 = 1/2. After this there are two mice left in the bag β one black and one white; one of them jumps out, and the other is drawn by the princess on her second turn. If the princess' mouse is white, she wins (probability is 1/2 * 1/2 = 1/4), otherwise nobody gets the white mouse, so according to the rule the dragon 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.
Description:
The mean (or average) is the most popular measure of central tendency; however it does not behave very well when the data is skewed (i.e. wages distribution). In such cases, it's better to use the median.
Your task for this kata is to find the median of an array consisting of n elements.
You can assume that all inputs are arrays of numbers in integer format. For the empty array your code should return `NaN` (false in JavaScript/`NULL` in PHP/`nil` in Ruby).
Examples:
Input `[1, 2, 3, 4]` --> Median `2.5`
Input `[3, 4, 1, 2, 5]` --> Median `3`
Write your solution by modifying this code:
```python
def median(arr):
```
Your solution should implemented in the function "median". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·a_{i} + qΒ·a_{j} + rΒ·a_{k} for given p, q, r and array a_1, a_2, ... a_{n} such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
-----Input-----
First line of input contains 4 integers n, p, q, r ( - 10^9 β€ p, q, r β€ 10^9, 1 β€ n β€ 10^5).
Next line of input contains n space separated integers a_1, a_2, ... a_{n} ( - 10^9 β€ a_{i} β€ 10^9).
-----Output-----
Output a single integer the maximum value of pΒ·a_{i} + qΒ·a_{j} + rΒ·a_{k} that can be obtained provided 1 β€ i β€ j β€ k β€ n.
-----Examples-----
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
-----Note-----
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarpus has got n candies and m friends (n β₯ m). He wants to make a New Year present with candies to each friend. Polycarpus is planning to present all candies and he wants to do this in the fairest (that is, most equal) manner. He wants to choose such a_{i}, where a_{i} is the number of candies in the i-th friend's present, that the maximum a_{i} differs from the least a_{i} as little as possible.
For example, if n is divisible by m, then he is going to present the same number of candies to all his friends, that is, the maximum a_{i} won't differ from the minimum one.
-----Input-----
The single line of the input contains a pair of space-separated positive integers n, m (1 β€ n, m β€ 100;n β₯ m) β the number of candies and the number of Polycarpus's friends.
-----Output-----
Print the required sequence a_1, a_2, ..., a_{m}, where a_{i} is the number of candies in the i-th friend's present. All numbers a_{i} must be positive integers, total up to n, the maximum one should differ from the minimum one by the smallest possible value.
-----Examples-----
Input
12 3
Output
4 4 4
Input
15 4
Output
3 4 4 4
Input
18 7
Output
2 2 2 3 3 3 3
-----Note-----
Print a_{i} in any order, separate the numbers by spaces.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
Timed Reading is an educational tool used in many schools to improve and advance reading skills. A young elementary student has just finished his very first timed reading exercise. Unfortunately he's not a very good reader yet, so whenever he encountered a word longer than maxLength, he simply skipped it and read on.
Help the teacher figure out how many words the boy has read by calculating the number of words in the text he has read, no longer than maxLength.
Formally, a word is a substring consisting of English letters, such that characters to the left of the leftmost letter and to the right of the rightmost letter are not letters.
# Example
For `maxLength = 4` and `text = "The Fox asked the stork, 'How is the soup?'"`, the output should be `7`
The boy has read the following words: `"The", "Fox", "the", "How", "is", "the", "soup".`
# Input/Output
- `[input]` integer `maxLength`
A positive integer, the maximum length of the word the boy can read.
Constraints: `1 β€ maxLength β€ 10.`
- `[input]` string `text`
A non-empty string of English letters and punctuation marks.
- `[output]` an integer
The number of words the boy has read.
Write your solution by modifying this code:
```python
def timed_reading(max_length, text):
```
Your solution should implemented in the function "timed_reading". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Byteland they have a very strange monetary system.
Each Bytelandian gold coin has an integer number written on it. A coin n
can be exchanged in a bank into three coins: n/2, n/3 and n/4.
But these numbers are all rounded down (the banks have to make a profit).
You can also sell Bytelandian coins for American dollars. The exchange
rate is 1:1. But you can not buy Bytelandian coins.
You have one gold coin. What is the maximum amount of American dollars
you can get for it?
------ Input Format ------
The input will contain several test cases (not more than 10). \
Each testcase is a single line with a number n, it is the number written on your coin.
------ Output Format ------
For each test case output a single line, containing the maximum amount of American dollars you can make.
------ Constraints ------
$0 β€ n β€ 10^{9}$
----- Sample Input 1 ------
12
2
----- Sample Output 1 ------
13
2
----- explanation 1 ------
Test case 1: You can change 12 into 6, 4 and 3, and then change these into $6+4+3 = 13$. \
Test case 2: If you try changing the coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1$ out of them. \
It is better just to change the $2$ coin directly into $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.
Sherlock Holmes and Dr. Watson played some game on a checkered board n Γ n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.
<image>
For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 > 19.
Input
The first line contains an integer n (1 β€ n β€ 30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.
Output
Print the single number β the number of the winning squares.
Examples
Input
1
1
Output
0
Input
2
1 2
3 4
Output
2
Input
4
5 7 8 4
9 5 3 2
1 6 6 4
9 5 7 3
Output
6
Note
In the first example two upper squares are winning.
In the third example three left squares in the both middle rows are winning:
5 7 8 4
9 5 3 2
1 6 6 4
9 5 7 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.
Theory
This section does not need to be read and can be skipped, but it does provide some clarity into the inspiration behind the problem.
In music theory, a major scale consists of seven notes, or scale degrees, in order (with tonic listed twice for demonstrative purposes):
Tonic, the base of the scale and the note the scale is named after (for example, C is the tonic note of the C major scale)
Supertonic, 2 semitones (or one tone) above the tonic
Mediant, 2 semitones above the supertonic and 4 above the tonic
Subdominant, 1 semitone above the median and 5 above the tonic
Dominant, 2 semitones above the subdominant and 7 above the tonic
Submediant, 2 semitones above the dominant and 9 above the tonic
Leading tone, 2 semitones above the mediant and 11 above the tonic
Tonic (again!), 1 semitone above the leading tone and 12 semitones (or one octave) above the tonic
An octave is an interval of 12 semitones, and the pitch class of a note consists of any note that is some integer
number of octaves apart from that note. Notes in the same pitch class sound different but share similar properties. If a note is in a major scale, then any note in that note's pitch class is also in that major scale.
Problem
Using integers to represent notes, the major scale of an integer note will be an array (or list) of integers that follows the major scale pattern note, note + 2, note + 4, note + 5, note + 7, note + 9, note + 11. For example, the array of integers [1, 3, 5, 6, 8, 10, 12] is the major scale of 1.
Secondly, the pitch class of a note will be the set of all integers some multiple of 12 above or below the note. For example, 1, 13, and 25 are all in the same pitch class.
Thirdly, an integer note1 is considered to be in the key of an integer note2 if note1, or some integer in note1's pitch class, is in the major scale of note2. More mathematically, an integer note1 is in the key of an integer note2 if there exists an integer i such that note1 + i Γ 12 is in the major scale of note2. For example, 22 is in the key of of 1 because, even though 22 is not in 1's major scale ([1, 3, 5, 6, 8, 10, 12]), 10 is and is also a multiple of 12 away from 22. Likewise, -21 is also in the key of 1 because -21 + (2 Γ 12) = 3 and 3 is present in the major scale of 1. An array is in the key of an integer if all its elements are in the key of the integer.
Your job is to create a function is_tune that will return whether or not an array (or list) of integers is a tune. An array will be considered a tune if there exists a single integer note all the integers in the array are in the key of. The function will accept an array of integers as its parameter and return True if the array is a tune or False otherwise. Empty and null arrays are not considered to be tunes. Additionally, the function should not change the input array.
Examples
```python
is_tune([1, 3, 6, 8, 10, 12]) # Returns True, all the elements are in the major scale
# of 1 ([1, 3, 5, 6, 8, 10, 12]) and so are in the key of 1.
is_tune([1, 3, 6, 8, 10, 12, 13, 15]) # Returns True, 14 and 15 are also in the key of 1 as
# they are in the major scale of 13 which is in the pitch class of 1 (13 = 1 + 12 * 1).
is_tune([1, 6, 3]) # Returns True, arrays don't need to be sorted.
is_tune([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # Returns False, this array is not in the
# key of any integer.
is_tune([2, 4, 7, 9, 11, 13]) # Returns True, the array is in the key of 2 (the arrays
# don't need to be in the key of 1, just some integer)
```
Write your solution by modifying this code:
```python
def is_tune(notes):
```
Your solution should implemented in the function "is_tune". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves darts as much as programming. Yu-kun was addicted to darts recently, but he got tired of ordinary darts, so he decided to make his own darts board.
See darts for darts.
Problem
The contents of the darts that Yu-kun thought about are as follows.
The infinitely wide darts board has several polygons with scores. The player has only one darts arrow. The player throws an arrow and stabs the arrow into one of the polygons to get the score written there. If you stab it in any other way, you will not get any points.
Yu-kun decided where to throw the arrow, but it doesn't always stick exactly. The darts board is a two-dimensional plane, and the position Yu-kun is aiming for is a point (cx, cy). The place where the arrow thrown by Yu-kun sticks is selected with a uniform probability from any point included in the circle with radius r centered on the point (cx, cy). The coordinates of the exposed points do not have to be integers.
Since the information on the darts board, the position (cx, cy) that Yu-kun aims at, and the radius r are given, answer the expected value of the score that Yu-kun can get.
Constraints
The input satisfies the following conditions.
* All inputs are given as integers
* 1 β€ n β€ 50
* 0 β€ cx, cy, x, y β€ 1000
* 1 β€ r β€ 100
* 3 β€ p β€ 10
* 1 β€ score β€ 100
* Polygon vertices are given in such an order that they visit adjacent vertices clockwise or counterclockwise.
* The sides of a polygon do not have anything in common with the sides of another polygon
* A polygon does not contain another polygon
* If the arrow sticks on the side of the polygon, no score will be given.
Input
n cx cy r
Information on the 0th polygon
Information on the first polygon
...
Information on the (n-1) th polygon
n is the number of polygons on the darts board. Polygonal information is given in the following format.
p score
x0 y0
x1 y1
...
x (p-1) y (p-1)
p represents the number of vertices of the polygon, and score represents the score written on the polygon. Each line segment of the polygon is a line segment connecting the vertices of (xi, yi) and (xi + 1, yi + 1) (i <p-1), and (xp-1, yp-1) and (x0, It is a line segment connecting the vertices of y0).
Output
Output the expected value of the score that Yu-kun can get in one line. Any number of digits after the decimal point may be output. However, the error in the answer must not exceed 0.000001 (10-6).
Examples
Input
1 2 2 1
4 1
0 0
2 0
2 2
0 2
Output
0.2500000000
Input
1 2 2 1
4 1
0 0
5 0
5 5
0 5
Output
1.0000000000
Input
4 3 3 2
3 1
1 1
3 3
1 5
4 2
2 0
5 0
4 2
3 2
3 3
4 3
6 1
6 5
4 4
3 4
4 4
5 6
2 6
Output
1.0574955319
Input
1 10 10 1
4 10
0 0
1 0
1 1
0 1
Output
0.0000000000
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $2n$ integers $1, 2, \dots, 2n$. You have to redistribute these $2n$ elements into $n$ pairs. After that, you choose $x$ pairs and take minimum elements from them, and from the other $n - x$ pairs, you take maximum elements.
Your goal is to obtain the set of numbers $\{b_1, b_2, \dots, b_n\}$ as the result of taking elements from the pairs.
What is the number of different $x$-s ($0 \le x \le n$) such that it's possible to obtain the set $b$ if for each $x$ you can choose how to distribute numbers into pairs and from which $x$ pairs choose minimum elements?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) β the number of test cases.
The first line of each test case contains the integer $n$ ($1 \le n \le 2 \cdot 10^5$).
The second line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_1 < b_2 < \dots < b_n \le 2n$) β the set you'd like to get.
It's guaranteed that the sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case, print one number β the number of different $x$-s such that it's possible to obtain the set $b$.
-----Examples-----
Input
3
1
1
5
1 4 5 9 10
2
3 4
Output
1
3
1
-----Note-----
In the first test case, $x = 1$ is the only option: you have one pair $(1, 2)$ and choose the minimum from this pair.
In the second test case, there are three possible $x$-s. If $x = 1$, then you can form the following pairs: $(1, 6)$, $(2, 4)$, $(3, 5)$, $(7, 9)$, $(8, 10)$. You can take minimum from $(1, 6)$ (equal to $1$) and the maximum elements from all other pairs to get set $b$.
If $x = 2$, you can form pairs $(1, 2)$, $(3, 4)$, $(5, 6)$, $(7, 9)$, $(8, 10)$ and take the minimum elements from $(1, 2)$, $(5, 6)$ and the maximum elements from the other pairs.
If $x = 3$, you can form pairs $(1, 3)$, $(4, 6)$, $(5, 7)$, $(2, 9)$, $(8, 10)$ and take the minimum elements from $(1, 3)$, $(4, 6)$, $(5, 7)$.
In the third test case, $x = 0$ is the only option: you can form pairs $(1, 3)$, $(2, 4)$ and take the maximum elements from both of them.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
On a two-dimensional plane, there are N red points and N blue points.
The coordinates of the i-th red point are (a_i, b_i), and the coordinates of the i-th blue point are (c_i, d_i).
A red point and a blue point can form a friendly pair when, the x-coordinate of the red point is smaller than that of the blue point, and the y-coordinate of the red point is also smaller than that of the blue point.
At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.
-----Constraints-----
- All input values are integers.
- 1 \leq N \leq 100
- 0 \leq a_i, b_i, c_i, d_i < 2N
- a_1, a_2, ..., a_N, c_1, c_2, ..., c_N are all different.
- b_1, b_2, ..., b_N, d_1, d_2, ..., d_N are all different.
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 b_1
a_2 b_2
:
a_N b_N
c_1 d_1
c_2 d_2
:
c_N d_N
-----Output-----
Print the maximum number of friendly pairs.
-----Sample Input-----
3
2 0
3 1
1 3
4 2
0 4
5 5
-----Sample Output-----
2
For example, you can pair (2, 0) and (4, 2), then (3, 1) and (5, 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.
When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riversideΒ β not tangerines, but blossoms instead.
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic.
The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.
When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.
You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.
-----Input-----
The first and only line of input contains a non-empty string $s$ consisting of uppercase English letters 'A', 'B', 'C' and characters '.' (dots) only ($\lvert s \rvert \leq 100$)Β β denoting cells containing an amber flower, a buff one, a canary yellow one, and no flowers, respectively.
-----Output-----
Output "Yes" if it's possible that all three colours appear in some cell, and "No" otherwise.
You can print each letter in any case (upper or lower).
-----Examples-----
Input
.BAC.
Output
Yes
Input
AA..CB
Output
No
-----Note-----
In the first example, the buff and canary yellow flowers can leave their petals in the central cell, blending all three colours in it.
In the second example, it's impossible to satisfy the requirement because there is no way that amber and buff meet in any cell.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
Constraints
* 1\leq N \leq 10^{16}
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
Examples
Input
100
Output
18
Input
9995
Output
35
Input
3141592653589793
Output
137
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.
People don't use cash as often as they used to. Having a credit card solves some of the hassles of cash, such as having to receive change when you can't form the exact amount of money needed to purchase an item. Typically cashiers will give you as few coins as possible in change, but they don't have to. For example, if your change is 30 cents, a cashier could give you a 5 cent piece and a 25 cent piece, or they could give you three 10 cent pieces, or ten 1 cent pieces, two 5 cent pieces, and one 10 cent piece. Altogether there are 18 different ways to make 30 cents using only 1 cent pieces, 5 cent pieces, 10 cent pieces, and 25 cent pieces. Two ways are considered different if they contain a different number of at least one type of coin. Given the denominations of the coins and an amount of change to be made, how many different ways are there to make change?
As we mentioned before, we lost all the test cases for this problem, so we're actually going to give you the number of ways, and want you to produce a test case for which the number of ways is the given number. There could be many ways to achieve this (we guarantee there's always at least one), so you can print any, as long as it meets the constraints described below.
Input
Input will consist of a single integer A (1 β€ A β€ 105), the desired number of ways.
Output
In the first line print integers N and M (1 β€ N β€ 106, 1 β€ M β€ 10), the amount of change to be made, and the number of denominations, respectively.
Then print M integers D1, D2, ..., DM (1 β€ Di β€ 106), the denominations of the coins. All denominations must be distinct: for any i β j we must have Di β Dj.
If there are multiple tests, print any of them. You can print denominations in atbitrary order.
Examples
Input
18
Output
30 4
1 5 10 25
Input
3
Output
20 2
5 2
Input
314
Output
183 4
6 5 2 139
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s β t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.
Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest.
The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.
-----Input-----
The first lines contain four integers n, m, s and t (2 β€ n β€ 10^5;Β 1 β€ m β€ 10^5;Β 1 β€ s, t β€ n) β the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s β t).
Next m lines contain the roads. Each road is given as a group of three integers a_{i}, b_{i}, l_{i} (1 β€ a_{i}, b_{i} β€ n;Β a_{i} β b_{i};Β 1 β€ l_{i} β€ 10^6) β the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city a_{i} to city b_{i}.
The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads.
-----Output-----
Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input).
If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes).
Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing.
If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes).
-----Examples-----
Input
6 7 1 6
1 2 2
1 3 10
2 3 7
2 4 8
3 5 3
4 5 2
5 6 1
Output
YES
CAN 2
CAN 1
CAN 1
CAN 1
CAN 1
YES
Input
3 3 1 3
1 2 10
2 3 10
1 3 100
Output
YES
YES
CAN 81
Input
2 2 1 2
1 2 1
1 2 2
Output
YES
NO
-----Note-----
The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing.
In the first sample president initially may choose one of the two following ways for a ride: 1 β 2 β 4 β 5 β 6 or 1 β 2 β 3 β 5 β 6.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N rabbits, numbered 1, 2, \ldots, N.
For each i, j (1 \leq i, j \leq N), the compatibility of Rabbit i and j is described by an integer a_{i, j}. Here, a_{i, i} = 0 for each i (1 \leq i \leq N), and a_{i, j} = a_{j, i} for each i and j (1 \leq i, j \leq N).
Taro is dividing the N rabbits into some number of groups. Here, each rabbit must belong to exactly one group. After grouping, for each i and j (1 \leq i < j \leq N), Taro earns a_{i, j} points if Rabbit i and j belong to the same group.
Find Taro's maximum possible total score.
Constraints
* All values in input are integers.
* 1 \leq N \leq 16
* |a_{i, j}| \leq 10^9
* a_{i, i} = 0
* a_{i, j} = a_{j, i}
Input
Input is given from Standard Input in the following format:
N
a_{1, 1} \ldots a_{1, N}
:
a_{N, 1} \ldots a_{N, N}
Output
Print Taro's maximum possible total score.
Examples
Input
3
0 10 20
10 0 -100
20 -100 0
Output
20
Input
2
0 -10
-10 0
Output
0
Input
4
0 1000000000 1000000000 1000000000
1000000000 0 1000000000 1000000000
1000000000 1000000000 0 -1
1000000000 1000000000 -1 0
Output
4999999999
Input
16
0 5 -4 -5 -8 -4 7 2 -4 0 7 0 2 -3 7 7
5 0 8 -9 3 5 2 -7 2 -7 0 -1 -4 1 -1 9
-4 8 0 -9 8 9 3 1 4 9 6 6 -6 1 8 9
-5 -9 -9 0 -7 6 4 -1 9 -3 -5 0 1 2 -4 1
-8 3 8 -7 0 -5 -9 9 1 -9 -6 -3 -8 3 4 3
-4 5 9 6 -5 0 -6 1 -2 2 0 -5 -2 3 1 2
7 2 3 4 -9 -6 0 -2 -2 -9 -3 9 -2 9 2 -5
2 -7 1 -1 9 1 -2 0 -6 0 -6 6 4 -1 -7 8
-4 2 4 9 1 -2 -2 -6 0 8 -6 -2 -4 8 7 7
0 -7 9 -3 -9 2 -9 0 8 0 0 1 -3 3 -6 -6
7 0 6 -5 -6 0 -3 -6 -6 0 0 5 7 -1 -5 3
0 -1 6 0 -3 -5 9 6 -2 1 5 0 -2 7 -8 0
2 -4 -6 1 -8 -2 -2 4 -4 -3 7 -2 0 -9 7 1
-3 1 1 2 3 3 9 -1 8 3 -1 7 -9 0 -6 -8
7 -1 8 -4 4 1 2 -7 7 -6 -5 -8 7 -6 0 -9
7 9 9 1 3 2 -5 8 7 -6 3 0 1 -8 -9 0
Output
132
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 managed to intercept an important message and you are trying to read it.
You realise that the message has been encoded and can be decoded by switching each letter with a corresponding letter.
You also notice that each letter is paired with the letter that it coincides with when the alphabet is reversed.
For example: "a" is encoded with "z", "b" with "y", "c" with "x", etc
You read the first sentence:
```
"r slkv mlylwb wvxlwvh gsrh nvhhztv"
```
After a few minutes you manage to decode it:
```
"i hope nobody decodes this message"
```
Create a function that will instantly decode any of these messages
You can assume no punctuation or capitals, only lower case letters, but remember spaces!
Write your solution by modifying this code:
```python
def decode(message):
```
Your solution should implemented in the function "decode". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a program that will take a string of digits and give you all the possible consecutive slices of length `n` in that string.
Raise an error if `n` is larger than the length of the string.
## Examples
For example, the string `"01234"` has the following 2-digit slices:
```
[0, 1], [1, 2], [2, 3], [3, 4]
```
The same string has the following 4-digit slices:
```
[0, 1, 2, 3], [1, 2, 3, 4]
```
Write your solution by modifying this code:
```python
def series_slices(digits, n):
```
Your solution should implemented in the function "series_slices". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this Kata, you will be given a string of numbers in sequence and your task will be to return the missing number. If there is no number
missing or there is an error in the sequence, return `-1`.
For example:
```Haskell
missing("123567") = 4
missing("899091939495") = 92
missing("9899101102") = 100
missing("599600601602") = -1 -- no number missing
missing("8990919395") = -1 -- error in sequence. Both 92 and 94 missing.
```
The sequence will always be in ascending order.
More examples in the test cases.
Good luck!
Write your solution by modifying this code:
```python
def missing(s):
```
Your solution should implemented in the function "missing". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements:
+ Accepts a case-insensitive hexadecimal color string as its parameter (ex. `"#FF9933"` or `"#ff9933"`)
+ Returns an object with the structure `{r: 255, g: 153, b: 51}` where *r*, *g*, and *b* range from 0 through 255
**Note:** your implementation does not need to support the shorthand form of hexadecimal notation (ie `"#FFF"`)
## Example
```
"#FF9933" --> {r: 255, g: 153, b: 51}
```
Write your solution by modifying this code:
```python
def hex_string_to_RGB(hex_string):
```
Your solution should implemented in the function "hex_string_to_RGB". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration $\frac{a_{i}}{1000}$. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration $\frac{n}{1000}$. The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass.
Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well.
Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration $\frac{n}{1000}$. Assume that the friends have unlimited amount of each Coke type.
-----Input-----
The first line contains two integers n, k (0 β€ n β€ 1000, 1 β€ k β€ 10^6)Β β carbon dioxide concentration the friends want and the number of Coke types.
The second line contains k integers a_1, a_2, ..., a_{k} (0 β€ a_{i} β€ 1000)Β β carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration.
-----Output-----
Print the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration $\frac{n}{1000}$, or -1 if it is impossible.
-----Examples-----
Input
400 4
100 300 450 500
Output
2
Input
50 2
100 25
Output
3
-----Note-----
In the first sample case, we can achieve concentration $\frac{400}{1000}$ using one liter of Coke of types $\frac{300}{1000}$ and $\frac{500}{1000}$: $\frac{300 + 500}{1000 + 1000} = \frac{400}{1000}$.
In the second case, we can achieve concentration $\frac{50}{1000}$ using two liters of $\frac{25}{1000}$ type and one liter of $\frac{100}{1000}$ type: $\frac{25 + 25 + 100}{3 \cdot 1000} = \frac{50}{1000}$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Genos needs your help. He was asked to solve the following programming problem by Saitama:
The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as $\sum_{i = 1}^{|s|}|s_{i} - t_{i}|$, where s_{i} is the i-th character of s and t_{i} is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.
Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.
-----Input-----
The first line of the input contains binary string a (1 β€ |a| β€ 200 000).
The second line of the input contains binary string b (|a| β€ |b| β€ 200 000).
Both strings are guaranteed to consist of characters '0' and '1' only.
-----Output-----
Print a single integerΒ β the sum of Hamming distances between a and all contiguous substrings of b of length |a|.
-----Examples-----
Input
01
00111
Output
3
Input
0011
0110
Output
2
-----Note-----
For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.
The second sample case is described in the statement.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.
Some of magic effects are able to affect several field cells at once, cells that are situated not farther than n cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.
It is easy to see that the number of cells affected by a magic effect grows rapidly when n increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given n, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than n cells away from a given cell. [Image]
-----Input-----
The only line of the input contains one integer n (0 β€ n β€ 10^9).
-----Output-----
Output one integer β the number of hexagons situated not farther than n cells away from a given cell.
-----Examples-----
Input
2
Output
19
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.
Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.
For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.
<image>
You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
Input
The first line of input contains two space-separated integers n and m (1 β€ n, m β€ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.
Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
Output
If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.
If it is impossible to cut the given graph, print "No solution" (without quotes).
Examples
Input
8 12
1 2
2 3
3 4
4 1
1 3
2 4
3 5
3 6
5 6
6 7
6 8
7 8
Output
1 2 4
1 3 2
1 4 3
5 3 6
5 6 8
6 7 8
Input
3 3
1 2
2 3
3 1
Output
No solution
Input
3 2
1 2
2 3
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.
A bracket sequence is a string, containing only characters "(", ")", "[" and "]".
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.
A substring s[l... r] (1 β€ l β€ r β€ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition.
You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets Β«[Β» as possible.
Input
The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.
Output
In the first line print a single integer β the number of brackets Β«[Β» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.
Examples
Input
([])
Output
1
([])
Input
(((
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.
Allen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n β R, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, ..., x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an i such that x_i = -1 and either setting x_i β 0 or x_i β 1.
After n rounds all variables are set, and the game value resolves to f(x_1, x_2, ..., x_n). Allen wants to maximize the game value, and Bessie wants to minimize it.
Your goal is to help Allen and Bessie find the expected game value! They will play r+1 times though, so between each game, exactly one value of f changes. In other words, between rounds i and i+1 for 1 β€ i β€ r, f(z_1, ..., z_n) β g_i for some (z_1, ..., z_n) β \{0, 1\}^n. You are to find the expected game value in the beginning and after each change.
Input
The first line contains two integers n and r (1 β€ n β€ 18, 0 β€ r β€ 2^{18}).
The next line contains 2^n integers c_0, c_1, ..., c_{2^n-1} (0 β€ c_i β€ 10^9), denoting the initial values of f. More specifically, f(x_0, x_1, ..., x_{n-1}) = c_x, if x = \overline{x_{n-1} β¦ x_0} in binary.
Each of the next r lines contains two integers z and g (0 β€ z β€ 2^n - 1, 0 β€ g β€ 10^9). If z = \overline{z_{n-1} ... z_0} in binary, then this means to set f(z_0, ..., z_{n-1}) β g.
Output
Print r+1 lines, the i-th of which denotes the value of the game f during the i-th round. Your answer must have absolute or relative error within 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
2 2
0 1 2 3
2 5
0 4
Output
1.500000
2.250000
3.250000
Input
1 0
2 3
Output
2.500000
Input
2 0
1 1 1 1
Output
1.000000
Note
Consider the second test case. If Allen goes first, he will set x_1 β 1, so the final value will be 3. If Bessie goes first, then she will set x_1 β 0 so the final value will be 2. Thus the answer is 2.5.
In the third test case, the game value will always be 1 regardless of Allen and Bessie's play.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the following games.
N characters are lined up in a vertical row. The color of these characters is red, blue, or yellow, and in the initial state, four or more characters of the same color are not lined up in a row. The player can select a character at a certain position and change it to another color. By this operation, if four or more characters of the same color are lined up in a row, those characters will disappear. When four or more characters of the same color are lined up in a row due to the disappearance of the characters, those characters also disappear, and this chain continues until there are no more places where four or more characters of the same color are lined up in a row. .. The purpose of this game is to reduce the number of characters remaining without disappearing.
For example, if the color of the sixth character from the top is changed from yellow to blue in the state at the left end of the figure below, five blue characters will disappear in a row, and finally three characters will remain without disappearing.
<image>
Given the color sequence of N characters in the initial state, create a program that finds the minimum value M of the number of characters that remain without disappearing when the color of the character is changed in only one place.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The first line consists of only the number of characters N (1 β€ N β€ 10000). The following N lines contain one of 1, 2, and 3 integers, and the i + 1st line (1 β€ i β€ N) represents the color of the i-th character from the top in the initial state (1). Is red, 2 is blue, and 3 is yellow).
When N is 0, it indicates the end of input. The number of datasets does not exceed 5.
output
For each dataset, output the minimum value M of the number of characters remaining without disappearing on one line.
Examples
Input
12
3
2
1
1
2
3
2
2
2
1
1
3
12
3
2
1
1
2
3
2
1
3
2
1
3
0
Output
3
12
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 sheets of square paper of the same size. Align the bottom of these papers horizontally and arrange them in several rows. However, adjacent rows must be arranged so that the left side is not lower than the right side. For example, n When = 5, the following 7 ways of arranging are possible.
<image>
We will represent these by the number of square columns in each column. For example, when n = 5, each of them will be represented.
(5) (4, 1) (3, 2) (3, 1, 1) (2, 2, 1) (2, 1, 1, 1) (1, 1, 1, 1, 1)
It is expressed as.
When n is input, create a program that outputs all in lexicographic order. n β€ 30. However, lexicographic order means that two arrangements (a1, a2, ..., as) are arranged (b1, For b2, ..., bt), when a1> b1 or an integer i> 1 exists and a1 = b1, ..., ai-1 = bi-1 and ai> bi holds (a1) , a2, ..., as) are arranged so that they are output before (b1, b2, ..., bt).
The input data consists of one line, with n written on the first line.
In the output, write one line in lexicographic order and insert a line break at the end. The output of (a1, a2, ..., as) is the integer a1, a2, ..., as. Output in this order separated by blanks.
Input example 1
---
Five
Output example 1
Five
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1
input
The input consists of multiple datasets. Input ends when n is 0. The number of datasets does not exceed 5.
output
All data sets are output in lexicographic order.
Example
Input
5
5
0
Output
5
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1
5
4 1
3 2
3 1 1
2 2 1
2 1 1 1
1 1 1 1 1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Definition
An **_element is leader_** *if it is greater than The Sum all the elements to its right side*.
____
# Task
**_Given_** an *array/list [] of integers* , **_Find_** *all the **_LEADERS_** in the array*.
___
# Notes
* **_Array/list_** size is *at least 3* .
* **_Array/list's numbers_** Will be **_mixture of positives , negatives and zeros_**
* **_Repetition_** of numbers in *the array/list could occur*.
* **_Returned Array/list_** *should store the leading numbers **_in the same order_** in the original array/list* .
___
# Input >> Output Examples
```
arrayLeaders ({1, 2, 3, 4, 0}) ==> return {4}
```
## **_Explanation_**:
* `4` *is greater than the sum all the elements to its right side*
* **_Note_** : **_The last element_** `0` *is equal to right sum of its elements (abstract zero)*.
____
```
arrayLeaders ({16, 17, 4, 3, 5, 2}) ==> return {17, 5, 2}
```
## **_Explanation_**:
* `17` *is greater than the sum all the elements to its right side*
* `5` *is greater than the sum all the elements to its right side*
* **_Note_** : **_The last element_** `2` *is greater than the sum of its right elements (abstract zero)*.
___
```
arrayLeaders ({5, 2, -1}) ==> return {5, 2}
```
## **_Explanation_**:
* `5` *is greater than the sum all the elements to its right side*
* `2` *is greater than the sum all the elements to its right side*
* **_Note_** : **_The last element_** `-1` *is less than the sum of its right elements (abstract zero)*.
___
```
arrayLeaders ({0, -1, -29, 3, 2}) ==> return {0, -1, 3, 2}
```
## **_Explanation_**:
* `0` *is greater than the sum all the elements to its right side*
* `-1` *is greater than the sum all the elements to its right side*
* `3` *is greater than the sum all the elements to its right side*
* **_Note_** : **_The last element_** `2` *is greater than the sum of its right elements (abstract zero)*.
Write your solution by modifying this code:
```python
def array_leaders(numbers):
```
Your solution should implemented in the function "array_leaders". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For given two circles $c1$ and $c2$, print
4
if they do not cross (there are 4 common tangent lines),
3
if they are circumscribed (there are 3 common tangent lines),
2
if they intersect (there are 2 common tangent lines),
1
if a circle is inscribed in another (there are 1 common tangent line),
0
if a circle includes another (there is no common tangent line).
Constraints
* $-1,000 \leq c1x, c1y, c2x, c2y \leq 1,000$
* $1 \leq c1r, c2r \leq 1,000$
* $c1$ and $c2$ are different
Input
Coordinates and radii of $c1$ and $c2$ are given in the following format.
$c1x \; c1y \; c1r$
$c2x \; c2y \; c2r$
$c1x$, $c1y$ and $c1r$ represent the center coordinate and radius of the first circle. $c2x$, $c2y$ and $c2r$ represent the center coordinate and radius of the second circle. All input values are given in integers.
Output
Print "4", "3", "2", "1" or "0" in a line.
Examples
Input
1 1 1
6 2 2
Output
4
Input
1 2 1
4 2 2
Output
3
Input
1 2 1
3 2 2
Output
2
Input
0 0 1
1 0 2
Output
1
Input
0 0 1
0 0 2
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.
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a_1, a_2, ..., a_{n} in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.
-----Input-----
The first line of the input contains an integer n (2 β€ n β€ 10^5). The next line contains n distinct integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ n).
-----Output-----
Output a single integer β the answer to the problem.
-----Examples-----
Input
3
3 1 2
Output
2
-----Note-----
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 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 an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.
According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:
* All even numbers written on the document are divisible by 3 or 5.
If the immigrant should be allowed entry according to the regulation, output `APPROVED`; otherwise, print `DENIED`.
Constraints
* All values in input are integers.
* 1 \leq N \leq 100
* 1 \leq A_i \leq 1000
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \dots A_N
Output
If the immigrant should be allowed entry according to the regulation, print `APPROVED`; otherwise, print `DENIED`.
Examples
Input
5
6 7 9 10 31
Output
APPROVED
Input
3
28 27 24
Output
DENIED
Read the inputs from stdin solve the problem and write the answer to stdout (do 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, the Pythagorean theorem β is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:
In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).
The theorem can be written as an equation relating the lengths of the sides a, b and c, often called the Pythagorean equation:
a^2 + b^2 = c^2
where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides.
[Image]
Given n, your task is to count how many right-angled triangles with side-lengths a, b and c that satisfied an inequality 1 β€ a β€ b β€ c β€ n.
-----Input-----
The only line contains one integer nΒ (1 β€ n β€ 10^4) as we mentioned above.
-----Output-----
Print a single integer β the answer to the problem.
-----Examples-----
Input
5
Output
1
Input
74
Output
35
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 the Jumbo will practice golf.
His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).
If he can achieve the objective, print OK; if he cannot, print NG.
-----Constraints-----
- All values in input are integers.
- 1 \leq A \leq B \leq 1000
- 1 \leq K \leq 1000
-----Input-----
Input is given from Standard Input in the following format:
K
A B
-----Output-----
If he can achieve the objective, print OK; if he cannot, print NG.
-----Sample Input-----
7
500 600
-----Sample Output-----
OK
Among the multiples of 7, for example, 567 lies between 500 and 600.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
It is not empty (that is n β 0). The length of the sequence is even. First $\frac{n}{2}$ charactes of the sequence are equal to "(". Last $\frac{n}{2}$ charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 10^9 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
-----Input-----
The only line of the input contains a string sΒ β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
-----Output-----
Output one numberΒ β the answer for the task modulo 10^9 + 7.
-----Examples-----
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
-----Note-----
In the first sample the following subsequences are possible:
If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())". If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()". If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()". If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()". If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()". If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given $n$ integers $a_1, a_2, \ldots, a_n$. Find the maximum value of $max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r)$ over all pairs $(l, r)$ of integers for which $1 \le l < r \le n$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10000$) β the number of test cases.
The first line of each test case contains a single integer $n$ ($2 \le n \le 10^5$).
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^6$).
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $3 \cdot 10^5$.
-----Output-----
For each test case, print a single integer β the maximum possible value of the product from the statement.
-----Examples-----
Input
4
3
2 4 3
4
3 2 3 1
2
69 69
6
719313 273225 402638 473783 804745 323328
Output
12
6
4761
381274500335
-----Note-----
Let $f(l, r) = max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r)$.
In the first test case,
$f(1, 2) = max(a_1, a_2) \cdot min(a_1, a_2) = max(2, 4) \cdot min(2, 4) = 4 \cdot 2 = 8$.
$f(1, 3) = max(a_1, a_2, a_3) \cdot min(a_1, a_2, a_3) = max(2, 4, 3) \cdot min(2, 4, 3) = 4 \cdot 2 = 8$.
$f(2, 3) = max(a_2, a_3) \cdot min(a_2, a_3) = max(4, 3) \cdot min(4, 3) = 4 \cdot 3 = 12$.
So the maximum is $f(2, 3) = 12$.
In the second test case, the maximum is $f(1, 2) = f(1, 3) = f(2, 3) = 6$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.
Consider that m (m β€ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:
1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.
After occupying all the window seats (for m > 2n) the non-window seats are occupied:
1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.
All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.
1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. [Image] The seating for n = 9 and m = 36.
You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.
-----Input-----
The only line contains two integers, n and m (1 β€ n β€ 100, 1 β€ m β€ 4n) β the number of pairs of rows and the number of passengers.
-----Output-----
Print m distinct integers from 1 to m β the order in which the passengers will get off the bus.
-----Examples-----
Input
2 7
Output
5 1 6 2 7 3 4
Input
9 36
Output
19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.
During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.
It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.
-----Input-----
The single line contains three integers k, d and t (1 β€ k, d, t β€ 10^18).
-----Output-----
Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10^{ - 9}.
Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if $\frac{|x - y|}{\operatorname{max}(1, y)} \leq 10^{-9}$.
-----Examples-----
Input
3 2 6
Output
6.5
Input
4 2 20
Output
20.0
-----Note-----
In the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for $\frac{3}{6}$. Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for $\frac{1}{12}$. Thus, after four minutes the chicken will be cooked for $\frac{3}{6} + \frac{1}{12} = \frac{7}{12}$. Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready $\frac{7}{12} + \frac{2.5}{6} = 1$.
In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Regex Failure - Bug Fixing #2
Oh no, Timmy's received some hate mail recently but he knows better. Help Timmy fix his regex filter so he can be awesome again!
Write your solution by modifying this code:
```python
def filter_words(phrase):
```
Your solution should implemented in the function "filter_words". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0, 0, 0), and the opposite one is at point (x1, y1, z1). The six faces of the box contain some numbers a1, a2, ..., a6, exactly one number right in the center of each face.
<image>
The numbers are located on the box like that:
* number a1 is written on the face that lies on the ZOX plane;
* a2 is written on the face, parallel to the plane from the previous point;
* a3 is written on the face that lies on the XOY plane;
* a4 is written on the face, parallel to the plane from the previous point;
* a5 is written on the face that lies on the YOZ plane;
* a6 is written on the face, parallel to the plane from the previous point.
At the moment Vasya is looking at the box from point (x, y, z). Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the ai numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some ai = 6, then he can't mistake this number for 9 and so on).
Input
The fist input line contains three space-separated integers x, y and z (|x|, |y|, |z| β€ 106) β the coordinates of Vasya's position in space. The second line contains three space-separated integers x1, y1, z1 (1 β€ x1, y1, z1 β€ 106) β the coordinates of the box's vertex that is opposite to the vertex at point (0, 0, 0). The third line contains six space-separated integers a1, a2, ..., a6 (1 β€ ai β€ 106) β the numbers that are written on the box faces.
It is guaranteed that point (x, y, z) is located strictly outside the box.
Output
Print a single integer β the sum of all numbers on the box faces that Vasya sees.
Examples
Input
2 2 2
1 1 1
1 2 3 4 5 6
Output
12
Input
0 0 10
3 2 3
1 2 3 4 5 6
Output
4
Note
The first sample corresponds to perspective, depicted on the picture. Vasya sees numbers a2 (on the top face that is the darkest), a6 (on the right face that is the lightest) and a4 (on the left visible face).
In the second sample Vasya can only see number a4.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.
Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the number of markers and the number of caps, correspondingly.
Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 β€ xi, yi β€ 1000) β the i-th marker's color and diameter, correspondingly.
Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 β€ aj, bj β€ 1000) β the color and diameter of the j-th cap, correspondingly.
Output
Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.
Examples
Input
3 4
1 2
3 4
2 4
5 4
2 4
1 1
1 2
Output
3 2
Input
2 2
1 2
2 1
3 4
5 1
Output
1 0
Note
In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed β the first and the third markers.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is the easier version of the problem. In this version 1 β€ n, m β€ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily go consecutively). For example, for the sequence a=[11,20,11,33,11,20,11]:
* [11,20,11,33,11,20,11], [11,20,11,33,11,20], [11,11,11,11], [20], [33,20] are subsequences (these are just some of the long list);
* [40], [33,33], [33,20,20], [20,20,11,11] are not subsequences.
Suppose that an additional non-negative integer k (1 β€ k β€ n) is given, then the subsequence is called optimal if:
* it has a length of k and the sum of its elements is the maximum possible among all subsequences of length k;
* and among all subsequences of length k that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence b=[b_1, b_2, ..., b_k] is lexicographically smaller than the sequence c=[c_1, c_2, ..., c_k] if the first element (from the left) in which they differ less in the sequence b than in c. Formally: there exists t (1 β€ t β€ k) such that b_1=c_1, b_2=c_2, ..., b_{t-1}=c_{t-1} and at the same time b_t<c_t. For example:
* [10, 20, 20] lexicographically less than [10, 21, 1],
* [7, 99, 99] is lexicographically less than [10, 21, 1],
* [10, 21, 0] is lexicographically less than [10, 21, 1].
You are given a sequence of a=[a_1,a_2,...,a_n] and m requests, each consisting of two numbers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j). For each query, print the value that is in the index pos_j of the optimal subsequence of the given sequence a for k=k_j.
For example, if n=4, a=[10,20,30,20], k_j=2, then the optimal subsequence is [20,30] β it is the minimum lexicographically among all subsequences of length 2 with the maximum total sum of items. Thus, the answer to the request k_j=2, pos_j=1 is the number 20, and the answer to the request k_j=2, pos_j=2 is the number 30.
Input
The first line contains an integer n (1 β€ n β€ 100) β the length of the sequence a.
The second line contains elements of the sequence a: integer numbers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9).
The third line contains an integer m (1 β€ m β€ 100) β the number of requests.
The following m lines contain pairs of integers k_j and pos_j (1 β€ k β€ n, 1 β€ pos_j β€ k_j) β the requests.
Output
Print m integers r_1, r_2, ..., r_m (1 β€ r_j β€ 10^9) one per line: answers to the requests in the order they appear in the input. The value of r_j should be equal to the value contained in the position pos_j of the optimal subsequence for k=k_j.
Examples
Input
3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3
Output
20
10
20
10
20
10
Input
7
1 2 1 3 1 2 1
9
2 1
2 2
3 1
3 2
3 3
1 1
7 1
7 7
7 4
Output
2
3
2
3
2
3
1
1
3
Note
In the first example, for a=[10,20,10] the optimal subsequences are:
* for k=1: [20],
* for k=2: [10,20],
* for k=3: [10,20,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.
Read problems statements in Mandarin Chinese and Russian as well.
Your friend Π‘hef has prepared a rectangular cake for you. Both of you want to divide the cake among yourselves. Your friend is generous enough to let you choose your share first. You have decided to take two pieces.
For the first piece you make a rectangular cut (each side of this cut is parallel to the corresponding side of the cake) inside the cake. Now the cake have two pieces. You take the piece inside the rectangle cut. For the second piece, you make another rectangular cut (each side of this cut is parallel to the corresponding side of the cake) inside the cake. Now the cake again have two pieces. You take the piece inside the rectangle cut (note that this piece may not be rectangular, because of cut may cross an empty space that remains from the first piece, also it can be empty). Your friend will have the rest of the cake.
Given the cuts determine the amount of cake that you will have. The amount is calculated as the sum of the areas covered by your pieces. The cake can be considered as a rectangle with the lower left corner at (0,0) and the upper right corner at (1001,1001).
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. Each test case consists of two lines. Each line contains the description of a rectangular cut by giving the information of the rectangle. A rectangle is defined by four integers (co-ordinate of the lower-left corner (x1,y1) and upper right corner (x2,y2)).
------ Output ------
For each test case, output a single line containing the amount of cake you will have.
------ Constraints ------
$1β€Tβ€100$
$1β€x1x2β€1000$
$1β€y1y2β€1000$
----- Sample Input 1 ------
2
1 1 10 10
11 11 20 20
1 1 20 20
11 11 30 30
----- Sample Output 1 ------
162
641
----- explanation 1 ------
Test Case 1:
The area of the first piece is 81 and the area of the second piece is 81, a total of 162.
Test Case 2:
The area of the first piece is 361 and the area of the second piece is 280, a total of 641.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this problem we consider a very simplified model of Barcelona city.
Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points (x, y) for which ax + by + c = 0.
One can walk along streets, including the avenue. You are given two integer points A and B somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to B from A.
Input
The first line contains three integers a, b and c (-10^9β€ a, b, cβ€ 10^9, at least one of a and b is not zero) representing the Diagonal Avenue.
The next line contains four integers x_1, y_1, x_2 and y_2 (-10^9β€ x_1, y_1, x_2, y_2β€ 10^9) denoting the points A = (x_1, y_1) and B = (x_2, y_2).
Output
Find the minimum possible travel distance between A and B. Your answer is 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 accepted if and only if \frac{|a - b|}{max{(1, |b|)}} β€ 10^{-6}.
Examples
Input
1 1 -3
0 3 3 0
Output
4.2426406871
Input
3 1 -9
0 3 3 -1
Output
6.1622776602
Note
The first example is shown on the left picture while the second example us shown on the right picture below. The avenue is shown with blue, the origin is shown with the black dot.
<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.
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.
The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.
Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
Input
The first line contains three integers n, m and s (2 β€ n β€ 105, <image>, 1 β€ s β€ n) β the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s.
Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 β€ vi, ui β€ n, vi β ui, 1 β€ wi β€ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 β€ l β€ 109) β the distance from the capital to the missile silos. It is guaranteed that:
* between any two cities no more than one road exists;
* each road connects two different cities;
* from each city there is at least one way to any other city by the roads.
Output
Print the single number β the number of Super Duper Secret Missile Silos that are located in Berland.
Examples
Input
4 6 1
1 2 1
1 3 3
2 3 1
2 4 1
3 4 1
1 4 2
2
Output
3
Input
5 6 3
3 1 1
3 2 1
3 4 1
3 5 1
1 2 6
4 5 8
4
Output
3
Note
In the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).
In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 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.
You are given $n$ elements numbered from $1$ to $n$, the element $i$ has value $a_i$ and color $c_i$, initially, $c_i = 0$ for all $i$.
The following operation can be applied:
Select three elements $i$, $j$ and $k$ ($1 \leq i < j < k \leq n$), such that $c_i$, $c_j$ and $c_k$ are all equal to $0$ and $a_i = a_k$, then set $c_j = 1$.
Find the maximum value of $\sum\limits_{i=1}^n{c_i}$ that can be obtained after applying the given operation any number of times.
-----Input-----
The first line contains an integer $n$ ($3 \leq n \leq 2 \cdot 10^5$) β the number of elements.
The second line consists of $n$ integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq n$), where $a_i$ is the value of the $i$-th element.
-----Output-----
Print a single integer in a line β the maximum value of $\sum\limits_{i=1}^n{c_i}$ that can be obtained after applying the given operation any number of times.
-----Examples-----
Input
7
1 2 1 2 7 4 7
Output
2
Input
13
1 2 3 2 1 3 3 4 5 5 5 4 7
Output
7
-----Note-----
In the first test, it is possible to apply the following operations in order:
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: $$$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$$
Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, β¦, p_k (k β₯ 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + β¦ + d(p_k, p_1).
For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.
Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures:
<image>
In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.
Your task is to compute f(3), f(4), β¦, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).
Input
The first line contains a single integer n (3 β€ n β€ 3β
10^5) β the number of points.
Each of the next n lines contains two integers x_i and y_i (-10^8 β€ x_i, y_i β€ 10^8) β the coordinates of point p_i.
The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.
Output
For each i (3β€ iβ€ n), output f(i).
Examples
Input
4
2 4
4 3
3 0
1 3
Output
12 14
Input
3
0 0
0 2
2 0
Output
8
Note
In the first example, for f(3), we consider four possible polygons:
* (p_1, p_2, p_3), with perimeter 12.
* (p_1, p_2, p_4), with perimeter 8.
* (p_1, p_3, p_4), with perimeter 12.
* (p_2, p_3, p_4), with perimeter 12.
For f(4), there is only one option, taking all the given points. Its perimeter 14.
In the second example, there is only one possible polygon. Its perimeter is 8.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
It is the hard version of the problem. The difference is that in this version, there are nodes with already chosen colors.
Theofanis is starving, and he wants to eat his favorite food, sheftalia. However, he should first finish his homework. Can you help him with this problem?
You have a perfect binary tree of $2^k - 1$ nodes β a binary tree where all vertices $i$ from $1$ to $2^{k - 1} - 1$ have exactly two children: vertices $2i$ and $2i + 1$. Vertices from $2^{k - 1}$ to $2^k - 1$ don't have any children. You want to color its vertices with the $6$ Rubik's cube colors (White, Green, Red, Blue, Orange and Yellow).
Let's call a coloring good when all edges connect nodes with colors that are neighboring sides in the Rubik's cube.
A picture of Rubik's cube and its 2D map.
More formally:
a white node can not be neighboring with white and yellow nodes;
a yellow node can not be neighboring with white and yellow nodes;
a green node can not be neighboring with green and blue nodes;
a blue node can not be neighboring with green and blue nodes;
a red node can not be neighboring with red and orange nodes;
an orange node can not be neighboring with red and orange nodes;
However, there are $n$ special nodes in the tree, colors of which are already chosen.
You want to calculate the number of the good colorings of the binary tree. Two colorings are considered different if at least one node is colored with a different color.
The answer may be too large, so output the answer modulo $10^9+7$.
-----Input-----
The first line contains the integers $k$ ($1 \le k \le 60$) β the number of levels in the perfect binary tree you need to color.
The second line contains the integer $n$ ($1 \le n \le \min(2^k - 1, 2000)$) β the number of nodes, colors of which are already chosen.
The next $n$ lines contains integer $v$ ($1 \le v \le 2^k - 1$) and string $s$ β the index of the node and the color of the node ($s$ is one of the white, yellow, green, blue, red and orange).
It is guaranteed that each node $v$ appears in the input at most once.
-----Output-----
Print one integer β the number of the different colorings modulo $10^9+7$.
-----Examples-----
Input
3
2
5 orange
2 white
Output
1024
Input
2
2
1 white
2 white
Output
0
Input
10
3
1 blue
4 red
5 orange
Output
328925088
-----Note-----
In the picture below, you can see one of the correct colorings of the first test example.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has N dogs and M monkeys. He wants them to line up in a row.
As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.
How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.
Constraints
* 1 β€ N,M β€ 10^5
Input
Input is given from Standard Input in the following format:
N M
Output
Print the number of possible arrangements, modulo 10^9+7.
Examples
Input
2 2
Output
8
Input
3 2
Output
12
Input
1 8
Output
0
Input
100000 100000
Output
530123477
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
There is a war and nobody knows - the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters called airstrike to help them in war - dashes and dots are spreaded everywhere on the battlefield.
# Task
Write a function that accepts `fight` string consists of only small letters and `*` which means a bomb drop place. Return who wins the fight after bombs are exploded. When the left side wins return `Left side wins!`, when the right side wins return `Right side wins!`, in other case return `Let's fight again!`.
The left side letters and their power:
```
w - 4
p - 3
b - 2
s - 1
```
The right side letters and their power:
```
m - 4
q - 3
d - 2
z - 1
```
The other letters don't have power and are only victims.
The `*` bombs kills the adjacent letters ( i.e. `aa*aa` => `a___a`, `**aa**` => `______` );
# Example
# Alphabet war Collection
Alphavet war
Alphabet war - airstrike - letters massacre
Alphabet wars - reinforces massacre
Alphabet wars - nuclear strike
Alphabet war - Wo lo loooooo priests join the war
Write your solution by modifying this code:
```python
def alphabet_war(fight):
```
Your solution should implemented in the function "alphabet_war". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.
Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner β a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely β on the upper side of the field (that is, in any cell that is in the row with number 10^9).
Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:
* Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1.
* Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.
<image> An example of a chessboard.
Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).
Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Input
The first line contains two integers n and m (0 β€ n,m β€ 10^5) β the number of vertical and horizontal spells.
Each of the following n lines contains one integer x (1 β€ x < 10^9) β the description of the vertical spell. It will create a blocking line between the columns of x and x+1.
Each of the following m lines contains three integers x_1, x_2 and y (1 β€ x_{1} β€ x_{2} β€ 10^9, 1 β€ y < 10^9) β the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.
It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.
Output
In a single line print one integer β the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9
Examples
Input
2 3
6
8
1 5 6
1 9 4
2 4 2
Output
1
Input
1 3
4
1 5 3
1 9 4
4 6 6
Output
1
Input
0 2
1 1000000000 4
1 1000000000 2
Output
2
Input
0 0
Output
0
Input
2 3
4
6
1 4 3
1 5 2
1 6 5
Output
2
Note
In the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.
<image> Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home.
In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.
<image> Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home.
In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.
<image> Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home.
In the fourth sample, we have no spells, which means that we do not need to remove anything.
In the fifth example, we can remove the first vertical and third horizontal spells.
<image> Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 function should take two string parameters: a person's name (`name`) and a quote of theirs (`quote`), and return a string attributing the quote to the person in the following format:
```python
'[name] said: "[quote]"'
```
For example, if `name` is `'Grae'` and `'quote'` is `'Practice makes perfect'` then your function should return the string
```python
'Grae said: "Practice makes perfect"'
```
Unfortunately, something is wrong with the instructions in the function body. Your job is to fix it so the function returns correctly formatted quotes.
Click the "Train" button to get started, and be careful with your quotation marks.
Write your solution by modifying this code:
```python
def quotable(name, quote):
```
Your solution should implemented in the function "quotable". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of $n$ problems and lasts for $T$ minutes. Each of the problems is defined by two positive integers $a_i$ and $p_i$Β β its difficulty and the score awarded by its solution.
Polycarp's experience suggests that his skill level is defined with positive real value $s$, and initially $s=1.0$. To solve the $i$-th problem Polycarp needs $a_i/s$ minutes.
Polycarp loves to watch series, and before solving each of the problems he will definitely watch one episode. After Polycarp watches an episode, his skill decreases by $10\%$, that is skill level $s$ decreases to $0.9s$. Each episode takes exactly $10$ minutes to watch. When Polycarp decides to solve some problem, he firstly has to watch one episode, and only then he starts solving the problem without breaks for $a_i/s$ minutes, where $s$ is his current skill level. In calculation of $a_i/s$ no rounding is performed, only division of integer value $a_i$ by real value $s$ happens.
Also, Polycarp can train for some time. If he trains for $t$ minutes, he increases his skill by $C \cdot t$, where $C$ is some given positive real constant. Polycarp can train only before solving any problem (and before watching series). Duration of the training can be arbitrary real value.
Polycarp is interested: what is the largest score he can get in the contest? It is allowed to solve problems in any order, while training is only allowed before solving the first problem.
-----Input-----
The first line contains one integer $tc$ ($1 \le tc \le 20$)Β β the number of test cases. Then $tc$ test cases follow.
The first line of each test contains one integer $n$ ($1 \le n \le 100$)Β β the number of problems in the contest.
The second line of the test contains two real values $C, T$ ($0 < C < 10$, $0 \le T \le 2 \cdot 10^5$), where $C$ defines the efficiency of the training and $T$ is the duration of the contest in minutes. Value $C, T$ are given exactly with three digits after the decimal point.
Each of the next $n$ lines of the test contain characteristics of the corresponding problem: two integers $a_i, p_i$ ($1 \le a_i \le 10^4$, $1 \le p_i \le 10$)Β β the difficulty and the score of the problem.
It is guaranteed that the value of $T$ is such that changing it by the $0.001$ in any direction will not change the test answer.
Please note that in hacks you can only use $tc = 1$.
-----Output-----
Print $tc$ integersΒ β the maximum possible score in each test case.
-----Examples-----
Input
2
4
1.000 31.000
12 3
20 6
30 1
5 1
3
1.000 30.000
1 10
10 10
20 8
Output
7
20
-----Note-----
In the first example, Polycarp can get score of $7$ as follows: Firstly he trains for $4$ minutes, increasing $s$ to the value of $5$; Then he decides to solve $4$-th problem: he watches one episode in $10$ minutes, his skill level decreases to $s=5*0.9=4.5$ and then he solves the problem in $5/s=5/4.5$, which is roughly $1.111$ minutes; Finally, he decides to solve $2$-nd problem: he watches one episode in $10$ minutes, his skill level decreases to $s=4.5*0.9=4.05$ and then he solves the problem in $20/s=20/4.05$, which is roughly $4.938$ minutes.
This way, Polycarp uses roughly $4+10+1.111+10+4.938=30.049$ minutes, to get score of $7$ points. It is not possible to achieve larger score in $31$ minutes.
In the second example, Polycarp can get $20$ points as follows: Firstly he trains for $4$ minutes, increasing $s$ to the value of $5$; Then he decides to solve $1$-st problem: he watches one episode in $10$ minutes, his skill decreases to $s=5*0.9=4.5$ and then he solves problem in $1/s=1/4.5$, which is roughly $0.222$ minutes. Finally, he decides to solve $2$-nd problem: he watches one episode in $10$ minutes, his skill decreases to $s=4.5*0.9=4.05$ and then he solves the problem in $10/s=10/4.05$, which is roughly $2.469$ minutes.
This way, Polycarp gets score of $20$ in $4+10+0.222+10+2.469=26.691$ minutes. It is not possible to achieve larger score in $30$ minutes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Professor Ibrahim has prepared the final homework for his algorithmβs class. He asked his students to implement the Posterization Image Filter.
Their algorithm will be tested on an array of integers, where the $i$-th integer represents the color of the $i$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).
To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the groupβs key. In order to preserve image details, the size of a group must not be greater than $k$, and each color should belong to exactly one group.
Finally, the students will replace the color of each pixel in the array with that colorβs assigned group key.
To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $k$ to the right.
[Image]
To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.
-----Input-----
The first line of input contains two integers $n$ and $k$ ($1 \leq n \leq 10^5$, $1 \leq k \leq 256$), the number of pixels in the image, and the maximum size of a group, respectively.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($0 \leq p_i \leq 255$), where $p_i$ is the color of the $i$-th pixel.
-----Output-----
Print $n$ space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.
-----Examples-----
Input
4 3
2 14 3 4
Output
0 12 3 3
Input
5 2
0 2 1 255 254
Output
0 1 1 254 254
-----Note-----
One possible way to group colors and assign keys for the first sample:
Color $2$ belongs to the group $[0,2]$, with group key $0$.
Color $14$ belongs to the group $[12,14]$, with group key $12$.
Colors $3$ and $4$ belong to group $[3, 5]$, with group key $3$.
Other groups won't affect the result so they are not listed here.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4 Γ 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 Γ 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed.
Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 Γ 2 square, consisting of cells of the same color.
-----Input-----
Four lines contain four characters each: the j-th character of the i-th line equals "." if the cell in the i-th row and the j-th column of the square is painted white, and "#", if the cell is black.
-----Output-----
Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.
-----Examples-----
Input
####
.#..
####
....
Output
YES
Input
####
....
####
....
Output
NO
-----Note-----
In the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 Γ 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 hobbits Frodo and Sam are carrying the One Ring to Mordor. In order not to be spotted by orcs, they decided to go through the mountains.
The mountain relief can be represented as a polyline with n points (x_i, y_i), numbered from 1 to n (x_i < x_{i + 1} for 1 β€ i β€ n - 1). Hobbits start their journey at the point (x_1, y_1) and should reach the point (x_n, y_n) to complete their mission.
The problem is that there is a tower with the Eye of Sauron, which watches them. The tower is located at the point (x_n, y_n) and has the height H, so the Eye is located at the point (x_n, y_n + H). In order to complete the mission successfully, the hobbits have to wear cloaks all the time when the Sauron Eye can see them, i. e. when there is a direct line from the Eye to the hobbits which is not intersected by the relief.
The hobbits are low, so their height can be considered negligibly small, but still positive, so when a direct line from the Sauron Eye to the hobbits only touches the relief, the Eye can see them.
<image> The Sauron Eye can't see hobbits when they are in the left position, but can see them when they are in the right position.
The hobbits do not like to wear cloaks, so they wear them only when they can be spotted by the Eye. Your task is to calculate the total distance the hobbits have to walk while wearing cloaks.
Input
The first line of the input contains two integers n and H (2 β€ n β€ 2 β
10^5; 1 β€ H β€ 10^4) β the number of vertices in polyline and the tower height.
The next n lines contain two integers x_i, y_i each (0 β€ x_i β€ 4 β
10^5; 0 β€ y_i β€ 10^4) β the coordinates of the polyline vertices. It is guaranteed that x_i < x_{i + 1} for 1 β€ i β€ n - 1.
Output
Print one real number β the total distance the hobbits have to walk while wearing cloaks. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6} β formally, if your answer is a, and the jury's answer is b, your answer will be accepted if (|a - b|)/(max(1, b)) β€ 10^{-6}.
Examples
Input
6 10
10 40
20 10
25 30
30 15
50 15
65 30
Output
70.4034587602
Input
9 5
0 0
5 10
15 10
20 0
25 11
30 0
35 10
50 10
60 5
Output
27.2787986124
Input
2 10000
0 10000
400000 0
Output
400124.9804748512
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Nobody knows, but $N$ frogs live in Chef's garden.
Now they are siting on the X-axis and want to speak to each other. One frog can send a message to another one if the distance between them is less or equal to $K$.
Chef knows all $P$ pairs of frogs, which want to send messages. Help him to define can they or not!
Note : More than $1$ frog can be on the same point on the X-axis.
-----Input-----
- The first line contains three integers $N$, $K$ and $P$.
- The second line contains $N$ space-separated integers $A_1$, $A_2$, β¦, $A_N$ denoting the x-coordinates of frogs".
- Each of the next $P$ lines contains two integers $A$ and $B$ denoting the numbers of frogs according to the input.
-----Output-----
For each pair print "Yes" without a brackets if frogs can speak and "No" if they cannot.
-----Constraints-----
- $1 \le N, P \le 10^5$
- $0 \le A_i, K \le 10^9$
- $1 \le A, B \le N$
-----Example-----
-----Sample Input:-----
5 3 3
0 3 8 5 12
1 2
1 3
2 5
-----Sample Output:-----
Yes
Yes
No
-----Explanation-----
-
For pair $(1, 2)$ frog $1$ can directly speak to the frog $2$ as the distance between them is $3 - 0 = 3 \le K$ .
-
For pair $(1, 3)$ frog $1$ can send a message to frog $2$, frog $2$ can send it to frog $4$ and it can send it to frog $3$.
-
For pair $(2, 5)$ frogs can't send a message under current constraints.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
[0, 0]
[0, 1] [1, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3] [3, 3]
[0, 4] [1, 4] [2, 4] [3, 4] [4, 4]
[0, 5] [1, 5] [2, 5] [3, 5] [4, 5] [5, 5]
[0, 6] [1, 6] [2, 6] [3, 6] [4, 6] [5, 6] [6, 6]
Consider the standard set of 28 western dominoes as shown in the above figure. Given a subset of the standard set dominoes, decide whether this subset can be arranged in a straight row in accordance with the familiar playing rule that touching ends must match. For example, the subset [1, 1], [2, 2], [1, 2] can be arranged in a row (as [1, 1] followed by [1, 2] followed by [2, 2]), while the subset [1, 1], [0, 3], [1, 4] can not be arranged in one row. Note that as in usual dominoes playing any pair [i, j] can also be treated as [j, i].
Your task is to write a program that takes as input any subset of the dominoes and output either yes (if the input subset can be arranged in one row) or no (if the input set can not be arranged in one row).
Input
Input file consists of pairs of lines. The first line of each pair is the number of elements N (1 β€ N β€ 18) in the subset, and the second line is the elements of the subset separated by blanks, see the input sample below.
The number of pairs (datasets) is less than 30.
Output
For each pair of lines of the input file, the corresponding output is either Yes or No, based on whether the input subset can be arranged in one line or not.
Example
Input
6
13 23 14 24 15 25
10
00 01 11 02 12 22 03 13 23 33
Output
Yes
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The squirrel Chokudai has N acorns. One day, he decides to do some trades in multiple precious metal exchanges to make more acorns.
His plan is as follows:
1. Get out of the nest with N acorns in his hands.
2. Go to Exchange A and do some trades.
3. Go to Exchange B and do some trades.
4. Go to Exchange A and do some trades.
5. Go back to the nest.
In Exchange X (X = A, B), he can perform the following operations any integer number of times (possibly zero) in any order:
* Lose g_{X} acorns and gain 1 gram of gold.
* Gain g_{X} acorns and lose 1 gram of gold.
* Lose s_{X} acorns and gain 1 gram of silver.
* Gain s_{X} acorns and lose 1 gram of silver.
* Lose b_{X} acorns and gain 1 gram of bronze.
* Gain b_{X} acorns and lose 1 gram of bronze.
Naturally, he cannot perform an operation that would leave him with a negative amount of acorns, gold, silver, or bronze.
What is the maximum number of acorns that he can bring to the nest? Note that gold, silver, or bronze brought to the nest would be worthless because he is just a squirrel.
Constraints
* 1 \leq N \leq 5000
* 1 \leq g_{X} \leq 5000
* 1 \leq s_{X} \leq 5000
* 1 \leq b_{X} \leq 5000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
g_A s_A b_A
g_B s_B b_B
Output
Print the maximum number of acorns that Chokudai can bring to the nest.
Example
Input
23
1 1 1
2 1 1
Output
46
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
Tuzik is a little dog. But despite the fact he is still a puppy he already knows about the pretty things that coins are. He knows that for every coin he can get very tasty bone from his master. He believes that some day he will find a treasure and have loads of bones.
And finally he found something interesting. A wooden chest containing N coins! But as you should remember, Tuzik is just a little dog, and so he can't open it by himself. Actually, the only thing he can really do is barking. He can use his barking to attract nearby people and seek their help. He can set the loudness of his barking very precisely, and therefore you can assume that he can choose to call any number of people, from a minimum of 1, to a maximum of K.
When people come and open the chest they divide all the coins between them in such a way that everyone will get the same amount of coins and this amount is maximal possible. If some coins are not used they will leave it on the ground and Tuzik will take them after they go away. Since Tuzik is clearly not a fool, he understands that his profit depends on the number of people he will call. While Tuzik works on his barking, you have to find the maximum possible number of coins he can get.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. Each of next T lines contains 2 space-separated integers: N and K, for this test case.
------ Output ------
For each test case output one integer - the maximum possible number of coins Tuzik can get.
------ Constraints ------
$1 β€ T β€ 50$
$1 β€ N, K β€ 10^{5}$
----- Sample Input 1 ------
2
5 2
11 3
----- Sample Output 1 ------
1
2
----- explanation 1 ------
In the first example he should call two people. Each of them will take 2 coins and they will leave 1 coin for Tuzik.
In the second example he should call 3 people.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
-----Input-----
The first line contains two space-separated integers: n and p (1 β€ n β€ 1000; 1 β€ p β€ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
-----Output-----
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
-----Examples-----
Input
3 3
cba
Output
NO
Input
3 4
cba
Output
cbd
Input
4 4
abcd
Output
abda
-----Note-----
String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s_1 = t_1, ..., s_{i} = t_{i}, s_{i} + 1 > t_{i} + 1.
The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.
A palindrome is a string that reads the same forward or reversed.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In some other world, today is Christmas.
Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:
- A level-0 burger is a patty.
- A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.
For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.
The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?
-----Constraints-----
- 1 \leq N \leq 50
- 1 \leq X \leq ( the total number of layers in a level-N burger )
- N and X are integers.
-----Input-----
Input is given from Standard Input in the following format:
N X
-----Output-----
Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.
-----Sample Input-----
2 7
-----Sample Output-----
4
There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.
To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".
Determine the minimum number of moves needed to make some table column consist only of numbers 1.
Input
The first line contains two space-separated integers: n (1 β€ n β€ 100) β the number of rows in the table and m (1 β€ m β€ 104) β the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table.
It is guaranteed that the description of the table contains no other characters besides "0" and "1".
Output
Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.
Examples
Input
3 6
101010
000100
100000
Output
3
Input
2 3
111
000
Output
-1
Note
In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.
In the second sample one can't shift the rows to get a column containing only 1s.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Learn, learn and learn again β Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of n numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by - 1. The second operation is to take some suffix and multiply all numbers in it by - 1. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?
Input
The first line contains integer n (1 β€ n β€ 105) β amount of elements in the sequence. The second line contains n integers ai ( - 104 β€ ai β€ 104) β the sequence itself.
Output
The first and the only line of the output should contain the answer to the problem.
Examples
Input
3
-1 -2 -3
Output
6
Input
5
-4 2 0 5 0
Output
11
Input
5
-1 10 -5 10 -2
Output
18
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Format any integer provided into a string with "," (commas) in the correct places.
**Example:**
``` csharp
Kata.NumberFormat(100000); // return "100,000"
Kata.NumberFormat(5678545); // return "5,678,545"
Kata.NumberFormat(-420902); // return "-420,902"
```
``` javascript
numberFormat(100000); // return '100,000'
numberFormat(5678545); // return '5,678,545'
numberFormat(-420902); // return '-420,902'
```
``` cpp
numberFormat(100000); // return '100,000'
numberFormat(5678545); // return '5,678,545'
numberFormat(-420902); // return '-420,902'
```
``` python
number_format(100000); # return '100,000'
number_format(5678545); # return '5,678,545'
number_format(-420902); # return '-420,902'
```
``` ruby
number_format(100000); # return '100,000'
number_format(5678545); # return '5,678,545'
number_format(-420902); # return '-420,902'
```
``` crystal
number_format(100000); # return '100,000'
number_format(5678545); # return '5,678,545'
number_format(-420902); # return '-420,902'
```
Write your solution by modifying this code:
```python
def number_format(n):
```
Your solution should implemented in the function "number_format". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in a_{i} burles (burle is the currency in Berland).
You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.
-----Input-----
The first line contains the integer n (1 β€ n β€ 100)Β β the number of citizens in the kingdom.
The second line contains n integers a_1, a_2, ..., a_{n}, where a_{i} (0 β€ a_{i} β€ 10^6)Β β the welfare of the i-th citizen.
-----Output-----
In the only line print the integer SΒ β the minimum number of burles which are had to spend.
-----Examples-----
Input
5
0 1 2 3 4
Output
10
Input
5
1 1 0 1 1
Output
1
Input
3
1 3 1
Output
4
Input
1
12
Output
0
-----Note-----
In the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.
In the second example it is enough to give one burle to the third citizen.
In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.
In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.
The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.
You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.
-----Input-----
The first line of input will contain two integers n and m (1 β€ n, m β€ 500), the dimensions of the puzzle piece.
The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.
It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.
-----Output-----
Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.
-----Examples-----
Input
2 3
XXX
XXX
Output
YES
Input
2 2
.X
XX
Output
NO
Input
5 5
.....
..X..
.....
.....
.....
Output
YES
-----Note-----
For the first sample, one example of a rectangle we can form is as follows
111222
111222
For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.
In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle:
.....
..XX.
.....
.....
.....
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 wants to watch $n$ videos. Each video is only one minute long, but its size may be arbitrary. The $i$-th video has the size $a_i$ megabytes. All videos are published on the Internet. A video should be downloaded before it can be watched. Monocarp has poor Internet connection β it takes exactly $1$ minute to download $1$ megabyte of data, so it will require $a_i$ minutes to download the $i$-th video.
Monocarp's computer has a hard disk of $m$ megabytes. The disk is used to store the downloaded videos. Once Monocarp starts the download of a video of size $s$, the $s$ megabytes are immediately reserved on a hard disk. If there are less than $s$ megabytes left, the download cannot be started until the required space is freed. Each single video can be stored on the hard disk, since $a_i \le m$ for all $i$. Once the download is started, it cannot be interrupted. It is not allowed to run two or more downloads in parallel.
Once a video is fully downloaded to the hard disk, Monocarp can watch it. Watching each video takes exactly $1$ minute and does not occupy the Internet connection, so Monocarp can start downloading another video while watching the current one.
When Monocarp finishes watching a video, he doesn't need it on the hard disk anymore, so he can delete the video, instantly freeing the space it occupied on a hard disk. Deleting a video takes negligible time.
Monocarp wants to watch all $n$ videos as quickly as possible. The order of watching does not matter, since Monocarp needs to watch all of them anyway. Please calculate the minimum possible time required for that.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5$; $1 \le m \le 10^9$) β the number of videos Monocarp wants to watch and the size of the hard disk, respectively.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le m$) β the sizes of the videos.
-----Output-----
Print one integer β the minimum time required to watch all $n$ videos.
-----Examples-----
Input
5 6
1 2 3 4 5
Output
16
Input
5 5
1 2 3 4 5
Output
17
Input
4 3
1 3 2 3
Output
12
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Pablo Squarson is a well-known cubism artist. This year's theme for Pablo Squarson is "Squares". Today we are visiting his studio to see how his masterpieces are given birth.
At the center of his studio, there is a huuuuuge table and beside it are many, many squares of the same size. Pablo Squarson puts one of the squares on the table. Then he places some other squares on the table in sequence. It seems his methodical nature forces him to place each square side by side to the one that he already placed on, with machine-like precision.
Oh! The first piece of artwork is done. Pablo Squarson seems satisfied with it. Look at his happy face.
Oh, what's wrong with Pablo? He is tearing his hair! Oh, I see. He wants to find a box that fits the new piece of work but he has trouble figuring out its size. Let's help him!
Your mission is to write a program that takes instructions that record how Pablo made a piece of his artwork and computes its width and height. It is known that the size of each square is 1. You may assume that Pablo does not put a square on another.
I hear someone murmured "A smaller box will do". No, poor Pablo, shaking his head, is grumbling "My square style does not seem to be understood by illiterates".
<image>
Input
The input consists of a number of datasets. Each dataset represents the way Pablo made a piece of his artwork. The format of a dataset is as follows.
> N
n1 d1
n2 d2
...
nN-1 dN-1
The first line contains the number of squares (= N) used to make the piece of artwork. The number is a positive integer and is smaller than 200.
The remaining (N-1) lines in the dataset are square placement instructions. The line "ni di" indicates placement of the square numbered i (β€ N-1). The rules of numbering squares are as follows. The first square is numbered "zero". Subsequently placed squares are numbered 1, 2, ..., (N-1). Note that the input does not give any placement instruction to the first square, which is numbered zero.
A square placement instruction for the square numbered i, namely "ni di", directs it to be placed next to the one that is numbered ni, towards the direction given by di, which denotes leftward (= 0), downward (= 1), rightward (= 2), and upward (= 3).
For example, pieces of artwork corresponding to the four datasets shown in Sample Input are depicted below. Squares are labeled by their numbers.
<image>
The end of the input is indicated by a line that contains a single zero.
Output
For each dataset, output a line that contains the width and the height of the piece of artwork as decimal numbers, separated by a space. Each line should not contain any other characters.
Sample Input
1
5
0 0
0 1
0 2
0 3
12
0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
9 3
10 3
10
0 2
1 2
2 2
3 2
2 1
5 1
6 1
7 1
8 1
0
Output for the Sample Input
1 1
3 3
4 4
5 6
Example
Input
1
5
0 0
0 1
0 2
0 3
12
0 0
1 0
2 0
3 1
4 1
5 1
6 2
7 2
8 2
9 3
10 3
10
0 2
1 2
2 2
3 2
2 1
5 1
6 1
7 1
8 1
0
Output
1 1
3 3
4 4
5 6
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are appointed director of a famous concert hall, to save it from bankruptcy. The hall is very popular, and receives many requests to use its two fine rooms, but unfortunately the previous director was not very efficient, and it has been losing money for many years. The two rooms are of the same size and arrangement. Therefore, each applicant wishing to hold a concert asks for a room without specifying which. Each room can be used for only one concert per day.
In order to make more money, you have decided to abandon the previous fixed price policy, and rather let applicants specify the price they are ready to pay. Each application shall specify a period [i, j] and an asking price w, where i and j are respectively the first and last days of the period (1 β€ i β€ j β€ 365), and w is a positive integer in yen, indicating the amount the applicant is willing to pay to use a room for the whole period.
You have received applications for the next year, and you should now choose the applications you will accept. Each application should be either accepted for its whole period or completely rejected. Each concert should use the same room during the whole applied period.
Considering the dire economic situation of the concert hall, artistic quality is to be ignored, and you should just try to maximize the total income for the whole year by accepting the most profitable applications.
Input
The input has multiple data sets, each starting with a line consisting of a single integer n, the number of applications in the data set. Then, it is followed by n lines, each of which represents one application with a period [i, j] and an asking price w yen in the following format.
i j w
A line containing a single zero indicates the end of the input.
The maximum number of applications in a data set is one thousand, and the maximum asking price is one million yen.
Output
For each data set, print a single line containing an integer, the maximum total income in yen for the data set.
Example
Input
4
1 2 10
2 3 10
3 3 10
1 3 10
6
1 20 1000
3 25 10000
5 15 5000
22 300 5500
10 295 9000
7 7 6000
8
32 251 2261
123 281 1339
211 235 5641
162 217 7273
22 139 7851
194 198 9190
119 274 878
122 173 8640
0
Output
30
25500
38595
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 train going from Station A to Station B that costs X yen (the currency of Japan).
Also, there is a bus going from Station B to Station C that costs Y yen.
Joisino got a special ticket. With this ticket, she can take the bus for half the fare if she travels from Station A to Station B by train and then travels from Station B to Station C by bus.
How much does it cost to travel from Station A to Station C if she uses this ticket?
-----Constraints-----
- 1 \leq X,Y \leq 100
- Y is an even number.
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
X Y
-----Output-----
If it costs x yen to travel from Station A to Station C, print x.
-----Sample Input-----
81 58
-----Sample Output-----
110
- The train fare is 81 yen.
- The train fare is 58 β 2=29 yen with the 50% discount.
Thus, it costs 110 yen to travel from Station A to Station C.
Read the inputs from 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.