question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.
You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.
-----Input-----
The first line contains integer number n (1 β€ n β€ 10^9) β current year in Berland.
-----Output-----
Output amount of years from the current year to the next lucky one.
-----Examples-----
Input
4
Output
1
Input
201
Output
99
Input
4000
Output
1000
-----Note-----
In the first example next lucky year is 5. In the second one β 300. In the third β 5000.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The king's birthday dinner was attended by $k$ guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.
All types of utensils in the kingdom are numbered from $1$ to $100$. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife.
After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.
-----Input-----
The first line contains two integer numbers $n$ and $k$ ($1 \le n \le 100, 1 \le k \le 100$) Β β the number of kitchen utensils remaining after the dinner and the number of guests correspondingly.
The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 100$) Β β the types of the utensils remaining. Equal values stand for identical utensils while different values stand for different utensils.
-----Output-----
Output a single value β the minimum number of utensils that could be stolen by the guests.
-----Examples-----
Input
5 2
1 2 2 1 3
Output
1
Input
10 3
1 3 3 1 3 5 5 5 5 100
Output
14
-----Note-----
In the first example it is clear that at least one utensil of type $3$ has been stolen, since there are two guests and only one such utensil. But it is also possible that every person received only one dish and there were only six utensils in total, when every person got a set $(1, 2, 3)$ of utensils. Therefore, the answer is $1$.
One can show that in the second example at least $2$ dishes should have been served for every guest, so the number of utensils should be at least $24$: every set contains $4$ utensils and every one of the $3$ guests gets two such sets. Therefore, at least $14$ objects have been stolen. Please note that utensils of some types (for example, of types $2$ and $4$ in this example) may be not present in the set served for dishes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In 21XX, an annual programming contest, Japan Algorithmist GrandPrix (JAG) has become one of the most popular mind sports events.
JAG is conducted as a knockout tournament. This year, $N$ contestants will compete in JAG. A tournament chart is represented as a string. '[[a-b]-[c-d]]' is an easy example. In this case, there are 4 contestants named a, b, c, and d, and all matches are described as follows:
* Match 1 is the match between a and b.
* Match 2 is the match between c and d.
* Match 3 is the match between [the winner of match 1] and [the winner of match 2].
More precisely, the tournament chart satisfies the following BNF:
* <winner> ::= <person> | "[" <winner> "-" <winner> "]"
* <person> ::= "a" | "b" | "c" | ... | "z"
You, the chairperson of JAG, are planning to announce the results of this year's JAG competition. However, you made a mistake and lost the results of all the matches. Fortunately, you found the tournament chart that was printed before all of the matches of the tournament. Of course, it does not contains results at all. Therefore, you asked every contestant for the number of wins in the tournament, and got $N$ pieces of information in the form of "The contestant $a_i$ won $v_i$ times".
Now, your job is to determine whether all of these replies can be true.
Input
The input consists of a single test case in the format below.
$S$
$a_1$ $v_1$
:
$a_N$ $v_N$
$S$ represents the tournament chart. $S$ satisfies the above BNF. The following $N$ lines represent the information of the number of wins. The ($i+1$)-th line consists of a lowercase letter $a_i$ and a non-negative integer $v_i$ ($v_i \leq 26$) separated by a space, and this means that the contestant $a_i$ won $v_i$ times. Note that $N$ ($2 \leq N \leq 26$) means that the number of contestants and it can be identified by string $S$. You can assume that each letter $a_i$ is distinct. It is guaranteed that $S$ contains each $a_i$ exactly once and doesn't contain any other lowercase letters.
Output
Print 'Yes' in one line if replies are all valid for the tournament chart. Otherwise, print 'No' in one line.
Examples
Input
[[m-y]-[a-o]]
o 0
a 1
y 2
m 0
Output
Yes
Input
[[r-i]-[m-e]]
e 0
r 1
i 1
m 2
Output
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
-----Input-----
The first line contains integer n (1 β€ n β€ 10^5) β the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 β the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.
-----Output-----
Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".
-----Examples-----
Input
4
25 25 50 50
Output
YES
Input
2
25 100
Output
NO
Input
4
50 50 25 25
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
JOI decided to play a game with his friends. N players participate in this game. The rules for a single game are as follows:
Each player writes a favorite integer from 1 to 100 on the card and submits it. Each player gets the same score as he wrote if no one else wrote the same number. If there is another person who wrote the same number as you, you will not get a score.
JOI You guys played this game 3 times. Create a program to find the total score each player has earned in the three games given the number each player has written in the three games.
input
The input consists of 1 + N lines.
The integer N (2 β€ N β€ 200) is written on the first line, which indicates the number of players.
In the i-th line (1 β€ i β€ N) of the following N lines, three integers from 1 to 100 are written separated by blanks, and the i-th player is the first, second, and third times, respectively. Represents the number written in the game of.
output
The output consists of N lines.
On line i (1 β€ i β€ N), output an integer representing the total score obtained by the i-th player in the three games.
Input / output example
Input example 1
Five
100 99 98
100 97 92
63 89 63
99 99 99
89 97 98
Output example 1
0
92
215
198
89
In example 1, the details of the points scored by each player in the three games are as follows:
Player 1: 0 + 0 + 0 = 0
---
Player 2: 0 + 0 + 92 = 92
Player 3: 63 + 89 + 63 = 215
Player 4: 99 + 0 + 99 = 198
Player 5: 89 + 0 + 0 = 89
Input example 2
3
89 92 77
89 92 63
89 63 77
Output example 2
0
63
63
The question text and the data used for the automatic referee are the question text and the test data for scoring that are created and published by the Japan Committee for Information Olympics.
Example
Input
5
100 99 98
100 97 92
63 89 63
99 99 99
89 97 98
Output
0
92
215
198
89
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.
The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.
One move happens as follows. Lets say there are m β₯ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move.
Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.
Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.
-----Input-----
The first line of input contains a single integer n (2 β€ n β€ 200 000)Β β the number of stickers, initially located on the wall.
The second line contains n integers a_1, a_2, ..., a_{n} ( - 10 000 β€ a_{i} β€ 10 000)Β β the numbers on stickers in order from left to right.
-----Output-----
Print one integerΒ β the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.
-----Examples-----
Input
3
2 4 8
Output
14
Input
4
1 -7 -2 3
Output
-3
-----Note-----
In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.
In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days.
In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day.
Du will chat in the group for $n$ days. On the $i$-th day: If Du can speak, he'll make fun of Boboniu with fun factor $a_i$. But after that, he may be muzzled depending on Boboniu's mood. Otherwise, Du won't do anything.
Boboniu's mood is a constant $m$. On the $i$-th day: If Du can speak and $a_i>m$, then Boboniu will be angry and muzzle him for $d$ days, which means that Du won't be able to speak on the $i+1, i+2, \cdots, \min(i+d,n)$-th days. Otherwise, Boboniu won't do anything.
The total fun factor is the sum of the fun factors on the days when Du can speak.
Du asked you to find the maximum total fun factor among all possible permutations of $a$.
-----Input-----
The first line contains three integers $n$, $d$ and $m$ ($1\le d\le n\le 10^5,0\le m\le 10^9$).
The next line contains $n$ integers $a_1, a_2, \ldots,a_n$ ($0\le a_i\le 10^9$).
-----Output-----
Print one integer: the maximum total fun factor among all permutations of $a$.
-----Examples-----
Input
5 2 11
8 10 15 23 5
Output
48
Input
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
Output
195
-----Note-----
In the first example, you can set $a'=[15, 5, 8, 10, 23]$. Then Du's chatting record will be: Make fun of Boboniu with fun factor $15$. Be muzzled. Be muzzled. Make fun of Boboniu with fun factor $10$. Make fun of Boboniu with fun factor $23$.
Thus the total fun factor is $48$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way. [Image]
An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.
A dungeon consists of n segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.
One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number i_1, he can make a sequence of jumps through the platforms i_1 < i_2 < ... < i_{k}, if i_2 - i_1 = i_3 - i_2 = ... = i_{k} - i_{k} - 1. Of course, all segments i_1, i_2, ... i_{k} should be exactly the platforms, not pits.
Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence i_1, i_2, ..., i_5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.
-----Input-----
The first line contains integer n (1 β€ n β€ 100) β the number of segments on the level.
Next line contains the scheme of the level represented as a string of n characters '*' and '.'.
-----Output-----
If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes).
-----Examples-----
Input
16
.**.*..*.***.**.
Output
yes
Input
11
.*.*...*.*.
Output
no
-----Note-----
In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Your task is to write a program which reads an expression and evaluates it.
* The expression consists of numerical values, operators and parentheses, and the ends with '='.
* The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division.
* Precedence of the operators is based on usual laws. That is one should perform all multiplication and division first, then addition and subtraction. When two operators have the same precedence, they are applied from left to right.
* You may assume that there is no division by zero.
* All calculation is performed as integers, and after the decimal point should be truncated
* Length of the expression will not exceed 100.
* -1 Γ 109 β€ intermediate results of computation β€ 109
Input
The input is a sequence of datasets. The first line contains an integer n which represents the number of datasets. There will be n lines where each line contains an expression.
Output
For each datasets, prints the result of calculation.
Example
Input
2
4-2*3=
4*(8+4+3)=
Output
-2
60
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 N be a positive integer. You are given a string s of length N - 1, consisting of `<` and `>`.
Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7:
* For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is `<`, and p_i > p_{i + 1} if the i-th character in s is `>`.
Constraints
* N is an integer.
* 2 \leq N \leq 3000
* s is a string of length N - 1.
* s consists of `<` and `>`.
Input
Input is given from Standard Input in the following format:
N
s
Output
Print the number of permutations that satisfy the condition, modulo 10^9 + 7.
Examples
Input
4
<><
Output
5
Input
5
<<<<
Output
1
Input
20
>>>><>>><>><>>><<>>
Output
217136290
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?
Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it!
Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absentΒ β cubes.
For completing the chamber Wheatley needs $n$ cubes. $i$-th cube has a volume $a_i$.
Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $i>1$, $a_{i-1} \le a_i$ must hold.
To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $i>1$ you can exchange cubes on positions $i-1$ and $i$.
But there is a problem: Wheatley is very impatient. If Wheatley needs more than $\frac{n \cdot (n-1)}{2}-1$ exchange operations, he won't do this boring work.
Wheatly wants to know: can cubes be sorted under this conditions?
-----Input-----
Each test contains multiple test cases.
The first line contains one positive integer $t$ ($1 \le t \le 1000$), denoting the number of test cases. Description of the test cases follows.
The first line of each test case contains one positive integer $n$ ($2 \le n \le 5 \cdot 10^4$)Β β number of cubes.
The second line contains $n$ positive integers $a_i$ ($1 \le a_i \le 10^9$)Β β volumes of cubes.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.
-----Example-----
Input
3
5
5 3 2 1 4
6
2 2 2 2 2 2
2
2 1
Output
YES
YES
NO
-----Note-----
In the first test case it is possible to sort all the cubes in $7$ exchanges.
In the second test case the cubes are already sorted.
In the third test case we can make $0$ exchanges, but the cubes are not sorted yet, so the answer is "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.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.
B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.
You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).
-----Input-----
The first and only line consists of a string $S$ ($ 1 \le |S| \le 5\,000 $). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.
-----Output-----
Print "YES" or "NO", according to the condition.
-----Examples-----
Input
aaabccc
Output
YES
Input
bbacc
Output
NO
Input
aabc
Output
YES
-----Note-----
Consider first example: the number of 'c' is equal to the number of 'a'.
Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.
Consider third example: the number of 'c' is equal to the number of 'b'.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) β₯ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 β₯ 5.
You are given an array a of n integers. Find some interesting nonempty subarray of a, or tell that it doesn't exist.
An array b is a subarray of an array a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.
Input
The first line contains integer number t (1 β€ t β€ 10 000). Then t test cases follow.
The first line of each test case contains a single integer n (2β€ n β€ 2β
10^5) β the length of the array.
The second line of each test case contains n integers a_1, a_2, ..., a_n (0β€ a_i β€ 10^9) β the elements of the array.
It is guaranteed that the sum of n over all test cases does not exceed 2 β
10^5.
Output
For each test case, output "NO" in a separate line if there is no interesting nonempty subarray in a.
Otherwise, output "YES" in a separate line. In the next line, output two integers l and r (1β€ l β€ r β€ n) β bounds of the chosen subarray. If there are multiple answers, print any.
You can print each letter in any case (upper or lower).
Example
Input
3
5
1 2 3 4 5
4
2 0 1 9
2
2019 2020
Output
NO
YES
1 4
NO
Note
In the second test case of the example, one of the interesting subarrays is a = [2, 0, 1, 9]: max(a) - min(a) = 9 - 0 = 9 β₯ 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here https://en.wikipedia.org/wiki/King_(chess). [Image] King moves from the position e4
-----Input-----
The only line contains the king's position in the format "cd", where 'c' is the column from 'a' to 'h' and 'd' is the row from '1' to '8'.
-----Output-----
Print the only integer x β the number of moves permitted for the king.
-----Example-----
Input
e4
Output
8
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Collatz conjecture is one of the most famous one. Take any positive integer n, if it is even divide it by 2, if it is odd multiply it by 3 and add 1 and continue indefinitely.The conjecture is that whatever is n the sequence will reach 1. There is many ways to approach this problem, each one of them had given beautifull graphs and impressive display of calculation power. The simplest approach can be found in this kata: http://www.codewars.com/kata/5286b2e162056fd0cb000c20
You look at the Collatz sequence of a number and see when it reaches 1.
In this kata we will take a look at the length of collatz sequences. And how they evolve. Write a function that take a positive integer n and return the number between 1 and n that has the maximum Collatz sequence length and the maximum length. The output has to take the form of an array [number, maxLength] For exemple the Collatz sequence of 4 is [4,2,1], 3 is [3,10,5,16,8,4,2,1], 2 is [2,1], 1 is [1], so `MaxCollatzLength(4)` should return `[3,8]`. If n is not a positive integer, the function have to return [].
* As you can see, numbers in Collatz sequences may exceed n.
The last tests use random big numbers so you may consider some optimisation in your code:
* You may get very unlucky and get only hard numbers: try submitting 2-3 times if it times out; if it still does, probably you need to optimize your code more;
* Optimisation 1: when calculating the length of a sequence, if n is odd, what 3n+1 will be ?
* Optimisation 2: when looping through 1 to n, take i such that i<n/2, what will be the lenght of the sequence for 2i ?
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 three integers $x, y$ and $n$. Your task is to find the maximum integer $k$ such that $0 \le k \le n$ that $k \bmod x = y$, where $\bmod$ is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given $x, y$ and $n$ you need to find the maximum possible integer from $0$ to $n$ that has the remainder $y$ modulo $x$.
You have to answer $t$ independent test cases. It is guaranteed that such $k$ exists for each test case.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 5 \cdot 10^4$) β the number of test cases. The next $t$ lines contain test cases.
The only line of the test case contains three integers $x, y$ and $n$ ($2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$).
It can be shown that such $k$ always exists under the given constraints.
-----Output-----
For each test case, print the answer β maximum non-negative integer $k$ such that $0 \le k \le n$ and $k \bmod x = y$. It is guaranteed that the answer always exists.
-----Example-----
Input
7
7 5 12345
5 0 4
10 5 15
17 8 54321
499999993 9 1000000000
10 5 187
2 0 999999999
Output
12339
0
15
54306
999999995
185
999999998
-----Note-----
In the first test case of the example, the answer is $12339 = 7 \cdot 1762 + 5$ (thus, $12339 \bmod 7 = 5$). It is obvious that there is no greater integer not exceeding $12345$ which has the remainder $5$ modulo $7$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $2n$ jars of strawberry and blueberry jam.
All the $2n$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $n$ jars to his left and $n$ jars to his right.
For example, the basement might look like this: [Image]
Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.
Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.
For example, this might be the result: [Image] He has eaten $1$ jar to his left and then $5$ jars to his right. There remained exactly $3$ full jars of both strawberry and blueberry jam.
Jars are numbered from $1$ to $2n$ from left to right, so Karlsson initially stands between jars $n$ and $n+1$.
What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?
Your program should answer $t$ independent test cases.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) β the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$).
The second line of each test case contains $2n$ integers $a_1, a_2, \dots, a_{2n}$ ($1 \le a_i \le 2$) β $a_i=1$ means that the $i$-th jar from the left is a strawberry jam jar and $a_i=2$ means that it is a blueberry jam jar.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case print the answer to it β the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
-----Example-----
Input
4
6
1 1 1 2 2 1 2 1 2 1 1 2
2
1 2 1 2
3
1 1 1 1 1 1
2
2 1 1 1
Output
6
0
6
2
-----Note-----
The picture from the statement describes the first test case.
In the second test case the number of strawberry and blueberry jam jars is already equal.
In the third test case Karlsson is required to eat all $6$ jars so that there remain $0$ jars of both jams.
In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $1$ jar of both jams.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string S consisting of lowercase English letters. We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.
Constraints
* 1 \leq w \leq |S| \leq 1000
* S consists of lowercase English letters.
* w is an integer.
Input
Input is given from Standard Input in the following format:
S
w
Output
Print the desired string in one line.
Examples
Input
abcdefgh
3
Output
adg
Input
lllll
1
Output
lllll
Input
souuundhound
2
Output
suudon
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 credit card number we can determine who the issuer/vendor is with a few basic knowns.
```if:python
Complete the function `get_issuer()` that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the string `Unknown`.
```
```if-not:python
Complete the function `getIssuer()` that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the string `Unknown`.
```
```if:typescript
Where `Issuer` is defined with the following enum type.
~~~typescript
enum Issuer {
VISA = 'VISA',
AMEX = 'AMEX',
Mastercard = 'Mastercard',
Discover = 'Discover',
Unknown = 'Unknown',
}
~~~
```
```markdown
| Card Type | Begins With | Number Length |
|------------|----------------------|---------------|
| AMEX | 34 or 37 | 15 |
| Discover | 6011 | 16 |
| Mastercard | 51, 52, 53, 54 or 55 | 16 |
| VISA | 4 | 13 or 16 |
```
```if:c,cpp
**C/C++ note:** The return value in C is not freed.
```
## Examples
```if-not:python
~~~js
getIssuer(4111111111111111) == "VISA"
getIssuer(4111111111111) == "VISA"
getIssuer(4012888888881881) == "VISA"
getIssuer(378282246310005) == "AMEX"
getIssuer(6011111111111117) == "Discover"
getIssuer(5105105105105100) == "Mastercard"
getIssuer(5105105105105106) == "Mastercard"
getIssuer(9111111111111111) == "Unknown"
~~~
```
```if:python
~~~py
get_issuer(4111111111111111) == "VISA"
get_issuer(4111111111111) == "VISA"
get_issuer(4012888888881881) == "VISA"
get_issuer(378282246310005) == "AMEX"
get_issuer(6011111111111117) == "Discover"
get_issuer(5105105105105100) == "Mastercard"
get_issuer(5105105105105106) == "Mastercard"
get_issuer(9111111111111111) == "Unknown"
~~~
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
M-kun has the following three cards:
* A red card with the integer A.
* A green card with the integer B.
* A blue card with the integer C.
He is a genius magician who can do the following operation at most K times:
* Choose one of the three cards and multiply the written integer by 2.
His magic is successful if both of the following conditions are satisfied after the operations:
* The integer on the green card is strictly greater than the integer on the red card.
* The integer on the blue card is strictly greater than the integer on the green card.
Determine whether the magic can be successful.
Constraints
* 1 \leq A, B, C \leq 7
* 1 \leq K \leq 7
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B C
K
Output
If the magic can be successful, print `Yes`; otherwise, print `No`.
Examples
Input
7 2 5
3
Output
Yes
Input
7 4 2
3
Output
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Russian here
The Head Chef has been playing with Fibonacci numbers for long . He has learnt several tricks related to Fibonacci numbers . Now he wants to test his chefs in the skills .
A fibonacci number is defined by the recurrence :
f(n) = f(n-1) + f(n-2) for n > 2
and f(1) = 0
and f(2) = 1 .
Given a number A , determine if it is a fibonacci number.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains a single integer A denoting the number to be checked .
------ Output ------
For each test case, output a single line containing "YES" if the given number is a fibonacci number , otherwise output a single line containing "NO" .
------ Constraints ------
$1 β€ T β€ 1000$
$1 β€ number of digits in A β€ 1000$
$ The sum of number of digits in A in all test cases β€ 10000. $
----- Sample Input 1 ------
3
3
4
5
----- Sample Output 1 ------
YES
NO
YES
----- explanation 1 ------
Example case 1. The first few fibonacci numbers are 0 , 1 , 1 , 2 , 3 ,5 , 8 , 13 and so on and the series is increasing . Only 3 and 5 appear in this series while 4 does not appear in the series .
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We start with a permutation a_1, a_2, β¦, a_n and with an empty array b. We apply the following operation k times.
On the i-th iteration, we select an index t_i (1 β€ t_i β€ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, β¦, a_n to the left in order to fill in the empty space.
You are given the initial permutation a_1, a_2, β¦, a_n and the resulting array b_1, b_2, β¦, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, β¦, t_k modulo 998 244 353.
Input
Each test contains multiple test cases. The first line contains an integer t (1 β€ t β€ 100 000), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains two integers n, k (1 β€ k < n β€ 200 000): sizes of arrays a and b.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n): elements of a. All elements of a are distinct.
The third line of each test case contains k integers b_1, b_2, β¦, b_k (1 β€ b_i β€ n): elements of b. All elements of b are distinct.
The sum of all n among all test cases is guaranteed to not exceed 200 000.
Output
For each test case print one integer: the number of possible sequences modulo 998 244 353.
Example
Input
3
5 3
1 2 3 4 5
3 2 5
4 3
4 3 2 1
4 3 1
7 4
1 4 7 3 6 2 5
3 2 4 5
Output
2
0
4
Note
\require{cancel}
Let's denote as a_1 a_2 β¦ \cancel{a_i} \underline{a_{i+1}} β¦ a_n β a_1 a_2 β¦ a_{i-1} a_{i+1} β¦ a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b.
In the first example test, the following two options can be used to produce the given array b:
* 1 2 \underline{3} \cancel{4} 5 β 1 \underline{2} \cancel{3} 5 β 1 \cancel{2} \underline{5} β 1 2; (t_1, t_2, t_3) = (4, 3, 2);
* 1 2 \underline{3} \cancel{4} 5 β \cancel{1} \underline{2} 3 5 β 2 \cancel{3} \underline{5} β 1 5; (t_1, t_2, t_3) = (4, 1, 2).
In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step.
In the third example test, there are four options to achieve the given array b:
* 1 4 \cancel{7} \underline{3} 6 2 5 β 1 4 3 \cancel{6} \underline{2} 5 β \cancel{1} \underline{4} 3 2 5 β 4 3 \cancel{2} \underline{5} β 4 3 5;
* 1 4 \cancel{7} \underline{3} 6 2 5 β 1 4 3 \cancel{6} \underline{2} 5 β 1 \underline{4} \cancel{3} 2 5 β 1 4 \cancel{2} \underline{5} β 1 4 5;
* 1 4 7 \underline{3} \cancel{6} 2 5 β 1 4 7 \cancel{3} \underline{2} 5 β \cancel{1} \underline{4} 7 2 5 β 4 7 \cancel{2} \underline{5} β 4 7 5;
* 1 4 7 \underline{3} \cancel{6} 2 5 β 1 4 7 \cancel{3} \underline{2} 5 β 1 \underline{4} \cancel{7} 2 5 β 1 4 \cancel{2} \underline{5} β 1 4 5;
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
_Based on [Project Euler problem 35](https://projecteuler.net/problem=35)_
A circular prime is a prime in which every circular permutation of that number is also prime. Circular permutations are created by rotating the digits of the number, for example: `197, 971, 719`. One-digit primes are circular primes by definition.
Complete the function that dertermines if a number is a circular prime.
There are 100 random tests for numbers up to 10000.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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.
Chef is playing a game. Currently in the game, he is at a field full of stones. There are total N kinds of
stones. There is unlimited supply of each kind of stone.
Chef knows that one stone of kind i needs A_{i} minutes to pick it from the ground and it will give Chef a profit of
B_{i} Rs.
Chef has K minutes of free time. During this free time, Chef want to pick stones so as to maximize his profit.
But he can not pick stones of different kinds, he has to pick stones of a single kind.
Please help Chef to find the maximal possible profit.
------ Input ------
First line contains single integer T denoting the number of test cases.
First line of each test case contains two integers N and K.
Next line contains N integers A_{i} denoting the time needed to pick one stone of kind i.
Next line contains N integers B_{i} denoting the profit due to picking i^{th}th stone.
------ Output ------
For each test case, print a single line containing maximal possible profit.
------ Constraints ------
$1 β€ T β€ 5$
$1 β€ N β€ 10^{5}$
$1 β€ K β€ 10^{9}$
$1 β€ A_{i}, B_{i} β€ 10^{9}$
------ Subtasks ------
$Subtask N β€ 5, T β€ 2 Points: 30 $
$Subtask N β€ 10^{5}, T β€ 5 Points: 70 $
----- Sample Input 1 ------
1
3 10
3 4 5
4 4 5
----- Sample Output 1 ------
12
----- explanation 1 ------
If Chef picks stones of first kind he can pick 3 stones, he will get a profit of 3*4 = 12 Rs.
If Chef picks stones of second kind he can pick 2 stones, he will get a profit of 2*4 = 8 Rs.
If Chef picks stones of third kind he can pick 2 stones, he will get a profit of 2*5 = 10 Rs.
So the maximum possible profit is 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.
In 20XX AD, a school competition was held. The tournament has finally left only the final competition. You are one of the athletes in the competition.
The competition you participate in is to compete for the time it takes to destroy all the blue objects placed in the space. Athletes are allowed to bring in competition guns. In the space, there are multiple blue objects, the same number of red objects, and multiple obstacles. There is a one-to-one correspondence between the blue object and the red object, and the blue object must be destroyed by shooting a bullet at the blue object from the coordinates where the red object is placed. The obstacles placed in the space are spherical and the composition is slightly different, but if it is a normal bullet, the bullet will stop there when it touches the obstacle.
The bullet used in the competition is a special bullet called Magic Bullet. This bullet can store magical power, and when the bullet touches an obstacle, it automatically consumes the magical power, and the magic that the bullet penetrates is activated. Due to the difference in the composition of obstacles, the amount of magic required to penetrate and the amount of magic power consumed to activate it are different. Therefore, even after the magic for one obstacle is activated, it is necessary to activate another magic in order to penetrate another obstacle. Also, if the bullet touches multiple obstacles at the same time, magic will be activated at the same time. The amount of magical power contained in the bullet decreases with each magic activation.
While the position and size of obstacles and the amount of magical power required to activate the penetrating magic have already been disclosed, the positions of the red and blue objects have not been disclosed. However, the position of the object could be predicted to some extent from the information of the same competition in the past. You want to save as much magical power as you can, because putting magical power into a bullet is very exhausting. Therefore, assuming the position of the red object and the corresponding blue object, the minimum amount of magical power required to be loaded in the bullet at that time, that is, the magical power remaining in the bullet when reaching the blue object is 0. Let's find the amount of magical power that becomes.
Constraints
* 0 β€ N β€ 50
* 1 β€ Q β€ 50
* -500 β€ xi, yi, zi β€ 500
* 1 β€ ri β€ 1,000
* 1 β€ li β€ 1016
* -500 β€ sxj, syj, szj β€ 500
* -500 β€ dxj, dyj, dzj β€ 500
* Obstacles are never stuck in other obstacles
* The coordinates of the object are not inside or on the surface of the obstacle
* Under each assumption, the coordinates of the red object and the blue object do not match.
Input
All inputs are integers. Each number is separated by a single space.
N Q
x1 y1 z1 r1 l1
::
xN yN zN rN lN
sx1 sy1 sz1 dx1 dy1 dz1
::
sxQ syQ szQ dxQ dyQ dzQ
* N is the number of obstacles, and Q is the number of coordinates of the assumed blue and red objects.
* xi, yi, and zi are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the center of the i-th obstacle, respectively.
* ri is the radius of the i-th obstacle.
* li is the amount of magical power consumed by magic to penetrate the i-th obstacle.
* sxj, syj, and szj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the red object in the jth assumption, respectively.
* dxj, dyj, and dzj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the blue object in the jth assumption, respectively.
Output
Assuming the position of each pair of red objects and the corresponding blue objects, the amount of magical power to be loaded in the bullet is output on one line, assuming that there are only obstacles, red objects, and one pair of blue objects in space. Let's do it. The bullet is supposed to fly in a straight line from the position of the red object to the position of the blue object, and since the size of the bullet is very small, it is treated as a point.
Examples
Input
5 1
0 10 0 5 2
0 20 0 5 12
0 30 0 5 22
0 40 0 5 32
0 50 0 5 42
0 0 0 0 60 0
Output
110
Input
1 1
10 5 0 5 9
0 0 0 9 12 0
Output
9
Input
5 5
-38 -71 -293 75 1
-158 -38 -405 66 1
-236 -303 157 266 1
316 26 411 190 1
207 -312 -27 196 1
-50 292 -375 -401 389 -389
460 278 409 -329 -303 411
215 -220 -200 309 -474 300
261 -494 -87 -300 123 -463
386 378 486 -443 -64 299
Output
0
2
1
3
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".
Find the number of cows that can currently show their hands without affecting any betting decisions.
-----Input-----
The first line contains a single integer, n (2 β€ n β€ 2Β·10^5). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".
-----Output-----
The first line should contain a single integer denoting the number of players that can currently show their hands.
-----Examples-----
Input
6
AFFAAA
Output
4
Input
3
AFI
Output
1
-----Note-----
In the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an array b of length m we define the function f as
f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] β b[2],b[2] β b[3],...,b[m-1] β b[m]) & otherwise, \end{cases}
where β is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, f(1,2,4,8)=f(1β2,2β4,4β8)=f(3,6,12)=f(3β6,6β12)=f(5,10)=f(5β10)=f(15)=15
You are given an array a and a few queries. Each query is represented as two integers l and r. The answer is the maximum value of f on all continuous subsegments of the array a_l, a_{l+1}, β¦, a_r.
Input
The first line contains a single integer n (1 β€ n β€ 5000) β the length of a.
The second line contains n integers a_1, a_2, ..., a_n (0 β€ a_i β€ 2^{30}-1) β the elements of the array.
The third line contains a single integer q (1 β€ q β€ 100 000) β the number of queries.
Each of the next q lines contains a query represented as two integers l, r (1 β€ l β€ r β€ n).
Output
Print q lines β the answers for the queries.
Examples
Input
3
8 4 1
2
2 3
1 2
Output
5
12
Input
6
1 2 4 8 16 32
4
1 6
2 5
3 4
1 2
Output
60
30
12
3
Note
In first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.
In second sample, optimal segment for first query are [3,6], for second query β [2,5], for third β [3,4], for fourth β [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.
There is a deck of $n$ cards. The $i$-th card has a number $a_i$ on the front and a number $b_i$ on the back. Every integer between $1$ and $2n$ appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if $a_i< a_{i+1}$ and $b_i> b_{i+1}$ for all $1\le i<n$.
To flip a card $i$ means swapping the values of $a_i$ and $b_i$. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
-----Input-----
The first line contains a single integer $n$ ($1\le n\le 2\cdot 10^5$) β the number of cards.
The next $n$ lines describe the cards. The $i$-th of these lines contains two integers $a_i, b_i$ ($1\le a_i, b_i\le 2n$). Every integer between $1$ and $2n$ appears exactly once.
-----Output-----
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
-----Examples-----
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
-----Note-----
In the first test case, we flip the cards $(1, 9)$ and $(2, 7)$. The deck is then ordered $(3,10), (5,8), (6,4), (7,2), (9,1)$. It is sorted because $3<5<6<7<9$ and $10>8>4>2>1$.
In the second test case, it is impossible to sort the deck.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
###Instructions
Write a function that takes a negative or positive integer, which represents the number of minutes before (-) or after (+) Sunday midnight, and returns the current day of the week and the current time in 24hr format ('hh:mm') as a string.
```python
day_and_time(0) should return 'Sunday 00:00'
day_and_time(-3) should return 'Saturday 23:57'
day_and_time(45) should return 'Sunday 00:45'
day_and_time(759) should return 'Sunday 12:39'
day_and_time(1236) should return 'Sunday 20:36'
day_and_time(1447) should return 'Monday 00:07'
day_and_time(7832) should return 'Friday 10:32'
day_and_time(18876) should return 'Saturday 02:36'
day_and_time(259180) should return 'Thursday 23:40'
day_and_time(-349000) should return 'Tuesday 15:20'
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it. He has A_i cards with an integer i.
Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1.
Snuke wants to create the maximum number of pairs from his cards, on the condition that no card should be used in multiple pairs. Find the maximum number of pairs that he can create.
Constraints
* 1 β¦ N β¦ 10^5
* 0 β¦ A_i β¦ 10^9 (1 β¦ i β¦ N)
* All input values are integers.
Input
The input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
Print the maximum number of pairs that Snuke can create.
Examples
Input
4
4
0
3
2
Output
4
Input
8
2
0
1
6
0
8
2
1
Output
9
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.
First, Snuke will arrange the N balls in a row from left to right.
Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.
How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.
-----Constraints-----
- 1 \leq K \leq N \leq 2000
-----Input-----
Input is given from Standard Input in the following format:
N K
-----Output-----
Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.
-----Sample Input-----
5 3
-----Sample Output-----
3
6
1
There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).
There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).
There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 function $f : R \rightarrow R$ is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| β€ KΒ·|x - y| holds for all $x, y \in R$. We'll deal with a more... discrete version of this term.
For an array $h [ 1 . . n ]$, we define it's Lipschitz constant $L(h)$ as follows: if n < 2, $L(h) = 0$ if n β₯ 2, $L(h) = \operatorname{max} [ \frac{|h [ j ] - h [ i ]|}{j - i} ]$ over all 1 β€ i < j β€ n
In other words, $L = L(h)$ is the smallest non-negative integer such that |h[i] - h[j]| β€ LΒ·|i - j| holds for all 1 β€ i, j β€ n.
You are given an array [Image] of size n and q queries of the form [l, r]. For each query, consider the subarray $s = a [ l . . r ]$; determine the sum of Lipschitz constants of all subarrays of $S$.
-----Input-----
The first line of the input contains two space-separated integers n and q (2 β€ n β€ 100 000 and 1 β€ q β€ 100)Β β the number of elements in array [Image] and the number of queries respectively.
The second line contains n space-separated integers $a [ 1 . . n ]$ ($0 \leq a [ i ] \leq 10^{8}$).
The following q lines describe queries. The i-th of those lines contains two space-separated integers l_{i} and r_{i} (1 β€ l_{i} < r_{i} β€ n).
-----Output-----
Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integerΒ β the sum of Lipschitz constants of all subarrays of [Image].
-----Examples-----
Input
10 4
1 5 2 9 1 3 4 2 1 7
2 4
3 8
7 10
1 9
Output
17
82
23
210
Input
7 6
5 7 7 4 6 6 2
1 2
2 3
2 6
1 7
4 7
3 5
Output
2
0
22
59
16
8
-----Note-----
In the first query of the first sample, the Lipschitz constants of subarrays of $[ 5,2,9 ]$ with length at least 2 are: $L([ 5,2 ]) = 3$ $L([ 2,9 ]) = 7$ $L([ 5,2,9 ]) = 7$
The answer to the query is their 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.
Read problems statements in Mandarin Chinese and Russian as well.
You had an array of integer numbers. You also had a beautiful operations called "Copy-Paste" which allowed you to copy any contiguous subsequence of your array and paste it in any position of your array. For example, if you have array [1, 2, 3, 4, 5] and copy it's subsequence from the second to the fourth element and paste it after the third one, then you will get [1, 2, 3, 2, 3, 4, 4, 5] array. You remember that you have done a finite(probably zero) number of such operations over your initial array and got an array A as a result. Unfortunately you don't remember the initial array itself, so you would like to know what could it be. You are interested by the smallest such array. So the task is to find the minimal size(length) of the array that A can be obtained from by using "Copy-Paste" operations.
Β
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the number of elements in obtained array A. The second line contains N space-separated integers A_{1}, A_{2}, ..., A_{N} denoting the array.
Β
------ Output ------
For each test case, output a single line containing the answer.
Β
------ Constraints ------
$1 β€ T β€ 20$
$1 β€ N β€ 10^{5}$
$1 β€ A_{i} β€ 10^{5}$
Β
----- Sample Input 1 ------
2
5
1 1 1 1 1
5
1 2 3 1 2
----- Sample Output 1 ------
1
3
----- explanation 1 ------
In the first case we could have only array [1] in the beginning and then obtain [1, 1], then [1, 1, 1, 1] and finally [1, 1, 1, 1, 1]. In the second one we could obtain A from [1, 2, 3] by copying it's first two elements to the end.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 median of an array of integers of length $n$ is the number standing on the $\lceil {\frac{n}{2}} \rceil$ (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with $1$. For example, a median of the array $[2, 6, 4, 1, 3, 5]$ is equal to $3$. There exist some other definitions of the median, but in this problem, we will use the described one.
Given two integers $n$ and $k$ and non-decreasing array of $nk$ integers. Divide all numbers into $k$ arrays of size $n$, such that each number belongs to exactly one array.
You want the sum of medians of all $k$ arrays to be the maximum possible. Find this maximum possible sum.
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 100$) β the number of test cases. The next $2t$ lines contain descriptions of test cases.
The first line of the description of each test case contains two integers $n$, $k$ ($1 \leq n, k \leq 1000$).
The second line of the description of each test case contains $nk$ integers $a_1, a_2, \ldots, a_{nk}$ ($0 \leq a_i \leq 10^9$) β given array. It is guaranteed that the array is non-decreasing: $a_1 \leq a_2 \leq \ldots \leq a_{nk}$.
It is guaranteed that the sum of $nk$ for all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case print a single integer β the maximum possible sum of medians of all $k$ arrays.
-----Examples-----
Input
6
2 4
0 24 34 58 62 64 69 78
2 2
27 61 81 91
4 3
2 4 16 18 21 27 36 53 82 91 92 95
3 4
3 11 12 22 33 35 38 67 69 71 94 99
2 1
11 41
3 3
1 1 1 1 1 1 1 1 1
Output
165
108
145
234
11
3
-----Note-----
The examples of possible divisions into arrays for all test cases of the first test:
Test case $1$: $[0, 24], [34, 58], [62, 64], [69, 78]$. The medians are $0, 34, 62, 69$. Their sum is $165$.
Test case $2$: $[27, 61], [81, 91]$. The medians are $27, 81$. Their sum is $108$.
Test case $3$: $[2, 91, 92, 95], [4, 36, 53, 82], [16, 18, 21, 27]$. The medians are $91, 36, 18$. Their sum is $145$.
Test case $4$: $[3, 33, 35], [11, 94, 99], [12, 38, 67], [22, 69, 71]$. The medians are $33, 94, 38, 69$. Their sum is $234$.
Test case $5$: $[11, 41]$. The median is $11$. The sum of the only median is $11$.
Test case $6$: $[1, 1, 1], [1, 1, 1], [1, 1, 1]$. The medians are $1, 1, 1$. Their sum is $3$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly n pixels.
Your task is to determine the size of the rectangular display β the number of lines (rows) of pixels a and the number of columns of pixels b, so that:
there are exactly n pixels on the display; the number of rows does not exceed the number of columns, it means a β€ b; the difference b - a is as small as possible.
-----Input-----
The first line contains the positive integer n (1 β€ n β€ 10^6)Β β the number of pixels display should have.
-----Output-----
Print two integersΒ β the number of rows and columns on the display.
-----Examples-----
Input
8
Output
2 4
Input
64
Output
8 8
Input
5
Output
1 5
Input
999999
Output
999 1001
-----Note-----
In the first example the minimum possible difference equals 2, so on the display should be 2 rows of 4 pixels.
In the second example the minimum possible difference equals 0, so on the display should be 8 rows of 8 pixels.
In the third example the minimum possible difference equals 4, so on the display should be 1 row of 5 pixels.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array of n integer numbers. Let sum(l, r) be the sum of all numbers on positions from l to r non-inclusive (l-th element is counted, r-th element is not counted). For indices l and r holds 0 β€ l β€ r β€ n. Indices in array are numbered from 0.
For example, if a = [ - 5, 3, 9, 4], then sum(0, 1) = - 5, sum(0, 2) = - 2, sum(1, 4) = 16 and sum(i, i) = 0 for each i from 0 to 4.
Choose the indices of three delimiters delim0, delim1, delim2 (0 β€ delim0 β€ delim1 β€ delim2 β€ n) and divide the array in such a way that the value of res = sum(0, delim0) - sum(delim0, delim1) + sum(delim1, delim2) - sum(delim2, n) is maximal.
Note that some of the expressions sum(l, r) can correspond to empty segments (if l = r for some segment).
Input
The first line contains one integer number n (1 β€ n β€ 5000).
The second line contains n numbers a0, a1, ..., an - 1 ( - 109 β€ ai β€ 109).
Output
Choose three indices so that the value of res is maximal. If there are multiple answers, print any of them.
Examples
Input
3
-1 2 3
Output
0 1 3
Input
4
0 0 -1 0
Output
0 0 0
Input
1
10000
Output
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.
Valera has got n domino pieces in a row. Each piece consists of two halves β the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
-----Input-----
The first line contains integer n (1 β€ n β€ 100), denoting the number of dominoes Valera has. Next n lines contain two space-separated integers x_{i}, y_{i} (1 β€ x_{i}, y_{i} β€ 6). Number x_{i} is initially written on the upper half of the i-th domino, y_{i} is initially written on the lower half.
-----Output-----
Print a single number β the minimum required number of seconds. If Valera can't do the task in any time, print - 1.
-----Examples-----
Input
2
4 2
6 4
Output
0
Input
1
2 3
Output
-1
Input
3
1 4
2 3
4 4
Output
1
-----Note-----
In the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.
In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.
In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 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.
You are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).
Your task is to determine if the rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square.
-----Input-----
The first line contains a single integer n (1 β€ n β€ 5). Next n lines contain four integers each, describing a single rectangle: x_1, y_1, x_2, y_2 (0 β€ x_1 < x_2 β€ 31400, 0 β€ y_1 < y_2 β€ 31400) β x_1 and x_2 are x-coordinates of the left and right edges of the rectangle, and y_1 and y_2 are y-coordinates of the bottom and top edges of the rectangle.
No two rectangles overlap (that is, there are no points that belong to the interior of more than one rectangle).
-----Output-----
In a single line print "YES", if the given rectangles form a square, or "NO" otherwise.
-----Examples-----
Input
5
0 0 2 3
0 3 3 5
2 0 5 2
3 2 5 5
2 2 3 3
Output
YES
Input
4
0 0 2 3
0 3 3 5
2 0 5 2
3 2 5 5
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have N logs of lengths A_1,A_2,\cdots A_N.
We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.
Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.
-----Constraints-----
- 1 \leq N \leq 2 \times 10^5
- 0 \leq K \leq 10^9
- 1 \leq A_i \leq 10^9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N K
A_1 A_2 \cdots A_N
-----Output-----
Print an integer representing the answer.
-----Sample Input-----
2 3
7 9
-----Sample Output-----
4
- First, we will cut the log of length 7 at a point whose distance from an end of the log is 3.5, resulting in two logs of length 3.5 each.
- Next, we will cut the log of length 9 at a point whose distance from an end of the log is 3, resulting in two logs of length 3 and 6.
- Lastly, we will cut the log of length 6 at a point whose distance from an end of the log is 3.3, resulting in two logs of length 3.3 and 2.7.
In this case, the longest length of a log will be 3.5, which is the shortest possible result. After rounding up to an integer, the output should be 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.
Given an array of $n$ positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$). Find the maximum value of $i + j$ such that $a_i$ and $a_j$ are coprime,$^{\dagger}$ or $-1$ if no such $i$, $j$ exist.
For example consider the array $[1, 3, 5, 2, 4, 7, 7]$. The maximum value of $i + j$ that can be obtained is $5 + 7$, since $a_5 = 4$ and $a_7 = 7$ are coprime.
$^{\dagger}$ Two integers $p$ and $q$ are coprime if the only positive integer that is a divisor of both of them is $1$ (that is, their greatest common divisor is $1$).
-----Input-----
The input consists of multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 10$) β the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ ($2 \leq n \leq 2\cdot10^5$) β the length of the array.
The following line contains $n$ space-separated positive integers $a_1$, $a_2$,..., $a_n$ ($1 \leq a_i \leq 1000$) β the elements of the array.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot10^5$.
-----Output-----
For each test case, output a single integer β the maximum value of $i + j$ such that $i$ and $j$ satisfy the condition that $a_i$ and $a_j$ are coprime, or output $-1$ in case no $i$, $j$ satisfy the condition.
-----Examples-----
Input
6
3
3 2 1
7
1 3 5 2 4 7 7
5
1 2 3 4 5
3
2 2 4
6
5 4 3 15 12 16
5
1 2 2 3 6
Output
6
12
9
-1
10
7
-----Note-----
For the first test case, we can choose $i = j = 3$, with sum of indices equal to $6$, since $1$ and $1$ are coprime.
For the second test case, we can choose $i = 7$ and $j = 5$, with sum of indices equal to $7 + 5 = 12$, since $7$ and $4$ are coprime.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Scenario
*You're saying good-bye your best friend* , **_See you next happy year_** .
**_Happy Year_** *is the year with only distinct digits* , (e.g) **_2018_**
___
# Task
**_Given_** a year, **_Find_** **_The next happy year_** or **_The closest year You'll see your best friend_**  
___
# Notes
* **_Year_** Of Course always **_Positive_** .
* **_Have no fear_** , *It is guaranteed that the answer exists* .
* **_It's not necessary_** *that the year passed to the function is Happy one* .
* **_Input Year with in range_** *(1000β β€β yβ β€β 9000)*
____
# Input >> Output Examples:
```
nextHappyYear (7712) ==> return (7801)
```
## **_Explanation_**:
As the **_Next closest year with only distinct digits is_** *7801* .
___
```
nextHappyYear (8989) ==> return (9012)
```
## **_Explanation_**:
As the **_Next closest year with only distinct digits is_** *9012* .
___
```
nextHappyYear (1001) ==> return (1023)
```
## **_Explanation_**:
As the **_Next closest year with only distinct digits is_** *1023* .
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a grid with N rows and M columns of squares. Initially, all the squares are white.
There is a button attached to each row and each column. When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa. When a button attached to a column is pressed, the colors of all the squares in that column are inverted.
Takahashi can freely press the buttons any number of times. Determine whether he can have exactly K black squares in the grid.
Constraints
* 1 \leq N,M \leq 1000
* 0 \leq K \leq NM
Input
Input is given from Standard Input in the following format:
N M K
Output
If Takahashi can have exactly K black squares in the grid, print `Yes`; otherwise, print `No`.
Examples
Input
2 2 2
Output
Yes
Input
2 2 1
Output
No
Input
3 5 8
Output
Yes
Input
7 9 20
Output
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n points on a plane. All points are different.
Find the number of different groups of three points (A, B, C) such that point B is the middle of segment AC.
The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A, B, C) and (C, B, A) are considered the same.
Input
The first line contains a single integer n (3 β€ n β€ 3000) β the number of points.
Next n lines contain the points. The i-th line contains coordinates of the i-th point: two space-separated integers xi, yi ( - 1000 β€ xi, yi β€ 1000).
It is guaranteed that all given points are different.
Output
Print the single number β the answer to the problem.
Examples
Input
3
1 1
2 2
3 3
Output
1
Input
3
0 0
-1 0
0 1
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.
# Task
Mobius function - an important function in number theory. For each given n, it only has 3 values:
```
0 -- if n divisible by square of a prime. Such as: 4, 8, 9
1 -- if n not divisible by any square of a prime
and have even number of prime factor. Such as: 6, 10, 21
-1 -- otherwise. Such as: 3, 5, 7, 30```
Your task is to find mobius(`n`)
# Input/Output
- `[input]` integer `n`
`2 <= n <= 1e12`
- `[output]` an integer
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
<image>
You know the merry-go-round in the amusement park. Vehicles such as horses and carriages are fixed on a large disk, and it is a standard playset that the vehicle swings up and down at the same time as the disk rotates. A merry-go-round in an amusement park has two four-seater carriages, two two-seater cars, four one-seater horses, and a total of eight vehicles in the order shown in Figure 1. .. Customers at the amusement park are waiting somewhere between platforms 0 and 7 shown in Fig. 1.
<image>
The merry-go-round in this amusement park always stops where the vehicle fits snugly into the landing. And the customers waiting in each of 0 to 7 are supposed to get on the vehicle that stopped in front of them. You cannot hurry to another platform and board from there. In order for customers to enjoy themselves efficiently, we must adjust the stop position of the merry-go-round to minimize the number of passengers who cannot ride.
Create a program that reads the number of passengers waiting at platform 0-7 and outputs which vehicle should stop at which position to reduce the number of passengers who cannot get on.
input
The input consists of multiple datasets. Each dataset is given in the following format:
p0 p1 p2 p3 p4 p5 p6 p7
Integers p0, p1, ..., p7 (0 β€ pi β€ 10,000) are given on one line, separated by blanks, to represent the number of passengers waiting at platform 0, 1, ..., 7.
output
Let's assume that the carriage of a merry-go-round vehicle is represented by 4, the car is represented by 2, and the horse is represented by 1. The vehicles that stop at platform 0, 1, ..., 7 are c0, c1, ..., c7, respectively. Prints c0, c1, ..., c7 on a single line, separated by blanks, for each dataset.
If there are multiple ways to minimize the number of passengers who cannot ride, c0c1c2c3c4c5c6c7 shall be regarded as an 8-digit integer V, and the method to minimize V shall be selected.
The number of datasets does not exceed 100.
Example
Input
2 3 1 4 0 1 0 1
4 2 3 2 2 2 1 1
Output
1 4 1 4 1 2 1 2
4 1 4 1 2 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.
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a_1, a_2, ..., a_{k}, that their sum is equal to n and greatest common divisor is maximal.
Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.
If there is no possible sequence then output -1.
-----Input-----
The first line consists of two numbers n and k (1 β€ n, k β€ 10^10).
-----Output-----
If the answer exists then output k numbers β resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.
-----Examples-----
Input
6 3
Output
1 2 3
Input
8 2
Output
2 6
Input
5 3
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem
There are $ N $ streetlights on a two-dimensional square of $ W \ times H $.
Gaccho wants to start with $ (1,1) $ and go to $ (W, H) $.
Gaccho is afraid of dark places, so he only wants to walk in the squares that are brightened by the streetlights.
Initially, all streetlights only brighten the squares with the streetlights.
So, Gaccho decided to set the cost $ r_i $ for his favorite streetlight $ i $. There may be street lights for which no cost is set.
By consuming the cost $ r_i $, the streetlight $ i $ can brighten the range within $ r_i $ in Manhattan distance around the streetlight. However, the cost is a positive integer.
Gaccho can move to the adjacent square in either the up, down, left, or right direction.
Gaccho decided to set the total value of $ r_i $ to be the minimum. Find the total value at that time.
The Manhattan distance between two points $ (a, b) $ and $ (c, d) $ is represented by $ | aβc | $ + $ | bβd | $.
Constraints
The input satisfies the following conditions.
* $ 1 \ leq W \ leq 500 $
* $ 1 \ leq H \ leq 500 $
* $ 1 \ leq N \ leq 100 $
* $ 1 \ leq N \ leq W \ times H $
* $ 1 \ leq $$ x_i $$ \ leq W $
* $ 1 \ leq $$ y_i $$ \ leq H $
* There are no multiple streetlights at the same coordinates
Input
The input is given in the following format.
$ W $ $ H $ $ N $
$ x_1 $ $ y_1 $
...
$ x_N $ $ y_N $
All inputs are given as integers.
$ W $, $ H $, and $ N $ are given on the first line, separated by blanks.
In the following $ N $ line, the coordinates $ ($$ x_i $, $ y_i $$) $ of the streetlight $ i $ are given, separated by blanks.
Output
Output the minimum value of the total value of $ r_i $ on one line.
Examples
Input
10 10 1
6 6
Output
10
Input
5 10 3
3 9
2 8
5 1
Output
8
Input
1 1 1
1 1
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a square grid with N rows and M columns. Takahashi will write an integer in each of the squares, as follows:
* First, write 0 in every square.
* For each i=1,2,...,N, choose an integer k_i (0\leq k_i\leq M), and add 1 to each of the leftmost k_i squares in the i-th row.
* For each j=1,2,...,M, choose an integer l_j (0\leq l_j\leq N), and add 1 to each of the topmost l_j squares in the j-th column.
Now we have a grid where each square contains 0, 1, or 2. Find the number of different grids that can be made this way, modulo 998244353. We consider two grids different when there exists a square with different integers.
Constraints
* 1 \leq N,M \leq 5\times 10^5
* N and M are integers.
Input
Input is given from Standard Input in the following format:
N M
Output
Print the number of different grids that can be made, modulo 998244353.
Examples
Input
1 2
Output
8
Input
2 3
Output
234
Input
10 7
Output
995651918
Input
314159 265358
Output
70273732
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequence of integers $a_1, a_2, \dots, a_k$ is called a good array if $a_1 = k - 1$ and $a_1 > 0$. For example, the sequences $[3, -1, 44, 0], [1, -99]$ are good arrays, and the sequences $[3, 7, 8], [2, 5, 4, 1], [0]$ β are not.
A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences $[2, -3, 0, 1, 4]$, $[1, 2, 3, -3, -9, 4]$ are good, and the sequences $[2, -3, 0, 1]$, $[1, 2, 3, -3 -9, 4, 1]$ β are not.
For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353.
-----Input-----
The first line contains the number $n~(1 \le n \le 10^3)$ β the length of the initial sequence. The following line contains $n$ integers $a_1, a_2, \dots, a_n~(-10^9 \le a_i \le 10^9)$ β the sequence itself.
-----Output-----
In the single line output one integer β the number of subsequences of the original sequence that are good sequences, taken modulo 998244353.
-----Examples-----
Input
3
2 1 1
Output
2
Input
4
1 1 1 1
Output
7
-----Note-----
In the first test case, two good subsequences β $[a_1, a_2, a_3]$ and $[a_2, a_3]$.
In the second test case, seven good subsequences β $[a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4]$ and $[a_3, a_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.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
-----Input-----
The first line of input contains an integer nΒ β the number of nodes in the tree (1 β€ n β€ 10^5).
The next n - 1 lines contain integers u and v (1 β€ u, v β€ n, u β v)Β β the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
-----Output-----
Output one integerΒ β the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
-----Examples-----
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
-----Note-----
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: https://en.wikipedia.org/wiki/Bipartite_graph
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A: A-Z Cat / A-Z Cat
story
Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. It's so cute. Aizu Nyan was asked by her friend Joy to take care of her cat. It is a rare cat called A-Z cat. Aizunyan named the A-Z cat he had entrusted to him as "Aizunyan No. 2" (without permission), and he was very much loved.
A-Z cats are said to prefer strings that meet certain conditions. Then, when Aizunyan gave a character string as a trial, Aizunyan No. 2 had a satisfying expression after cutting a part of the character string with his nails. Apparently, I'm trying to rewrite it to my favorite character string.
D, who is crazy about Aizu Nyan, who is cute like an angel, found out the character string conditions that A-Z Cat likes for Aizu Nyan. It is a string in which'A'and'Z'are repeated alternately, and a string that starts with'A' and ends with'Z'. The A-Z cat is so smart that it tries to convert it to a string of your choice with minimal erasing. D, who wants to look good, decided to write a program to find out what kind of string the A-Z cat would convert from a given string consisting only of'A'and'Z'.
problem
Given a string S consisting only of uppercase letters. By deleting any number of S characters as much as you like, you can create a string in which'A'and'Z' appear alternately, and start with'A' and end with'Z'. Find the character string obtained when the number of deletions is minimized.
Input format
The string S is given on one line as input. S consists of uppercase letters only and satisfies 1 β€ | S | β€ 20.
Output format
Output the string that is obtained by deleting the minimum number of characters for S, in which'A'and'Z' appear alternately, and start with'A' and end with'Z' on one line. If no character string that meets the conditions is obtained by deleting any character, output -1 on one line.
Input example 1
AIZUNYAN PEROPERO
Output example 1
AZ
Input example 2
AZAZ
Output example 2
AZAZ
Input example 3
ZDDYAZAWABDDZAZPIDDA
Output example 3
AZAZAZ
Input example 4
ZZZZAAAAAA
Output example 4
-1
Example
Input
AIZUNYANPEROPERO
Output
AZ
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times.
Polycarp analysed all his affairs over the next n days and made a sequence of n integers a_1, a_2, ..., a_{n}, where a_{i} is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).
Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times.
Write a program that will find the minumum number of additional walks and the appropriate scheduleΒ β the sequence of integers b_1, b_2, ..., b_{n} (b_{i} β₯ a_{i}), where b_{i} means the total number of walks with the dog on the i-th day.
-----Input-----
The first line contains two integers n and k (1 β€ n, k β€ 500)Β β the number of days and the minimum number of walks with Cormen for any two consecutive days.
The second line contains integers a_1, a_2, ..., a_{n} (0 β€ a_{i} β€ 500)Β β the number of walks with Cormen on the i-th day which Polycarp has already planned.
-----Output-----
In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.
In the second line print n integers b_1, b_2, ..., b_{n}, where b_{i}Β β the total number of walks on the i-th day according to the found solutions (a_{i} β€ b_{i} for all i from 1 to n). If there are multiple solutions, print any of them.
-----Examples-----
Input
3 5
2 0 1
Output
4
2 3 2
Input
3 1
0 0 0
Output
1
0 1 0
Input
4 6
2 4 3 5
Output
0
2 4 3 5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.
Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.
* A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.
* An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.
A string S is assigned indicating attributes of all participants. If the i-th character of string S is `a`, this means the participant ranked i-th in the Qualification contests is a Japanese student; `b` means the participant ranked i-th is an overseas student; and `c` means the participant ranked i-th is neither of these.
Write a program that outputs for all the participants in descending rank either `Yes` if they passed the Qualification contests or `No` if they did not pass.
Constraints
* 1β¦N,A,Bβ¦100000
* A+Bβ¦N
* S is N characters long.
* S consists only of the letters `a`, `b` and `c`.
Input
Inputs are provided from Standard Input in the following form.
N A B
S
Output
Output N lines. On the i-th line, output `Yes` if the i-th participant passed the Qualification contests or `No` if that participant did not pass.
Examples
Input
10 2 3
abccabaabb
Output
Yes
Yes
No
No
Yes
Yes
Yes
No
No
No
Input
12 5 2
cabbabaacaba
Output
No
Yes
Yes
Yes
Yes
No
Yes
Yes
No
Yes
No
No
Input
5 2 2
ccccc
Output
No
No
No
No
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.
Let's call a positive integer $n$ ordinary if in the decimal notation all its digits are the same. For example, $1$, $2$ and $99$ are ordinary numbers, but $719$ and $2021$ are not ordinary numbers.
For a given number $n$, find the number of ordinary numbers among the numbers from $1$ to $n$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.
Each test case is characterized by one integer $n$ ($1 \le n \le 10^9$).
-----Output-----
For each test case output the number of ordinary numbers among numbers from $1$ to $n$.
-----Examples-----
Input
6
1
2
3
4
5
100
Output
1
2
3
4
5
18
-----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.
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:
* Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.
* Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
Input
The first line contains a single integer n (1 β€ n β€ 3Β·105). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 106) β the initial group that is given to Toastman.
Output
Print a single integer β the largest possible score.
Examples
Input
3
3 1 5
Output
26
Input
1
10
Output
10
Note
Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements.
-----Input-----
The first line of the input contains one integer n (1 β€ n β€ 100)Β β the length of the sequence. The second line contains the sequence consisting of n characters U and R.
-----Output-----
Print the minimum possible length of the sequence of moves after all replacements are done.
-----Examples-----
Input
5
RUURU
Output
3
Input
17
UUURRRRRUUURURUUU
Output
13
-----Note-----
In the first test the shortened sequence of moves may be DUD (its length is 3).
In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider the set of all nonnegative integers: ${0, 1, 2, \dots}$. Given two integers $a$ and $b$ ($1 \le a, b \le 10^4$). We paint all the numbers in increasing number first we paint $0$, then we paint $1$, then $2$ and so on.
Each number is painted white or black. We paint a number $i$ according to the following rules: if $i = 0$, it is colored white; if $i \ge a$ and $i - a$ is colored white, $i$ is also colored white; if $i \ge b$ and $i - b$ is colored white, $i$ is also colored white; if $i$ is still not colored white, it is colored black.
In this way, each nonnegative integer gets one of two colors.
For example, if $a=3$, $b=5$, then the colors of the numbers (in the order from $0$) are: white ($0$), black ($1$), black ($2$), white ($3$), black ($4$), white ($5$), white ($6$), black ($7$), white ($8$), white ($9$), ...
Note that: It is possible that there are infinitely many nonnegative integers colored black. For example, if $a = 10$ and $b = 10$, then only $0, 10, 20, 30$ and any other nonnegative integers that end in $0$ when written in base 10 are white. The other integers are colored black. It is also possible that there are only finitely many nonnegative integers colored black. For example, when $a = 1$ and $b = 10$, then there is no nonnegative integer colored black at all.
Your task is to determine whether or not the number of nonnegative integers colored black is infinite.
If there are infinitely many nonnegative integers colored black, simply print a line containing "Infinite" (without the quotes). Otherwise, print "Finite" (without the quotes).
-----Input-----
The first line of input contains a single integer $t$ ($1 \le t \le 100$) β the number of test cases in the input. Then $t$ lines follow, each line contains two space-separated integers $a$ and $b$ ($1 \le a, b \le 10^4$).
-----Output-----
For each test case, print one line containing either "Infinite" or "Finite" (without the quotes). Output is case-insensitive (i.e. "infinite", "inFiNite" or "finiTE" are all valid answers).
-----Example-----
Input
4
10 10
1 10
6 9
7 3
Output
Infinite
Finite
Infinite
Finite
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
I love Fibonacci numbers in general, but I must admit I love some more than others.
I would like for you to write me a function that when given a number (n) returns the n-th number in the Fibonacci Sequence.
For example:
```python
nth_fib(4) == 2
```
Because 2 is the 4th number in the Fibonacci Sequence.
For reference, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).
Takahashi forgot the price of his apple pie before tax, X, and wants to know it again. Write a program that takes N as input and finds X. We assume X is an integer.
If there are multiple possible values for X, find any one of them. Also, Takahashi's memory of N, the amount he paid, may be incorrect. If no value could be X, report that fact.
Constraints
* 1 \leq N \leq 50000
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
If there are values that could be X, the price of the apple pie before tax, print any one of them.
If there are multiple such values, printing any one of them will be accepted.
If no value could be X, print `:(`.
Examples
Input
432
Output
400
Input
1079
Output
:(
Input
1001
Output
927
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Given the squares of $ R * C $. Each square is either an empty square or a square with a hole. The given square meets the following conditions.
* The cells with holes are connected. (You can move a square with a hole in the cross direction to any square with a hole)
* Empty cells are connected.
You can generate rectangular tiles of any length with a width of $ 1 $. I would like to install multiple tiles to fill all the holes in the square. When installing tiles, the following restrictions must be observed.
* Tiles can only be installed vertically or horizontally in the $ 2 $ direction.
* Do not install more than one tile on one square.
* There should be no tiles on the squares without holes.
Please answer the minimum number of tiles when all the squares with holes are filled with tiles while observing the above restrictions.
output
Output the minimum number of times. Please also output a line break at the end.
Example
Input
5 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 are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c_1, c_2, ..., c_{n}. The Old Peykan wants to travel from city c_1 to c_{n} using roads. There are (n - 1) one way roads, the i-th road goes from city c_{i} to city c_{i} + 1 and is d_{i} kilometers long.
The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.
Each city c_{i} (except for the last city c_{n}) has a supply of s_{i} liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times.
Initially (at time zero) the Old Peykan is at city c_1 and s_1 liters of fuel is transferred to it's empty tank from c_1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.
Find the minimum time the Old Peykan needs to reach city c_{n}.
-----Input-----
The first line of the input contains two space-separated integers m and k (1 β€ m, k β€ 1000). The value m specifies the number of roads between cities which is equal to n - 1.
The next line contains m space-separated integers d_1, d_2, ..., d_{m} (1 β€ d_{i} β€ 1000) and the following line contains m space-separated integers s_1, s_2, ..., s_{m} (1 β€ s_{i} β€ 1000).
-----Output-----
In the only line of the output print a single integer β the minimum time required for The Old Peykan to reach city c_{n} from city c_1.
-----Examples-----
Input
4 6
1 2 5 2
2 3 3 4
Output
10
Input
2 3
5 6
5 5
Output
14
-----Note-----
In the second sample above, the Old Peykan stays in c_1 for 3 hours.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Task
You are a lifelong fan of your local football club, and proud to say you rarely miss a game. Even though you're a superfan, you still hate boring games. Luckily, boring games often end in a draw, at which point the winner is determined by a penalty shoot-out, which brings some excitement to the viewing experience. Once, in the middle of a penalty shoot-out, you decided to count the lowest total number of shots required to determine the winner. So, given the number of shots each team has already made and the current score, `how soon` can the game end?
If you are not familiar with penalty shoot-out rules, here they are:
`Teams take turns to kick from the penalty mark until each has taken five kicks. However, if one side has scored more successful kicks than the other could possibly reach with all of its remaining kicks, the shoot-out immediately ends regardless of the number of kicks remaining.`
`If at the end of these five rounds of kicks the teams have scored an equal number of successful kicks, additional rounds of one kick each will be used until the tie is broken.`
# Input/Output
`[input]` integer `shots`
An integer, the number of shots each team has made thus far.
`0 β€ shots β€ 100.`
`[input]` integer array `score`
An array of two integers, where score[0] is the current score of the first team and score[1] - of the second team.
`score.length = 2,`
`0 β€ score[i] β€ shots.`
`[output]` an integer
The minimal possible total number of shots required to determine the winner.
# Example
For `shots = 2 and score = [1, 2]`, the output should be `3`.
The possible 3 shots can be:
```
shot1: the first team misses the penalty
shot2: the second team scores
shot3: the first one misses again```
then, score will be [1, 3]. As the first team can't get 2 more points in the last remaining shot until the end of the initial five rounds, the winner is determined.
For `shots = 10 and score = [10, 10]`, the output should be `2`.
If one of the teams misses the penalty and the other one scores, the game ends.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.
Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3 Γ 3 with digits from 1 to 9.
Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.
Input
Input contains the matrix of three rows of three symbols each. Symbol Β«XΒ» means that the corresponding button was pressed, and Β«.Β» means that is was not pressed. The matrix may contain no Β«XΒ», also it may contain no Β«.Β».
Output
Print YES if the password is symmetric with respect to the central button of the terminal and NO otherwise.
Examples
Input
XX.
...
.XX
Output
YES
Input
X.X
X..
...
Output
NO
Note
If you are not familiar with the term Β«central symmetryΒ», you may look into http://en.wikipedia.org/wiki/Central_symmetry
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Niwango has N cards, numbered 1,2,\ldots,N. He will now arrange these cards in a row.
Niwango wants to know if there is a way to arrange the cards while satisfying all the N conditions below. To help him, determine whether such a way exists. If the answer is yes, also find the lexicographically smallest such arrangement.
* To the immediate right of Card 1 (if any) is NOT Card a_1.
* To the immediate right of Card 2 (if any) is NOT Card a_2.
* \vdots
* To the immediate right of Card N (if any) is NOT Card a_N.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i \leq N
* a_i \neq i
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 \ldots a_N
Output
If no arrangements satisfy the conditions, print `-1`. If such arrangements exist, print the lexicographically smallest such arrangement, in the following format:
b_1 b_2 \ldots b_N
Here, b_i represents the i-th card from the left.
Examples
Input
4
2 3 4 1
Output
1 3 2 4
Input
2
2 1
Output
-1
Input
13
2 3 4 5 6 7 8 9 10 11 12 13 12
Output
1 3 2 4 6 5 7 9 8 10 12 11 13
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given are two sequences a=\{a_0,\ldots,a_{N-1}\} and b=\{b_0,\ldots,b_{N-1}\} of N non-negative integers each.
Snuke will choose an integer k such that 0 \leq k < N and an integer x not less than 0, to make a new sequence of length N, a'=\{a_0',\ldots,a_{N-1}'\}, as follows:
- a_i'= a_{i+k \mod N}\ XOR \ x
Find all pairs (k,x) such that a' will be equal to b.What is \mbox{ XOR }?
The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:
- When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.
For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)
-----Constraints-----
- 1 \leq N \leq 2 \times 10^5
- 0 \leq a_i,b_i < 2^{30}
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
a_0 a_1 ... a_{N-1}
b_0 b_1 ... b_{N-1}
-----Output-----
Print all pairs (k, x) such that a' and b will be equal, using one line for each pair, in ascending order of k (ascending order of x for pairs with the same k).
If there are no such pairs, the output should be empty.
-----Sample Input-----
3
0 2 1
1 2 3
-----Sample Output-----
1 3
If (k,x)=(1,3),
- a_0'=(a_1\ XOR \ 3)=1
- a_1'=(a_2\ XOR \ 3)=2
- a_2'=(a_0\ XOR \ 3)=3
and we have a' = b.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Theofanis has a riddle for you and if you manage to solve it, he will give you a Cypriot snack halloumi for free (Cypriot cheese).
You are given an integer $n$. You need to find two integers $l$ and $r$ such that $-10^{18} \le l < r \le 10^{18}$ and $l + (l + 1) + \ldots + (r - 1) + r = n$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) β the number of test cases.
The first and only line of each test case contains a single integer $n$ ($1 \le n \le 10^{18}$).
-----Output-----
For each test case, print the two integers $l$ and $r$ such that $-10^{18} \le l < r \le 10^{18}$ and $l + (l + 1) + \ldots + (r - 1) + r = n$.
It can be proven that an answer always exists. If there are multiple answers, print any.
-----Examples-----
Input
7
1
2
3
6
100
25
3000000000000
Output
0 1
-1 2
1 2
1 3
18 22
-2 7
999999999999 1000000000001
-----Note-----
In the first test case, $0 + 1 = 1$.
In the second test case, $(-1) + 0 + 1 + 2 = 2$.
In the fourth test case, $1 + 2 + 3 = 6$.
In the fifth test case, $18 + 19 + 20 + 21 + 22 = 100$.
In the sixth test case, $(-2) + (-1) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 25$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Example
Input
4
Durett 7
Gayles 3
Facenda 6
Daughtery 0
1
+ Mccourtney 2
Output
Mccourtney is not working now.
Durett is working hard now.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, thatβs why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?
Input
The input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 106 symbols inclusive, the first string contains exactly 1 symbol more than the second one.
Output
In the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0.
Examples
Input
abdrakadabra
abrakadabra
Output
1
3
Input
aa
a
Output
2
1 2
Input
competition
codeforces
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.
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.
It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.
Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?
Input
The first line of the input contains two integers n and m (1 β€ n β€ 10^5, 0 β€ m β€ min((n(n-1))/(2),10^5)), the number of vertices and the number of edges of weight 1 in the graph.
The i-th of the next m lines contains two integers a_i and b_i (1 β€ a_i, b_i β€ n, a_i β b_i), the endpoints of the i-th edge of weight 1.
It is guaranteed that no edge appears twice in the input.
Output
Output a single integer, the weight of the minimum spanning tree of the graph.
Examples
Input
6 11
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
Output
2
Input
3 0
Output
0
Note
The graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2.
<image>
In the second sample, all edges have weight 0 so any spanning tree has total weight 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.
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.
Input
The first input line contains integer n (1 β€ n β€ 100) β amount of numbers in the sequence. The second line contains n space-separated integer numbers β elements of the sequence. These numbers don't exceed 100 in absolute value.
Output
If the given sequence has the second order statistics, output this order statistics, otherwise output NO.
Examples
Input
4
1 2 2 -4
Output
1
Input
5
1 2 3 1 1
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two arrays $a$ and $b$, both of length $n$.
You can perform the following operation any number of times (possibly zero): select an index $i$ ($1 \leq i \leq n$) and swap $a_i$ and $b_i$.
Let's define the cost of the array $a$ as $\sum_{i=1}^{n} \sum_{j=i + 1}^{n} (a_i + a_j)^2$. Similarly, the cost of the array $b$ is $\sum_{i=1}^{n} \sum_{j=i + 1}^{n} (b_i + b_j)^2$.
Your task is to minimize the total cost of two arrays.
-----Input-----
Each test case consists of several test cases. The first line contains a single integer $t$ ($1 \leq t \leq 40$) β the number of test cases. The following is a description of the input data sets.
The first line of each test case contains an integer $n$ ($1 \leq n \leq 100$) β the length of both arrays.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$) β elements of the first array.
The third line of each test case contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \leq b_i \leq 100$) β elements of the second array.
It is guaranteed that the sum of $n$ over all test cases does not exceed $100$.
-----Output-----
For each test case, print the minimum possible total cost.
-----Examples-----
Input
3
1
3
6
4
3 6 6 6
2 7 4 1
4
6 7 2 4
2 5 3 5
Output
0
987
914
-----Note-----
In the second test case, in one of the optimal answers after all operations $a = [2, 6, 4, 6]$, $b = [3, 7, 6, 1]$.
The cost of the array $a$ equals to $(2 + 6)^2 + (2 + 4)^2 + (2 + 6)^2 + (6 + 4)^2 + (6 + 6)^2 + (4 + 6)^2 = 508$.
The cost of the array $b$ equals to $(3 + 7)^2 + (3 + 6)^2 + (3 + 1)^2 + (7 + 6)^2 + (7 + 1)^2 + (6 + 1)^2 = 479$.
The total cost of two arrays equals to $508 + 479 = 987$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
BerOilGasDiamondBank has branches in n cities, at that n is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly n / 2 lines of strictly equal length, each of which contains exactly two names and exactly one separator character between them. The name of every city should be used in the calendar exactly once. For historical reasons the symbol d is used as the separator of words in the calendar.
The BerOilGasDiamondBank management wants to show that all its branches are equally important to it, that's why the order of their appearance in the calendar should be following: if we "glue"(concatinate) all the n / 2 calendar lines (from top to bottom) to make a single line, then the lexicographically minimal line is obtained. No separator character will be used to separate calendar lines. For example, if the lines are "bertown!berville", "newberville!bera", then the resulting line is "bertown!bervillenewberville!bera". In some sense one has to find the lexicographically minimal calendar, where the comparison of calendars happens line by line.
Help BerOilGasDiamondBank and construct the required calendar.
Input
The first line contains an integer n (1 β€ n β€ 104, n is even) which is the number of branches. Then follow n lines which are the names of the cities. All the names consist of lowercase Latin letters; their lengths are no less than 1 and no more than 10 symbols. The next line contains a single symbol d (d has an ASCII-code from 33 to 126 inclusively, excluding lowercase Latin letters) which is the separator between words in the calendar lines. It is guaranteed that the calendar is possible to be constructed and all the names are different.
Output
Print n / 2 lines of similar length which are the required calendar. Every line should contain exactly two words and exactly one separator between them. If there are several solutions, print the lexicographically minimal one. The lexicographical comparison of lines is realized by the "<" operator in the modern programming languages.
Examples
Input
4
b
aa
hg
c
.
Output
aa.b
c.hg
Input
2
aa
a
!
Output
a!aa
Input
2
aa
a
|
Output
aa|a
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The only difference between easy and hard versions are constraints on $n$ and $k$.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $k$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $0$).
Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.
You (suddenly!) have the ability to see the future. You know that during the day you will receive $n$ messages, the $i$-th message will be received from the friend with ID $id_i$ ($1 \le id_i \le 10^9$).
If you receive a message from $id_i$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.
Otherwise (i.e. if there is no conversation with $id_i$ on the screen):
Firstly, if the number of conversations displayed on the screen is $k$, the last conversation (which has the position $k$) is removed from the screen. Now the number of conversations on the screen is guaranteed to be less than $k$ and the conversation with the friend $id_i$ is not displayed on the screen. The conversation with the friend $id_i$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.
Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $n$ messages.
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 2 \cdot 10^5)$ β the number of messages and the number of conversations your smartphone can show.
The second line of the input contains $n$ integers $id_1, id_2, \dots, id_n$ ($1 \le id_i \le 10^9$), where $id_i$ is the ID of the friend which sends you the $i$-th message.
-----Output-----
In the first line of the output print one integer $m$ ($1 \le m \le min(n, k)$) β the number of conversations shown after receiving all $n$ messages.
In the second line print $m$ integers $ids_1, ids_2, \dots, ids_m$, where $ids_i$ should be equal to the ID of the friend corresponding to the conversation displayed on the position $i$ after receiving all $n$ messages.
-----Examples-----
Input
7 2
1 2 3 2 1 3 2
Output
2
2 1
Input
10 4
2 3 3 1 1 2 1 2 3 3
Output
3
1 3 2
-----Note-----
In the first example the list of conversations will change in the following way (in order from the first to last message):
$[]$; $[1]$; $[2, 1]$; $[3, 2]$; $[3, 2]$; $[1, 3]$; $[1, 3]$; $[2, 1]$.
In the second example the list of conversations will change in the following way:
$[]$; $[2]$; $[3, 2]$; $[3, 2]$; $[1, 3, 2]$; and then the list will not change till the end.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Andrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom.
A bar of chocolate can be presented as an n Γ n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following q actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge.
After each action, he wants to know how many pieces he ate as a result of this action.
-----Input-----
The first line contains integers n (1 β€ n β€ 10^9) and q (1 β€ q β€ 2Β·10^5) β the size of the chocolate bar and the number of actions.
Next q lines contain the descriptions of the actions: the i-th of them contains numbers x_{i} and y_{i} (1 β€ x_{i}, y_{i} β€ n, x_{i} + y_{i} = n + 1) β the numbers of the column and row of the chosen cell and the character that represents the direction (L β left, U β up).
-----Output-----
Print q lines, the i-th of them should contain the number of eaten pieces as a result of the i-th action.
-----Examples-----
Input
6 5
3 4 U
6 1 L
2 5 L
1 6 U
4 3 U
Output
4
3
2
1
2
Input
10 6
2 9 U
10 1 U
1 10 U
8 3 L
10 1 L
6 5 U
Output
9
1
10
6
0
2
-----Note-----
Pictures to the sample tests:
[Image]
The pieces that were eaten in the same action are painted the same color. The pieces lying on the anti-diagonal contain the numbers of the action as a result of which these pieces were eaten.
In the second sample test the Andrewid tries to start eating chocolate for the second time during his fifth action, starting from the cell at the intersection of the 10-th column and the 1-st row, but this cell is already empty, so he does not eat anything.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An extension of a complex number is called a quaternion. It is a convenient number that can be used to control the arm of a robot because it is convenient for expressing the rotation of an object. Quaternions are $ using four real numbers $ x $, $ y $, $ z $, $ w $ and special numbers (extended imaginary numbers) $ i $, $ j $, $ k $. It is expressed as x + yi + zj + wk $. The sum of such quaternions is defined as:
$ (x_1 + y_1 i + z_1 j + w_1 k) + (x_2 + y_2 i + z_2 j + w_2 k) = (x_1 + x_2) + (y_1 + y_2) i + (z_1 + z_2) j + (w_1 + w_2) k $
On the other hand, the product between 1, $ i $, $ j $, and $ k $ is given as follows.
<image>
This table represents the product $ AB $ of two special numbers $ A $ and $ B $. For example, the product $ ij $ of $ i $ and $ j $ is $ k $, and the product $ ji $ of $ j $ and $ i $ is $ -k $.
The product of common quaternions is calculated to satisfy this relationship. For example, the product of two quaternions, $ 1 + 2i + 3j + 4k $ and $ 7 + 6i + 7j + 8k $, is calculated as follows:
$ (1 + 2i + 3j + 4k) \ times (7 + 6i + 7j + 8k) = $
$ 7 + 6i + 7j + 8k $
$ + 14i + 12i ^ 2 + 14ij + 16ik $
$ + 21j + 18ji + 21j ^ 2 + 24jk $
$ + 28k + 24ki + 28kj + 32k ^ 2 $
By applying the table above
$ = -58 + 16i + 36j + 32k $
It will be.
Two quaternions ($ x_1 + y_1 i + z_1 j + w_1 k $) and ($) where the four coefficients $ x $, $ y $, $ z $, $ w $ are integers and not all zeros x_2 + y_2 i + z_2 j + w_2 k $), and the product is ($ x_3 + y_3 i + z_3 j + w_3 k $), $ x_3 $, $ y_3 $, $ z_3 $, $ Create a program that outputs w_3 $.
input
Given multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
$ n $
$ data_1 $
$ data_2 $
::
$ data_n $
The first line gives the number of pairs of quaternions to process $ n $ ($ n \ leq 10 $). The following $ n $ line is given the $ i $ th quaternion pair of information $ data_i $ in the following format:
$ x_1 $ $ y_1 $ $ z_1 $ $ w_1 $ $ x_2 $ $ y_2 $ $ z_2 $ $ w_2 $
All coefficients given should be -1000 or more and 1000 or less. The number of datasets does not exceed 50.
output
Prints the product of a given set of quaternions for each dataset.
Example
Input
2
1 2 3 4 7 6 7 8
5 6 7 8 3 2 3 4
0
Output
-58 16 36 32
-50 32 28 48
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first k Latin letters and not containing any other ones. Also, the title should be a palindrome, that is it should be read similarly from the left to the right and from the right to the left.
Vasya has already composed the approximate variant of the title. You are given the title template s consisting of lowercase Latin letters and question marks. Your task is to replace all the question marks by lowercase Latin letters so that the resulting word satisfies the requirements, described above. Each question mark should be replaced by exactly one letter, it is not allowed to delete characters or add new ones to the template. If there are several suitable titles, choose the first in the alphabetical order, for Vasya's book to appear as early as possible in all the catalogues.
Input
The first line contains an integer k (1 β€ k β€ 26) which is the number of allowed alphabet letters. The second line contains s which is the given template. In s only the first k lowercase letters of Latin alphabet and question marks can be present, the length of s is from 1 to 100 characters inclusively.
Output
If there is no solution, print IMPOSSIBLE. Otherwise, a single line should contain the required title, satisfying the given template. The title should be a palindrome and it can only contain the first k letters of the Latin alphabet. At that, each of those k letters must be present at least once. If there are several suitable titles, print the lexicographically minimal one.
The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if exists such an i (1 β€ i β€ |s|), that ai < bi, and for any j (1 β€ j < i) aj = bj. |s| stands for the length of the given template.
Examples
Input
3
a?c
Output
IMPOSSIBLE
Input
2
a??a
Output
abba
Input
2
?b?a
Output
abba
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N squares arranged in a row, numbered 1 to N from left to right. Takahashi will stack building blocks on these squares, on which there are no blocks yet.
He wants to stack blocks on the squares evenly, so he will repeat the following operation until there are H blocks on every square:
* Let M and m be the maximum and minimum numbers of blocks currently stacked on a square, respectively. Choose a square on which m blocks are stacked (if there are multiple such squares, choose any one of them), and add a positive number of blocks on that square so that there will be at least M and at most M + D blocks on that square.
Tell him how many ways there are to have H blocks on every square by repeating this operation. Since there can be extremely many ways, print the number modulo 10^9+7.
Constraints
* 2 \leq N \leq 10^6
* 1 \leq D \leq H \leq 10^6
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N H D
Output
Print the number of ways to have H blocks on every square, modulo 10^9+7.
Examples
Input
2 2 1
Output
6
Input
2 30 15
Output
94182806
Input
31415 9265 3589
Output
312069529
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 contest is `CODEFESTIVAL`, which can be shortened to the string `CF` by deleting some characters.
Mr. Takahashi, full of curiosity, wondered if he could obtain `CF` from other strings in the same way.
You are given a string s consisting of uppercase English letters. Determine whether the string `CF` can be obtained from the string s by deleting some characters.
Constraints
* 2 β€ |s| β€ 100
* All characters in s are uppercase English letters (`A`-`Z`).
Input
The input is given from Standard Input in the following format:
s
Output
Print `Yes` if the string `CF` can be obtained from the string s by deleting some characters. Otherwise print `No`.
Examples
Input
CODEFESTIVAL
Output
Yes
Input
FESTIVALCODE
Output
No
Input
CF
Output
Yes
Input
FCF
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.
You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.
Input
The only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1 000 000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks.
Output
The first line of the output should contain "Possible" (without quotes) if rebus has a solution and "Impossible" (without quotes) otherwise.
If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples.
Examples
Input
? + ? - ? + ? + ? = 42
Output
Possible
9 + 13 - 39 + 28 + 31 = 42
Input
? - ? = 1
Output
Impossible
Input
? = 1000000
Output
Possible
1000000 = 1000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.
The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)
Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem.
Input
The first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} β they are the colors of gems with which the box should be decorated.
Output
Print the required number of different ways to decorate the box.
Examples
Input
YYYYYY
Output
1
Input
BOOOOB
Output
2
Input
ROYGBV
Output
30
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Example
Input
3
0 2 7
2 0 4
5 8 0
Output
11
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string S of length 2N consisting of lowercase English letters.
There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition?
* The string obtained by reading the characters painted red from left to right is equal to the string obtained by reading the characters painted blue from right to left.
Constraints
* 1 \leq N \leq 18
* The length of S is 2N.
* S consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
N
S
Output
Print the number of ways to paint the string that satisfy the condition.
Examples
Input
4
cabaacba
Output
4
Input
11
mippiisssisssiipsspiim
Output
504
Input
4
abcdefgh
Output
0
Input
18
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Output
9075135300
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Today's Random Number
E869120 You ran a campaign called "Today's Random Numbers" for N days. This is a project to generate a random number once a day and post the value on Twitter.
The "random numbers of the day" on day $ 1, 2, 3, \ dots, N $ were $ A_1, A_2, A_3, \ dots, A_N $, respectively.
E869120 You would be happy if today's random number is higher than yesterday's random number.
How many times in the $ N $ day did E869120 make you happy with "Today's Random Numbers"?
input
Input is given from standard input in the following format.
$ N $
$ A_1 $ $ A_2 $ $ A_3 $ $ \ dots $ $ A_N $
output
Print out the number of times E869120 was pleased with "Today's Random Numbers" in one line in $ N $ days.
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 100000 \ (= 10 ^ 5) $
* $ 1 \ leq A_i \ leq 1000000000 \ (= 10 ^ 9) $
* All inputs are integers.
Input example 1
Five
8 6 9 1 20
Output example 1
2
On the 3rd and 5th days, E869120 is happy.
Input example 2
6
3 3 4 3 3 4
Output example 2
2
On the 3rd and 6th days, E869120 is happy.
Input example 3
Ten
10 9 8 7 6 5 4 3 2 1
Output example 3
0
E869120 You will not be happy with "Today's Random Numbers".
Example
Input
5
8 6 9 1 20
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.
The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is <image>.
The pseudo code of the unexpected code is as follows:
input n
for i from 1 to n
input the i-th point's coordinates into p[i]
sort array p[] by increasing of x coordinate first and increasing of y coordinate second
d=INF //here INF is a number big enough
tot=0
for i from 1 to n
for j from (i+1) to n
++tot
if (p[j].x-p[i].x>=d) then break //notice that "break" is only to be
//out of the loop "for j"
d=min(d,distance(p[i],p[j]))
output d
Here, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.
You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
Input
A single line which contains two space-separated integers n and k (2 β€ n β€ 2000, 1 β€ k β€ 109).
Output
If there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| β€ 109) representing the coordinates of the i-th point.
The conditions below must be held:
* All the points must be distinct.
* |xi|, |yi| β€ 109.
* After running the given code, the value of tot should be larger than k.
Examples
Input
4 3
Output
0 0
0 1
1 0
1 1
Input
2 100
Output
no solution
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Turbulent times are coming, so you decided to buy sugar in advance. There are $n$ shops around that sell sugar: the $i$-th shop sells one pack of sugar for $a_i$ coins, but only one pack to one customer each day. So in order to buy several packs, you need to visit several shops.
Another problem is that prices are increasing each day: during the first day the cost is $a_i$, during the second day cost is $a_i + 1$, during the third day β $a_i + 2$ and so on for each shop $i$.
On the contrary, your everyday budget is only $x$ coins. In other words, each day you go and buy as many packs as possible with total cost not exceeding $x$. Note that if you don't spend some amount of coins during a day, you can't use these coins during the next days.
Eventually, the cost for each pack will exceed $x$, and you won't be able to buy even a single pack. So, how many packs will you be able to buy till that moment in total?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) β the number of test cases. Next $t$ cases follow.
The first line of each test case contains two integers $n$ and $x$ ($1 \le n \le 2 \cdot 10^5$; $1 \le x \le 10^9$) β the number of shops and your everyday budget.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) β the initial cost of one pack in each shop.
It's guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case, print one integer β the total number of packs you will be able to buy until prices exceed your everyday budget.
-----Examples-----
Input
4
3 7
2 1 2
5 9
10 20 30 40 50
1 1
1
2 1000
1 1
Output
11
0
1
1500
-----Note-----
In the first test case,
Day 1: prices are $[2, 1, 2]$. You can buy all $3$ packs, since $2 + 1 + 2 \le 7$.
Day 2: prices are $[3, 2, 3]$. You can't buy all $3$ packs, since $3 + 2 + 3 > 7$, so you buy only $2$ packs.
Day 3: prices are $[4, 3, 4]$. You can buy $2$ packs with prices $4$ and $3$.
Day 4: prices are $[5, 4, 5]$. You can't buy $2$ packs anymore, so you buy only $1$ pack.
Day 5: prices are $[6, 5, 6]$. You can buy $1$ pack.
Day 6: prices are $[7, 6, 7]$. You can buy $1$ pack.
Day 7: prices are $[8, 7, 8]$. You still can buy $1$ pack of cost $7$.
Day 8: prices are $[9, 8, 9]$. Prices are too high, so you can't buy anything.
In total, you bought $3 + 2 + 2 + 1 + 1 + 1 + 1 = 11$ packs.
In the second test case, prices are too high even at the first day, so you can't buy anything.
In the third test case, you can buy only one pack at day one.
In the fourth test case, you can buy $2$ packs first $500$ days. At day $501$ prices are $[501, 501]$, so you can buy only $1$ pack the next $500$ days. At day $1001$ prices are $[1001, 1001]$ so can't buy anymore. In total, you bought $500 \cdot 2 + 500 \cdot 1 = 1500$ packs.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.
Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".
You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by $1$. For example, if you delete the character in the position $2$ from the string "exxxii", then the resulting string is "exxii".
-----Input-----
The first line contains integer $n$ $(3 \le n \le 100)$ β the length of the file name.
The second line contains a string of length $n$ consisting of lowercase Latin letters only β the file name.
-----Output-----
Print the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0.
-----Examples-----
Input
6
xxxiii
Output
1
Input
5
xxoxx
Output
0
Input
10
xxxxxxxxxx
Output
8
-----Note-----
In the first example Polycarp tried to send a file with name contains number $33$, written in Roman numerals. But he can not just send the file, because it name contains three letters "x" in a row. To send the file he needs to remove any one of this letters.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through $n \cdot k$ cities. The cities are numerated from $1$ to $n \cdot k$, the distance between the neighboring cities is exactly $1$ km.
Sergey does not like beetles, he loves burgers. Fortunately for him, there are $n$ fast food restaurants on the circle, they are located in the $1$-st, the $(k + 1)$-st, the $(2k + 1)$-st, and so on, the $((n-1)k + 1)$-st cities, i.e. the distance between the neighboring cities with fast food restaurants is $k$ km.
Sergey began his journey at some city $s$ and traveled along the circle, making stops at cities each $l$ km ($l > 0$), until he stopped in $s$ once again. Sergey then forgot numbers $s$ and $l$, but he remembers that the distance from the city $s$ to the nearest fast food restaurant was $a$ km, and the distance from the city he stopped at after traveling the first $l$ km from $s$ to the nearest fast food restaurant was $b$ km. Sergey always traveled in the same direction along the circle, but when he calculated distances to the restaurants, he considered both directions.
Now Sergey is interested in two integers. The first integer $x$ is the minimum number of stops (excluding the first) Sergey could have done before returning to $s$. The second integer $y$ is the maximum number of stops (excluding the first) Sergey could have done before returning to $s$.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n, k \le 100\,000$)Β β the number of fast food restaurants on the circle and the distance between the neighboring restaurants, respectively.
The second line contains two integers $a$ and $b$ ($0 \le a, b \le \frac{k}{2}$)Β β the distances to the nearest fast food restaurants from the initial city and from the city Sergey made the first stop at, respectively.
-----Output-----
Print the two integers $x$ and $y$.
-----Examples-----
Input
2 3
1 1
Output
1 6
Input
3 2
0 0
Output
1 3
Input
1 10
5 3
Output
5 5
-----Note-----
In the first example the restaurants are located in the cities $1$ and $4$, the initial city $s$ could be $2$, $3$, $5$, or $6$. The next city Sergey stopped at could also be at cities $2, 3, 5, 6$. Let's loop through all possible combinations of these cities. If both $s$ and the city of the first stop are at the city $2$ (for example, $l = 6$), then Sergey is at $s$ after the first stop already, so $x = 1$. In other pairs Sergey needs $1, 2, 3$, or $6$ stops to return to $s$, so $y = 6$.
In the second example Sergey was at cities with fast food restaurant both initially and after the first stop, so $l$ is $2$, $4$, or $6$. Thus $x = 1$, $y = 3$.
In the third example there is only one restaurant, so the possible locations of $s$ and the first stop are: $(6, 8)$ and $(6, 4)$. For the first option $l = 2$, for the second $l = 8$. In both cases Sergey needs $x=y=5$ stops to go to $s$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Sereja has an n Γ m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a component form a rectangle of size h Γ w, then the component must contain exactly hw cells.
A connected component of the same values is a set of cells of the table that meet the following conditions: every two cells of the set have the same value; the cells of the set form a connected region on the table (two cells are connected if they are adjacent in some row or some column of the table); it is impossible to add any cell to the set unless we violate the two previous conditions.
Can Sereja change the values of at most k cells of the table so that the table met the described requirement? What minimum number of table cells should he change in this case?
-----Input-----
The first line contains integers n, m and k (1 β€ n, m β€ 100;Β 1 β€ k β€ 10). Next n lines describe the table a: the i-th of them contains m integers a_{i}1, a_{i}2, ..., a_{im} (0 β€ a_{i}, j β€ 1) β the values in the cells of the i-th row.
-----Output-----
Print -1, if it is impossible to meet the requirement. Otherwise, print the minimum number of cells which should be changed.
-----Examples-----
Input
5 5 2
1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
1 1 1 1 1
1 1 1 1 1
Output
1
Input
3 4 1
1 0 0 0
0 1 1 1
1 1 1 0
Output
-1
Input
3 4 1
1 0 0 1
0 1 1 0
1 0 0 1
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.
You are given an array a consisting of n integers. We denote the subarray a[l..r] as the array [a_l, a_{l + 1}, ..., a_r] (1 β€ l β€ r β€ n).
A subarray is considered good if every integer that occurs in this subarray occurs there exactly thrice. For example, the array [1, 2, 2, 2, 1, 1, 2, 2, 2] has three good subarrays:
* a[1..6] = [1, 2, 2, 2, 1, 1];
* a[2..4] = [2, 2, 2];
* a[7..9] = [2, 2, 2].
Calculate the number of good subarrays of the given array a.
Input
The first line contains one integer n (1 β€ n β€ 5 β
10^5).
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ n).
Output
Print one integer β the number of good subarrays of the array a.
Examples
Input
9
1 2 2 2 1 1 2 2 2
Output
3
Input
10
1 2 3 4 1 2 3 1 2 3
Output
0
Input
12
1 2 3 4 3 4 2 1 3 4 2 1
Output
1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus.
* Initially, there is a pile that contains x 100-yen coins and y 10-yen coins.
* They take turns alternatively. Ciel takes the first turn.
* In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins.
* If Ciel or Hanako can't take exactly 220 yen from the pile, she loses.
Determine the winner of the game.
Input
The first line contains two integers x (0 β€ x β€ 106) and y (0 β€ y β€ 106), separated by a single space.
Output
If Ciel wins, print "Ciel". Otherwise, print "Hanako".
Examples
Input
2 2
Output
Ciel
Input
3 22
Output
Hanako
Note
In the first turn (Ciel's turn), she will choose 2 100-yen coins and 2 10-yen coins. In the second turn (Hanako's turn), she will choose 1 100-yen coin and 12 10-yen coins. In the third turn (Ciel's turn), she can't pay exactly 220 yen, so Ciel will lose.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given two numbers (m and n) :
- convert all numbers from m to n to binary
- sum them as if they were in base 10
- convert the result to binary
- return as string
Eg: with the numbers 1 and 4
1 // 1 to binary is 1
+ 10 // 2 to binary is 10
+ 11 // 3 to binary is 11
+100 // 4 to binary is 100
----
122 // 122 in Base 10 to Binary is 1111010
So BinaryPyramid ( 1 , 4 ) should return "1111010"
range should be ascending 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.
On Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 β€ i β€ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should be equal to each other, the heights of the 2-nd and the (n - 1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not.
Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.
Input
The first line contains integer n (1 β€ n β€ 105) which is the number of trees. The second line contains integers ai (1 β€ ai β€ 105) which are the heights of the trees.
Output
Print a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.
Examples
Input
3
2 2 2
Output
1
Input
4
1 2 2 1
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i.
There is one cursor. The cursor's location β is denoted by an integer in \{0, β¦, |s|\}, with the following meaning:
* If β = 0, then the cursor is located before the first character of s.
* If β = |s|, then the cursor is located right after the last character of s.
* If 0 < β < |s|, then the cursor is located between s_β and s_{β+1}.
We denote by s_left the string to the left of the cursor and s_right the string to the right of the cursor.
We also have a string c, which we call our clipboard, which starts out as empty. There are three types of actions:
* The Move action. Move the cursor one step to the right. This increments β once.
* The Cut action. Set c β s_right, then set s β s_left.
* The Paste action. Append the value of c to the end of the string s. Note that this doesn't modify c.
The cursor initially starts at β = 0. Then, we perform the following procedure:
1. Perform the Move action once.
2. Perform the Cut action once.
3. Perform the Paste action s_β times.
4. If β = x, stop. Otherwise, return to step 1.
You're given the initial string s and the integer x. What is the length of s when the procedure stops? Since this value may be very large, only find it modulo 10^9 + 7.
It is guaranteed that β β€ |s| at any time.
Input
The first line of input contains a single integer t (1 β€ t β€ 1000) denoting the number of test cases. The next lines contain descriptions of the test cases.
The first line of each test case contains a single integer x (1 β€ x β€ 10^6). The second line of each test case consists of the initial string s (1 β€ |s| β€ 500). It is guaranteed, that s consists of the characters "1", "2", "3".
It is guaranteed that the sum of x in a single file is at most 10^6. It is guaranteed that in each test case before the procedure will stop it will be true that β β€ |s| at any time.
Output
For each test case, output a single line containing a single integer denoting the answer for that test case modulo 10^9 + 7.
Example
Input
4
5
231
7
2323
6
333
24
133321333
Output
25
1438
1101
686531475
Note
Let's illustrate what happens with the first test case. Initially, we have s = 231. Initially, β = 0 and c = \varepsilon (the empty string). The following things happen if we follow the procedure above:
* Step 1, Move once: we get β = 1.
* Step 2, Cut once: we get s = 2 and c = 31.
* Step 3, Paste s_β = 2 times: we get s = 23131.
* Step 4: β = 1 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 2.
* Step 2, Cut once: we get s = 23 and c = 131.
* Step 3, Paste s_β = 3 times: we get s = 23131131131.
* Step 4: β = 2 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 3.
* Step 2, Cut once: we get s = 231 and c = 31131131.
* Step 3, Paste s_β = 1 time: we get s = 23131131131.
* Step 4: β = 3 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 4.
* Step 2, Cut once: we get s = 2313 and c = 1131131.
* Step 3, Paste s_β = 3 times: we get s = 2313113113111311311131131.
* Step 4: β = 4 not= x = 5, so we return to step 1.
* Step 1, Move once: we get β = 5.
* Step 2, Cut once: we get s = 23131 and c = 13113111311311131131.
* Step 3, Paste s_β = 1 times: we get s = 2313113113111311311131131.
* Step 4: β = 5 = x, so we stop.
At the end of the procedure, s has length 25.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In this task Anna and Maria play the following game. Initially they have a checkered piece of paper with a painted n Γ m rectangle (only the border, no filling). Anna and Maria move in turns and Anna starts. During each move one should paint inside the last-painted rectangle a new lesser rectangle (along the grid lines). The new rectangle should have no common points with the previous one. Note that when we paint a rectangle, we always paint only the border, the rectangles aren't filled.
Nobody wins the game β Anna and Maria simply play until they have done k moves in total. Count the number of different ways to play this game.
Input
The first and only line contains three integers: n, m, k (1 β€ n, m, k β€ 1000).
Output
Print the single number β the number of the ways to play the game. As this number can be very big, print the value modulo 1000000007 (109 + 7).
Examples
Input
3 3 1
Output
1
Input
4 4 1
Output
9
Input
6 7 2
Output
75
Note
Two ways to play the game are considered different if the final pictures are different. In other words, if one way contains a rectangle that is not contained in the other way.
In the first sample Anna, who performs her first and only move, has only one possible action plan β insert a 1 Γ 1 square inside the given 3 Γ 3 square.
In the second sample Anna has as much as 9 variants: 4 ways to paint a 1 Γ 1 square, 2 ways to insert a 1 Γ 2 rectangle vertically, 2 more ways to insert it horizontally and one more way is to insert a 2 Γ 2 square.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Define crossover operation over two equal-length strings A and B as follows:
the result of that operation is a string of the same length as the input strings result[i] is chosen at random between A[i] and B[i].
Given array of strings `arr` and a string result, find for how many pairs of strings from `arr` the result of the crossover operation over them may be equal to result.
Note that (A, B) and (B, A) are the same pair. Also note that the pair cannot include the same element of the array twice (however, if there are two equal elements in the array, they can form a pair).
# Example
For `arr = ["abc", "aaa", "aba", "bab"]` and `result = "bbb"`, the output should be `2`.
```
"abc" and "bab" can crossover to "bbb"
"aba" and "bab" can crossover to "bbb"
```
# Input/Output
- `[input]` string array `arr`
A non-empty array of equal-length strings.
Constraints: `2 β€ arr.length β€ 10, 1 β€ arr[i].length β€ 10.`
- `[input]` string `result`
A string of the same length as each of the arr elements.
Constraints: `result.length = arr[i].length.`
- `[output]` an integer
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 an integer n not less than 0, let us define f(n) as follows:
- f(n) = 1 (if n < 2)
- f(n) = n f(n-2) (if n \geq 2)
Given is an integer N. Find the number of trailing zeros in the decimal notation of f(N).
-----Constraints-----
- 0 \leq N \leq 10^{18}
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the number of trailing zeros in the decimal notation of f(N).
-----Sample Input-----
12
-----Sample Output-----
1
f(12) = 12 Γ 10 Γ 8 Γ 6 Γ 4 Γ 2 = 46080, which has one trailing zero.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Matrix of given integers
a1,1 a1,2 ... a1, n
a2,1 a2,2 ... a2, n
::
an, 1 an, 2 ... an, n
Then, create a program that outputs the maximum value of the sum of one or more consecutive terms (submatrix) in the vertical and horizontal directions and ends.
Input
The input data is given in the following format.
n
a1,1 a1,2 ... a1, n
a2,1 a2,2 ... a2, n
::
an, 1 an, 2 ... an, n
n is 1 or more and 100 or less, and ai, j is -10000 or more and 10000 or less.
Output
Print the maximum value on one line.
Examples
Input
3
1 -2 3
-4 5 6
7 8 -9
Output
16
Input
4
1 3 -9 2
2 7 -1 5
-8 3 2 -1
5 0 -3 1
Output
15
Read the inputs from stdin solve the problem and write the answer to stdout (do 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, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.
A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.
Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.
This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 10^5$) β the number of bracket sequences.
Each of the following $n$ lines contains one bracket sequence β a non-empty string which consists only of characters "(" and ")".
The sum of lengths of all bracket sequences in the input is at most $5 \cdot 10^5$.
Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.
-----Output-----
Print a single integer β the maximum number of pairs which can be made, adhering to the conditions in the statement.
-----Examples-----
Input
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
-----Note-----
In the first example, it's optimal to construct two pairs: "(( Β Β Β )())" and "( Β Β Β )".
Read the inputs from 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.