question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).
Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.
Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.
-----Constraints-----
- All values in input are integers.
- 1 \leq H, W \leq 3 \times 10^5
- 1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)
- 1 \leq h_i \leq H
- 1 \leq w_i \leq W
- \left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)
-----Input-----
Input is given from Standard Input in the following format:
H W M
h_1 w_1
\vdots
h_M w_M
-----Output-----
Print the answer.
-----Sample Input-----
2 3 3
2 2
1 1
1 3
-----Sample Output-----
3
We can destroy all the targets by placing the bomb at \left(1, 2\right).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second block, he gets the integer 12.
Wet Shark then takes this number modulo x. Please, tell him how many ways he can choose one digit from each block so that he gets exactly k as the final result. As this number may be too large, print it modulo 10^9 + 7.
Note, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are 3 ways to choose digit 5 from block 3 5 6 7 8 9 5 1 1 1 1 5.
-----Input-----
The first line of the input contains four space-separated integers, n, b, k and x (2 β€ n β€ 50 000, 1 β€ b β€ 10^9, 0 β€ k < x β€ 100, x β₯ 2)Β β the number of digits in one block, the number of blocks, interesting remainder modulo x and modulo x itself.
The next line contains n space separated integers a_{i} (1 β€ a_{i} β€ 9), that give the digits contained in each block.
-----Output-----
Print the number of ways to pick exactly one digit from each blocks, such that the resulting integer equals k modulo x.
-----Examples-----
Input
12 1 5 10
3 5 6 7 8 9 5 1 1 1 1 5
Output
3
Input
3 2 1 2
6 2 2
Output
0
Input
3 2 1 2
3 1 2
Output
6
-----Note-----
In the second sample possible integers are 22, 26, 62 and 66. None of them gives the remainder 1 modulo 2.
In the third sample integers 11, 13, 21, 23, 31 and 33 have remainder 1 modulo 2. There is exactly one way to obtain each of these integers, so the total answer is 6.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Transformation
Write a program which performs a sequence of commands to a given string $str$. The command is one of:
* print a b: print from the a-th character to the b-th character of $str$
* reverse a b: reverse from the a-th character to the b-th character of $str$
* replace a b p: replace from the a-th character to the b-th character of $str$ with p
Note that the indices of $str$ start with 0.
Constraints
* $1 \leq $ length of $str \leq 1000$
* $1 \leq q \leq 100$
* $0 \leq a \leq b < $ length of $str$
* for replace command, $b - a + 1 = $ length of $p$
Input
In the first line, a string $str$ is given. $str$ consists of lowercase letters. In the second line, the number of commands q is given. In the next q lines, each command is given in the above mentioned format.
Output
For each print command, print a string in a line.
Examples
Input
abcde
3
replace 1 3 xyz
reverse 0 2
print 1 4
Output
xaze
Input
xyz
3
print 0 2
replace 0 2 abc
print 0 2
Output
xyz
abc
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 a sequence made up of the consecutive prime numbers. This infinite sequence would start with:
```python
"2357111317192329313741434753596167717379..."
```
You will be given two numbers: `a` and `b`, and your task will be to return `b` elements starting from index `a` in this sequence.
```
For example:
solve(10,5) == `19232` Because these are 5 elements from index 10 in the sequence.
```
Tests go up to about index `20000`.
More examples in test cases. Good luck!
Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar. If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar. If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
-----Input-----
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 10^6), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
-----Output-----
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
-----Examples-----
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
-----Note-----
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
[Image]
[Image]
[Image]
$\Delta \Delta \Delta \Delta$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
D: Sunburn-Suntan-
story
Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. Cute like an angel. Aizu Nyan is planning to participate in this summer festival, so I made a schedule for the band to go to listen to. I'm worried about sunburn here. All live performances are held outdoors, but Aizu Nyan has a constitution that makes it easy to get sunburned, so if you are exposed to too much ultraviolet rays outdoors for a long time, you will get sunburned immediately. I plan to avoid UV rays as much as possible by evacuating indoors while there is no live performance, but during the live performance, it will inevitably hit the sun. Therefore, Aizu Nyan thought about taking measures against ultraviolet rays by applying sunscreen.
problem
If you apply sunscreen, you can get the effect for T minutes from the time you apply it. Sunscreen can only be applied once, so I want to use it effectively. Aizu Nyan is outdoors from the start time to the end time of the live, and is indoors at other times. You'll be given a live schedule that Aizu Nyan will listen to, so find the maximum amount of time you can get the sunscreen effect while you're outdoors.
Input format
The input can be given in the following format.
T
N
s_1 t_1
...
s_N t_N
The first line is given an integer T that represents the time it takes to get the sunscreen effect. The second line is given an integer N that represents the number of live concerts Aizu Nyan listens to. The following N lines are given the integer s_i, which represents the start time of the live that Aizu Nyan listens to thi, and the integer t_i, which represents the end time, separated by spaces.
Constraint
* 1 β€ T β€ 10 ^ {15}
* 1 β€ N β€ 10 ^ 5
* 0 β€ s_i <t_i β€ 10 ^ {15} (1 β€ i β€ N)
* The start time of the (i + 1) th live is the same as or later than the end time of the i-th live. That is, t_i β€ s_ {i + 1} (1 β€ i <N)
output
Print one line for the maximum amount of time you can get the sunscreen effect while you're outdoors.
Input example 1
20
1
0 10
Output example 1
Ten
Input example 2
20
1
0 100
Output example 2
20
Input example 3
9
3
1 5
9 11
13 20
Output example 3
7
Input example 4
twenty five
Five
9 12
15 20
21 25
28 40
45 60
Output example 4
twenty one
Example
Input
20
1
0 10
Output
10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
Some chefs go for a tour lasting N days. They take packages of bread for food. Each package has K pieces of breads. On the i^{th} day, they eat A_{i} pieces of bread.
Unfortunately, chefs are very lazy people, and they always forget to close the package of breads, so each day the last piece of bread becomes exposed to mold (a fungus), and is no longer suitable for eating. Such a bad piece is not eaten, and is instead thrown away.
Let us take an example. If K = 4 and N = 3, then A = {3, 1, 2}. Chefs have packages of bread each having 4 pieces of bread, and their travel lasts 3 days. In the first day, they must eat 3 pieces of bread. So they open new package of bread and eat 3 pieces. They forget to close the package, so the 4^{th} piece becomes bad. In the next day, they want to eat one piece of bread. And in the first package we don't have any good pieces of bread left, so they open a new package of bread and eat one piece from that. On the 3^{rd} day, they want to eat 2 pieces of bread. In the second package, we have three pieces, and one of them is bad; so we have 2 good pieces. They eat 2 pieces from this package. So they must buy 2 packages of bread.
Please help chefs in finding out the minimum number of packages of breads they should take with them on the tour.
------ Input ------
The first line of input contains a single integer T denoting the number of test cases.
The first line of each test contains two space separated integers N and K.
The next line of each test case contains N space separated integers denoting the number of pieces of bread the chefs want to eat each day.
------ Output ------
For each of the T test cases, output a single line - minimum number of packages of bread the chefs should take.
------
------ Constraints -----
$1 β€ T β€ 10$
Subtask 1: 15 points
$1 β€ N β€ 100$
$1 β€ K β€ 100$
$1 β€ A_{i} β€ 100$
Subtask 2: 25 points
$1 β€ N β€ 10^{5}$
$1 β€ K β€ 10^{6}$
$1 β€ A_{i} β€ 10^{6}$
Subtask 3: 60 points
$1 β€ N β€ 10^{5}$
$1 β€ K β€ 10^{11}$
$1 β€ A_{i} β€ 10^{6}$
----- Sample Input 1 ------
3
3 4
3 1 2
1 1
1
2 4
8 8
----- Sample Output 1 ------
2
1
4
----- explanation 1 ------
Test case 1 has already been explained in the statement.
In test case 2, we have one day tour and packages with one piece each. In the first day, we have to eat one piece of bread, so we open a package and eat one piece. Tour ended, and our answer is 1.
In test case 3, we have a two days tour, and packages with 4 pieces of bread each. In the first day, we have to eat 8 pieces. We need to open two packages and eat all the pieces. In the second day, we have to eat 8 pieces again. We open two packages and eat all pieces. Tour ended. Answer is 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.
Polycarp remembered the $2020$-th year, and he is happy with the arrival of the new $2021$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $n$ as the sum of a certain number of $2020$ and a certain number of $2021$.
For example, if:
$n=4041$, then the number $n$ can be represented as the sum $2020 + 2021$;
$n=4042$, then the number $n$ can be represented as the sum $2021 + 2021$;
$n=8081$, then the number $n$ can be represented as the sum $2020 + 2020 + 2020 + 2021$;
$n=8079$, then the number $n$ cannot be represented as the sum of the numbers $2020$ and $2021$.
Help Polycarp to find out whether the number $n$ can be represented as the sum of a certain number of numbers $2020$ and a certain number of numbers $2021$.
-----Input-----
The first line contains one integer $t$ ($1 \leq t \leq 10^4$) β the number of test cases. Then $t$ test cases follow.
Each test case contains one integer $n$ ($1 \leq n \leq 10^6$) β the number that Polycarp wants to represent as the sum of the numbers $2020$ and $2021$.
-----Output-----
For each test case, output on a separate line:
"YES" if the number $n$ is representable as the sum of a certain number of $2020$ and a certain number of $2021$;
"NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
-----Examples-----
Input
5
1
4041
4042
8081
8079
Output
NO
YES
YES
YES
NO
-----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.
Example
Input
1+2*3+4
11
Output
M
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.
Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt.
You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$)Β β the numer of citizens.
The next line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_{i} \le 10^{9}$)Β β the initial balances of citizens.
The next line contains a single integer $q$ ($1 \le q \le 2 \cdot 10^{5}$)Β β the number of events.
Each of the next $q$ lines contains a single event. The events are given in chronological order.
Each event is described as either 1 p x ($1 \le p \le n$, $0 \le x \le 10^{9}$), or 2 x ($0 \le x \le 10^{9}$). In the first case we have a receipt that the balance of the $p$-th person becomes equal to $x$. In the second case we have a payoff with parameter $x$.
-----Output-----
Print $n$ integersΒ β the balances of all citizens after all events.
-----Examples-----
Input
4
1 2 3 4
3
2 3
1 2 2
2 1
Output
3 2 3 4
Input
5
3 50 2 1 10
3
1 2 0
2 8
1 3 20
Output
8 8 20 8 10
-----Note-----
In the first example the balances change as follows: 1 2 3 4 $\rightarrow$ 3 3 3 4 $\rightarrow$ 3 2 3 4 $\rightarrow$ 3 2 3 4
In the second example the balances change as follows: 3 50 2 1 10 $\rightarrow$ 3 0 2 1 10 $\rightarrow$ 8 8 8 8 10 $\rightarrow$ 8 8 20 8 10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
-----Input-----
The first line of input will be a single string s (1 β€ |s| β€ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'β'z').
-----Output-----
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
-----Examples-----
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
-----Note-----
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 studies music.
He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitones
Vasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads β major and minor.
Let's define a major triad. Let the triad consist of notes X, Y and Z. If we can order the notes so as the distance along the musical scale between X and Y equals 4 semitones and the distance between Y and Z is 3 semitones, then the triad is major. The distance between X and Z, accordingly, equals 7 semitones.
A minor triad is different in that the distance between X and Y should be 3 semitones and between Y and Z β 4 semitones.
For example, the triad "C E G" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet "C# B F" is minor, because if we order the notes as "B C# F", than between B and C# will be 3 semitones, and between C# and F β 4 semitones.
Help Vasya classify the triad the teacher has given to him.
Input
The only line contains 3 space-separated notes in the above-given notation.
Output
Print "major" if the chord is major, "minor" if it is minor, and "strange" if the teacher gave Vasya some weird chord which is neither major nor minor. Vasya promises you that the answer will always be unambiguous. That is, there are no chords that are both major and minor simultaneously.
Examples
Input
C E G
Output
major
Input
C# B F
Output
minor
Input
A B H
Output
strange
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal $a$ instant damage to him, and then heal that enemy $b$ health points at the end of every second, for exactly $c$ seconds, starting one second after the ability is used. That means that if the ability is used at time $t$, the enemy's health decreases by $a$ at time $t$, and then increases by $b$ at time points $t + 1$, $t + 2$, ..., $t + c$ due to this ability.
The ability has a cooldown of $d$ seconds, i.Β e. if Meka-Naruto uses it at time moment $t$, next time he can use it is the time $t + d$. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.
The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under $k$ spells gets $k\cdot b$ amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.
Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every $d$ seconds). The enemy is killed if their health points become $0$ or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them?
-----Input-----
The first line contains an integer $t$ ($1\leq t\leq 10^5$) standing for the number of testcases.
Each test case is described with one line containing four numbers $a$, $b$, $c$ and $d$ ($1\leq a, b, c, d\leq 10^6$) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively.
-----Output-----
For each testcase in a separate line print $-1$ if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed.
-----Example-----
Input
7
1 1 1 1
2 2 2 2
1 2 3 4
4 3 2 1
228 21 11 3
239 21 11 3
1000000 1 1000000 1
Output
1
2
1
5
534
-1
500000500000
-----Note-----
In the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.
In the fourth test case of the example the enemy gets: $4$ damage ($1$-st spell cast) at time $0$; $4$ damage ($2$-nd spell cast) and $3$ heal ($1$-st spell cast) at time $1$ (the total of $5$ damage to the initial health); $4$ damage ($3$-nd spell cast) and $6$ heal ($1$-st and $2$-nd spell casts) at time $2$ (the total of $3$ damage to the initial health); and so on.
One can prove that there is no time where the enemy gets the total of $6$ damage or more, so the answer is $5$. Please note how the health is recalculated: for example, $8$-health enemy would not die at time $1$, as if we first subtracted $4$ damage from his health and then considered him dead, before adding $3$ heal.
In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.
In the seventh test case the answer does not fit into a 32-bit integer type.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 undirected unweighted graph consisting of $n$ vertices and $m$ edges (which represents the map of Bertown) and the array of prices $p$ of length $m$. It is guaranteed that there is a path between each pair of vertices (districts).
Mike has planned a trip from the vertex (district) $a$ to the vertex (district) $b$ and then from the vertex (district) $b$ to the vertex (district) $c$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $p$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.
You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) β the number of test cases. Then $t$ test cases follow.
The first line of the test case contains five integers $n, m, a, b$ and $c$ ($2 \le n \le 2 \cdot 10^5$, $n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$, $1 \le a, b, c \le n$) β the number of vertices, the number of edges and districts in Mike's trip.
The second line of the test case contains $m$ integers $p_1, p_2, \dots, p_m$ ($1 \le p_i \le 10^9$), where $p_i$ is the $i$-th price from the array.
The following $m$ lines of the test case denote edges: edge $i$ is represented by a pair of integers $v_i$, $u_i$ ($1 \le v_i, u_i \le n$, $u_i \ne v_i$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($v_i, u_i$) there are no other pairs ($v_i, u_i$) or ($u_i, v_i$) in the array of edges, and for each pair $(v_i, u_i)$ the condition $v_i \ne u_i$ is satisfied. It is guaranteed that the given graph is connected.
It is guaranteed that the sum of $n$ (as well as the sum of $m$) does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$, $\sum m \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer β the minimum possible price of Mike's trip if you distribute prices between edges optimally.
-----Example-----
Input
2
4 3 2 3 4
1 2 3
1 2
1 3
1 4
7 9 1 5 7
2 10 4 8 5 6 7 3 3
1 2
1 3
1 4
3 2
3 5
4 2
5 6
1 7
6 7
Output
7
12
-----Note-----
One of the possible solution to the first test case of the example:
[Image]
One of the possible solution to the second test case of the example:
[Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height $h$, and there is a moving platform on each height $x$ from $1$ to $h$.
Each platform is either hidden inside the cliff or moved out. At first, there are $n$ moved out platforms on heights $p_1, p_2, \dots, p_n$. The platform on height $h$ is moved out (and the character is initially standing there).
If you character is standing on some moved out platform on height $x$, then he can pull a special lever, which switches the state of two platforms: on height $x$ and $x - 1$. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. Note that this is the only way to move from one platform to another.
Your character is quite fragile, so it can safely fall from the height no more than $2$. In other words falling from the platform $x$ to platform $x - 2$ is okay, but falling from $x$ to $x - 3$ (or lower) is certain death.
Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height $h$, which is unaffected by the crystals). After being used, the crystal disappears.
What is the minimum number of magic crystal you need to buy to safely land on the $0$ ground level?
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 100$) β the number of queries. Each query contains two lines and is independent of all other queries.
The first line of each query contains two integers $h$ and $n$ ($1 \le h \le 10^9$, $1 \le n \le \min(h, 2 \cdot 10^5)$) β the height of the cliff and the number of moved out platforms.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($h = p_1 > p_2 > \dots > p_n \ge 1$) β the corresponding moved out platforms in the descending order of their heights.
The sum of $n$ over all queries does not exceed $2 \cdot 10^5$.
-----Output-----
For each query print one integer β the minimum number of magic crystals you have to spend to safely come down on the ground level (with height $0$).
-----Example-----
Input
4
3 2
3 1
8 6
8 7 6 5 3 2
9 6
9 8 5 4 3 1
1 1
1
Output
0
1
2
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer sequence of length N. The i-th term in the sequence is a_i. In one operation, you can select a term and either increment or decrement it by one.
At least how many operations are necessary to satisfy the following conditions?
* For every i (1β€iβ€n), the sum of the terms from the 1-st through i-th term is not zero.
* For every i (1β€iβ€n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.
Constraints
* 2 β€ n β€ 10^5
* |a_i| β€ 10^9
* Each a_i is an integer.
Input
Input is given from Standard Input in the following format:
n
a_1 a_2 ... a_n
Output
Print the minimum necessary count of operations.
Examples
Input
4
1 -3 1 0
Output
4
Input
5
3 -6 4 -5 7
Output
0
Input
6
-1 4 3 2 -5 4
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.
Little Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.
But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer n?"
Petya knows only 5 integer types:
1) byte occupies 1 byte and allows you to store numbers from - 128 to 127
2) short occupies 2 bytes and allows you to store numbers from - 32768 to 32767
3) int occupies 4 bytes and allows you to store numbers from - 2147483648 to 2147483647
4) long occupies 8 bytes and allows you to store numbers from - 9223372036854775808 to 9223372036854775807
5) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower.
For all the types given above the boundary values are included in the value range.
From this list, Petya wants to choose the smallest type that can store a positive integer n. Since BigInteger works much slower, Peter regards it last. Help him.
Input
The first line contains a positive number n. It consists of no more than 100 digits and doesn't contain any leading zeros. The number n can't be represented as an empty string.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Output
Print the first type from the list "byte, short, int, long, BigInteger", that can store the natural number n, in accordance with the data given above.
Examples
Input
127
Output
byte
Input
130
Output
short
Input
123456789101112131415161718192021222324
Output
BigInteger
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Count the number of divisors of a positive integer `n`.
Random tests go up to `n = 500000`.
## Examples
```python
divisors(4) == 3 # 1, 2, 4
divisors(5) == 2 # 1, 5
divisors(12) == 6 # 1, 2, 3, 4, 6, 12
divisors(30) == 8 # 1, 2, 3, 5, 6, 10, 15, 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.
Little Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw $n$ squares in the snow with a side length of $1$. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length $1$, parallel to the coordinate axes, with vertices at integer points.
In order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends $(x, y)$ and $(x, y+1)$. Then Sofia looks if there is already a drawn segment with the coordinates of the ends $(x', y)$ and $(x', y+1)$ for some $x'$. If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates $x$, $x+1$ and the differing coordinate $y$.
For example, if Sofia needs to draw one square, she will have to draw two segments using a ruler: [Image]
After that, she can draw the remaining two segments, using the first two as a guide: [Image]
If Sofia needs to draw two squares, she will have to draw three segments using a ruler: [Image]
After that, she can draw the remaining four segments, using the first three as a guide: [Image]
Sofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number.
-----Input-----
The only line of input contains a single integer $n$ ($1 \le n \le 10^{9}$), the number of squares that Sofia wants to draw.
-----Output-----
Print single integer, the minimum number of segments that Sofia will have to draw with a ruler without a guide in order to draw $n$ squares in the manner described above.
-----Examples-----
Input
1
Output
2
Input
2
Output
3
Input
4
Output
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A programming contest is held every year at White Tiger University. When the total number of teams is N, each team is assigned a team ID from 1 to N. The contest starts with all teams scoring 0 and runs continuously for L seconds.
This year's contest will be broadcast on TV. Only the team with the highest score at the time will be shown on TV during the contest. However, if there are multiple applicable teams, the team with the smallest team ID will be displayed. When the team to be projected changes, the camera changes instantly.
You got the contest log. The log contains all the records when a team's score changed. Each record is given in the form of "Team d scored x points t seconds after the start of the contest". The current score may be less than 0 because points may be deducted.
Create a program that takes the contest log as input and reports the ID of the team that has been on TV for the longest time between the start and end of the contest.
input
The input consists of one dataset. The input is given in the following format.
N R L
d1 t1 x1
d2 t2 x2
::
dR tR xR
The first line consists of three integers. N (2 β€ N β€ 100000) is the number of teams and R (0 β€ R β€ 1000000) is the number of records in the log. L (1 β€ L β€ 1000000) represents the time (length) of the contest. The information of each record is given in the following R line. Each record shows that team di (1 β€ di β€ N) has scored or deducted xi (-1000 β€ xi β€ 1000) points ti (0 <ti <L) seconds after the start of the contest. However, ti and xi are integers, and ti-1 β€ ti.
output
The ID of the team that has been shown on TV for the longest time between the start and end of the contest is output on one line. However, if there are multiple teams with the longest length, the team with the smallest team ID is output.
Example
Input
3 4 600
3 100 5
1 200 10
2 400 20
3 500 20
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.
Many cats live on the campus of a school. Natsume's daily routine is to pet those cats. However, the cats may be capricious and go for a walk off campus.
The campus site is a rectangle with each side parallel to the x-axis or y-axis and is surrounded by a fence except for the gate, but cats can freely enter and exit through the gate and move over the fence. Sometimes.
One day, Natsume wanted to know how many cats were on campus in order to pet the cats on campus as equally as possible. Your job is to find the number of cats on campus given the location of the campus on the coordinate plane and the coordinates of the cats. However, cats walking on the fence and cats just passing through the gate are also considered to be on campus.
Notes on Submission
Multiple datasets are given in the above format. The first line of input data gives the number of datasets. Create a program that outputs the output for each data set in order in the above format.
Input
On the first line of input, four integers X, Y, W, H are given, separated by a space character. These represent the x-coordinate of the southwestern end of the campus, the y-coordinate of the same point, the east-west width of the campus, and the north-south length of the campus, respectively. These values ββsatisfy -10000 <= X, Y <= 10000 and 0 <W, H <= 10000.
The second line of input is given the number of cats N (0 <N <= 100).
The following N lines are given a set of integers (-50000 <= x, y <= 50000) representing the x, y coordinates of the cat's position, one per line for each cat.
The positive direction on the x-axis is east, the positive direction on the y-axis is north, and all numbers given are integers.
Output
Output the number of cats on campus.
Example
Input
2
1 3 20 10
4
21 13
1 15
10 10
25 10
1 3 20 10
4
21 13
1 15
10 10
25 10
Output
2
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## The Story
Green Lantern's long hours of study and practice with his ring have really paid off -- his skills, focus, and control have improved so much that now he can even use his ring to update and redesign his web site. Earlier today he was focusing his will and a beam from his ring upon the Justice League web server, while intensely brainstorming and visualizing in minute detail different looks and ideas for his web site, and when he finished and reloaded his home page, he was absolutely thrilled to see that among other things it now displayed
~~~~
In brightest day, in blackest night,
There's nothing cooler than my site!
~~~~
in his favorite font in very large blinking green letters.
The problem is, Green Lantern's ring has no power over anything yellow, so if he's experimenting with his web site and accidentally changes some text or background color to yellow, he will no longer be able to make any changes to those parts of the content or presentation (because he doesn't actually know any HTML, CSS, programming languages, frameworks, etc.) until he gets a more knowledgable friend to edit the code for him.
## Your Mission
You can help Green Lantern by writing a function that will replace any color property values that are too yellow with shades of green or blue-green. Presumably at a later time the two of you will be doing some testing to find out at exactly which RGB values yellow stops being yellow and starts being off-white, orange, brown, etc. as far as his ring is concerned, but here's the plan to get version 1.0 up and running as soon as possible:
Your function will receive either an HTML color name or a six-digit hex color code. (You're not going to bother with other types of color codes just now because you don't think they will come up.) If the color is too yellow, your function needs to return a green or blue-green shade instead, but if it is not too yellow, it needs to return the original color name or hex color code unchanged.
### HTML Color Names
(If don't know what HTML color names are, take a look at this HTML colors names reference.)
For HMTL color names, you are going to start out trying a pretty strict definition of yellow, replacing any of the following colors as specified:
~~~~
Gold => ForestGreen
Khaki => LimeGreen
LemonChiffon => PaleGreen
LightGoldenRodYellow => SpringGreen
LightYellow => MintCream
PaleGoldenRod => LightGreen
Yellow => Lime
~~~~
HTML color names are case-insensitive, so your function will need to be able to identify the above yellow shades regardless of the cases used, but should output the green shades as capitalized above.
Some examples:
```
"lemonchiffon" "PaleGreen"
"GOLD" "ForestGreen"
"pAlEgOlDeNrOd" "LightGreen"
"BlueViolet" "BlueViolet"
```
### Hex Color Codes
(If you don't know what six-digit hex color codes are, take a look at this Wikipedia description. Basically the six digits are made up of three two-digit numbers in base 16, known as hexidecimal or hex, from 00 to FF (equivalent to 255 in base 10, also known as decimal), with the first two-digit number specifying the color's red value, the second the green value, and the third blue.)
With six-digit color hex codes, you are going to start out going really overboard, interpreting as "yellow" any hex code where the red (R) value and the green (G) value are each greater than the blue (B) value. When you find one of these "yellow" hex codes, your function will take the three hex values and rearrange them that the largest goes to G, the middle goes to B, and the smallest to R.
For example, with the six-digit hex color code `#FFD700`, which has an R value of hex FF (decimal 255), a G value of hex D7 (decimal 215), and a B value of hex 00 (decimal 0), as the R and G values are each larger than the B value, you would return it as `#00FFD7` -- the FF reassigned to G, the D7 to B, and the 00 to R.
Hex color codes are also case-insensitive, but your function should output them in the same case they were received in, just for consistency with whatever style is being used.
Some examples:
```
"#000000" "#000000"
"#b8860b" "#0bb886"
"#8FBC8F" "#8FBC8F"
"#C71585" "#C71585"
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.
You will now successively do the following Q operations:
- In the i-th operation, you replace every element whose value is B_{i} with C_{i}.
For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.
-----Constraints-----
- All values in input are integers.
- 1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}
- B_{i} \neq C_{i}
-----Input-----
Input is given from Standard Input in the following format:
N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}
-----Output-----
Print Q integers S_{i} to Standard Output in the following format:
S_{1}
S_{2}
\vdots
S_{Q}
Note that S_{i} may not fit into a 32-bit integer.
-----Sample Input-----
4
1 2 3 4
3
1 2
3 4
2 4
-----Sample Output-----
11
12
16
Initially, the sequence A is 1,2,3,4.
After each operation, it becomes the following:
- 2, 2, 3, 4
- 2, 2, 4, 4
- 4, 4, 4, 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.
There are $ n $ acitivities with start times $ \\ {s_i \\} $ and finish times $ \\ {t_i \\} $. Assuming that a person can only work on a single activity at a time, find the maximum number of activities that can be performed by a single person.
Constraints
* $ 1 \ le n \ le 10 ^ 5 $
* $ 1 \ le s_i \ lt t_i \ le 10 ^ 9 (1 \ le i \ le n) $
Input
$ n $
$ s_1 $ $ t_1 $
$ s_2 $ $ t_2 $
::
$ s_n $ $ t_n $
The first line consists of the integer $ n $. In the following $ n $ lines, the start time $ s_i $ and the finish time $ t_i $ of the activity $ i $ are given.
output
Print the maximum number of activities in a line.
Examples
Input
5
1 2
3 9
3 5
5 9
6 8
Output
3
Input
3
1 5
3 4
2 5
Output
1
Input
3
1 2
2 3
3 4
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.
Let's call an array $t$ dominated by value $v$ in the next situation.
At first, array $t$ should have at least $2$ elements. Now, let's calculate number of occurrences of each number $num$ in $t$ and define it as $occ(num)$. Then $t$ is dominated (by $v$) if (and only if) $occ(v) > occ(v')$ for any other number $v'$. For example, arrays $[1, 2, 3, 4, 5, 2]$, $[11, 11]$ and $[3, 2, 3, 2, 3]$ are dominated (by $2$, $11$ and $3$ respectevitely) but arrays $[3]$, $[1, 2]$ and $[3, 3, 2, 2, 1]$ are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array $a_1, a_2, \dots, a_n$. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of $a$ is a contiguous part of the array $a$, i. e. the array $a_i, a_{i + 1}, \dots, a_j$ for some $1 \le i \le j \le n$.
-----Input-----
The first line contains single integer $T$ ($1 \le T \le 1000$) β the number of test cases. Each test case consists of two lines.
The first line contains single integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) β the corresponding values of the array $a$.
It's guaranteed that the total length of all arrays in one test doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers β one per test case. For each test case print the only integer β the length of the shortest dominated subarray, or $-1$ if there are no such subarrays.
-----Example-----
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
-----Note-----
In the first test case, there are no subarrays of length at least $2$, so the answer is $-1$.
In the second test case, the whole array is dominated (by $1$) and it's the only dominated subarray.
In the third test case, the subarray $a_4, a_5, a_6$ is the shortest dominated subarray.
In the fourth test case, all subarrays of length more than one are dominated.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
-----Input-----
The first line of the input contains a single integer n (1 β€ n β€ 1000)Β β the number of rows of seats in the bus.
Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.
Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.
-----Output-----
If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).
If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.
If there are multiple solutions, you may print any of them.
-----Examples-----
Input
6
OO|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
Output
YES
++|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
Input
4
XO|OX
XO|XX
OX|OX
XX|OX
Output
NO
Input
5
XX|XX
XX|XX
XO|OX
XO|OO
OX|XO
Output
YES
XX|XX
XX|XX
XO|OX
XO|++
OX|XO
-----Note-----
Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 β€ |V| β€ 100000
* 0 β€ di β€ 10000
* 0 β€ |E| β€ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and the source r.
|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1
|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.
si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.
Output
Print the costs of SSSP in the following format.
c0
c1
:
c|V|-1
The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.
Examples
Input
4 5 0
0 1 1
0 2 4
1 2 2
2 3 1
1 3 5
Output
0
1
3
4
Input
4 6 1
0 1 1
0 2 4
2 0 1
1 2 2
3 1 1
3 2 5
Output
3
0
2
INF
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Toad Pimple has an array of integers $a_1, a_2, \ldots, a_n$.
We say that $y$ is reachable from $x$ if $x<y$ and there exists an integer array $p$ such that $x = p_1 < p_2 < \ldots < p_k=y$, and $a_{p_i}\, \&\, a_{p_{i+1}} > 0$ for all integers $i$ such that $1 \leq i < k$.
Here $\&$ denotes the bitwise AND operation.
You are given $q$ pairs of indices, check reachability for each of them.
-----Input-----
The first line contains two integers $n$ and $q$ ($2 \leq n \leq 300\,000$, $1 \leq q \leq 300\,000$)Β β the number of integers in the array and the number of queries you need to answer.
The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 300\,000$)Β β the given array.
The next $q$ lines contain two integers each. The $i$-th of them contains two space-separated integers $x_i$ and $y_i$ ($1 \leq x_i < y_i \leq n$). You need to check if $y_i$ is reachable from $x_i$.
-----Output-----
Output $q$ lines. In the $i$-th of them print "Shi" if $y_i$ is reachable from $x_i$, otherwise, print "Fou".
-----Example-----
Input
5 3
1 3 0 2 1
1 3
2 4
1 4
Output
Fou
Shi
Shi
-----Note-----
In the first example, $a_3 = 0$. You can't reach it, because AND with it is always zero. $a_2\, \&\, a_4 > 0$, so $4$ is reachable from $2$, and to go from $1$ to $4$ you can use $p = [1, 2, 4]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A sequence $a_1, a_2, \dots, a_k$ is called an arithmetic progression if for each $i$ from $1$ to $k$ elements satisfy the condition $a_i = a_1 + c \cdot (i - 1)$ for some fixed $c$.
For example, these five sequences are arithmetic progressions: $[5, 7, 9, 11]$, $[101]$, $[101, 100, 99]$, $[13, 97]$ and $[5, 5, 5, 5, 5]$. And these four sequences aren't arithmetic progressions: $[3, 1, 2]$, $[1, 2, 4, 8]$, $[1, -1, 1, -1]$ and $[1, 2, 3, 3, 3]$.
You are given a sequence of integers $b_1, b_2, \dots, b_n$. Find any index $j$ ($1 \le j \le n$), such that if you delete $b_j$ from the sequence, you can reorder the remaining $n-1$ elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 2\cdot10^5$) β length of the sequence $b$. The second line contains $n$ integers $b_1, b_2, \dots, b_n$ ($-10^9 \le b_i \le 10^9$) β elements of the sequence $b$.
-----Output-----
Print such index $j$ ($1 \le j \le n$), so that if you delete the $j$-th element from the sequence, you can reorder the remaining elements, so that you will get an arithmetic progression. If there are multiple solutions, you are allowed to print any of them. If there is no such index, print -1.
-----Examples-----
Input
5
2 6 8 7 4
Output
4
Input
8
1 2 3 4 5 6 7 8
Output
1
Input
4
1 2 4 8
Output
-1
-----Note-----
Note to the first example. If you delete the $4$-th element, you can get the arithmetic progression $[2, 4, 6, 8]$.
Note to the second example. The original sequence is already arithmetic progression, so you can delete $1$-st or last element and you will get an arithmetical progression again.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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. For each $i$ ($1 \le i \le n$) the following inequality is true: $-2 \le a_i \le 2$.
You can remove any number (possibly $0$) of elements from the beginning of the array and any number (possibly $0$) of elements from the end of the array. You are allowed to delete the whole array.
You need to answer the question: how many elements should be removed from the beginning of the array, and how many elements should be removed from the end of the array, so that the result will be an array whose product (multiplication) of elements is maximal. If there is more than one way to get an array with the maximum product of elements on it, you are allowed to output any of them.
The product of elements of an empty array (array of length $0$) should be assumed to be $1$.
-----Input-----
The first line of input data contains an integer $t$ ($1 \le t \le 10^4$) βthe number of test cases in the test.
Then the descriptions of the input test cases follow.
The first line of each test case description contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$) βthe length of array $a$.
The next line contains $n$ integers $a_1, a_2, \dots, a_n$ ($|a_i| \le 2$) β elements of array $a$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output two non-negative numbers $x$ and $y$ ($0 \le x + y \le n$) β such that the product (multiplication) of the array numbers, after removing $x$ elements from the beginning and $y$ elements from the end, is maximal.
If there is more than one way to get the maximal product, it is allowed to output any of them. Consider the product of numbers on empty array to be $1$.
-----Examples-----
Input
5
4
1 2 -1 2
3
1 1 -2
5
2 0 -2 2 -1
3
-2 -1 -1
3
-1 -2 -2
Output
0 2
3 0
2 0
0 1
1 0
-----Note-----
In the first case, the maximal value of the product is $2$. Thus, we can either delete the first three elements (obtain array $[2]$), or the last two and one first element (also obtain array $[2]$), or the last two elements (obtain array $[1, 2]$). Thus, in the first case, the answers fit: "3 0", or "1 2", or "0 2".
In the second case, the maximum value of the product is $1$. Then we can remove all elements from the array because the value of the product on the empty array will be $1$. So the answer is "3 0", but there are other possible answers.
In the third case, we can remove the first two elements of the array. Then we get the array: $[-2, 2, -1]$. The product of the elements of the resulting array is $(-2) \cdot 2 \cdot (-1) = 4$. This value is the maximum possible value that can be obtained. Thus, for this case the answer is: "2 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.
Takahashi is playing a board game called Sugoroku.
On the board, there are N + 1 squares numbered 0 to N. Takahashi starts at Square 0, and he has to stop exactly at Square N to win the game.
The game uses a roulette with the M numbers from 1 to M. In each turn, Takahashi spins the roulette. If the number x comes up when he is at Square s, he moves to Square s+x. If this makes him go beyond Square N, he loses the game.
Additionally, some of the squares are Game Over Squares. He also loses the game if he stops at one of those squares. You are given a string S of length N + 1, representing which squares are Game Over Squares. For each i (0 \leq i \leq N), Square i is a Game Over Square if S[i] = 1 and not if S[i] = 0.
Find the sequence of numbers coming up in the roulette in which Takahashi can win the game in the fewest number of turns possible. If there are multiple such sequences, find the lexicographically smallest such sequence. If Takahashi cannot win the game, print -1.
-----Constraints-----
- 1 \leq N \leq 10^5
- 1 \leq M \leq 10^5
- |S| = N + 1
- S consists of 0 and 1.
- S[0] = 0
- S[N] = 0
-----Input-----
Input is given from Standard Input in the following format:
N M
S
-----Output-----
If Takahashi can win the game, print the lexicographically smallest sequence among the shortest sequences of numbers coming up in the roulette in which Takahashi can win the game, with spaces in between.
If Takahashi cannot win the game, print -1.
-----Sample Input-----
9 3
0001000100
-----Sample Output-----
1 3 2 3
If the numbers 1, 3, 2, 3 come up in this order, Takahashi can reach Square 9 via Square 1, 4, and 6. He cannot reach Square 9 in three or fewer turns, and this is the lexicographically smallest sequence in which he reaches Square 9 in four turns.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In the 2050 Conference, some people from the competitive programming community meet together and are going to take a photo. The n people form a line. They are numbered from 1 to n from left to right. Each of them either holds a cardboard with the letter 'C' or a cardboard with the letter 'P'.
Let C=\\{c_1,c_2,...,c_m\} (c_1<c_2<β¦ <c_m) be the set of people who hold cardboards of 'C'. Let P=\\{p_1,p_2,...,p_k\} (p_1<p_2<β¦ <p_k) be the set of people who hold cardboards of 'P'. The photo is good if and only if it satisfies the following constraints:
1. Cβͺ P=\{1,2,...,n\}
2. Cβ© P =β
.
3. c_i-c_{i-1}β€ c_{i+1}-c_i(1< i <m).
4. p_i-p_{i-1}β₯ p_{i+1}-p_i(1< i <k).
Given an array a_1,β¦, a_n, please find the number of good photos satisfying the following condition: $$$β_{xβ C} a_x < β_{yβ P} a_y.$$$
The answer can be large, so output it modulo 998 244 353. Two photos are different if and only if there exists at least one person who holds a cardboard of 'C' in one photo but holds a cardboard of 'P' in the other.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 200 000). Description of the test cases follows.
The first line of each test case contains a single integer n (1β€ nβ€ 200 000).
The second line contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ 10^9).
It is guaranteed that the sum of n over all test cases does not exceed 200 000.
Output
For each test case, output the answer modulo 998 244 353 in a separate line.
Example
Input
3
5
2 1 2 1 1
4
9 2 2 2
1
998244353
Output
10
7
1
Note
For the first test case, there are 10 possible good photos satisfying the condition: PPPPP, CPPPP, PCPPP, CCPPP, PCCPP, PCPCP, PPPPC, CPPPC, PCPPC, PPPCC.
For the second test case, there are 7 possible good photos satisfying the condition: PPPP, PCPP, PCCP, PPPC, PCPC, PPCC, PCCC.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
Taro bought 10 books. Later, I tried to find out the price based on the receipt, but the receipt was dirty and I could not read the price of a book. We decided to calculate the price of the book from the total price of 10 books and the prices of the other 9 books.
Write a program that outputs the price of the book whose price could not be read. The prices of books are all positive integers. Also, there is no need to consider the consumption tax.
Example
Input
9850
1050
800
420
380
600
820
2400
1800
980
0
Output
600
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Yamada Springfield Tanaka was appointed as Deputy Deputy Director of the National Land Readjustment Business Bureau. Currently, his country is in the midst of a major land readjustment, and if this land readjustment can be completed smoothly, his promotion is certain.
However, there are many people who are not happy with his career advancement. One such person was Mr. Sato Seabreeze Suzuki. He has planned to pull Mr. Yamada's foot every time. Again, Mr. Sato put pressure on the organization responsible for the actual land readjustment in order to pull back, making the land readjustment results very confusing.
Therefore, the result passed to Mr. Yamada was only information about which straight line divided a square land. At the very least, Mr. Yamada is sure to be fired rather than promoted if he doesn't know just how many divisions the square land has.
Your job is how many square regions with vertices (-100, -100), (100, -100), (100, 100), (-100, 100) are divided by a given n straight lines. To save Mr. Yamada from the crisis of dismissal by writing a program to find out.
Input
The input consists of multiple test cases.
The first line of each test case is given the integer n representing the number of straight lines (1 <= n <= 100). Subsequent n lines contain four integers x1, y1, x2, and y2, respectively. These integers represent two different points (x1, y1) and (x2, y2) on a straight line. The two points given are always guaranteed to be points on the sides of the square. The n straight lines given are different from each other, and the straight lines do not overlap. Also, the straight line does not overlap the sides of the square.
The end of input is represented by n = 0.
Output
For each test case, print the number of regions divided by n straight lines in one line.
Two points with a distance of less than 10-10 can be considered to match. Also, there is no set of intersections P, Q, R such that | PQ | <10-10, | QR | <10-10 and | PR |> = 10-10.
Example
Input
2
-100 -20 100 20
-20 -100 20 100
2
-100 -20 -20 -100
20 100 100 20
0
Output
4
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As usual, Sereja has array a, its elements are integers: a[1], a[2], ..., a[n]. Let's introduce notation:
$f(a, l, r) = \sum_{i = l}^{r} a [ i ] ; m(a) = \operatorname{max}_{1 \leq l \leq r \leq n} f(a, l, r)$
A swap operation is the following sequence of actions:
choose two indexes i, j (i β j); perform assignments tmp = a[i], a[i] = a[j], a[j] = tmp.
What maximum value of function m(a) can Sereja get if he is allowed to perform at most k swap operations?
-----Input-----
The first line contains two integers n and k (1 β€ n β€ 200;Β 1 β€ k β€ 10). The next line contains n integers a[1], a[2], ..., a[n] ( - 1000 β€ a[i] β€ 1000).
-----Output-----
In a single line print the maximum value of m(a) that Sereja can get if he is allowed to perform at most k swap operations.
-----Examples-----
Input
10 2
10 -1 2 2 2 2 2 2 -1 10
Output
32
Input
5 10
-1 -1 -1 -1 -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.
While playing yet another strategy game, Mans has recruited $n$ Swedish heroes, whose powers which can be represented as an array $a$.
Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to accomplish his goal, he can pick two consecutive heroes, with powers $a_i$ and $a_{i+1}$, remove them and insert a hero with power $-(a_i+a_{i+1})$ back in the same position.
For example if the array contains the elements $[5, 6, 7, 8]$, he can pick $6$ and $7$ and get $[5, -(6+7), 8] = [5, -13, 8]$.
After he will perform this operation $n-1$ times, Mans will end up having only one hero. He wants his power to be as big as possible. What's the largest possible power he can achieve?
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 200000$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-10^9 \le a_i \le 10^9$)Β β powers of the heroes.
-----Output-----
Print the largest possible power he can achieve after $n-1$ operations.
-----Examples-----
Input
4
5 6 7 8
Output
26
Input
5
4 -5 9 -2 1
Output
15
-----Note-----
Suitable list of operations for the first sample:
$[5, 6, 7, 8] \rightarrow [-11, 7, 8] \rightarrow [-11, -15] \rightarrow [26]$
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 got an integer sequence of length N from his mother, as a birthday present. The i-th (1 β¦ i β¦ N) element of the sequence is a_i. The elements are pairwise distinct. He is sorting this sequence in increasing order. With supernatural power, he can perform the following two operations on the sequence in any order:
* Operation 1: choose 2 consecutive elements, then reverse the order of those elements.
* Operation 2: choose 3 consecutive elements, then reverse the order of those elements.
Snuke likes Operation 2, but not Operation 1. Find the minimum number of Operation 1 that he has to perform in order to sort the sequence in increasing order.
Constraints
* 1 β¦ N β¦ 10^5
* 0 β¦ A_i β¦ 10^9
* If i β j, then A_i β A_j.
* 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 minimum number of times Operation 1 that Snuke has to perform.
Examples
Input
4
2
4
3
1
Output
1
Input
5
10
8
5
3
2
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
- Input: Integer `n`
- Output: String
Example:
`a(4)` prints as
```
A
A A
A A A
A A
```
`a(8)` prints as
```
A
A A
A A
A A
A A A A A
A A
A A
A A
```
`a(12)` prints as
```
A
A A
A A
A A
A A
A A
A A A A A A A
A A
A A
A A
A A
A A
```
Note:
- Each line's length is `2n - 1`
- Each line should be concatenate by line break `"\n"`
- If `n` is less than `4`, it should return `""`
- If `n` is odd, `a(n) = a(n - 1)`, eg `a(5) == a(4); a(9) == a(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.
Write a function which takes one parameter representing the dimensions of a checkered board. The board will always be square, so 5 means you will need a 5x5 board.
The dark squares will be represented by a unicode white square, while the light squares will be represented by a unicode black square (the opposite colours ensure the board doesn't look reversed on code wars' dark background). It should return a string of the board with a space in between each square and taking into account new lines.
An even number should return a board that begins with a dark square. An odd number should return a board that begins with a light square.
The input is expected to be a whole number that's at least two, and returns false otherwise (Nothing in Haskell).
Examples:
```python
checkered_board(5)
```
returns the string
```
β β‘ β β‘ β
β‘ β β‘ β β‘
β β‘ β β‘ β
β‘ β β‘ β β‘
β β‘ β β‘ β
```
**There should be no trailing white space at the end of each line, or new line characters at the end of the string.**
**Note**
Do not use HTML entities for the squares (e.g. `β‘` for white square) as the code doesn't consider it a valid square. A good way to check is if your solution prints a correct checker board on your local terminal.
**Ruby note:**
CodeWars has encoding issues with rendered unicode in Ruby.
You'll need to use unicode source code (e.g. "\u25A0") instead of rendered unicode (e.g "β ").
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are N integers, A_1, A_2, ..., A_N, written on a blackboard.
We will repeat the following operation N-1 times so that we have only one integer on the blackboard.
* Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.
Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.
Constraints
* 2 \leq N \leq 10^5
* -10^4 \leq A_i \leq 10^4
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.
Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.
If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.
M
x_1 y_1
:
x_{N-1} y_{N-1}
Output
Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.
Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.
If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.
M
x_1 y_1
:
x_{N-1} y_{N-1}
Examples
Input
3
1 -1 2
Output
4
-1 1
2 -2
Input
3
1 1 1
Output
1
1 1
1 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.
A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.
The store will work seven days a week, but not around the clock. Every day at least k people must work in the store.
Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly n consecutive days, then rest for exactly m days, then work for n more days and rest for m more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day x, then he should work on days [x, x + 1, ..., x + n - 1], [x + m + n, x + m + n + 1, ..., x + m + 2n - 1], and so on. Day x can be chosen arbitrarily by Vitaly.
There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day β otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.
Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least k working employees, and one of the working employees should have the key to the store.
Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.
Input
The first line contains three integers n, m and k (1 β€ m β€ n β€ 1000, n β 1, 1 β€ k β€ 1000).
Output
In the first line print a single integer z β the minimum required number of employees.
In the second line print z positive integers, separated by spaces: the i-th integer ai (1 β€ ai β€ 104) should represent the number of the day, on which Vitaly should hire the i-th employee.
If there are multiple answers, print any of them.
Examples
Input
4 3 2
Output
4
1 1 4 5
Input
3 3 1
Output
3
1 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.
Ivan wants to play a game with you. He picked some string $s$ of length $n$ consisting only of lowercase Latin letters.
You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $1$ to $n-1$), but he didn't tell you which strings are prefixes and which are suffixes.
Ivan wants you to guess which of the given $2n-2$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!
-----Input-----
The first line of the input contains one integer number $n$ ($2 \le n \le 100$) β the length of the guessed string $s$.
The next $2n-2$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $1$ to $n-1$ consisting only of lowercase Latin letters. They can be given in arbitrary order.
It is guaranteed that there are exactly $2$ strings of each length from $1$ to $n-1$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $n$.
-----Output-----
Print one string of length $2n-2$ β the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $i$-th character of this string should be 'P' if the $i$-th of the input strings is the prefix and 'S' otherwise.
If there are several possible answers, you can print any.
-----Examples-----
Input
5
ba
a
abab
a
aba
baba
ab
aba
Output
SPPSPSPS
Input
3
a
aa
aa
a
Output
PPSS
Input
2
a
c
Output
PS
-----Note-----
The only string which Ivan can guess in the first example is "ababa".
The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.
In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function that takes a Number as its argument and returns a Chinese numeral string. You don't need to validate the input argument, it will always be a Number in the range `[-99999.999, 99999.999]`, rounded to 8 decimal places.
Simplified Chinese numerals have characters representing each number from 0 to 9 and additional numbers representing larger numbers like 10, 100, 1000, and 10000.
```
0 lΓng ιΆ
1 yΔ« δΈ
2 Γ¨r δΊ
3 sΔn δΈ
4 sΓ¬ ε
5 wΗ δΊ
6 liΓΉ ε
7 qΔ« δΈ
8 bΔ ε
«
9 jiΗ δΉ
10 shΓ ε
100 bΗi ηΎ
1000 qiΔn ε
10000 wΓ n δΈ
```
Multiple-digit numbers are constructed by first the digit value (1 to 9) and then the place multiplier (such as 10, 100, 1000), starting with the most significant digit. A special case is made for 10 - 19 where the leading digit value (yΔ« δΈ) is dropped. Note that this special case is only made for the actual values 10 - 19, not any larger values.
```
10 ε
11 εδΈ
18 εε
«
21 δΊεδΈ
110 δΈηΎδΈε
123 δΈηΎδΊεδΈ
24681 δΊδΈεεε
ηΎε
«εδΈ
```
Trailing zeros are omitted, but interior zeros are grouped together and indicated by a single ιΆ character without giving the place multiplier.
```
10 ε
20 δΊε
104 δΈηΎιΆε
1004 δΈειΆε
10004 δΈδΈιΆε
10000 δΈδΈ
```
Decimal numbers are constructed by first writing the whole number part, and then inserting a point (diΗn ηΉ), followed by the decimal portion. The decimal portion is expressed using only the digits 0 to 9, without any positional characters and without grouping zeros.
```
0.1 ιΆηΉδΈ
123.45 δΈηΎδΊεδΈηΉεδΊ
```
Negative numbers are the same as other numbers, but add a θ΄ (fΓΉ) before the number.
For more information, please see http://en.wikipedia.org/wiki/Chinese_numerals.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
-----Input-----
The first line contains string a, and the second lineΒ β string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 10^5 characters.
-----Output-----
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output Β«-Β» (a minus sign).
-----Examples-----
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
-----Note-----
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string 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.
AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms.
For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition:
* For each room i\ (1 \leq i \leq N), if we leave Room i, pass through some passages whose levels are all equal and get back to Room i, the number of times we pass through a passage is always even.
Your task is to set levels to the passages so that the highest level of a passage is minimized.
Constraints
* N is an integer between 2 and 500 (inclusive).
Input
Input is given from Standard Input in the following format:
N
Output
Print one way to set levels to the passages so that the objective is achieved, as follows:
a_{1,2} a_{1,3} ... a_{1,N}
a_{2,3} ... a_{2,N}
.
.
.
a_{N-1,N}
Here a_{i,j} is the level of the passage connecting Room i and Room j.
If there are multiple solutions, any of them will be accepted.
Example
Input
3
Output
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.
The Aizu Wakamatsu city office decided to lay a hot water pipeline covering the whole area of the city to heat houses. The pipeline starts from some hot springs and connects every district in the city. The pipeline can fork at a hot spring or a district, but no cycle is allowed. The city office wants to minimize the length of pipeline in order to build it at the least possible expense.
Write a program to compute the minimal length of the pipeline. The program reads an input that consists of the following three parts:
Hint
The first line correspondings to the first part: there are three hot springs and five districts. The following three lines are the second part: the distances between a hot spring and a district. For instance, the distance between the first hot spring and the third district is 25. The last four lines are the third part: the distances between two districts. For instance, the distance between the second and the third districts is 9. The second hot spring and the fourth district are not connectable The second and the fifth districts are not connectable, either.
Input
* The first part consists of two positive integers in one line, which represent the number s of hot springs and the number d of districts in the city, respectively.
* The second part consists of s lines: each line contains d non-negative integers. The i-th integer in the j-th line represents the distance between the j-th hot spring and the i-th district if it is non-zero. If zero it means they are not connectable due to an obstacle between them.
* The third part consists of d-1 lines. The i-th line has d - i non-negative integers. The i-th integer in the j-th line represents the distance between the j-th and the (i + j)-th districts if it is non-zero. The meaning of zero is the same as mentioned above.
For the sake of simplicity, you can assume the following:
* The number of hot springs and that of districts do not exceed 50.
* Each distance is no more than 100.
* Each line in the input file contains at most 256 characters.
* Each number is delimited by either whitespace or tab.
The input has several test cases. The input terminate with a line which has two 0. The number of test cases is less than 20.
Output
Output the minimum length of pipeline for each test case.
Example
Input
3 5
12 8 25 19 23
9 13 16 0 17
20 14 16 10 22
17 27 18 16
9 7 0
19 5
21
0 0
Output
38
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy β she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of leaves Alyona has found. The next n lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.
Output
Output the single number β the number of Alyona's leaves.
Examples
Input
5
birch yellow
maple red
birch yellow
maple yellow
maple green
Output
4
Input
3
oak yellow
oak yellow
oak yellow
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.
DZY has a sequence a, consisting of n integers.
We'll call a sequence ai, ai + 1, ..., aj (1 β€ i β€ j β€ n) a subsegment of the sequence a. The value (j - i + 1) denotes the length of the subsegment.
Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
Input
The first line contains integer n (1 β€ n β€ 105). The next line contains n integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
In a single line print the answer to the problem β the maximum length of the required subsegment.
Examples
Input
6
7 2 3 1 5 6
Output
5
Note
You can choose subsegment a2, a3, a4, a5, a6 and change its 3rd element (that is a4) to 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.
Recently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most m different nucleotides, numbered from 1 to m. Special characteristics of the Martian DNA prevent some nucleotide pairs from following consecutively in this chain. For example, if the nucleotide 1 and nucleotide 2 can not follow consecutively in the Martian DNA, then the chain of nucleotides [1, 2] is not a valid chain of Martian DNA, but the chain of nucleotides [2, 1] can be a valid chain (if there is no corresponding restriction). The number of nucleotide pairs that can't follow in the DNA chain consecutively, is k.
The needs of gene research required information about the quantity of correct n-long chains of the Martian DNA. Your task is to write a program that will calculate this value.
Input
The first line contains three space-separated integers n, m, k (1 β€ n β€ 1015, 1 β€ m β€ 52, 0 β€ k β€ m2).
Next k lines contain two characters each, without a space between them, representing a forbidden nucleotide pair. The first character represents the first nucleotide in the forbidden pair, the second character represents the second nucleotide.
The nucleotides with assigned numbers from 1 to 26 are represented by English alphabet letters from "a" to "z" (1 is an "a", 2 is a "b", ..., 26 is a "z"). Nucleotides with assigned numbers from 27 to 52 are represented by English alphabet letters from "A" to "Z" (27 is an "A", 28 is a "B", ..., 52 is a "Z").
It is guaranteed that each forbidden pair occurs at most once in the input. It is guaranteed that nucleotide's numbers in all forbidden pairs cannot be more than m. Note that order is important in nucleotide pairs.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.
Output
Print a single integer β the sought number modulo 1000000007 (109 + 7).
Examples
Input
3 3 2
ab
ba
Output
17
Input
3 3 0
Output
27
Input
2 1 1
aa
Output
0
Note
In the second test case all possible three-nucleotide DNAs are permitted. Each nucleotide can take one of three values, thus in total there are 27 distinct three nucleotide DNAs.
In the third test sample we cannot make any DNA of two nucleotides β the only possible nucleotide "a" cannot occur two times consecutively.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.
Given is a string S. Find the minimum number of hugs needed to make S palindromic.
-----Constraints-----
- S is a string consisting of lowercase English letters.
- The length of S is between 1 and 100 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the minimum number of hugs needed to make S palindromic.
-----Sample Input-----
redcoder
-----Sample Output-----
1
For example, we can change the fourth character to o and get a palindrome redooder.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 rational number n
``` n >= 0, with denominator strictly positive```
- as a string (example: "2/3" in Ruby, Python, Clojure, JS, CS, Go)
- or as two strings (example: "2" "3" in Haskell, Java, CSharp, C++, Swift)
- or as a rational or decimal number (example: 3/4, 0.67 in R)
- or two integers (Fortran)
decompose
this number as a sum of rationals with numerators equal to one and without repetitions
(2/3 = 1/2 + 1/6 is correct but not 2/3 = 1/3 + 1/3, 1/3 is repeated).
The algorithm must be "greedy", so at each stage the new rational obtained in the decomposition must have a denominator as small as possible.
In this manner the sum of a few fractions in the decomposition gives a rather good approximation of the rational to decompose.
2/3 = 1/3 + 1/3 doesn't fit because of the repetition but also because the first 1/3 has a denominator bigger than the one in 1/2
in the decomposition 2/3 = 1/2 + 1/6.
### Example:
(You can see other examples in "Sample Tests:")
```
decompose("21/23") or "21" "23" or 21/23 should return
["1/2", "1/3", "1/13", "1/359", "1/644046"] in Ruby, Python, Clojure, JS, CS, Haskell, Go
"[1/2, 1/3, 1/13, 1/359, 1/644046]" in Java, CSharp, C++
"1/2,1/3,1/13,1/359,1/644046" in C, Swift, R
```
### Notes
1) The decomposition of 21/23 as
```
21/23 = 1/2 + 1/3 + 1/13 + 1/598 + 1/897
```
is exact but don't fulfill our requirement because 598 is bigger than 359.
Same for
```
21/23 = 1/2 + 1/3 + 1/23 + 1/46 + 1/69 (23 is bigger than 13)
or
21/23 = 1/2 + 1/3 + 1/15 + 1/110 + 1/253 (15 is bigger than 13).
```
2) The rational given to decompose could be greater than one or equal to one, in which case the first "fraction" will be an integer
(with an implicit denominator of 1).
3) If the numerator parses to zero the function "decompose" returns [] (or "".
4) The number could also be a decimal which can be expressed as a rational.
examples:
`0.6` in Ruby, Python, Clojure,JS, CS, Julia, Go
`"66" "100"` in Haskell, Java, CSharp, C++, C, Swift, Scala, Kotlin
`0.67` in R.
**Ref:**
http://en.wikipedia.org/wiki/Egyptian_fraction
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 prime number sequence starts with: `2,3,5,7,11,13,17,19...`. Notice that `2` is in position `one`.
`3` occupies position `two`, which is a prime-numbered position. Similarly, `5`, `11` and `17` also occupy prime-numbered positions. We shall call primes such as `3,5,11,17` dominant primes because they occupy prime-numbered positions in the prime number sequence. Let's call this `listA`.
As you can see from listA, for the prime range `range(0,10)`, there are `only two` dominant primes (`3` and `5`) and the sum of these primes is: `3 + 5 = 8`.
Similarly, as shown in listA, in the `range (6,20)`, the dominant primes in this range are `11` and `17`, with a sum of `28`.
Given a `range (a,b)`, what is the sum of dominant primes within that range? Note that `a <= range <= b` and `b` will not exceed `500000`.
Good luck!
If you like this Kata, you will enjoy:
[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
[Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b)
[Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?
-----Input-----
The first line contains a single integer n (1 β€ n β€ 100).
The next line contains an integer p (0 β€ p β€ n) at first, then follows p distinct integers a_1, a_2, ..., a_{p} (1 β€ a_{i} β€ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.
-----Output-----
If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).
-----Examples-----
Input
4
3 1 2 3
2 2 4
Output
I become the guy.
Input
4
3 1 2 3
2 2 3
Output
Oh, my keyboard!
-----Note-----
In the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.
In the second sample, no one can pass level 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.
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)?
The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the N - 1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive.
-----Input-----
The only line of input contains one integer: N, the number of attendees (1 β€ N β€ 10^9).
-----Output-----
Output one integer: the smallest number of brains in the chest which allows Heidi to merely survive.
-----Examples-----
Input
1
Output
0
Input
3
Output
1
Input
99
Output
49
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.
The display is represented by n Γ n square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to n upside down, the columns are numbered with integers from 1 to n from the left to the right. The display can perform commands like "x, y". When a traditional display fulfills such command, it simply inverts a color of (x, y), where x is the row number and y is the column number. But in our new display every pixel that belongs to at least one of the segments (x, x) - (x, y) and (y, y) - (x, y) (both ends of both segments are included) inverts a color.
For example, if initially a display 5 Γ 5 in size is absolutely white, then the sequence of commands (1, 4), (3, 5), (5, 1), (3, 3) leads to the following changes:
<image>
You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.
Input
The first line contains number n (1 β€ n β€ 2000).
Next n lines contain n characters each: the description of the picture that needs to be shown. "0" represents the white color and "1" represents the black color.
Output
Print one integer z β the least number of commands needed to display the picture.
Examples
Input
5
01110
10010
10001
10011
11110
Output
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.
In this Kata, you will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows.
```Haskell
Solve("*'&ABCDabcde12345") = [4,5,5,3].
--the order is: uppercase letters, lowercase, numbers and special characters.
```
More examples in the test cases.
Good luck!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little penguin Polo adores integer segments, that is, pairs of integers [l;Β r] (l β€ r).
He has a set that consists of n integer segments: [l_1;Β r_1], [l_2;Β r_2], ..., [l_{n};Β r_{n}]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l;Β r] to either segment [l - 1;Β r], or to segment [l;Β r + 1].
The value of a set of segments that consists of n segments [l_1;Β r_1], [l_2;Β r_2], ..., [l_{n};Β r_{n}] is the number of integers x, such that there is integer j, for which the following inequality holds, l_{j} β€ x β€ r_{j}.
Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.
-----Input-----
The first line contains two integers n and k (1 β€ n, k β€ 10^5). Each of the following n lines contain a segment as a pair of integers l_{i} and r_{i} ( - 10^5 β€ l_{i} β€ r_{i} β€ 10^5), separated by a space.
It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 β€ i < j β€ n) the following inequality holds, min(r_{i}, r_{j}) < max(l_{i}, l_{j}).
-----Output-----
In a single line print a single integer β the answer to the problem.
-----Examples-----
Input
2 3
1 2
3 4
Output
2
Input
3 7
1 2
3 3
4 7
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 a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.
It can be shown that the process marks all nodes in the tree.
The final array a is the list of the nodes' labels in order of the time each node was marked.
Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.
The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).
Input
The first line contains a single integer n (2 β€ n β€ 200) β the number of nodes in the tree.
The next n - 1 lines each contains two integers x and y (1 β€ x, y β€ n; x β y), denoting an edge between node x and y.
It's guaranteed that the given edges form a tree.
Output
Output the expected number of inversions in the generated array modulo 10^9+7.
Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not β‘ 0 \pmod{M}. Output the integer equal to p β
q^{-1} mod M. In other words, output such an integer x that 0 β€ x < M and x β
q β‘ p \pmod{M}.
Examples
Input
3
1 2
1 3
Output
166666669
Input
6
2 1
2 3
6 1
1 4
2 5
Output
500000009
Input
5
1 2
1 3
1 4
2 5
Output
500000007
Note
This is the tree from the first sample:
<image>
For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3β
1 + 1/3 β
2 + 1/3 β
(1/2 β
0 + 1/2 β
1) = 7/6.
166666669 β
6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.
This is the tree from the second sample:
<image>
This is the tree from the third sample:
<image>
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In Berland, $n$ different types of banknotes are used. Banknotes of the $i$-th type have denomination $10^{a_i}$ burles (burles are the currency used in Berland); the denomination of banknotes of the first type is exactly $1$.
Let's denote $f(s)$ as the minimum number of banknotes required to represent exactly $s$ burles. For example, if the denominations of banknotes used in Berland are $1$, $10$ and $100$, then $f(59) = 14$: $9$ banknotes with denomination of $1$ burle and $5$ banknotes with denomination of $10$ burles can be used to represent exactly $9 \cdot 1 + 5 \cdot 10 = 59$ burles, and there's no way to do it with fewer banknotes.
For a given integer $k$, find the minimum positive number of burles $s$ that cannot be represented with $k$ or fewer banknotes (that is, $f(s) > k$).
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) β number of test cases.
The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 10; 1 \le k \le 10^9$).
The next line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 = a_1 < a_2 < \dots < a_n \le 9$).
-----Output-----
For each test case, print one integer β the minimum positive number of burles $s$ that cannot be represented with $k$ or fewer banknotes.
-----Examples-----
Input
4
3 13
0 1 2
2 777
0 4
3 255
0 1 3
10 1000000000
0 1 2 3 4 5 6 7 8 9
Output
59
778
148999
999999920999999999
-----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.
Snuke has a calculator. It has a display and two buttons.
Initially, the display shows an integer x. Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:
* Button A: When pressed, the value on the display is incremented by 1.
* Button B: When pressed, the sign of the value on the display is reversed.
Find the minimum number of times Snuke needs to press the buttons to achieve his objective. It can be shown that the objective is always achievable regardless of the values of the integers x and y.
Constraints
* x and y are integers.
* |x|, |y| β€ 10^9
* x and y are different.
Input
The input is given from Standard Input in the following format:
x y
Output
Print the minimum number of times Snuke needs to press the buttons to achieve his objective.
Examples
Input
10 20
Output
10
Input
10 -10
Output
1
Input
-10 -20
Output
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.
The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
- It must start with a hashtag (`#`).
- All words must have their first letter capitalized.
- If the final result is longer than 140 chars it must return `false`.
- If the input or the result is an empty string it must return `false`.
## Examples
```
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Entrance Examination
The International Competitive Programming College (ICPC) is famous for its research on competitive programming. Applicants to the college are required to take its entrance examination.
The successful applicants of the examination are chosen as follows.
* The score of any successful applicant is higher than that of any unsuccessful applicant.
* The number of successful applicants n must be between nmin and nmax, inclusive. We choose n within the specified range that maximizes the gap. Here, the gap means the difference between the lowest score of successful applicants and the highest score of unsuccessful applicants.
* When two or more candidates for n make exactly the same gap, use the greatest n among them.
Let's see the first couple of examples given in Sample Input below. In the first example, nmin and nmax are two and four, respectively, and there are five applicants whose scores are 100, 90, 82, 70, and 65. For n of two, three and four, the gaps will be 8, 12, and 5, respectively. We must choose three as n, because it maximizes the gap.
In the second example, nmin and nmax are two and four, respectively, and there are five applicants whose scores are 100, 90, 80, 75, and 65. For n of two, three and four, the gap will be 10, 5, and 10, respectively. Both two and four maximize the gap, and we must choose the greatest number, four.
You are requested to write a program that computes the number of successful applicants that satisfies the conditions.
Input
The input consists of multiple datasets. Each dataset is formatted as follows.
> m nmin nmax
> P1
> P2
> ...
> Pm
>
The first line of a dataset contains three integers separated by single spaces. m represents the number of applicants, nmin represents the minimum number of successful applicants, and nmax represents the maximum number of successful applicants. Each of the following m lines contains an integer Pi, which represents the score of each applicant. The scores are listed in descending order. These numbers satisfy 0 < nmin < nmax < m β€ 200, 0 β€ Pi β€ 10000 (1 β€ i β€ m) and Pnmin > Pnmax+1. These ensure that there always exists an n satisfying the conditions.
The end of the input is represented by a line containing three zeros separated by single spaces.
Output
For each dataset, output the number of successful applicants in a line.
Sample Input
5 2 4
100
90
82
70
65
5 2 4
100
90
80
75
65
3 1 2
5000
4000
3000
4 2 3
10000
10000
8000
8000
4 2 3
10000
10000
10000
8000
5 2 3
100
80
68
60
45
0 0 0
Output for the Sample Input
3
4
2
2
3
2
Example
Input
5 2 4
100
90
82
70
65
5 2 4
100
90
80
75
65
3 1 2
5000
4000
3000
4 2 3
10000
10000
8000
8000
4 2 3
10000
10000
10000
8000
5 2 3
100
80
68
60
45
0 0 0
Output
3
4
2
2
3
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.
Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.
A subtree of some vertex is a subgraph containing that vertex and all its descendants.
Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed.
Input
The first line contains single integer n (2 β€ n β€ 105) β the number of vertices in the tree.
Each of the next n - 1 lines contains two integers u and v (1 β€ u, v β€ n, u β v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree.
The next line contains n integers c1, c2, ..., cn (1 β€ ci β€ 105), denoting the colors of the vertices.
Output
Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him.
Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them.
Examples
Input
4
1 2
2 3
3 4
1 2 1 1
Output
YES
2
Input
3
1 2
2 3
1 2 3
Output
YES
2
Input
4
1 2
2 3
3 4
1 2 1 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.
Gift Exchange Party
A gift exchange party will be held at a school in TKB City.
For every pair of students who are close friends, one gift must be given from one to the other at this party, but not the other way around. It is decided in advance the gift directions, that is, which student of each pair receives a gift. No other gift exchanges are made.
If each pair randomly decided the gift direction, some might receive countless gifts, while some might receive only few or even none.
You'd like to decide the gift directions for all the friend pairs that minimize the difference between the smallest and the largest numbers of gifts received by a student. Find the smallest and the largest numbers of gifts received when the difference between them is minimized. When there is more than one way to realize that, find the way that maximizes the smallest number of received gifts.
Input
The input consists of at most 10 datasets, each in the following format.
n m
u1 v1
...
um vm
n is the number of students, and m is the number of friendship relations (2 β€ n β€ 100, 1 β€ m β€ n (n-1)/2). Students are denoted by integers between 1 and n, inclusive. The following m lines describe the friendship relations: for each i, student ui and vi are close friends (ui < vi). The same friendship relations do not appear more than once.
The end of the input is indicated by a line containing two zeros.
Output
For each dataset, output a single line containing two integers l and h separated by a single space. Here, l and h are the smallest and the largest numbers, respectively, of gifts received by a student.
Sample Input
3 3
1 2
2 3
1 3
4 3
1 2
1 3
1 4
4 6
1 2
1 3
1 4
2 3
3 4
2 4
0 0
Output for the Sample Input
1 1
0 1
1 2
Example
Input
3 3
1 2
2 3
1 3
4 3
1 2
1 3
1 4
4 6
1 2
1 3
1 4
2 3
3 4
2 4
0 0
Output
1 1
0 1
1 2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.
You have to find minimum k such that there exists at least one k-dominant character.
-----Input-----
The first line contains string s consisting of lowercase Latin letters (1 β€ |s| β€ 100000).
-----Output-----
Print one number β the minimum value of k such that there exists at least one k-dominant character.
-----Examples-----
Input
abacaba
Output
2
Input
zzzzz
Output
1
Input
abcde
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.
J - Tree Reconstruction
Problem Statement
You have a directed graph. Some non-negative value is assigned on each edge of the graph. You know that the value of the graph satisfies the flow conservation law That is, for every node v, the sum of values on edges incoming to v equals to the sum of values of edges outgoing from v. For example, the following directed graph satisfies the flow conservation law.
<image>
Suppose that you choose a subset of edges in the graph, denoted by E', and then you erase all the values on edges other than E'. Now you want to recover the erased values by seeing only remaining information. Due to the flow conservation law, it may be possible to recover all the erased values. Your task is to calculate the smallest possible size for such E'.
For example, the smallest subset E' for the above graph will be green edges in the following figure. By the flow conservation law, we can recover values on gray edges.
<image>
Input
The input consists of multiple test cases. The format of each test case is as follows.
N M
s_1 t_1
...
s_M t_M
The first line contains two integers N (1 \leq N \leq 500) and M (0 \leq M \leq 3,000) that indicate the number of nodes and edges, respectively. Each of the following M lines consists of two integers s_i and t_i (1 \leq s_i, t_i \leq N). This means that there is an edge from s_i to t_i in the graph.
You may assume that the given graph is simple:
* There are no self-loops: s_i \neq t_i.
* There are no multi-edges: for all i < j, \\{s_i, t_i\\} \neq \\{s_j, t_j\\}.
Also, it is guaranteed that each component of the given graph is strongly connected. That is, for every pair of nodes v and u, if there exist a path from v to u, then there exists a path from u to v.
Note that you are NOT given information of values on edges because it does not effect the answer.
Output
For each test case, print an answer in one line.
Sample Input 1
9 13
1 2
1 3
2 9
3 4
3 5
3 6
4 9
5 7
6 7
6 8
7 9
8 9
9 1
Output for the Sample Input 1
5
Sample Input 2
7 9
1 2
1 3
2 4
3 4
4 5
4 6
5 7
6 7
7 1
Output for the Sample Input 2
3
Sample Input 3
4 4
1 2
2 1
3 4
4 3
Output for the Sample Input 3
2
Example
Input
9 13
1 2
1 3
2 9
3 4
3 5
3 6
4 9
5 7
6 7
6 8
7 9
8 9
9 1
Output
5
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
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.
4 different points on the plane Read the coordinates of $ A (x_a, y_a) $, $ B (x_b, y_b) $, $ C (x_c, y_c) $, $ D (x_d, y_d) $ and read those 4 points Create a program that outputs YES if there is no dent in the quadrangle $ ABCD $ with the coordinates as the vertices, and NO if there is a dent.
A quadrangle with a dent is a quadrangle as shown in Figure 1.
<image>
Input
Given multiple datasets. The format of each dataset is as follows.
$ x_a $, $ y_a $, $ x_b $, $ y_b $, $ x_c $, $ y_c $, $ x_d $, $ y_d $
$ x_a $, $ y_a $, $ x_b $, $ y_b $, $ x_c $, $ y_c $, $ x_d $, $ y_d $ are -100 or more and 100 or less, respectively, and are given as real numbers.
1 No more than two points can be lined up on a straight line. Also, if you connect the points in the order of input, the coordinates of the points will be input in the order of forming a quadrangle. (That is, the points are not given in the order shown in Figure 2.)
The number of datasets does not exceed 100.
Output
Print YES or NO on one line for each dataset.
Example
Input
0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0
0.0,0.0,3.0,0.0,1.0,1.0,1.0,3.0
Output
YES
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two strings of equal length $s$ and $t$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.
For example, if $s$ is "acbc" you can get the following strings in one operation: "aabc" (if you perform $s_2 = s_1$); "ccbc" (if you perform $s_1 = s_2$); "accc" (if you perform $s_3 = s_2$ or $s_3 = s_4$); "abbc" (if you perform $s_2 = s_3$); "acbb" (if you perform $s_4 = s_3$);
Note that you can also apply this operation to the string $t$.
Please determine whether it is possible to transform $s$ into $t$, applying the operation above any number of times.
Note that you have to answer $q$ independent queries.
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 100$)Β β the number of queries. Each query is represented by two consecutive lines.
The first line of each query contains the string $s$ ($1 \le |s| \le 100$) consisting of lowercase Latin letters.
The second line of each query contains the string $t$ ($1 \le |t| \leq 100$, $|t| = |s|$) consisting of lowercase Latin letters.
-----Output-----
For each query, print "YES" if it is possible to make $s$ equal to $t$, and "NO" otherwise.
You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes", and "YES" will all be recognized as positive answer).
-----Example-----
Input
3
xabb
aabx
technocup
technocup
a
z
Output
YES
YES
NO
-----Note-----
In the first query, you can perform two operations $s_1 = s_2$ (after it $s$ turns into "aabb") and $t_4 = t_3$ (after it $t$ turns into "aabb").
In the second query, the strings are equal initially, so the answer is "YES".
In the third query, you can not make strings $s$ and $t$ equal. Therefore, 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.
A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.
A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.
The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.
All students are divided into three groups: r of them like to ascend only in the red cablecars, g of them prefer only the green ones and b of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,
The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.
Input
The first line contains three integers r, g and b (0 β€ r, g, b β€ 100). It is guaranteed that r + g + b > 0, it means that the group consists of at least one student.
Output
Print a single number β the minimal time the students need for the whole group to ascend to the top of the mountain.
Examples
Input
1 3 2
Output
34
Input
3 2 1
Output
33
Note
Let's analyze the first sample.
At the moment of time 0 a red cablecar comes and one student from the r group get on it and ascends to the top at the moment of time 30.
At the moment of time 1 a green cablecar arrives and two students from the g group get on it; they get to the top at the moment of time 31.
At the moment of time 2 comes the blue cablecar and two students from the b group get on it. They ascend to the top at the moment of time 32.
At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.
At the moment of time 4 a green cablecar arrives and one student from the g group gets on it. He ascends to top at the moment of time 34.
Thus, all the students are on the top, overall the ascension took exactly 34 minutes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function that takes a list of one or more non-negative integers, and arranges them such that they form the largest possible number.
Examples:
`largestArrangement([4, 50, 8, 145])` returns 8504145 (8-50-4-145)
`largestArrangement([4, 40, 7])` returns 7440 (7-4-40)
`largestArrangement([4, 46, 7])` returns 7464 (7-46-4)
`largestArrangement([5, 60, 299, 56])` returns 60565299 (60-56-5-299)
`largestArrangement([5, 2, 1, 9, 50, 56])` returns 95655021 (9-56-5-50-21)
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After passing a test, Vasya got himself a box of $n$ candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.
This means the process of eating candies is the following: in the beginning Vasya chooses a single integer $k$, same for all days. After that, in the morning he eats $k$ candies from the box (if there are less than $k$ candies in the box, he eats them all), then in the evening Petya eats $10\%$ of the candies remaining in the box. If there are still candies left in the box, the process repeatsΒ β next day Vasya eats $k$ candies again, and PetyaΒ β $10\%$ of the candies left in a box, and so on.
If the amount of candies in the box is not divisible by $10$, Petya rounds the amount he takes from the box down. For example, if there were $97$ candies in the box, Petya would eat only $9$ of them. In particular, if there are less than $10$ candies in a box, Petya won't eat any at all.
Your task is to find out the minimal amount of $k$ that can be chosen by Vasya so that he would eat at least half of the $n$ candies he initially got. Note that the number $k$ must be integer.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^{18}$)Β β the initial amount of candies in the box.
-----Output-----
Output a single integerΒ β the minimal amount of $k$ that would allow Vasya to eat at least half of candies he got.
-----Example-----
Input
68
Output
3
-----Note-----
In the sample, the amount of candies, with $k=3$, would change in the following way (Vasya eats first):
$68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0$.
In total, Vasya would eat $39$ candies, while PetyaΒ β $29$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Did you ever hear about 'Dragon Food' ? Its used to refer to the chocolates bought for your loved ones :). Po offers dragon food to master Shifu, who is a famous cook in the valley of food. In return, Shifu hands over the dragon scroll to Po, which is said to hold the ingredients of the secret recipe. To open the dragon scroll, one has to solve the following puzzle.
1. Consider a N-bit integer A. We call an integer A' as shuffle-A, if A' can be obtained by shuffling the bits of A in its binary representation. For eg. if N = 5 and A = 6 = (00110)_{2}, A' can be any 5-bit integer having exactly two 1s in it i.e., any of (00011)_{2}, (00101)_{2}, (00110)_{2}, (01010)_{2}, ...., (11000)_{2}.
2. Given two N-bit integers A and B, find the maximum possible value of (A' xor B') where A' is a shuffle-A, B' is a shuffle-B and xor is the bit-wise xor operator.
Given N, A and B, please help Po in opening the dragon scroll.
Notes
1. xor operator takes two bit strings of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 OR only the second bit is 1, but will be 0 if both are 1 or both are 0. For eg: 5 (0101) xor 3(0011) = 6(0110). In most languages it is represented using ^ symbol. 5 ^ 3 = 6.
2. If the integer actually needs less than N bits to represent in binary, append sufficient number of leading 0 bits. For eg. as shown in the problem statement for N = 5, A = 6 = (00110)_{2}
------ Input ------
First line contains an integer T ( number of test cases, around 100 ). T cases follow, each having N A B in a single line, separated by a space. ( 1 β€ N β€ 30, 0 β€ A,B < 2^{N} )
------ Output ------
For each case, output the maximum possible value of (shuffle-A xor shuffle-B) in a separate line.
----- Sample Input 1 ------
3
3 5 4
5 0 1
4 3 7
----- Sample Output 1 ------
7
16
14
----- explanation 1 ------
Case 1: 5 and 4 as 3-bit binary strings are (101)2 and (100)2 respectively. After shuffling, xor can be maximum for (110)2 ^ (001)2 = (111)2 = 7
Case 2: Maximum Possible result can be for (00000)2 ^ (10000)2 = (10000)2 = 16
Case 3: Maximum Possible result can be for (0011)2 ^ (1101)2 = (1110)2 = 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.
Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.
Help Kurt find the maximum possible product of digits among all integers from $1$ to $n$.
-----Input-----
The only input line contains the integer $n$ ($1 \le n \le 2\cdot10^9$).
-----Output-----
Print the maximum product of digits among all integers from $1$ to $n$.
-----Examples-----
Input
390
Output
216
Input
7
Output
7
Input
1000000000
Output
387420489
-----Note-----
In the first example the maximum product is achieved for $389$ (the product of digits is $3\cdot8\cdot9=216$).
In the second example the maximum product is achieved for $7$ (the product of digits is $7$).
In the third example the maximum product is achieved for $999999999$ (the product of digits is $9^9=387420489$).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.
You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.
You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.
The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as <image>, where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.
The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.
Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.
Input
The first line contains a single integer n (1 β€ n β€ 4) β the number of words in Lesha's problem. The second line contains n space-separated words β the short description of the problem.
The third line contains a single integer m (1 β€ m β€ 10) β the number of problems in the Torcoder.com archive. Next m lines contain the descriptions of the problems as "k s1 s2 ... sk", where k (1 β€ k β€ 20) is the number of words in the problem and si is a word of the problem description.
All words from all problem descriptions contain no more than 10 lowercase English letters.
Output
If Lesha's problem is brand new, print string "Brand new problem!" (without quotes).
Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated p times, and characters :], where p is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input.
Examples
Input
4
find the next palindrome
1
10 find the previous palindrome or print better luck next time
Output
1
[:||||||:]
Input
3
add two numbers
3
1 add
2 two two
3 numbers numbers numbers
Output
Brand new problem!
Input
4
these papers are formulas
3
6 what are these formulas and papers
5 papers are driving me crazy
4 crazy into the night
Output
1
[:||||:]
Input
3
add two decimals
5
4 please two decimals add
5 decimals want to be added
4 two add decimals add
4 add one two three
7 one plus two plus three equals six
Output
3
[:|||:]
Note
Let us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions β pairs of words "numbers" and "add", "numbers" and "two".
Sequence b1, b2, ..., bk is a subsequence of sequence a1, a2, ..., an if there exists such a set of indices 1 β€ i1 < i2 < ... < ik β€ n that aij = bj (in other words, if sequence b can be obtained from a by deleting some of its elements).
In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next").
In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 will define Ginkgo numbers and multiplication on Ginkgo numbers.
A Ginkgo number is a pair <m, n> where m and n are integers. For example, <1, 1>, <-2, 1> and <-3,-1> are Ginkgo numbers.
The multiplication on Ginkgo numbers is defined by <m, n> * <x, y> = <mx β ny, my + nx>. For example, <1, 1> * <-2, 1> = <-3,-1>.
A Ginkgo number <m, n> is called a divisor of a Ginkgo number <p, q> if there exists a Ginkgo number <x, y> such that <m, n> * <x, y> = <p, q>.
For any Ginkgo number <m, n>, Ginkgo numbers <1, 0>, <0, 1>, <-1, 0>, <0,-1>, <m, n>, <-n,m>, <-m,-n> and <n,-m> are divisors of <m, n>. If m2+n2 > 1, these Ginkgo numbers are distinct. In other words, any Ginkgo number such that m2 + n2 > 1 has at least eight divisors.
A Ginkgo number <m, n> is called a prime if m2+n2 > 1 and it has exactly eight divisors. Your mission is to check whether a given Ginkgo number is a prime or not.
The following two facts might be useful to check whether a Ginkgo number is a divisor of another Ginkgo number.
* Suppose m2 + n2 > 0. Then, <m, n> is a divisor of <p, q> if and only if the integer m2 + n2 is a common divisor of mp + nq and mq β np.
* If <m, n> * <x, y> = <p, q>, then (m2 + n2)(x2 + y2) = p2 + q2.
Input
The first line of the input contains a single integer, which is the number of datasets.
The rest of the input is a sequence of datasets. Each dataset is a line containing two integers m and n, separated by a space. They designate the Ginkgo number <m, n>. You can assume 1 < m2 + n2 < 20000.
Output
For each dataset, output a character 'P' in a line if the Ginkgo number is a prime. Output a character 'C' in a line otherwise.
Example
Input
8
10 0
0 2
-3 0
4 2
0 -13
-4 1
-2 -1
3 -1
Output
C
C
P
C
C
P
P
C
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ consisting of $n$ positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by $2$) or determine that there is no such subset.
Both the given array and required subset may contain equal values.
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 100$), number of test cases to solve. Descriptions of $t$ test cases follow.
A description of each test case consists of two lines. The first line contains a single integer $n$ ($1 \leq n \leq 100$), length of array $a$.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 100$), elements of $a$. The given array $a$ can contain equal values (duplicates).
-----Output-----
For each test case output $-1$ if there is no such subset of elements. Otherwise output positive integer $k$, number of elements in the required subset. Then output $k$ distinct integers ($1 \leq p_i \leq n$), indexes of the chosen elements. If there are multiple solutions output any of them.
-----Example-----
Input
3
3
1 4 3
1
15
2
3 5
Output
1
2
-1
2
1 2
-----Note-----
There are three test cases in the example.
In the first test case, you can choose the subset consisting of only the second element. Its sum is $4$ and it is even.
In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.
In the third test case, the subset consisting of all array's elements has even 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.
Jump is a simple one-player game:
You are initially at the first cell of an array of cells containing non-negative integers;
At each step you can jump ahead in the array as far as the integer at the current cell, or any smaller number of cells.
You win if there is a path that allows you to jump from one cell to another, eventually jumping past the end of the array, otherwise you lose.
For instance, if the array contains the integers
`[2, 0, 3, 5, 0, 0, 3, 0, 0, 3, 1, 0]`,
you can win by jumping from **2**, to **3**, to **5**, to **3**, to **3**, then past the end of the array.
You can also directly jump from from the initial cell(first cell) past the end of the array if they are integers to the right of that cell.
E.g
`[6, 1, 1]` is winnable
`[6]` is **not** winnable
Note: You can **not** jump from the last cell!
`[1, 1, 3]` is **not** winnable
## -----
Your task is to complete the function `canJump()` that determines if a given game is winnable.
### More Examples
``` javascript
canJump([5]) //=> false
canJump([2, 5]) //=> true
canJump([3, 0, 2, 3]) //=> true (3 to 2 then past end of array)
canJump([4, 1, 2, 0, 1]) //=> false
canJump([5, 0, 0, 0]) //=> true
canJump([1, 1]) //=> false
```
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).
Input
The first line contains the integer n (2 β€ n β€ 2Β·105). The second line contains elements of the sequence a1, a2, ..., an (1 β€ ai β€ 1000). All the elements are positive integers.
Output
Print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n.
If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.
Examples
Input
5
1 2 3 4 5
Output
1
3
Input
4
50 50 50 50
Output
4
1 2 3 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.
k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.
Determine if Snark and Philip can make an interesting problemset!
-----Input-----
The first line contains two integers n, k (1 β€ n β€ 10^5, 1 β€ k β€ 4)Β β the number of problems and the number of experienced teams.
Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.
-----Output-----
Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise.
You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").
-----Examples-----
Input
5 3
1 0 1
1 1 0
1 0 0
1 0 0
1 0 0
Output
NO
Input
3 2
1 0
1 1
0 1
Output
YES
-----Note-----
In the first example you can't make any interesting problemset, because the first team knows all problems.
In the second example you can choose the first and the third problems.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.
You are given the sequence A and q questions where each question contains Mi.
Notes
You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:
solve(0, M)
solve(1, M-{sum created from elements before 1st element})
solve(2, M-{sum created from elements before 2nd element})
...
The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.
For example, the following figure shows that 8 can be made by A[0] + A[2].
<image>
Constraints
* n β€ 20
* q β€ 200
* 1 β€ elements in A β€ 2000
* 1 β€ Mi β€ 2000
Input
In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.
Output
For each question Mi, print yes or no.
Example
Input
5
1 5 7 10 21
8
2 4 17 8 22 21 100 35
Output
no
no
yes
yes
yes
yes
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.
Casimir has a rectangular piece of paper with a checkered field of size $n \times m$. Initially, all cells of the field are white.
Let us denote the cell with coordinates $i$ vertically and $j$ horizontally by $(i, j)$. The upper left cell will be referred to as $(1, 1)$ and the lower right cell as $(n, m)$.
Casimir draws ticks of different sizes on the field. A tick of size $d$ ($d > 0$) with its center in cell $(i, j)$ is drawn as follows:
First, the center cell $(i, j)$ is painted black.
Then exactly $d$ cells on the top-left diagonally to the center and exactly $d$ cells on the top-right diagonally to the center are also painted black.
That is all the cells with coordinates $(i - h, j \pm h)$ for all $h$ between $0$ and $d$ are painted. In particular, a tick consists of $2d + 1$ black cells.
An already painted cell will remain black if painted again. Below you can find an example of the $4 \times 9$ box, with two ticks of sizes $2$ and $3$.
You are given a description of a checkered field of size $n \times m$. Casimir claims that this field came about after he drew some (possibly $0$) ticks on it. The ticks could be of different sizes, but the size of each tick is at least $k$ (that is, $d \ge k$ for all the ticks).
Determine whether this field can indeed be obtained by drawing some (possibly none) ticks of sizes $d \ge k$ or not.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 100$) β the number test cases.
The following lines contain the descriptions of the test cases.
The first line of the test case description contains the integers $n$, $m$, and $k$ ($1 \le k \le n \le 10$; $1 \le m \le 19$) β the field size and the minimum size of the ticks that Casimir drew. The following $n$ lines describe the field: each line consists of $m$ characters either being '.' if the corresponding cell is not yet painted or '*' otherwise.
-----Output-----
Print $t$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if the given field can be obtained by drawing ticks of at least the given size and NO otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).
-----Examples-----
Input
8
2 3 1
*.*
...
4 9 2
*.*.*...*
.*.*...*.
..*.*.*..
.....*...
4 4 1
*.*.
****
.**.
....
5 5 1
.....
*...*
.*.*.
..*.*
...*.
5 5 2
.....
*...*
.*.*.
..*.*
...*.
4 7 1
*.....*
.....*.
..*.*..
...*...
3 3 1
***
***
***
3 5 1
*...*
.***.
.**..
Output
NO
YES
YES
YES
NO
NO
NO
NO
-----Note-----
The first sample test case consists of two asterisks neither of which can be independent ticks since ticks of size $0$ don't exist.
The second sample test case is already described in the statement (check the picture in the statement). This field can be obtained by drawing ticks of sizes $2$ and $3$, as shown in the figure.
The field in the third sample test case corresponds to three ticks of size $1$. Their center cells are marked with $\color{blue}{\text{blue}}$, ${\text{red}}$ and $\color{green}{\text{green}}$ colors:
*.*.
*$\color{blue}{\textbf{*}}$**
.$\color{green}{\textbf{*}}{\textbf{*}}$.
....
The field in the fourth sample test case could have been obtained by drawing two ticks of sizes $1$ and $2$. Their vertices are marked below with $\color{blue}{\text{blue}}$ and ${\text{red}}$ colors respectively:
.....
*...*
.*.*.
..${\textbf{*}}$.*
...$\color{blue}{\textbf{*}}$.
The field in the fifth sample test case can not be obtained because $k = 2$, and the last asterisk in the fourth row from the top with coordinates $(4, 5)$ can only be a part of a tick of size $1$.
The field in the sixth sample test case can not be obtained because the top left asterisk $(1, 1)$ can't be an independent tick, since the sizes of the ticks must be positive, and cannot be part of a tick with the center cell in the last row, since it is separated from it by a gap (a point, '.') in $(2, 2)$.
In the seventh sample test case, similarly, the field can not be obtained by the described process because the asterisks with coordinates $(1, 2)$ (second cell in the first row), $(3, 1)$ and $(3, 3)$ (leftmost and rightmost cells in the bottom) can not be parts of any ticks.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Gildong is playing with his dog, Badugi. They're at a park that has $n$ intersections and $n-1$ bidirectional roads, each $1$ meter in length and connecting two intersections with each other. The intersections are numbered from $1$ to $n$, and for every $a$ and $b$ ($1 \le a, b \le n$), it is possible to get to the $b$-th intersection from the $a$-th intersection using some set of roads.
Gildong has put one snack at every intersection of the park. Now Gildong will give Badugi a mission to eat all of the snacks. Badugi starts at the $1$-st intersection, and he will move by the following rules:
Badugi looks for snacks that are as close to him as possible. Here, the distance is the length of the shortest path from Badugi's current location to the intersection with the snack. However, Badugi's sense of smell is limited to $k$ meters, so he can only find snacks that are less than or equal to $k$ meters away from himself. If he cannot find any such snack, he fails the mission.
Among all the snacks that Badugi can smell from his current location, he chooses a snack that minimizes the distance he needs to travel from his current intersection. If there are multiple such snacks, Badugi will choose one arbitrarily.
He repeats this process until he eats all $n$ snacks. After that, he has to find the $1$-st intersection again which also must be less than or equal to $k$ meters away from the last snack he just ate. If he manages to find it, he completes the mission. Otherwise, he fails the mission.
Unfortunately, Gildong doesn't know the value of $k$. So, he wants you to find the minimum value of $k$ that makes it possible for Badugi to complete his mission, if Badugi moves optimally.
-----Input-----
Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$).
The first line of each test case contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) β the number of intersections of the park.
The next $n-1$ lines contain two integers $u$ and $v$ ($1 \le u,v \le n$, $u \ne v$) each, which means there is a road between intersection $u$ and $v$. All roads are bidirectional and distinct.
It is guaranteed that:
For each test case, for every $a$ and $b$ ($1 \le a, b \le n$), it is possible to get to the $b$-th intersection from the $a$-th intersection.
The sum of $n$ in all test cases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case, print one integer β the minimum possible value of $k$ such that Badugi can complete the mission.
-----Examples-----
Input
3
3
1 2
1 3
4
1 2
2 3
3 4
8
1 2
2 3
3 4
1 5
5 6
6 7
5 8
Output
2
3
3
-----Note-----
In the first case, Badugi can complete his mission with $k=2$ by moving as follows:
Initially, Badugi is at the $1$-st intersection. The closest snack is obviously at the $1$-st intersection, so he just eats it.
Next, he looks for the closest snack, which can be either the one at the $2$-nd or the one at the $3$-rd intersection. Assume that he chooses the $2$-nd intersection. He moves to the $2$-nd intersection, which is $1$ meter away, and eats the snack.
Now the only remaining snack is on the $3$-rd intersection, and he needs to move along $2$ paths to get to it.
After eating the snack at the $3$-rd intersection, he needs to find the $1$-st intersection again, which is only $1$ meter away. As he gets back to it, he completes the mission.
In the second case, the only possible sequence of moves he can make is $1$ β $2$ β $3$ β $4$ β $1$. Since the distance between the $4$-th intersection and the $1$-st intersection is $3$, $k$ needs to be at least $3$ for Badugi to complete his mission.
In the third case, Badugi can make his moves as follows: $1$ β $5$ β $6$ β $7$ β $8$ β $2$ β $3$ β $4$ β $1$. It can be shown that this is the only possible sequence of moves for Badugi to complete his mission with $k=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.
We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i.
In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y).
We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle.
Constraints
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* 1 \leq B_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 B_1
A_2 B_2
:
A_N B_N
Output
Print the minimum total weight of the edges in such a cycle.
Examples
Input
3
1 5
4 2
6 3
Output
7
Input
4
1 5
2 6
3 7
4 8
Output
10
Input
6
19 92
64 64
78 48
57 33
73 6
95 73
Output
227
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS".
You are given a sequence $s$ of $n$ characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence.
You have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced.
Determine if it is possible to obtain an RBS after these replacements.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) β the number of test cases.
Each test case consists of one line containing $s$ ($2 \le |s| \le 100$) β a sequence of characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence.
-----Output-----
For each test case, print YES if it is possible to obtain a regular bracket sequence, or NO otherwise}.
You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).
-----Examples-----
Input
5
()
(?)
(??)
??()
)?(?
Output
YES
NO
YES
YES
NO
-----Note-----
In the first test case, the sequence is already an RBS.
In the third test case, you can obtain an RBS as follows: ()() or (()).
In the fourth test case, you can obtain an RBS as follows: ()().
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 given a `moment` in time and space. What you must do is break it down into time and space, to determine if that moment is from the past, present or future.
`Time` is the sum of characters that increase time (i.e. numbers in range ['1'..'9'].
`Space` in the number of characters which do not increase time (i.e. all characters but those that increase time).
The moment of time is determined as follows:
```
If time is greater than space, than the moment is from the future.
If time is less than space, then the moment is from the past.
Otherwise, it is the present moment.```
You should return an array of three elements, two of which are false, and one is true. The true value should be at the `1st, 2nd or 3rd` place for `past, present and future` respectively.
# Examples
For `moment = "01:00 pm"`, the output should be `[true, false, false]`.
time equals 1, and space equals 7, so the moment is from the past.
For `moment = "12:02 pm"`, the output should be `[false, true, false]`.
time equals 5, and space equals 5, which means that it's a present moment.
For `moment = "12:30 pm"`, the output should be `[false, false, true]`.
time equals 6, space equals 5, so the moment is from the future.
# Input/Output
- `[input]` string `moment`
The moment of time and space that the input time came from.
- `[output]` a boolean array
Array of three elements, two of which are false, and one is true. The true value should be at the 1st, 2nd or 3rd place for past, present and future respectively.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A witch named Marie lived deep in a remote forest. Since she is a witch, she magically covers everything she needs to live, such as food, water, and fuel.
Her magic is activated by drawing a magic circle using some magical stones and strings. This magic circle is drawn by placing stones and tying several pairs of stones together. However, the string must not be loose. In addition, no string (except at both ends) should touch any other string or stone. Of course, you can't put multiple stones in the same place. As long as this restriction is adhered to, there are no restrictions on the positional relationship between stones or the length of the string. Also, the stone is small enough to be treated as a point, and the string is thin enough to be treated as a line segment. Moreover, she does not tie the same pair of stones with more than one string, nor does she tie both ends of a string to the same stone.
Marie initially painted a magic circle by pasting stones on the flat walls of her house. However, she soon realized that there was a magic circle that she could never create. After a while, she devised a way to determine if the magic circle could be created on a flat wall, a two-dimensional plane. A magic circle cannot be created on a two-dimensional plane if it contains, and only then, the following parts:
Magic Square
| | Magic Square
--- | --- | ---
Figure 1 Complete graph with 5 vertices
| | Figure 2 Complete bipartite graph with 3 or 3 vertices
To draw such a magic circle, she devised the magic of fixing the stone in the air. In three-dimensional space, these magic circles can also be drawn. On the contrary, she found that any magic circle could be drawn in three-dimensional space.
Now, the problem is from here. One day Marie decides to create a magic circle of footlights at the front door of her house. However, she had already set up various magic circles in the narrow entrance, so she had to draw the magic circle of the footlights on the one-dimensional straight line, which is the only space left. For some of the footlight magic circles she designed, write a program that determines if it can be drawn on a straight line and outputs yes if it can be drawn, no if not.
The magic circle is given by the information of the number of stones n, the number of strings m, and the number of strings m. The string is represented by the stone numbers u and v at both ends. Stones are numbered from 1 to n, where n is greater than or equal to 1 and less than 100,000 and m is greater than or equal to 0 and less than 1,000,000.
input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is as follows.
1st line Number of stones n Number of strings m (integer integer; half-width space delimited)
2nd line 1st string information u v (integer integer; half-width space delimited)
3rd line 2nd string information
::
m + 1 line information of the mth string
The number of datasets does not exceed 20.
output
Prints yes or no on one line for each input dataset.
Example
Input
5 4
1 2
2 3
3 4
4 5
4 6
1 2
1 3
1 4
2 3
2 4
3 4
5 0
0 0
Output
yes
no
yes
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given the strings $a$ and $b$, consisting of lowercase Latin letters. You can do any number of the following operations in any order:
if $|a| > 0$ (the length of the string $a$ is greater than zero), delete the first character of the string $a$, that is, replace $a$ with $a_2 a_3 \ldots a_n$;
if $|a| > 0$, delete the last character of the string $a$, that is, replace $a$ with $a_1 a_2 \ldots a_{n-1}$;
if $|b| > 0$ (the length of the string $b$ is greater than zero), delete the first character of the string $b$, that is, replace $b$ with $b_2 b_3 \ldots b_n$;
if $|b| > 0$, delete the last character of the string $b$, that is, replace $b$ with $b_1 b_2 \ldots b_{n-1}$.
Note that after each of the operations, the string $a$ or $b$ may become empty.
For example, if $a=$"hello" and $b=$"icpc", then you can apply the following sequence of operations:
delete the first character of the string $a$ $\Rightarrow$ $a=$"ello" and $b=$"icpc";
delete the first character of the string $b$ $\Rightarrow$ $a=$"ello" and $b=$"cpc";
delete the first character of the string $b$ $\Rightarrow$ $a=$"ello" and $b=$"pc";
delete the last character of the string $a$ $\Rightarrow$ $a=$"ell" and $b=$"pc";
delete the last character of the string $b$ $\Rightarrow$ $a=$"ell" and $b=$"p".
For the given strings $a$ and $b$, find the minimum number of operations for which you can make the strings $a$ and $b$ equal. Note that empty strings are also equal.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$). Then $t$ test cases follow.
The first line of each test case contains the string $a$ ($1 \le |a| \le 20$), consisting of lowercase Latin letters.
The second line of each test case contains the string $b$ ($1 \le |b| \le 20$), consisting of lowercase Latin letters.
-----Output-----
For each test case, output the minimum number of operations that can make the strings $a$ and $b$ equal.
-----Examples-----
Input
5
a
a
abcd
bc
hello
codeforces
hello
helo
dhjakjsnasjhfksafasd
adjsnasjhfksvdafdser
Output
0
2
13
3
20
-----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.
A flower shop has got n bouquets, and the i-th bouquet consists of a_{i} flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets.
Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.
Determine the maximum possible number of large bouquets Vasya can make.
-----Input-----
The first line contains a single positive integer n (1 β€ n β€ 10^5) β the number of initial bouquets.
The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 10^6) β the number of flowers in each of the initial bouquets.
-----Output-----
Print the maximum number of large bouquets Vasya can make.
-----Examples-----
Input
5
2 3 4 2 7
Output
2
Input
6
2 2 6 8 6 12
Output
0
Input
3
11 4 10
Output
1
-----Note-----
In the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme.
In the second example it is not possible to form a single bouquet with odd number of flowers.
In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 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.
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.
Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?
Heidi's n friends are labeled 0 through n - 1, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly n - 1 pairs of friends who know each other directly.
Jenny is given the number 0.
-----Input-----
The first line of the input contains the number of friends n (3 β€ n β€ 100). The next n - 1 lines each contain three space-separated integers u, v and c (0 β€ u, v β€ n - 1, 1 β€ c β€ 10^4), meaning that u and v are friends (know each other directly) and the cost for travelling between u and v is c.
It is guaranteed that the social network of the input forms a tree.
-----Output-----
Output a single integer β the maximum sum of costs.
-----Examples-----
Input
4
0 1 4
0 2 2
2 3 3
Output
5
Input
6
1 2 3
0 2 100
1 4 2
0 3 7
3 5 10
Output
105
Input
11
1 0 1664
2 0 881
3 2 4670
4 2 1555
5 1 1870
6 2 1265
7 2 288
8 7 2266
9 2 1536
10 6 3378
Output
5551
-----Note-----
In the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then friend 2 sends her to friend 1 (costing Heidi 3), and finally friend 1 relays her to friend 4 (incurring an additional cost of 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 an array $a$ consisting of $n$ integers.
Your task is to determine if $a$ has some subsequence of length at least $3$ that is a palindrome.
Recall that an array $b$ is called a subsequence of the array $a$ if $b$ can be obtained by removing some (possibly, zero) elements from $a$ (not necessarily consecutive) without changing the order of remaining elements. For example, $[2]$, $[1, 2, 1, 3]$ and $[2, 3]$ are subsequences of $[1, 2, 1, 3]$, but $[1, 1, 2]$ and $[4]$ are not.
Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array $a$ of length $n$ is the palindrome if $a_i = a_{n - i - 1}$ for all $i$ from $1$ to $n$. For example, arrays $[1234]$, $[1, 2, 1]$, $[1, 3, 2, 2, 3, 1]$ and $[10, 100, 10]$ are palindromes, but arrays $[1, 2]$ and $[1, 2, 3, 1]$ are not.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 100$) β the number of test cases.
Next $2t$ lines describe test cases. The first line of the test case contains one integer $n$ ($3 \le n \le 5000$) β the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $5000$ ($\sum n \le 5000$).
-----Output-----
For each test case, print the answer β "YES" (without quotes) if $a$ has some subsequence of length at least $3$ that is a palindrome and "NO" otherwise.
-----Example-----
Input
5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
Output
YES
YES
NO
YES
NO
-----Note-----
In the first test case of the example, the array $a$ has a subsequence $[1, 2, 1]$ which is a palindrome.
In the second test case of the example, the array $a$ has two subsequences of length $3$ which are palindromes: $[2, 3, 2]$ and $[2, 2, 2]$.
In the third test case of the example, the array $a$ has no subsequences of length at least $3$ which are palindromes.
In the fourth test case of the example, the array $a$ has one subsequence of length $4$ which is a palindrome: $[1, 2, 2, 1]$ (and has two subsequences of length $3$ which are palindromes: both are $[1, 2, 1]$).
In the fifth test case of the example, the array $a$ has no subsequences of length at least $3$ which are palindromes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a giftΒ β a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume V_{i} and put it in her garden.
Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is T_{i}, each pile will reduce its volume by T_{i}. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other.
Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day.
You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day.
-----Input-----
The first line contains a single integer N (1 β€ N β€ 10^5)Β β the number of days.
The second line contains N integers V_1, V_2, ..., V_{N} (0 β€ V_{i} β€ 10^9), where V_{i} is the initial size of a snow pile made on the day i.
The third line contains N integers T_1, T_2, ..., T_{N} (0 β€ T_{i} β€ 10^9), where T_{i} is the temperature on the day i.
-----Output-----
Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i.
-----Examples-----
Input
3
10 10 5
5 7 2
Output
5 12 4
Input
5
30 25 20 15 10
9 10 12 4 13
Output
9 20 35 11 25
-----Note-----
In the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
### Tongues
Gandalf's writings have long been available for study, but no one has yet figured out what language they are written in. Recently, due to programming work by a hacker known only by the code name ROT13, it has been discovered that Gandalf used nothing but a simple letter substitution scheme, and further, that it is its own inverse|the same operation scrambles the message as unscrambles it.
This operation is performed by replacing vowels in the sequence `'a' 'i' 'y' 'e' 'o' 'u'` with the vowel three advanced, cyclicly, while preserving case (i.e., lower or upper).
Similarly, consonants are replaced from the sequence `'b' 'k' 'x' 'z' 'n' 'h' 'd' 'c' 'w' 'g' 'p' 'v' 'j' 'q' 't' 's' 'r' 'l' 'm' 'f'` by advancing ten letters.
So for instance the phrase `'One ring to rule them all.'` translates to `'Ita dotf ni dyca nsaw ecc.'`
The fascinating thing about this transformation is that the resulting language yields pronounceable words. For this problem, you will write code to translate Gandalf's manuscripts into plain text.
Your job is to write a function that decodes Gandalf's writings.
### Input
The function will be passed a string for the function to decode. Each string will contain up to 100 characters, representing some text written by Gandalf. All characters will be plain ASCII, in the range space (32) to tilde (126).
### Output
For each string passed to the decode function return its translation.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Luntik came out for a morning stroll and found an array $a$ of length $n$. He calculated the sum $s$ of the elements of the array ($s= \sum_{i=1}^{n} a_i$). Luntik calls a subsequence of the array $a$ nearly full if the sum of the numbers in that subsequence is equal to $s-1$.
Luntik really wants to know the number of nearly full subsequences of the array $a$. But he needs to come home so he asks you to solve that problem!
A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) β the number of test cases. The next $2 \cdot t$ lines contain descriptions of test cases. The description of each test case consists of two lines.
The first line of each test case contains a single integer $n$ ($1 \le n \le 60$) β the length of the array.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) β the elements of the array $a$.
-----Output-----
For each test case print the number of nearly full subsequences of the array.
-----Examples-----
Input
5
5
1 2 3 4 5
2
1000 1000
2
1 0
5
3 0 2 1 1
5
2 1 0 3 0
Output
1
0
2
4
4
-----Note-----
In the first test case, $s=1+2+3+4+5=15$, only $(2,3,4,5)$ is a nearly full subsequence among all subsequences, the sum in it is equal to $2+3+4+5=14=15-1$.
In the second test case, there are no nearly full subsequences.
In the third test case, $s=1+0=1$, the nearly full subsequences are $(0)$ and $()$ (the sum of an empty subsequence is $0$).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has N strings. The i-th string is s_i.
Let us concatenate these strings into one string after arranging them in some order. Find the maximum possible number of occurrences of `AB` in the resulting string.
Constraints
* 1 \leq N \leq 10^{4}
* 2 \leq |s_i| \leq 10
* s_i consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
N
s_1
\vdots
s_N
Output
Print the answer.
Examples
Input
3
ABCA
XBAZ
BAD
Output
2
Input
9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA
Output
4
Input
7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA
Output
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.
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.
Find the minimum possible total cost incurred before the frog reaches Stone N.
Constraints
* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq K \leq 100
* 1 \leq h_i \leq 10^4
Input
Input is given from Standard Input in the following format:
N K
h_1 h_2 \ldots h_N
Output
Print the minimum possible total cost incurred.
Examples
Input
5 3
10 30 40 50 20
Output
30
Input
3 1
10 20 10
Output
20
Input
2 100
10 10
Output
0
Input
10 4
40 10 20 70 80 10 20 70 80 60
Output
40
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified characters, the function should return null (throw an `ArgumentException` in C#).
Keep in mind, you cannot divide by zero. If an attempt to divide by zero is made, return null (throw an `ArgumentException` in C#)/(None in Python).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer a_{i}Β β number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute.
Vitalya will definitely wake up if during some m consecutive minutes at least k alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.
Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on.
-----Input-----
First line contains three integers n, m and k (1 β€ k β€ n β€ 2Β·10^5, 1 β€ m β€ 10^6)Β β number of alarm clocks, and conditions of Vitalya's waking up.
Second line contains sequence of distinct integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 10^6) in which a_{i} equals minute on which i-th alarm clock will ring. Numbers are given in arbitrary order. Vitalya lives in a Berland in which day lasts for 10^6 minutes.
-----Output-----
Output minimal number of alarm clocks that Vitalya should turn off to sleep all next day long.
-----Examples-----
Input
3 3 2
3 5 1
Output
1
Input
5 10 3
12 8 18 25 1
Output
0
Input
7 7 2
7 3 4 1 6 5 2
Output
6
Input
2 2 2
1 3
Output
0
-----Note-----
In first example Vitalya should turn off first alarm clock which rings at minute 3.
In second example Vitalya shouldn't turn off any alarm clock because there are no interval of 10 consequence minutes in which 3 alarm clocks will ring.
In third example Vitalya should turn off any 6 alarm clocks.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 decided to make a new wooden roof for the house. He has $n$ rectangular planks numbered from $1$ to $n$. The $i$-th plank has size $a_i \times 1$ (that is, the width is $1$ and the height is $a_i$).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.
For example, if Ujan had planks with lengths $4$, $3$, $1$, $4$ and $5$, he could choose planks with lengths $4$, $3$ and $5$. Then he can cut out a $3 \times 3$ square, which is the maximum possible. Note that this is not the only way he can obtain a $3 \times 3$ square.
[Image]
What is the maximum side length of the square Ujan can get?
-----Input-----
The first line of input contains a single integer $k$ ($1 \leq k \leq 10$), the number of test cases in the input.
For each test case, the first line contains a single integer $n$ ($1 \leq n \leq 1\,000$), the number of planks Ujan has in store. The next line contains $n$ integers $a_1, \ldots, a_n$ ($1 \leq a_i \leq n$), the lengths of the planks.
-----Output-----
For each of the test cases, output a single integer, the maximum possible side length of the square.
-----Example-----
Input
4
5
4 3 1 4 5
4
4 4 4 4
3
1 1 1
5
5 5 1 1 5
Output
3
4
1
3
-----Note-----
The first sample corresponds to the example in the statement.
In the second sample, gluing all $4$ planks will result in a $4 \times 4$ square.
In the third sample, the maximum possible square is $1 \times 1$ and can be taken simply as any of the planks.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
"Duel!"
Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.
There are $n$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly $k$ consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these $n$ cards face the same direction after one's move, the one who takes this move will win.
Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$).
The second line contains a single string of length $n$ that only consists of $0$ and $1$, representing the situation of these $n$ cards, where the color side of the $i$-th card faces up if the $i$-th character is $1$, or otherwise, it faces down and the $i$-th character is $0$.
-----Output-----
Print "once again" (without quotes) if the total number of their moves can exceed $10^9$, which is considered a draw.
In other cases, print "tokitsukaze" (without quotes) if Tokitsukaze will win, or "quailty" (without quotes) if Quailty will win.
Note that the output characters are case-sensitive, and any wrong spelling would be rejected.
-----Examples-----
Input
4 2
0101
Output
quailty
Input
6 1
010101
Output
once again
Input
6 5
010101
Output
tokitsukaze
Input
4 1
0011
Output
once again
-----Note-----
In the first example, no matter how Tokitsukaze moves, there would be three cards with color sides facing the same direction after her move, and Quailty can flip the last card to this direction and win.
In the second example, no matter how Tokitsukaze moves, Quailty can choose the same card and flip back to the initial situation, which can allow the game to end in a draw.
In the third example, Tokitsukaze can win by flipping the leftmost five cards up or flipping the rightmost five cards down.
The fourth example can be explained in the same way as the second example does.
Read the inputs from 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.