question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
The only difference between the two versions is that this version asks the maximal possible answer.
Homer likes arrays a lot. Today he is painting an array $a_1, a_2, \dots, a_n$ with two kinds of colors, white and black. A painting assignment for $a_1, a_2, \dots, a_n$ is described by an array $b_1, b_2, \dots, b_n$ that $b_i$ indicates the color of $a_i$ ($0$ for white and $1$ for black).
According to a painting assignment $b_1, b_2, \dots, b_n$, the array $a$ is split into two new arrays $a^{(0)}$ and $a^{(1)}$, where $a^{(0)}$ is the sub-sequence of all white elements in $a$ and $a^{(1)}$ is the sub-sequence of all black elements in $a$. For example, if $a = [1,2,3,4,5,6]$ and $b = [0,1,0,1,0,0]$, then $a^{(0)} = [1,3,5,6]$ and $a^{(1)} = [2,4]$.
The number of segments in an array $c_1, c_2, \dots, c_k$, denoted $\mathit{seg}(c)$, is the number of elements if we merge all adjacent elements with the same value in $c$. For example, the number of segments in $[1,1,2,2,3,3,3,2]$ is $4$, because the array will become $[1,2,3,2]$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $0$.
Homer wants to find a painting assignment $b$, according to which the number of segments in both $a^{(0)}$ and $a^{(1)}$, i.e. $\mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)})$, is as large as possible. Find this number.
-----Input-----
The first line contains an integer $n$ ($1 \leq n \leq 10^5$).
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq n$).
-----Output-----
Output a single integer, indicating the maximal possible total number of segments.
-----Examples-----
Input
7
1 1 2 2 3 3 3
Output
6
Input
7
1 2 3 4 5 6 7
Output
7
-----Note-----
In the first example, we can choose $a^{(0)} = [1,2,3,3]$, $a^{(1)} = [1,2,3]$ and $\mathit{seg}(a^{(0)}) = \mathit{seg}(a^{(1)}) = 3$. So the answer is $3+3 = 6$.
In the second example, we can choose $a^{(0)} = [1,2,3,4,5,6,7]$ and $a^{(1)}$ is empty. We can see that $\mathit{seg}(a^{(0)}) = 7$ and $\mathit{seg}(a^{(1)}) = 0$. So the answer is $7+0 = 7$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Palindrome
Problem Statement
Find the number of palindromes closest to the integer n.
Note that the non-negative integer x is the number of palindromes, which means that the character string in which x is expressed in decimal notation and the character string in which it is inverted are equal.
For example, 0,7,33,10301 is the number of palindromes, and 32,90,1010 is not the number of palindromes.
Constraints
* 1 ≤ n ≤ 10 ^ 4
Input
Input follows the following format. All given numbers are integers.
n
Output
Output the number of palindromes closest to n.
If there are multiple such numbers, output the smallest one.
Examples
Input
13
Output
11
Input
7447
Output
7447
Input
106
Output
101
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 define the cost of a string s as the number of index pairs i and j (1 ≤ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If there are multiple such strings with minimum cost — find any of them.
Input
The only line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 26).
Output
Print the string s such that it consists of n characters, each its character is one of the k first Latin letters, and it has the minimum possible cost among all these strings. If there are multiple such strings — print any of them.
Examples
Input
9 4
Output
aabacadbb
Input
5 1
Output
aaaaa
Input
10 26
Output
codeforces
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.
More formally, you are given two strings s_1, s_2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s_3 of length n, such that f(s_1, s_3) = f(s_2, s_3) = t. If there is no such string, print - 1.
-----Input-----
The first line contains two integers n and t (1 ≤ n ≤ 10^5, 0 ≤ t ≤ n).
The second line contains string s_1 of length n, consisting of lowercase English letters.
The third line contain string s_2 of length n, consisting of lowercase English letters.
-----Output-----
Print a string of length n, differing from string s_1 and from s_2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.
-----Examples-----
Input
3 2
abc
xyc
Output
ayd
Input
1 0
c
b
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.
It's a Pokemon battle! Your task is to calculate the damage that a particular move would do using the following formula (not the actual one from the game):
Where:
* attack = your attack power
* defense = the opponent's defense
* effectiveness = the effectiveness of the attack based on the matchup (see explanation below)
Effectiveness:
Attacks can be super effective, neutral, or not very effective depending on the matchup. For example, water would be super effective against fire, but not very effective against grass.
* Super effective: 2x damage
* Neutral: 1x damage
* Not very effective: 0.5x damage
To prevent this kata from being tedious, you'll only be dealing with four types: `fire`, `water`, `grass`, and `electric`. Here is the effectiveness of each matchup:
* `fire > grass`
* `fire < water`
* `fire = electric`
* `water < grass`
* `water < electric`
* `grass = electric`
For this kata, any type against itself is not very effective. Also, assume that the relationships between different types are symmetric (if `A` is super effective against `B`, then `B` is not very effective against `A`).
The function you must implement takes in:
1. your type
2. the opponent's type
3. your attack power
4. the opponent's defense
Write your solution by modifying this code:
```python
def calculate_damage(your_type, opponent_type, attack, defense):
```
Your solution should implemented in the function "calculate_damage". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Igor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.
The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (x1, y1) and (x2, y2).
Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the i-th mouse is equal to (vix, viy), that means that the x coordinate of the mouse increases by vix units per second, while the y coordinates increases by viy units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap.
Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once.
Input
The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of computer mice on the desk.
The second line contains four integers x1, y1, x2 and y2 (0 ≤ x1 ≤ x2 ≤ 100 000), (0 ≤ y1 ≤ y2 ≤ 100 000) — the coordinates of the opposite corners of the mousetrap.
The next n lines contain the information about mice.
The i-th of these lines contains four integers rix, riy, vix and viy, (0 ≤ rix, riy ≤ 100 000, - 100 000 ≤ vix, viy ≤ 100 000), where (rix, riy) is the initial position of the mouse, and (vix, viy) is its speed.
Output
In the only line print minimum possible non-negative number t such that if Igor closes the mousetrap at t seconds from the beginning, then all the mice are strictly inside the mousetrap. If there is no such t, print -1.
Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>.
Examples
Input
4
7 7 9 8
3 5 7 5
7 5 2 4
3 3 7 8
6 6 3 2
Output
0.57142857142857139685
Input
4
7 7 9 8
0 3 -5 4
5 0 5 4
9 9 -1 -6
10 5 -7 -10
Output
-1
Note
Here is a picture of the first sample
Points A, B, C, D - start mice positions, segments are their paths.
<image>
Then, at first time when all mice will be in rectangle it will be looks like this:
<image>
Here is a picture of the second sample
<image>
Points A, D, B will never enter rectangle.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 has finally found the mythical Tree of Life – a legendary combinatorial structure which is said to contain a prophecy crucially needed to defeat the undead armies.
On the surface, the Tree of Life is just a regular undirected tree well-known from computer science. This means that it is a collection of n points (called vertices), some of which are connected using n - 1 line segments (edges) so that each pair of vertices is connected by a path (a sequence of one or more edges).
To decipher the prophecy, Heidi needs to perform a number of steps. The first is counting the number of lifelines in the tree – these are paths of length 2, i.e., consisting of two edges. Help her!
-----Input-----
The first line of the input contains a single integer n – the number of vertices in the tree (1 ≤ n ≤ 10000). The vertices are labeled with the numbers from 1 to n. Then n - 1 lines follow, each describing one edge using two space-separated numbers a b – the labels of the vertices connected by the edge (1 ≤ a < b ≤ n). It is guaranteed that the input represents a tree.
-----Output-----
Print one integer – the number of lifelines in the tree.
-----Examples-----
Input
4
1 2
1 3
1 4
Output
3
Input
5
1 2
2 3
3 4
3 5
Output
4
-----Note-----
In the second sample, there are four lifelines: paths between vertices 1 and 3, 2 and 4, 2 and 5, and 4 and 5.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A popular reality show is recruiting a new cast for the third season! $n$ candidates numbered from $1$ to $n$ have been interviewed. The candidate $i$ has aggressiveness level $l_i$, and recruiting this candidate will cost the show $s_i$ roubles.
The show host reviewes applications of all candidates from $i=1$ to $i=n$ by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate $i$ is strictly higher than that of any already accepted candidates, then the candidate $i$ will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.
The show makes revenue as follows. For each aggressiveness level $v$ a corresponding profitability value $c_v$ is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant $i$ enters the stage, events proceed as follows:
The show makes $c_{l_i}$ roubles, where $l_i$ is initial aggressiveness level of the participant $i$. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is:
the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes $c_t$ roubles, where $t$ is the new aggressiveness level.
The fights continue until all participants on stage have distinct aggressiveness levels.
It is allowed to select an empty set of participants (to choose neither of the candidates).
The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total $s_i$). Help the host to make the show as profitable as possible.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2000$) — the number of candidates and an upper bound for initial aggressiveness levels.
The second line contains $n$ integers $l_i$ ($1 \le l_i \le m$) — initial aggressiveness levels of all candidates.
The third line contains $n$ integers $s_i$ ($0 \le s_i \le 5000$) — the costs (in roubles) to recruit each of the candidates.
The fourth line contains $n + m$ integers $c_i$ ($|c_i| \le 5000$) — profitability for each aggrressiveness level.
It is guaranteed that aggressiveness level of any participant can never exceed $n + m$ under given conditions.
-----Output-----
Print a single integer — the largest profit of the show.
-----Examples-----
Input
5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
Output
6
Input
2 2
1 2
0 0
2 1 -100 -100
Output
2
Input
5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
Output
62
-----Note-----
In the first sample case it is optimal to recruit candidates $1, 2, 3, 5$. Then the show will pay $1 + 2 + 1 + 1 = 5$ roubles for recruitment. The events on stage will proceed as follows:
a participant with aggressiveness level $4$ enters the stage, the show makes $4$ roubles; a participant with aggressiveness level $3$ enters the stage, the show makes $3$ roubles; a participant with aggressiveness level $1$ enters the stage, the show makes $1$ rouble; a participant with aggressiveness level $1$ enters the stage, the show makes $1$ roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to $2$. The show will make extra $2$ roubles for this.
Total revenue of the show will be $4 + 3 + 1 + 1 + 2=11$ roubles, and the profit is $11 - 5 = 6$ roubles.
In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate $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.
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power $x$ deals $x$ damage to the monster, and lightning spell of power $y$ deals $y$ damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power $5$, a lightning spell of power $1$, and a lightning spell of power $8$. There are $6$ ways to choose the order in which he casts the spells:
first, second, third. This order deals $5 + 1 + 2 \cdot 8 = 22$ damage; first, third, second. This order deals $5 + 8 + 2 \cdot 1 = 15$ damage; second, first, third. This order deals $1 + 2 \cdot 5 + 8 = 19$ damage; second, third, first. This order deals $1 + 2 \cdot 8 + 2 \cdot 5 = 27$ damage; third, first, second. This order deals $8 + 2 \cdot 5 + 1 = 19$ damage; third, second, first. This order deals $8 + 2 \cdot 1 + 2 \cdot 5 = 20$ damage.
Initially, Polycarp knows $0$ spells. His spell set changes $n$ times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of changes to the spell set.
Each of the next $n$ lines contains two integers $tp$ and $d$ ($0 \le tp_i \le 1$; $-10^9 \le d \le 10^9$; $d_i \neq 0$) — the description of the change. If $tp_i$ if equal to $0$, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If $d_i > 0$, then Polycarp learns a spell of power $d_i$. Otherwise, Polycarp forgets a spell with power $-d_i$, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
-----Output-----
After each change, print the maximum damage Polycarp can deal with his current set of spells.
-----Example-----
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
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.
Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $a=[1, 3, 3, 7]$ is good because there is the element $a_4=7$ which equals to the sum $1 + 3 + 3$.
You are given an array $a$ consisting of $n$ integers. Your task is to print all indices $j$ of this array such that after removing the $j$-th element from the array it will be good (let's call such indices nice).
For example, if $a=[8, 3, 5, 2]$, the nice indices are $1$ and $4$: if you remove $a_1$, the array will look like $[3, 5, 2]$ and it is good; if you remove $a_4$, the array will look like $[8, 3, 5]$ and it is good.
You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.
-----Input-----
The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of elements in the array $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^6$) — elements of the array $a$.
-----Output-----
In the first line print one integer $k$ — the number of indices $j$ of the array $a$ such that after removing the $j$-th element from the array it will be good (i.e. print the number of the nice indices).
In the second line print $k$ distinct integers $j_1, j_2, \dots, j_k$ in any order — nice indices of the array $a$.
If there are no such indices in the array $a$, just print $0$ in the first line and leave the second line empty or do not print it at all.
-----Examples-----
Input
5
2 5 1 2 2
Output
3
4 1 5
Input
4
8 3 5 2
Output
2
1 4
Input
5
2 1 2 4 3
Output
0
-----Note-----
In the first example you can remove any element with the value $2$ so the array will look like $[5, 1, 2, 2]$. The sum of this array is $10$ and there is an element equals to the sum of remaining elements ($5 = 1 + 2 + 2$).
In the second example you can remove $8$ so the array will look like $[3, 5, 2]$. The sum of this array is $10$ and there is an element equals to the sum of remaining elements ($5 = 3 + 2$). You can also remove $2$ so the array will look like $[8, 3, 5]$. The sum of this array is $16$ and there is an element equals to the sum of remaining elements ($8 = 3 + 5$).
In the third example you cannot make the given array good by removing exactly one element.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Aizuwakamatsu Village, which is located far north of Aizuwakamatsu City, a bridge called "Yabashi" is the only way to move to the surrounding villages. Despite the large number of passers-by, the bridge is so old that it is almost broken.
<image>
Yabashi is strong enough to withstand up to 150 [kg]. For example, 80 [kg] people and 50 [kg] people can cross at the same time, but if 90 [kg] people start crossing while 80 [kg] people are crossing, Yabashi will It will break.
If the Ya Bridge is broken, the people of Aizu Komatsu Village will lose the means to move to the surrounding villages. So, as the only programmer in the village, you decided to write a program to determine if the bridge would break based on how you crossed the bridge, in order to protect the lives of the villagers.
Number of passersby crossing the bridge n (1 ≤ n ≤ 100), weight of each passer mi (1 ≤ mi ≤ 100), time to start crossing the bridge ai, time to finish crossing bi (0 ≤ ai, bi <231) If the bridge does not break, output "OK", and if it breaks, output "NG". If the total weight of passers-by on the bridge exceeds 150 [kg], the bridge will be destroyed. Also, at the time of ai, the passersby are on the bridge, but at the time of bi, they are not on the bridge.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
n
m1 a1 b1
m2 a2 b2
::
mn an bn
The number of datasets does not exceed 1200.
Output
For each input dataset, prints on one line whether the bridge will break or not.
Example
Input
3
80 0 30
50 5 25
90 27 50
3
80 0 30
70 5 25
71 30 50
0
Output
NG
OK
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.
After the contest was over, Valera was interested in results. He found out that:
* each student in the team scored at least l points and at most r points;
* in total, all members of the team scored exactly sall points;
* the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 ≥ a2 ≥ ... ≥ an), then sk = a1 + a2 + ... + ak.
However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
Input
The first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≤ n, k, l, r ≤ 1000; l ≤ r; k ≤ n; 1 ≤ sk ≤ sall ≤ 106).
It's guaranteed that the input is such that the answer exists.
Output
Print exactly n integers a1, a2, ..., an — the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order.
Examples
Input
5 3 1 3 13 9
Output
2 3 2 3 3
Input
5 3 1 3 15 9
Output
3 3 3 3 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Assume we take a number `x` and perform any one of the following operations:
```Pearl
a) Divide x by 3 (if it is divisible by 3), or
b) Multiply x by 2
```
After each operation, we write down the result. If we start with `9`, we can get a sequence such as:
```
[9,3,6,12,4,8] -- 9/3=3 -> 3*2=6 -> 6*2=12 -> 12/3=4 -> 4*2=8
```
You will be given a shuffled sequence of integers and your task is to reorder them so that they conform to the above sequence. There will always be an answer.
```
For the above example:
solve([12,3,9,4,6,8]) = [9,3,6,12,4,8].
```
More examples in the test cases. Good luck!
Write your solution by modifying this code:
```python
def solve(arr):
```
Your solution should implemented in the function "solve". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.
Find the maximum number of consecutive rainy days in this period.
-----Constraints-----
- |S| = 3
- Each character of S is S or R.
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Print the maximum number of consecutive rainy days in the period.
-----Sample Input-----
RRS
-----Sample Output-----
2
We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 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.
Vova again tries to play some computer card game.
The rules of deck creation in this game are simple. Vova is given an existing deck of n cards and a magic number k. The order of the cards in the deck is fixed. Each card has a number written on it; number a_{i} is written on the i-th card in the deck.
After receiving the deck and the magic number, Vova removes x (possibly x = 0) cards from the top of the deck, y (possibly y = 0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards x + 1, x + 2, ... n - y - 1, n - y from the original deck.
Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by k. So Vova received a deck (possibly not a valid one) and a number k, and now he wonders, how many ways are there to choose x and y so the deck he will get after removing x cards from the top and y cards from the bottom is valid?
-----Input-----
The first line contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 10^9).
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the numbers written on the cards.
-----Output-----
Print the number of ways to choose x and y so the resulting deck is valid.
-----Examples-----
Input
3 4
6 2 8
Output
4
Input
3 6
9 1 14
Output
1
-----Note-----
In the first example the possible values of x and y are:
x = 0, y = 0; x = 1, y = 0; x = 2, y = 0; x = 0, y = 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.
On a circle lie $2n$ distinct points, with the following property: however you choose $3$ chords that connect $3$ disjoint pairs of points, no point strictly inside the circle belongs to all $3$ chords. The points are numbered $1, \, 2, \, \dots, \, 2n$ in clockwise order.
Initially, $k$ chords connect $k$ pairs of points, in such a way that all the $2k$ endpoints of these chords are distinct.
You want to draw $n - k$ additional chords that connect the remaining $2(n - k)$ points (each point must be an endpoint of exactly one chord).
In the end, let $x$ be the total number of intersections among all $n$ chords. Compute the maximum value that $x$ can attain if you choose the $n - k$ chords optimally.
Note that the exact position of the $2n$ points is not relevant, as long as the property stated in the first paragraph holds.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.
The first line of each test case contains two integers $n$ and $k$ ($1 \le n \le 100$, $0 \le k \le n$) — half the number of points and the number of chords initially drawn.
Then $k$ lines follow. The $i$-th of them contains two integers $x_i$ and $y_i$ ($1 \le x_i, \, y_i \le 2n$, $x_i \ne y_i$) — the endpoints of the $i$-th chord. It is guaranteed that the $2k$ numbers $x_1, \, y_1, \, x_2, \, y_2, \, \dots, \, x_k, \, y_k$ are all distinct.
-----Output-----
For each test case, output the maximum number of intersections that can be obtained by drawing $n - k$ additional chords.
-----Examples-----
Input
4
4 2
8 2
1 5
1 1
2 1
2 0
10 6
14 6
2 20
9 10
13 18
15 12
11 7
Output
4
0
1
14
-----Note-----
In the first test case, there are three ways to draw the $2$ additional chords, shown below (black chords are the ones initially drawn, while red chords are the new ones):
We see that the third way gives the maximum number of intersections, namely $4$.
In the second test case, there are no more chords to draw. Of course, with only one chord present there are no intersections.
In the third test case, we can make at most one intersection by drawing chords $1-3$ and $2-4$, as shown below:
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a square matrix n × n, consisting of non-negative integer numbers. You should find such a way on it that
* starts in the upper left cell of the matrix;
* each following cell is to the right or down from the current cell;
* the way ends in the bottom right cell.
Moreover, if we multiply together all the numbers along the way, the result should be the least "round". In other words, it should end in the least possible number of zeros.
Input
The first line contains an integer number n (2 ≤ n ≤ 1000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).
Output
In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.
Examples
Input
3
1 2 3
4 5 6
7 8 9
Output
0
DDRR
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.
Strictly speaking, it makes a photo of all points with coordinates $(x, y)$, such that $x_1 \leq x \leq x_2$ and $y_1 \leq y \leq y_2$, where $(x_1, y_1)$ and $(x_2, y_2)$ are coordinates of the left bottom and the right top corners of the rectangle being photographed. The area of this rectangle can be zero.
After taking the photo, Pavel wrote down coordinates of $n$ of his favourite stars which appeared in the photo. These points are not necessarily distinct, there can be multiple stars in the same point of the sky.
Pavel has lost his camera recently and wants to buy a similar one. Specifically, he wants to know the dimensions of the photo he took earlier. Unfortunately, the photo is also lost. His notes are also of not much help; numbers are written in random order all over his notepad, so it's impossible to tell which numbers specify coordinates of which points.
Pavel asked you to help him to determine what are the possible dimensions of the photo according to his notes. As there are multiple possible answers, find the dimensions with the minimal possible area of the rectangle.
-----Input-----
The first line of the input contains an only integer $n$ ($1 \leq n \leq 100\,000$), the number of points in Pavel's records.
The second line contains $2 \cdot n$ integers $a_1$, $a_2$, ..., $a_{2 \cdot n}$ ($1 \leq a_i \leq 10^9$), coordinates, written by Pavel in some order.
-----Output-----
Print the only integer, the minimal area of the rectangle which could have contained all points from Pavel's records.
-----Examples-----
Input
4
4 1 3 2 3 2 1 3
Output
1
Input
3
5 8 5 5 7 5
Output
0
-----Note-----
In the first sample stars in Pavel's records can be $(1, 3)$, $(1, 3)$, $(2, 3)$, $(2, 4)$. In this case, the minimal area of the rectangle, which contains all these points is $1$ (rectangle with corners at $(1, 3)$ and $(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.
In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.
You are given an integer array $a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$.
Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $[3, 4, 4]$ currently in the deque, adding an element $1$ to the beginning will produce the sequence $[{1}, 3, 4, 4]$, and adding the same element to the end will produce $[3, 4, 4, {1}]$.
The elements of the array are sequentially added to the initially empty deque, starting with $a_1$ and finishing with $a_n$. Before adding each element to the deque, you may choose whether to add it to the beginning or to the end.
For example, if we consider an array $a = [3, 7, 5, 5]$, one of the possible sequences of actions looks like this:
$\quad$ 1.
add $3$ to the beginning of the deque:
deque has a sequence $[{3}]$ in it;
$\quad$ 2.
add $7$ to the end of the deque:
deque has a sequence $[3, {7}]$ in it;
$\quad$ 3.
add $5$ to the end of the deque:
deque has a sequence $[3, 7, {5}]$ in it;
$\quad$ 4.
add $5$ to the beginning of the deque:
deque has a sequence $[{5}, 3, 7, 5]$ in it;
Find the minimal possible number of inversions in the deque after the whole array is processed.
An inversion in sequence $d$ is a pair of indices $(i, j)$ such that $i < j$ and $d_i > d_j$. For example, the array $d = [5, 3, 7, 5]$ has exactly two inversions — $(1, 2)$ and $(3, 4)$, since $d_1 = 5 > 3 = d_2$ and $d_3 = 7 > 5 = d_4$.
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 1000$) — the number of test cases.
The next $2t$ lines contain descriptions of the test cases.
The first line of each test case description contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$) — array size. The second line of the description contains $n$ space-separated integers $a_i$ ($-10^9 \le a_i \le 10^9$) — elements of the array.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
Print $t$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be a single integer — the minimal possible number of inversions in the deque after executing the described algorithm.
-----Examples-----
Input
6
4
3 7 5 5
3
3 2 1
3
3 1 2
4
-1 2 2 -1
4
4 5 1 3
5
1 3 1 3 2
Output
2
0
1
0
1
2
-----Note-----
One of the ways to get the sequence $[5, 3, 7, 5]$ in the deque, containing only two inversions, from the initial array $[3, 7, 5, 5]$ (the first sample test case) is described in the problem statement.
Also, in this example, you could get the answer of two inversions by simply putting each element of the original array at the end of the deque. In this case, the original sequence $[3, 7, 5, 5]$, also containing exactly two inversions, will be in the deque as-is.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let’s try a dice puzzle. The rules of this puzzle are as follows.
1. Dice with six faces as shown in Figure 1 are used in the puzzle.
<image>
Figure 1: Faces of a die
2. With twenty seven such dice, a 3 × 3 × 3 cube is built as shown in Figure 2.
<image>
Figure 2: 3 × 3 × 3 cube
3. When building up a cube made of dice, the sum of the numbers marked on the faces of adjacent dice that are placed against each other must be seven (See Figure 3). For example, if one face of the pair is marked “2”, then the other face must be “5”.
<image>
Figure 3: A pair of faces placed against each other
4. The top and the front views of the cube are partially given, i.e. the numbers on faces of some of the dice on the top and on the front are given.
<image>
Figure 4: Top and front views of the cube
5. The goal of the puzzle is to find all the plausible dice arrangements that are consistent with the given top and front view information.
Your job is to write a program that solves this puzzle.
Input
The input consists of multiple datasets in the following format.
N
Dataset1
Dataset2
...
DatasetN
N is the number of the datasets.
The format of each dataset is as follows.
T11 T12 T13
T21 T22 T23
T31 T32 T33
F11 F12 F13
F21 F22 F23
F31 F32 F33
Tij and Fij (1 ≤ i ≤ 3, 1 ≤ j ≤ 3) are the faces of dice appearing on the top and front views, as shown in Figure 2, or a zero. A zero means that the face at the corresponding position is unknown.
Output
For each plausible arrangement of dice, compute the sum of the numbers marked on the nine faces appearing on the right side of the cube, that is, with the notation given in Figure 2, ∑3i=1∑3j=1Rij.
For each dataset, you should output the right view sums for all the plausible arrangements, in ascending order and without duplicates. Numbers should be separated by a single space.
When there are no plausible arrangements for a dataset, output a zero.
For example, suppose that the top and the front views are given as follows.
<image>
Figure 5: Example
There are four plausible right views as shown in Figure 6. The right view sums are 33, 36, 32, and 33, respectively. After rearranging them into ascending order and eliminating duplicates, the answer should be “32 33 36”.
<image>
Figure 6: Plausible right views
The output should be one line for each dataset. The output may have spaces at ends of lines.
Example
Input
4
1 1 1
1 1 1
1 1 1
2 2 2
2 2 2
2 2 2
4 3 3
5 2 2
4 3 3
6 1 1
6 1 1
6 1 0
1 0 0
0 2 0
0 0 0
5 1 2
5 1 2
0 0 0
2 0 0
0 3 0
0 0 0
0 0 0
0 0 0
3 0 1
Output
27
24
32 33 36
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.
Implement a function to calculate the sum of the numerical values in a nested list. For example :
```python
sum_nested([1, [2, [3, [4]]]]) -> 10
```
Write your solution by modifying this code:
```python
def sum_nested(lst):
```
Your solution should implemented in the function "sum_nested". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider the numbers `6969` and `9116`. When you rotate them `180 degrees` (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as `2` or `5` don't yield numbers when rotated.
Given a range, return the count of upside down numbers within that range. For example, `solve(0,10) = 3`, because there are only `3` upside down numbers `>= 0 and < 10`. They are `0, 1, 8`.
More examples in the test cases.
Good luck!
If you like this Kata, please try
[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
[Life without primes](https://www.codewars.com/kata/59f8750ac374cba8f0000033)
Please also try the performance version of this kata at [Upside down numbers - Challenge Edition ](https://www.codewars.com/kata/59f98052120be4abfa000304)
Write your solution by modifying this code:
```python
def solve(a, b):
```
Your solution should implemented in the function "solve". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least $a$ minutes to feel refreshed.
Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in $b$ minutes.
Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than $a$ minutes in total, then he sets his alarm to go off in $c$ minutes after it is reset and spends $d$ minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.
If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another $c$ minutes and tries to fall asleep for $d$ minutes again.
You just want to find out when will Polycarp get out of his bed or report that it will never happen.
Please check out the notes for some explanations of the example.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of testcases.
The only line of each testcase contains four integers $a, b, c, d$ ($1 \le a, b, c, d \le 10^9$) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.
-----Output-----
For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.
-----Example-----
Input
7
10 3 6 4
11 3 6 4
5 9 4 10
6 5 2 3
1 1 1 1
3947465 47342 338129 123123
234123843 13 361451236 361451000
Output
27
27
9
-1
1
6471793
358578060125049
-----Note-----
In the first testcase Polycarp wakes up after $3$ minutes. He only rested for $3$ minutes out of $10$ minutes he needed. So after that he sets his alarm to go off in $6$ minutes and spends $4$ minutes falling asleep. Thus, he rests for $2$ more minutes, totaling in $3+2=5$ minutes of sleep. Then he repeats the procedure three more times and ends up with $11$ minutes of sleep. Finally, he gets out of his bed. He spent $3$ minutes before the first alarm and then reset his alarm four times. The answer is $3+4 \cdot 6 = 27$.
The second example is almost like the first one but Polycarp needs $11$ minutes of sleep instead of $10$. However, that changes nothing because he gets $11$ minutes with these alarm parameters anyway.
In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is $b=9$.
In the fourth testcase Polycarp wakes up after $5$ minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographically smallest one.
-----Constraints-----
- 1 \leq N,K \leq 3 × 10^5
- N and K are integers.
-----Input-----
Input is given from Standard Input in the following format:
K N
-----Output-----
Print the (X/2)-th (rounded up to the nearest integer) lexicographically smallest sequence listed in FEIS, with spaces in between, where X is the total number of sequences listed in FEIS.
-----Sample Input-----
3 2
-----Sample Output-----
2 1
There are 12 sequences listed in FEIS: (1),(1,1),(1,2),(1,3),(2),(2,1),(2,2),(2,3),(3),(3,1),(3,2),(3,3).
The (12/2 = 6)-th lexicographically smallest one among them is (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.
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $c_1, c_2, \dots, c_n$ where $c_i$ is the number of consecutive brackets "(" if $i$ is an odd number or the number of consecutive brackets ")" if $i$ is an even number.
For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $[3, 2, 1, 3]$.
You need to find the total number of continuous subsequences (subsegments) $[l, r]$ ($l \le r$) of the original bracket sequence, which are regular bracket sequences.
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.
-----Input-----
The first line contains a single integer $n$ $(1 \le n \le 1000)$, the size of the compressed sequence.
The second line contains a sequence of integers $c_1, c_2, \dots, c_n$ $(1 \le c_i \le 10^9)$, the compressed sequence.
-----Output-----
Output a single integer — the total number of subsegments of the original bracket sequence, which are regular bracket sequences.
It can be proved that the answer fits in the signed 64-bit integer data type.
-----Examples-----
Input
5
4 1 2 3 1
Output
5
Input
6
1 3 2 1 2 4
Output
6
Input
6
1 1 1 1 2 2
Output
7
-----Note-----
In the first example a sequence (((()(()))( is described. This bracket sequence contains $5$ subsegments which form regular bracket sequences:
Subsequence from the $3$rd to $10$th character: (()(()))
Subsequence from the $4$th to $5$th character: ()
Subsequence from the $4$th to $9$th character: ()(())
Subsequence from the $6$th to $9$th character: (())
Subsequence from the $7$th to $8$th character: ()
In the second example a sequence ()))(()(()))) is described.
In the third example a sequence ()()(()) is described.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".
We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").
The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.
A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.
Notice, that any year between 2013 and 2015 is not a leap year.
Input
The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.
Output
In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.
Examples
Input
777-444---21-12-2013-12-2013-12-2013---444-777
Output
13-12-2013
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take d minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.
Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get n cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.
-----Input-----
The only line contains four integers n, t, k, d (1 ≤ n, t, k, d ≤ 1 000) — the number of cakes needed, the time needed for one oven to bake k cakes, the number of cakes baked at the same time, the time needed to build the second oven.
-----Output-----
If it is reasonable to build the second oven, print "YES". Otherwise print "NO".
-----Examples-----
Input
8 6 4 5
Output
YES
Input
8 6 4 6
Output
NO
Input
10 3 11 4
Output
NO
Input
4 2 1 4
Output
YES
-----Note-----
In the first example it is possible to get 8 cakes in 12 minutes using one oven. The second oven can be built in 5 minutes, so after 6 minutes the first oven bakes 4 cakes, the second oven bakes 4 more ovens after 11 minutes. Thus, it is reasonable to build the second oven.
In the second example it doesn't matter whether we build the second oven or not, thus it takes 12 minutes to bake 8 cakes in both cases. Thus, it is unreasonable to build the second oven.
In the third example the first oven bakes 11 cakes in 3 minutes, that is more than needed 10. It is unreasonable to build the second oven, because its building takes more time that baking the needed number of cakes using the only oven.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 and Aoki are playing a stone-taking game. Initially, there are N piles of stones, and the i-th pile contains A_i stones and has an associated integer K_i.
Starting from Takahashi, Takahashi and Aoki take alternate turns to perform the following operation:
- Choose a pile. If the i-th pile is selected and there are X stones left in the pile, remove some number of stones between 1 and floor(X/K_i) (inclusive) from the pile.
The player who first becomes unable to perform the operation loses the game. Assuming that both players play optimally, determine the winner of the game.
Here, floor(x) represents the largest integer not greater than x.
-----Constraints-----
- 1 \leq N \leq 200
- 1 \leq A_i,K_i \leq 10^9
- All input values are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 K_1
:
A_N K_N
-----Output-----
If Takahashi will win, print Takahashi; if Aoki will win, print Aoki.
-----Sample Input-----
2
5 2
3 3
-----Sample Output-----
Aoki
Initially, from the first pile at most floor(5/2)=2 stones can be removed at a time, and from the second pile at most floor(3/3)=1 stone can be removed at a time.
- If Takahashi first takes two stones from the first pile, from the first pile at most floor(3/2)=1 stone can now be removed at a time, and from the second pile at most floor(3/3)=1 stone can be removed at a time.
- Then, if Aoki takes one stone from the second pile, from the first pile at most floor(3/2)=1 stone can be removed at a time, and from the second pile no more stones can be removed (since floor(2/3)=0).
- Then, if Takahashi takes one stone from the first pile, from the first pile at most floor(2/2)=1 stone can now be removed at a time, and from the second pile no more stones can be removed.
- Then, if Aoki takes one stone from the first pile, from the first pile at most floor(1/2)=0 stones can now be removed at a time, and from the second pile no more stones can be removed.
No more operation can be performed, thus Aoki wins. If Takahashi plays differently, Aoki can also win by play accordingly.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
John Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points.
John Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by 1000000007 (109 + 7).
You should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other.
Input
A single line contains space-separated integers n, m, k (1 ≤ n ≤ 100; n ≤ m ≤ 1018; 0 ≤ k ≤ n2) — the number of rows of the table, the number of columns of the table and the number of points each square must contain.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
In a single line print a single integer — the remainder from dividing the described number of ways by 1000000007 (109 + 7).
Examples
Input
5 6 1
Output
45
Note
Let's consider the first test case:
<image> The gray area belongs to both 5 × 5 squares. So, if it has one point, then there shouldn't be points in any other place. If one of the white areas has a point, then the other one also must have a point. Thus, there are about 20 variants, where the point lies in the gray area and 25 variants, where each of the white areas contains a point. Overall there are 45 variants.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.
At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.
The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.
-----Input-----
The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: x_{i}1, x_{i}2, ..., x_{im} (0 ≤ x_{ij} ≤ k), where x_{ij} is the instruction that must be executed by the i-th core at the j-th cycle. If x_{ij} equals 0, then the corresponding instruction is «do nothing». But if x_{ij} is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number x_{ij}».
We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.
-----Output-----
Print n lines. In the i-th line print integer t_{i}. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.
-----Examples-----
Input
4 3 5
1 0 0
1 0 2
2 3 1
3 2 0
Output
1
1
3
0
Input
3 2 2
1 2
1 2
2 2
Output
1
1
0
Input
1 1 1
0
Output
0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Little Egor likes to play with positive integers and their divisors. Bigger the number to play with, more the fun! The boy asked you to come up with an algorithm, that could play the following game:
Let's define f(n) as the sum of all odd divisors of n. I.e. f(10) = 1 + 5 = 6 and f(21) = 1 + 3 + 7 + 21 = 32. The game is to calculate f(l) + f(l + 1) + ... + f(r - 1) + f(r) for the given integers l and r.
Have fun! But be careful, the integers might be quite big.
------ Input ------
The first line of the input contains one integer T denoting the number of test cases.
The only line of the test case description contains two positive integers l and r.
------ Output ------
For each test case, output the required sum on a separate line.
------ Constraints ------
$1 ≤ T ≤ 10$
$1 ≤ l ≤ r ≤ 10^{5}$
----- Sample Input 1 ------
2
1 10
42 42
----- Sample Output 1 ------
45
32
----- explanation 1 ------
In the first example case, f(1) + f(2) + ... + f(10) = 1 + 1 + 4 + 1 + 6 + 4 + 8 + 1 + 13 + 6 = 45
In the second example case, f(42) = 32.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.
-----Constraints-----
- 1 ≤ N ≤ 50
- 1 ≤ K ≤ N
- S is a string of length N consisting of A, B and C.
-----Input-----
Input is given from Standard Input in the following format:
N K
S
-----Output-----
Print the string S after lowercasing the K-th character in it.
-----Sample Input-----
3 1
ABC
-----Sample Output-----
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.
When you want to get the square of a binomial of two variables x and y, you will have:
`$(x+y)^2 = x^2 + 2xy + y ^2$`
And the cube:
`$(x+y)^3 = x^3 + 3x^2y + 3xy^2 +y^3$`
It is known from many centuries ago that for an exponent n, the result of a binomial x + y raised to the n-th power is:
Or using the sumation notation:
Each coefficient of a term has the following value:
Each coefficient value coincides with the amount of combinations without replacements of a set of n elements using only k different ones of that set.
Let's see the total sum of the coefficients of the different powers for the binomial:
`$(x+y)^0(1)$`
`$(x+y)^1 = x+y(2)$`
`$(x+y)^2 = x^2 + 2xy + y ^2(4)$`
`$(x+y)^3 = x^3 + 3x^2y + 3xy^2 +y^3(8)$`
We need a function that may generate an array with the values of all the coefficients sums from 0 to the value of n included and has the addition of all the sum values as last element.
We add some examples below:
```
f(0) = [1, 1]
f(1) = [1, 2, 3]
f(2) = [1, 2, 4, 7]
f(3) = [1, 2, 4, 8, 15]
```
Features of the test
```
Low Performance Tests
Number of tests = 50
9 < n < 101
High Performance Tests
Number of Tests = 50
99 < n < 5001
```
Write your solution by modifying this code:
```python
def f(n):
```
Your solution should implemented in the function "f". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
problem
In the area where Kazakhstan is now located, there used to be a trade route called the "Silk Road".
There are N + 1 cities on the Silk Road, numbered from west as city 0, city 1, ..., city N. The distance between city i -1 and city i (1 ≤ i ≤ N) is Di.
JOI, a trader, decided to start from city 0, go through the cities in order, and carry silk to city N. Must travel from city 0 to city N within M days. JOI chooses one of the following two actions for each day.
* Move: Move from the current city to the city one east in one day. If you are currently in city i -1 (1 ≤ i ≤ N), move to city i.
* Wait: Do not move and wait for one day in your current city.
It is difficult to move, and the degree of fatigue accumulates each time you move. The weather on the Silk Road fluctuates from day to day, and the worse the weather, the harder it is to move.
It is known that the bad weather on the jth day (1 ≤ j ≤ M) of the M days that JOI can use to carry silk is Cj. When moving from city i -1 to city i (1 ≤ i ≤ N) to day j (1 ≤ j ≤ M), the degree of fatigue accumulates by Di × Cj. Fatigue does not accumulate on days when you are waiting without moving.
JOI wants to move with as little fatigue as possible by choosing the behavior of each day. Find the minimum total fatigue that JOI will accumulate from the start to the end of the move to city N within M days.
input
The input consists of 1 + N + M lines.
On the first line, two integers N and M (1 ≤ N ≤ M ≤ 1000) are written separated by a blank. This means that the Silk Road consists of N + 1 cities and JOI must carry the silk from city 0 to city N within M days.
The integer Di (1 ≤ Di ≤ 1000) is written on the i-th line (1 ≤ i ≤ N) of the following N lines. This means that the distance between city i -1 and city i is Di.
The integer Cj (1 ≤ Cj ≤ 1000) is written on the jth line (1 ≤ j ≤ M) of the following M lines. This means that the bad weather on day j is Cj.
output
Output the minimum value of the total fatigue level accumulated from the start to the end of the movement when JOI moves to the city N within M days in one line.
Example
Input
3 5
10
25
15
50
30
15
40
30
Output
1125
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.
Tablecity can be represented as 1000 × 2 grid, where every cell represents one district. Each district has its own unique name “(X, Y)”, where X and Y are the coordinates of the district in the grid. The thief’s movement is as
Every hour the thief will leave the district (X, Y) he is currently hiding in, and move to one of the districts: (X - 1, Y), (X + 1, Y), (X - 1, Y - 1), (X - 1, Y + 1), (X + 1, Y - 1), (X + 1, Y + 1) as long as it exists in Tablecity.
Below is an example of thief’s possible movements if he is located in district (7,1):
[Image]
Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.
-----Input-----
There is no input for this problem.
-----Output-----
The first line of output contains integer N – duration of police search in hours. Each of the following N lines contains exactly 4 integers X_{i}1, Y_{i}1, X_{i}2, Y_{i}2 separated by spaces, that represent 2 districts (X_{i}1, Y_{i}1), (X_{i}2, Y_{i}2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thief’s initial position and movement. N ≤ 2015 1 ≤ X ≤ 1000 1 ≤ Y ≤ 2
-----Examples-----
Input
В этой задаче нет примеров ввода-вывода.
This problem doesn't have sample input and output.
Output
Смотрите замечание ниже.
See the note below.
-----Note-----
Let's consider the following output:
2
5 1 50 2
8 1 80 2
This output is not guaranteed to catch the thief and is not correct. It is given to you only to show the expected output format. There exists a combination of an initial position and a movement strategy such that the police will not catch the thief.
Consider the following initial position and thief’s movement:
In the first hour, the thief is located in district (1,1). Police officers will search districts (5,1) and (50,2) and will not find him.
At the start of the second hour, the thief moves to district (2,2). Police officers will search districts (8,1) and (80,2) and will not find him.
Since there is no further investigation by the police, the thief escaped!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by $n$ streets along the Eastern direction and $m$ streets across the Southern direction. Naturally, this city has $nm$ intersections. At any intersection of $i$-th Eastern street and $j$-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.
When Dora passes through the intersection of the $i$-th Eastern and $j$-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.
Formally, on every of $nm$ intersections Dora solves an independent problem. She sees $n + m - 1$ skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer $x$ and assign every skyscraper a height from $1$ to $x$. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible $x$.
For example, if the intersection and the two streets corresponding to it look as follows: [Image]
Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved) [Image]
The largest used number is $5$, hence the answer for this intersection would be $5$.
Help Dora to compute the answers for each intersection.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of streets going in the Eastern direction and the number of the streets going in Southern direction.
Each of the following $n$ lines contains $m$ integers $a_{i,1}$, $a_{i,2}$, ..., $a_{i,m}$ ($1 \le a_{i,j} \le 10^9$). The integer $a_{i,j}$, located on $j$-th position in the $i$-th line denotes the height of the skyscraper at the intersection of the $i$-th Eastern street and $j$-th Southern direction.
-----Output-----
Print $n$ lines containing $m$ integers each. The integer $x_{i,j}$, located on $j$-th position inside the $i$-th line is an answer for the problem at the intersection of $i$-th Eastern street and $j$-th Southern street.
-----Examples-----
Input
2 3
1 2 1
2 1 2
Output
2 2 2
2 2 2
Input
2 2
1 2
3 4
Output
2 3
3 2
-----Note-----
In the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.
In the second example, the answers are as follows: For the intersection of the first line and the first column [Image] For the intersection of the first line and the second column [Image] For the intersection of the second line and the first column [Image] For the intersection of the second line and the second column [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.
Note that the memory limit is unusual.
You are given an integer n and two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n.
Let's call a set of integers S such that S ⊆ \{1, 2, 3, ..., n\} strange, if, for every element i of S, the following condition is met: for every j ∈ [1, i - 1], if a_j divides a_i, then j is also included in S. An empty set is always strange.
The cost of the set S is ∑_{i ∈ S} b_i. You have to calculate the maximum possible cost of a strange set.
Input
The first line contains one integer n (1 ≤ n ≤ 3000).
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100).
The third line contains n integers b_1, b_2, ..., b_n (-10^5 ≤ b_i ≤ 10^5).
Output
Print one integer — the maximum cost of a strange set.
Examples
Input
9
4 7 3 4 5 6 7 8 13
-2 3 -19 5 -6 7 -8 9 1
Output
16
Input
2
42 42
-37 13
Output
0
Input
2
42 42
13 -37
Output
13
Note
The strange set with the maximum cost in the first example is \{1, 2, 4, 8, 9\}.
The strange set with the maximum cost in the second example is empty.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 colored permutation $p_1, p_2, \dots, p_n$. The $i$-th element of the permutation has color $c_i$.
Let's define an infinite path as infinite sequence $i, p[i], p[p[i]], p[p[p[i]]] \dots$ where all elements have same color ($c[i] = c[p[i]] = c[p[p[i]]] = \dots$).
We can also define a multiplication of permutations $a$ and $b$ as permutation $c = a \times b$ where $c[i] = b[a[i]]$. Moreover, we can define a power $k$ of permutation $p$ as $p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$.
Find the minimum $k > 0$ such that $p^k$ has at least one infinite path (i.e. there is a position $i$ in $p^k$ such that the sequence starting from $i$ is an infinite path).
It can be proved that the answer always exists.
-----Input-----
The first line contains single integer $T$ ($1 \le T \le 10^4$) — the number of test cases.
Next $3T$ lines contain test cases — one per three lines. The first line contains single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the permutation.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, $p_i \neq p_j$ for $i \neq j$) — the permutation $p$.
The third line contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le n$) — the colors of elements of the permutation.
It is guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers — one per test case. For each test case print minimum $k > 0$ such that $p^k$ has at least one infinite path.
-----Example-----
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
-----Note-----
In the first test case, $p^1 = p = [1, 3, 4, 2]$ and the sequence starting from $1$: $1, p[1] = 1, \dots$ is an infinite path.
In the second test case, $p^5 = [1, 2, 3, 4, 5]$ and it obviously contains several infinite paths.
In the third test case, $p^2 = [3, 6, 1, 8, 7, 2, 5, 4]$ and the sequence starting from $4$: $4, p^2[4]=8, p^2[8]=4, \dots$ is an infinite path since $c_4 = c_8 = 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.
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem.[Image]
You are given four positive integers $a$, $b$, $c$, $d$, such that $a \leq b \leq c \leq d$.
Your task is to find three integers $x$, $y$, $z$, satisfying the following conditions: $a \leq x \leq b$. $b \leq y \leq c$. $c \leq z \leq d$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $x$, $y$, and $z$.
Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 1000$) — the number of test cases.
The next $t$ lines describe test cases. Each test case is given as four space-separated integers $a$, $b$, $c$, $d$ ($1 \leq a \leq b \leq c \leq d \leq 10^9$).
-----Output-----
For each test case, print three integers $x$, $y$, $z$ — the integers you found satisfying the conditions given in the statement.
It is guaranteed that the answer always exists. If there are multiple answers, print any.
-----Example-----
Input
4
1 3 5 7
1 5 5 7
100000 200000 300000 400000
1 1 977539810 977539810
Output
3 4 5
5 5 5
182690 214748 300999
1 977539810 977539810
-----Note-----
One of the possible solutions to the first test case:
[Image]
One of the possible solutions to the second test case:
[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.
JAG mock qualifying practice session
The ACM-ICPC OB / OG Association (Japanese Alumni Group; JAG) has N questions in stock of questions to be asked in the mock contest, and each question is numbered with an integer from 1 to N. Difficulty evaluation and recommendation voting are conducted for each problem. Problem i has a difficulty level of di and a recommendation level of vi. The maximum difficulty level is M.
In the next contest, we plan to ask a total of M questions, one for each of the difficulty levels 1 to M. In order to improve the quality of the contest, I would like to select the questions so that the total recommendation level is maximized. However, since JAG's questioning ability is tremendous, it can be assumed that there is at least one question for each difficulty level.
Your job is to create a program that finds the maximum sum of the sums of recommendations when the questions are selected to meet the conditions.
Input
The input consists of multiple datasets. Each dataset is represented in the following format.
> N M
> d1 v1
> ...
> dN vN
>
The first line of the dataset is given an integer N, which represents the number of problem stocks, and a maximum difficulty value, M, separated by blanks. These numbers satisfy 1 ≤ M ≤ N ≤ 100. On the i-th line of the following N lines, the integers di and vi representing the difficulty level and recommendation level of problem i are given, separated by blanks. These numbers satisfy 1 ≤ di ≤ M and 0 ≤ vi ≤ 100. Also, for each 1 ≤ j ≤ M, it is guaranteed that there is at least one i such that di = j.
> The end of the input is represented by two zeros separated by a blank. Also, the number of datasets does not exceed 50.
> ### Output
For each data set, output the maximum value of the sum of the recommendation levels of the questions to be asked when one question is asked from each difficulty level on one line.
> ### Sample Input
5 3
1 1
twenty three
3 2
3 5
twenty one
4 2
1 7
twenty one
13
1 5
6 1
13
1 2
1 8
1 2
1 7
1 6
20 9
4 10
twenty four
5 3
6 6
6 3
7 4
8 10
4 6
7 5
1 8
5 7
1 5
6 6
9 9
5 8
6 7
14
6 4
7 10
3 5
19 6
4 1
6 5
5 10
1 10
3 10
4 6
twenty three
5 4
2 10
1 8
3 4
3 1
5 4
1 10
13
5 6
5 2
1 10
twenty three
0 0
There are 5 sample datasets, in order
Lines 1 to 6 are the first (N = 5, M = 3) test cases,
Lines 7 to 11 are the second (N = 4, M = 2) test case,
Lines 12-18 are the third (N = 6, M = 1) test case,
The fourth (N = 20, M = 9) test case from line 19 to line 39,
Lines 40 to 59 represent the fifth test case (N = 19, M = 6).
Output for Sample Input
9
8
8
71
51
Example
Input
5 3
1 1
2 3
3 2
3 5
2 1
4 2
1 7
2 1
1 3
1 5
6 1
1 3
1 2
1 8
1 2
1 7
1 6
20 9
4 10
2 4
5 3
6 6
6 3
7 4
8 10
4 6
7 5
1 8
5 7
1 5
6 6
9 9
5 8
6 7
1 4
6 4
7 10
3 5
19 6
4 1
6 5
5 10
1 10
3 10
4 6
2 3
5 4
2 10
1 8
3 4
3 1
5 4
1 10
1 3
5 6
5 2
1 10
2 3
0 0
Output
9
8
8
71
51
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 any sentence and redistributes the spaces (and adds additional spaces if needed) so that each word starts with a vowel. The letters should all be in the same order but every vowel in the sentence should be the start of a new word. The first word in the new sentence may start without a vowel. It should return a string in all lowercase with no punctuation (only alphanumeric characters).
EXAMPLES
'It is beautiful weather today!' becomes 'it isb e a ut if ulw e ath ert od ay'
'Coding is great' becomes 'c od ing isgr e at'
'my number is 0208-533-2325' becomes 'myn umb er is02085332325'
Write your solution by modifying this code:
```python
def vowel_start(st):
```
Your solution should implemented in the function "vowel_start". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?
If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.
-----Input-----
The first line of the input contains integers n and m (1 ≤ n, m ≤ 100) — the number of buttons and the number of bulbs respectively.
Each of the next n lines contains x_{i} (0 ≤ x_{i} ≤ m) — the number of bulbs that are turned on by the i-th button, and then x_{i} numbers y_{ij} (1 ≤ y_{ij} ≤ m) — the numbers of these bulbs.
-----Output-----
If it's possible to turn on all m bulbs print "YES", otherwise print "NO".
-----Examples-----
Input
3 4
2 1 4
3 1 3 1
1 2
Output
YES
Input
3 3
1 1
1 2
1 1
Output
NO
-----Note-----
In the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Berkomnadzor — Federal Service for Supervision of Communications, Information Technology and Mass Media — is a Berland federal executive body that protects ordinary residents of Berland from the threats of modern internet.
Berkomnadzor maintains a list of prohibited IPv4 subnets (blacklist) and a list of allowed IPv4 subnets (whitelist). All Internet Service Providers (ISPs) in Berland must configure the network equipment to block access to all IPv4 addresses matching the blacklist. Also ISPs must provide access (that is, do not block) to all IPv4 addresses matching the whitelist. If an IPv4 address does not match either of those lists, it's up to the ISP to decide whether to block it or not. An IPv4 address matches the blacklist (whitelist) if and only if it matches some subnet from the blacklist (whitelist). An IPv4 address can belong to a whitelist and to a blacklist at the same time, this situation leads to a contradiction (see no solution case in the output description).
An IPv4 address is a 32-bit unsigned integer written in the form $a.b.c.d$, where each of the values $a,b,c,d$ is called an octet and is an integer from $0$ to $255$ written in decimal notation. For example, IPv4 address $192.168.0.1$ can be converted to a 32-bit number using the following expression $192 \cdot 2^{24} + 168 \cdot 2^{16} + 0 \cdot 2^8 + 1 \cdot 2^0$. First octet $a$ encodes the most significant (leftmost) $8$ bits, the octets $b$ and $c$ — the following blocks of $8$ bits (in this order), and the octet $d$ encodes the least significant (rightmost) $8$ bits.
The IPv4 network in Berland is slightly different from the rest of the world. There are no reserved or internal addresses in Berland and use all $2^{32}$ possible values.
An IPv4 subnet is represented either as $a.b.c.d$ or as $a.b.c.d/x$ (where $0 \le x \le 32$). A subnet $a.b.c.d$ contains a single address $a.b.c.d$. A subnet $a.b.c.d/x$ contains all IPv4 addresses with $x$ leftmost (most significant) bits equal to $x$ leftmost bits of the address $a.b.c.d$. It is required that $32 - x$ rightmost (least significant) bits of subnet $a.b.c.d/x$ are zeroes.
Naturally it happens that all addresses matching subnet $a.b.c.d/x$ form a continuous range. The range starts with address $a.b.c.d$ (its rightmost $32 - x$ bits are zeroes). The range ends with address which $x$ leftmost bits equal to $x$ leftmost bits of address $a.b.c.d$, and its $32 - x$ rightmost bits are all ones. Subnet contains exactly $2^{32-x}$ addresses. Subnet $a.b.c.d/32$ contains exactly one address and can also be represented by just $a.b.c.d$.
For example subnet $192.168.0.0/24$ contains range of 256 addresses. $192.168.0.0$ is the first address of the range, and $192.168.0.255$ is the last one.
Berkomnadzor's engineers have devised a plan to improve performance of Berland's global network. Instead of maintaining both whitelist and blacklist they want to build only a single optimised blacklist containing minimal number of subnets. The idea is to block all IPv4 addresses matching the optimised blacklist and allow all the rest addresses. Of course, IPv4 addresses from the old blacklist must remain blocked and all IPv4 addresses from the old whitelist must still be allowed. Those IPv4 addresses which matched neither the old blacklist nor the old whitelist may be either blocked or allowed regardless of their accessibility before.
Please write a program which takes blacklist and whitelist as input and produces optimised blacklist. The optimised blacklist must contain the minimal possible number of subnets and satisfy all IPv4 addresses accessibility requirements mentioned above.
IPv4 subnets in the source lists may intersect arbitrarily. Please output a single number -1 if some IPv4 address matches both source whitelist and blacklist.
-----Input-----
The first line of the input contains single integer $n$ ($1 \le n \le 2\cdot10^5$) — total number of IPv4 subnets in the input.
The following $n$ lines contain IPv4 subnets. Each line starts with either '-' or '+' sign, which indicates if the subnet belongs to the blacklist or to the whitelist correspondingly. It is followed, without any spaces, by the IPv4 subnet in $a.b.c.d$ or $a.b.c.d/x$ format ($0 \le x \le 32$). The blacklist always contains at least one subnet.
All of the IPv4 subnets given in the input are valid. Integer numbers do not start with extra leading zeroes. The provided IPv4 subnets can intersect arbitrarily.
-----Output-----
Output -1, if there is an IPv4 address that matches both the whitelist and the blacklist. Otherwise output $t$ — the length of the optimised blacklist, followed by $t$ subnets, with each subnet on a new line. Subnets may be printed in arbitrary order. All addresses matching the source blacklist must match the optimised blacklist. All addresses matching the source whitelist must not match the optimised blacklist. You can print a subnet $a.b.c.d/32$ in any of two ways: as $a.b.c.d/32$ or as $a.b.c.d$.
If there is more than one solution, output any.
-----Examples-----
Input
1
-149.154.167.99
Output
1
0.0.0.0/0
Input
4
-149.154.167.99
+149.154.167.100/30
+149.154.167.128/25
-149.154.167.120/29
Output
2
149.154.167.99
149.154.167.120/29
Input
5
-127.0.0.4/31
+127.0.0.8
+127.0.0.0/30
-195.82.146.208/29
-127.0.0.6/31
Output
2
195.0.0.0/8
127.0.0.4/30
Input
2
+127.0.0.1/32
-127.0.0.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.
Ringo is giving a present to Snuke.
Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with `YAKI` in Japanese, and does not like other things.
You are given a string S representing the Japanese name of Ringo's present to Snuke. Determine whether S starts with `YAKI`.
Constraints
* 1 \leq |S| \leq 10
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If S starts with `YAKI`, print `Yes`; otherwise, print `No`.
Examples
Input
YAKINIKU
Output
Yes
Input
TAKOYAKI
Output
No
Input
YAK
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.
Write a program which reads two integers x and y, and prints them in ascending order.
Constraints
* 0 ≤ x, y ≤ 10000
* the number of datasets ≤ 3000
Input
The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.
The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.
Output
For each dataset, print x and y in ascending order in a line. Put a single space between x and y.
Example
Input
3 2
2 2
5 3
0 0
Output
2 3
2 2
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.
Today, Yasser and Adel are at the shop buying cupcakes. There are $n$ cupcake types, arranged from $1$ to $n$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $i$ is an integer $a_i$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.
On the other hand, Adel will choose some segment $[l, r]$ $(1 \le l \le r \le n)$ that does not include all of cupcakes (he can't choose $[l, r] = [1, n]$) and buy exactly one cupcake of each of types $l, l + 1, \dots, r$.
After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.
For example, let the tastinesses of the cupcakes be $[7, 4, -1]$. Yasser will buy all of them, the total tastiness will be $7 + 4 - 1 = 10$. Adel can choose segments $[7], [4], [-1], [7, 4]$ or $[4, -1]$, their total tastinesses are $7, 4, -1, 11$ and $3$, respectively. Adel can choose segment with tastiness $11$, and as $10$ is not strictly greater than $11$, Yasser won't be happy :(
Find out if Yasser will be happy after visiting the shop.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.
The first line of each test case contains $n$ ($2 \le n \le 10^5$).
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-10^9 \le a_i \le 10^9$), where $a_i$ represents the tastiness of the $i$-th type of cupcake.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".
-----Example-----
Input
3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
Output
YES
NO
NO
-----Note-----
In the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.
In the second example, Adel will choose the segment $[1, 2]$ with total tastiness $11$, which is not less than the total tastiness of all cupcakes, which is $10$.
In the third example, Adel can choose the segment $[3, 3]$ with total tastiness of $5$. Note that Yasser's cupcakes' total tastiness is also $5$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with $n$ vertices, then he will ask you $q$ queries. Each query contains $5$ integers: $x$, $y$, $a$, $b$, and $k$. This means you're asked to determine if there exists a path from vertex $a$ to $b$ that contains exactly $k$ edges after adding a bidirectional edge between vertices $x$ and $y$. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
-----Input-----
The first line contains an integer $n$ ($3 \le n \le 10^5$), the number of vertices of the tree.
Next $n-1$ lines contain two integers $u$ and $v$ ($1 \le u,v \le n$, $u \ne v$) each, which means there is an edge between vertex $u$ and $v$. All edges are bidirectional and distinct.
Next line contains an integer $q$ ($1 \le q \le 10^5$), the number of queries Gildong wants to ask.
Next $q$ lines contain five integers $x$, $y$, $a$, $b$, and $k$ each ($1 \le x,y,a,b \le n$, $x \ne y$, $1 \le k \le 10^9$) – the integers explained in the description. It is guaranteed that the edge between $x$ and $y$ does not exist in the original tree.
-----Output-----
For each query, print "YES" if there exists a path that contains exactly $k$ edges from vertex $a$ to $b$ after adding an edge between vertices $x$ and $y$. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
-----Example-----
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
-----Note-----
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). [Image]
Possible paths for the queries with "YES" answers are: $1$-st query: $1$ – $3$ – $2$ $2$-nd query: $1$ – $2$ – $3$ $4$-th query: $3$ – $4$ – $2$ – $3$ – $4$ – $2$ – $3$ – $4$ – $2$ – $3$
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) × (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection.
[Image]
The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.
-----Input-----
The first line of input contains two integers n and m, (2 ≤ n, m ≤ 20), denoting the number of horizontal streets and the number of vertical streets.
The second line contains a string of length n, made of characters '<' and '>', denoting direction of each horizontal street. If the i-th character is equal to '<', the street is directed from east to west otherwise, the street is directed from west to east. Streets are listed in order from north to south.
The third line contains a string of length m, made of characters '^' and 'v', denoting direction of each vertical street. If the i-th character is equal to '^', the street is directed from south to north, otherwise the street is directed from north to south. Streets are listed in order from west to east.
-----Output-----
If the given pattern meets the mayor's criteria, print a single line containing "YES", otherwise print a single line containing "NO".
-----Examples-----
Input
3 3
><>
v^v
Output
NO
Input
4 6
<><>
v^v^v^
Output
YES
-----Note-----
The figure above shows street directions in the second sample test case.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.
You are given N numbers X_1, X_2, ..., X_N, where N is an even number. For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.
Find B_i for each i = 1, 2, ..., N.
Constraints
* 2 \leq N \leq 200000
* N is even.
* 1 \leq X_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
X_1 X_2 ... X_N
Output
Print N lines. The i-th line should contain B_i.
Examples
Input
4
2 4 4 3
Output
4
3
3
4
Input
2
1 2
Output
2
1
Input
6
5 5 4 4 3 3
Output
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.
An NBA game runs 48 minutes (Four 12 minute quarters). Players do not typically play the full game, subbing in and out as necessary. Your job is to extrapolate a player's points per game if they played the full 48 minutes.
Write a function that takes two arguments, ppg (points per game) and mpg (minutes per game) and returns a straight extrapolation of ppg per 48 minutes rounded to the nearest tenth. Return 0 if 0.
Examples:
```python
nba_extrap(12, 20) # 28.8
nba_extrap(10, 10) # 48
nba_extrap(5, 17) # 14.1
nba_extrap(0, 0) # 0
```
Notes:
All inputs will be either be an integer or float.
Follow your dreams!
Write your solution by modifying this code:
```python
def nba_extrap(ppg, mpg):
```
Your solution should implemented in the function "nba_extrap". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Childan is making up a legendary story and trying to sell his forgery — a necklace with a strong sense of "Wu" to the Kasouras. But Mr. Kasoura is challenging the truth of Childan's story. So he is going to ask a few questions about Childan's so-called "personal treasure" necklace.
This "personal treasure" is a multiset S of m "01-strings".
A "01-string" is a string that contains n characters "0" and "1". For example, if n=4, strings "0110", "0000", and "1110" are "01-strings", but "00110" (there are 5 characters, not 4) and "zero" (unallowed characters) are not.
Note that the multiset S can contain equal elements.
Frequently, Mr. Kasoura will provide a "01-string" t and ask Childan how many strings s are in the multiset S such that the "Wu" value of the pair (s, t) is not greater than k.
Mrs. Kasoura and Mr. Kasoura think that if s_i = t_i (1≤ i≤ n) then the "Wu" value of the character pair equals to w_i, otherwise 0. The "Wu" value of the "01-string" pair is the sum of the "Wu" values of every character pair. Note that the length of every "01-string" is equal to n.
For example, if w=[4, 5, 3, 6], "Wu" of ("1001", "1100") is 7 because these strings have equal characters only on the first and third positions, so w_1+w_3=4+3=7.
You need to help Childan to answer Mr. Kasoura's queries. That is to find the number of strings in the multiset S such that the "Wu" value of the pair is not greater than k.
Input
The first line contains three integers n, m, and q (1≤ n≤ 12, 1≤ q, m≤ 5⋅ 10^5) — the length of the "01-strings", the size of the multiset S, and the number of queries.
The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_i ≤ 100) — the value of the i-th caracter.
Each of the next m lines contains the "01-string" s of length n — the string in the multiset S.
Each of the next q lines contains the "01-string" t of length n and integer k (0≤ k≤ 100) — the query.
Output
For each query, print the answer for this query.
Examples
Input
2 4 5
40 20
01
01
10
11
00 20
00 40
11 20
11 40
11 60
Output
2
4
2
3
4
Input
1 2 4
100
0
1
0 0
0 100
1 0
1 100
Output
1
2
1
2
Note
In the first example, we can get:
"Wu" of ("01", "00") is 40.
"Wu" of ("10", "00") is 20.
"Wu" of ("11", "00") is 0.
"Wu" of ("01", "11") is 20.
"Wu" of ("10", "11") is 40.
"Wu" of ("11", "11") is 60.
In the first query, pairs ("11", "00") and ("10", "00") satisfy the condition since their "Wu" is not greater than 20.
In the second query, all strings satisfy the condition.
In the third query, pairs ("01", "11") and ("01", "11") satisfy the condition. Note that since there are two "01" strings in the multiset, the answer is 2, not 1.
In the fourth query, since k was increased, pair ("10", "11") satisfies the condition too.
In the fifth query, since k was increased, pair ("11", "11") satisfies the condition too.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's denote that some array $b$ is bad if it contains a subarray $b_l, b_{l+1}, \dots, b_{r}$ of odd length more than $1$ ($l < r$ and $r - l + 1$ is odd) such that $\forall i \in \{0, 1, \dots, r - l\}$ $b_{l + i} = b_{r - i}$.
If an array is not bad, it is good.
Now you are given an array $a_1, a_2, \dots, a_n$. Some elements are replaced by $-1$. Calculate the number of good arrays you can obtain by replacing each $-1$ with some integer from $1$ to $k$.
Since the answer can be large, print it modulo $998244353$.
-----Input-----
The first line contains two integers $n$ and $k$ ($2 \le n, k \le 2 \cdot 10^5$) — the length of array $a$ and the size of "alphabet", i. e., the upper bound on the numbers you may use to replace $-1$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($a_i = -1$ or $1 \le a_i \le k$) — the array $a$.
-----Output-----
Print one integer — the number of good arrays you can get, modulo $998244353$.
-----Examples-----
Input
2 3
-1 -1
Output
9
Input
5 2
1 -1 -1 1 2
Output
0
Input
5 3
1 -1 -1 1 2
Output
2
Input
4 200000
-1 -1 12345 -1
Output
735945883
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 17th century, Fermat wrote that he proved for any integer $n \geq 3$, there exist no positive integers $x$, $y$, $z$ such that $x^n + y^n = z^n$. However he never disclosed the proof. Later, this claim was named Fermat's Last Theorem or Fermat's Conjecture.
If Fermat's Last Theorem holds in case of $n$, then it also holds in case of any multiple of $n$. Thus it suffices to prove cases where $n$ is a prime number and the special case $n$ = 4.
A proof for the case $n$ = 4 was found in Fermat's own memorandum. The case $n$ = 3 was proved by Euler in the 18th century. After that, many mathematicians attacked Fermat's Last Theorem. Some of them proved some part of the theorem, which was a partial success. Many others obtained nothing. It was a long history. Finally, Wiles proved Fermat's Last Theorem in 1994.
Fermat's Last Theorem implies that for any integers $n \geq 3$ and $z > 1$, it always holds that
$z^n > $ max { $x^n + y^n | x > 0, y > 0, x^n + y^n \leq z^n$ }.
Your mission is to write a program that verifies this in the case $n$ = 3 for a given $z$. Your program should read in integer numbers greater than 1, and, corresponding to each input $z$, it should output the following:
$z^3 - $ max { $x^3 + y^3 | x > 0, y > 0, x^3 + y^3 \leq z^3$ }.
Input
The input is a sequence of lines each containing one positive integer number followed by a line containing a zero. You may assume that all of the input integers are greater than 1 and less than 1111.
Output
The output should consist of lines each containing a single integer number. Each output integer should be
$z^3 - $ max { $x^3 + y^3 | x > 0, y > 0, x^3 + y^3 \leq z^3$ }.
for the corresponding input integer z. No other characters should appear in any output line.
Example
Input
6
4
2
0
Output
27
10
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.
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:
- The 0 key: a letter 0 will be inserted to the right of the string.
- The 1 key: a letter 1 will be inserted to the right of the string.
- The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.
Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?
-----Constraints-----
- 1 ≦ |s| ≦ 10 (|s| denotes the length of s)
- s consists of the letters 0, 1 and B.
- The correct answer is not an empty string.
-----Input-----
The input is given from Standard Input in the following format:
s
-----Output-----
Print the string displayed in the editor in the end.
-----Sample Input-----
01B0
-----Sample Output-----
00
Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.
Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs a rubles, or in glass liter bottle, that costs b rubles. Also, you may return empty glass bottle and get c (c < b) rubles back, but you cannot return plastic bottles.
Kolya has n rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.
-----Input-----
First line of the input contains a single integer n (1 ≤ n ≤ 10^18) — the number of rubles Kolya has at the beginning.
Then follow three lines containing integers a, b and c (1 ≤ a ≤ 10^18, 1 ≤ c < b ≤ 10^18) — the cost of one plastic liter bottle, the cost of one glass liter bottle and the money one can get back by returning an empty glass bottle, respectively.
-----Output-----
Print the only integer — maximum number of liters of kefir, that Kolya can drink.
-----Examples-----
Input
10
11
9
8
Output
2
Input
10
5
6
1
Output
2
-----Note-----
In the first sample, Kolya can buy one glass bottle, then return it and buy one more glass bottle. Thus he will drink 2 liters of kefir.
In the second sample, Kolya can buy two plastic bottle and get two liters of kefir, or he can buy one liter glass bottle, then return it and buy one plastic bottle. In both cases he will drink two liters of kefir.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 are a game developer and have programmed the #1 MMORPG(Massively Multiplayer Online Role Playing Game) worldwide!!! Many suggestions came across you to make the game better, one of which you are interested in and will start working on at once.
Players in the game have levels from 1 to 170, XP(short for experience) is required to increase the player's level and is obtained by doing all sorts of things in the game, a new player starts at level 1 with 0 XP. You want to add a feature that would enable the player to input a target level and the output would be how much XP the player must obtain in order for him/her to reach the target level...simple huh.
Create a function called ```xp_to_target_lvl``` that takes 2 arguments(```current_xp``` and ```target_lvl```, both as integer) and returns the remaining XP for the player to reach the ```target_lvl``` formatted as a rounded down integer.
Leveling up from level 1 to level 2 requires 314 XP, at first each level up requires 25% XP more than the previous level up, every 10 levels the percentage increase reduces by 1. See the examples for a better understanding.
Keep in mind that when players reach level 170 they stop leveling up but they continue gaining experience.
If one or both of the arguments are invalid(not given, not in correct format, not in range...etc) return "Input is invalid.".
If the player has already reached the ```target_lvl``` return ```"You have already reached level target_lvl."```.
Examples:
```
xp_to_target_lvl(0,5) => XP from lvl1 to lvl2 = 314
XP from lvl2 to lvl3 = 314 + (314*0.25) = 392
XP from lvl3 to lvl4 = 392 + (392*0.25) = 490
XP from lvl4 to lvl5 = 490 + (490*0.25) = 612
XP from lvl1 to target_lvl = 314 + 392 + 490 + 612 = 1808
XP from current_xp to target_lvl = 1808 - 0 = 1808
xp_to_target_lvl(12345,17) => XP from lvl1 to lvl2 = 314
XP from lvl2 to lvl3 = 314 + (314*0.25) = 392
XP from lvl3 to lvl4 = 392 + (392*0.25) = 490
...
XP from lvl9 to lvl10 = 1493 + (1493*0.25) = 1866
XP from lvl10 to lvl11 = 1866 + (1866*0.24) = 2313 << percentage increase is
... reduced by 1 (25 - 1 = 24)
XP from lvl16 to lvl17 = 6779 + (6779*0.24) = 8405
XP from lvl1 to target_lvl = 314 + 392 + 490 + 612 + ... + 8405 = 41880
XP from current_xp to target_lvl = 41880 - 12345 = 29535
xp_to_target_lvl() => "Input is invalid." }
xp_to_target_lvl(-31428.7,'47') => "Input is invalid." }> Invalid input
xp_to_target_lvl(83749,0) => "Input is invalid." }
xp_to_target_lvl(2017,4) => "You have already reached level 4."
xp_to_target_lvl(0,1) => 'You have already reached level 1.'
```
Make sure you round down the XP required for each level up, rounding up will result in the output being slightly wrong.
Write your solution by modifying this code:
```python
def xp_to_target_lvl(current_xp=None, target_lvl=None):
```
Your solution should implemented in the function "xp_to_target_lvl". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
## Task
Given a positive integer `n`, calculate the following sum:
```
n + n/2 + n/4 + n/8 + ...
```
All elements of the sum are the results of integer division.
## Example
```
25 => 25 + 12 + 6 + 3 + 1 = 47
```
Write your solution by modifying this code:
```python
def halving_sum(n):
```
Your solution should implemented in the function "halving_sum". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As bad weather continues and vegetable prices soar, Seven-Eleven is offering customers bulk purchase sales of vegetables. The store is very busy, as you can get vegetables that are hard to find in stores at reasonable prices.
One day, a group of three good friends living in the Matsunaga housing complex bloomed with an advertisement for Seven-Eleven. Since this sale was called "Customer Thanksgiving Day", the highlight is that the cheapest vegetables in the bag are free. When I read the advertisement, it looks like the following sale.
* Up to m vegetables can be packed in one bag.
* For bags packed with m vegetables, the cheapest vegetables are free.
* Bags with less than m vegetables are not eligible for the discount.
The three went shopping at Seven Mart immediately.
When the three people who met outside the store after shopping were satisfied with the fact that they were able to buy a lot at a low price, they apparently found that they were all buying the same vegetables. One person said, "It's really cheap, isn't it? This is XXX yen!", And the other was surprised, "What? I was ** yen higher than that! Why?", And the rest One of them saw the receipt and noticed that he bought the cheapest one.
Now, how can you pack the bag at the lowest purchase price? Enter the number of vegetables to purchase, the number of vegetables in the bag, and the price of each vegetable, and create a program that outputs the minimum purchase price.
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 given in the following format:
n m
p1 p2 ... pn
The first line gives the number of vegetables to buy n (1 ≤ n ≤ 1000) and the number of vegetables to put in the bag m (1 ≤ m ≤ 1000). The second line gives the price pi (10 ≤ pi ≤ 10000) for each vegetable.
The number of datasets does not exceed 100.
Output
Prints the minimum purchase price on one line for each input dataset.
Example
Input
4 2
50 40 100 80
7 3
400 300 100 700 200 600 500
0 0
Output
150
2100
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms.
Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)).
Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs.
-----Input-----
The first line of the input contains single integer n (1 ≤ n ≤ 10^5) — the number of moves in the walking sequence.
The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.
-----Output-----
On a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.
-----Examples-----
Input
1
U
Output
0
Input
6
RURUUR
Output
1
Input
7
URRRUUU
Output
2
-----Note-----
The figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at which Fafa have to pay silver coins. [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.
Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.
There are m buses running between the house and the school: the i-th bus goes from stop si to ti (si < ti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to ti - 1 inclusive, but he can get off the i-th bus only on the bus stop ti.
Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.
Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109 + 7).
Input
The first line contains two space-separated integers: n and m (1 ≤ n ≤ 109, 0 ≤ m ≤ 105). Then follow m lines each containing two integers si, ti. They are the numbers of starting stops and end stops of the buses (0 ≤ si < ti ≤ n).
Output
Print the only number — the number of ways to get to the school modulo 1000000007 (109 + 7).
Examples
Input
2 2
0 1
1 2
Output
1
Input
3 2
0 1
1 2
Output
0
Input
5 5
0 1
0 2
0 3
0 4
0 5
Output
16
Note
The first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two.
In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0.
In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 24 = 16.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Cyael is a teacher at a very famous school in Byteland and she is known by her students for being very polite to them and also to encourage them to get good marks on their tests.
Then, if they get good marks she will reward them with candies :) However, she knows they are all very good at Mathematics, so she decided to split the candies evenly to all the students she considers worth of receiving them, so they don't fight with each other.
She has a bag which initially contains N candies and she intends to split the candies evenly to K students. To do this she will proceed as follows: while she has more than K candies she will give exactly 1 candy to each student until she has less than K candies. On this situation, as she can't split candies equally among all students she will keep the remaining candies to herself.
Your job is to tell how many candies will each student and the teacher
receive after the splitting is performed.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case will consist of 2 space separated integers, N and K denoting the number of candies and the number of students as described above.
-----Output-----
For each test case, output a single line containing two space separated integers, the first one being the number of candies each student will get, followed by the number of candies the teacher will get.
-----Constraints-----
- T<=100 in each test file
- 0 <= N,K <= 233 - 1
-----Example-----Input:
2
10 2
100 3
Output:
5 0
33 1
-----Explanation-----
For the first test case, all students can get an equal number of candies and teacher receives no candies at all
For the second test case, teacher can give 33 candies to each student and keep 1 candy to herselfUpdate:
There may be multiple whitespaces before, after or between the numbers in input.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched.
Example:
'acb' --> 'bca'
'aabacbaa' --> 'bbabcabb'
Write your solution by modifying this code:
```python
def switcheroo(string):
```
Your solution should implemented in the function "switcheroo". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's define a good tree:It is a tree with k * n nodes labeled from 0 to k * n - 1
Node i and node j are not adjacent, for all 0 ≤ i, j < k * n such that i div k = j div k (here div means integer division. E.g. 7 div 2 = 3)
Given n and k, how many different good trees are there?
------ Input ------
Two integers n(1 ≤ n ≤ 10^{5}), k(1≤ k ≤3)
------ Output ------
Output the number of different good trees. As the result may be very large, just output the remainder when divided by (10^{9} + 7).
----- Sample Input 1 ------
2 2
----- Sample Output 1 ------
4
----- explanation 1 ------
----- Sample Input 2 ------
1 2
----- Sample Output 2 ------
0
----- explanation 2 ------
----- Sample Input 3 ------
4 1
----- Sample Output 3 ------
16
----- explanation 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.
# Task
Given a sorted array of integers `A`, find such an integer x that the value of `abs(A[0] - x) + abs(A[1] - x) + ... + abs(A[A.length - 1] - x)`
is the smallest possible (here abs denotes the `absolute value`).
If there are several possible answers, output the smallest one.
# Example
For `A = [2, 4, 7]`, the output should be `4`.
# Input/Output
- `[input]` integer array `A`
A non-empty array of integers, sorted in ascending order.
Constraints:
`1 ≤ A.length ≤ 200,`
`-1000000 ≤ A[i] ≤ 1000000.`
- `[output]` an integer
Write your solution by modifying this code:
```python
def absolute_values_sum_minimization(A):
```
Your solution should implemented in the function "absolute_values_sum_minimization". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $k$ flowers.
The work material for the wreaths for all $n$ citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence $a_1$, $a_2$, ..., $a_m$, where $a_i$ is an integer that denotes the type of flower at the position $i$. This year the liana is very long ($m \ge n \cdot k$), and that means every citizen will get a wreath.
Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts $k$ flowers from the beginning of the liana, then another $k$ flowers and so on. Each such piece of $k$ flowers is called a workpiece. The machine works until there are less than $k$ flowers on the liana.
Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, $k$ flowers must contain flowers of types $b_1$, $b_2$, ..., $b_s$, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.
Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least $n$ workpieces?
-----Input-----
The first line contains four integers $m$, $k$, $n$ and $s$ ($1 \le n, k, m \le 5 \cdot 10^5$, $k \cdot n \le m$, $1 \le s \le k$): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively.
The second line contains $m$ integers $a_1$, $a_2$, ..., $a_m$ ($1 \le a_i \le 5 \cdot 10^5$) — types of flowers on the liana.
The third line contains $s$ integers $b_1$, $b_2$, ..., $b_s$ ($1 \le b_i \le 5 \cdot 10^5$) — the sequence in Diana's schematic.
-----Output-----
If it's impossible to remove some of the flowers so that there would be at least $n$ workpieces and at least one of them fullfills Diana's schematic requirements, output $-1$.
Otherwise in the first line output one integer $d$ — the number of flowers to be removed by Diana.
In the next line output $d$ different integers — the positions of the flowers to be removed.
If there are multiple answers, print any.
-----Examples-----
Input
7 3 2 2
1 2 3 3 2 1 2
2 2
Output
1
4
Input
13 4 3 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
-1
Input
13 4 1 3
3 2 6 4 1 4 4 7 1 3 3 2 4
4 3 4
Output
9
1 2 3 4 5 9 11 12 13
-----Note-----
In the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types $[1, 2, 3]$ and $[3, 2, 1]$. Those workpieces don't fit Diana's schematic. But if you remove flower on $4$-th place, the machine would output workpieces $[1, 2, 3]$ and $[2, 1, 2]$. The second workpiece fits Diana's schematic.
In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.
In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string.
The words in the input String will only contain valid consecutive numbers.
## Examples
```
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"" --> ""
```
Write your solution by modifying this code:
```python
def order(sentence):
```
Your solution should implemented in the function "order". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has decided to construct a string that starts with A and ends with Z, by taking out a substring of a string s (that is, a consecutive part of s).
Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with A and ends with Z.
-----Constraints-----
- 1 ≦ |s| ≦ 200{,}000
- s consists of uppercase English letters.
- There exists a substring of s that starts with A and ends with Z.
-----Input-----
The input is given from Standard Input in the following format:
s
-----Output-----
Print the answer.
-----Sample Input-----
QWERTYASDFZXCV
-----Sample Output-----
5
By taking out the seventh through eleventh characters, it is possible to construct ASDFZ, which starts with A and ends with Z.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a positive even number N.
Find the number of strings s of length N consisting of `A`, `B`, and `C` that satisfy the following condition:
* s can be converted to the empty string by repeating the following operation:
* Choose two consecutive characters in s and erase them. However, choosing `AB` or `BA` is not allowed.
For example, `ABBC` satisfies the condition for N=4, because we can convert it as follows: `ABBC` → (erase `BB`) → `AC` → (erase `AC`) → `(empty)`.
The answer can be enormous, so compute the count modulo 998244353.
Constraints
* 2 \leq N \leq 10^7
* N is an even number.
Input
Input is given from Standard Input in the following format:
N
Output
Print the number of strings that satisfy the conditions, modulo 998244353.
Examples
Input
2
Output
7
Input
10
Output
50007
Input
1000000
Output
210055358
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 number is self-descriptive when the n'th digit describes the amount n appears in the number.
E.g. 21200:
There are two 0's in the number, so the first digit is 2.
There is one 1 in the number, so the second digit is 1.
There are two 2's in the number, so the third digit is 2.
There are no 3's in the number, so the fourth digit is 0.
There are no 4's in the number, so the fifth digit is 0
Numbers can be of any length up to 9 digits and are only full integers. For a given number derive a function ```selfDescriptive(num)``` that returns; ```true``` if the number is self-descriptive or ```false``` if the number is not.
Write your solution by modifying this code:
```python
def self_descriptive(num):
```
Your solution should implemented in the function "self_descriptive". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This version of the problem differs from the next one only in the constraint on n.
Note that the memory limit in this problem is lower than in others.
You have a vertical strip with n cells, numbered consecutively from 1 to n from top to bottom.
You also have a token that is initially placed in cell n. You will move the token up until it arrives at cell 1.
Let the token be in cell x > 1 at some moment. One shift of the token can have either of the following kinds:
* Subtraction: you choose an integer y between 1 and x-1, inclusive, and move the token from cell x to cell x - y.
* Floored division: you choose an integer z between 2 and x, inclusive, and move the token from cell x to cell ⌊ x/z ⌋ (x divided by z rounded down).
Find the number of ways to move the token from cell n to cell 1 using one or more shifts, and print it modulo m. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered distinct (check example explanation for a better understanding).
Input
The only line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5; 10^8 < m < 10^9; m is a prime number) — the length of the strip and the modulo.
Output
Print the number of ways to move the token from cell n to cell 1, modulo m.
Examples
Input
3 998244353
Output
5
Input
5 998244353
Output
25
Input
42 998244353
Output
793019428
Note
In the first test, there are three ways to move the token from cell 3 to cell 1 in one shift: using subtraction of y = 2, or using division by z = 2 or z = 3.
There are also two ways to move the token from cell 3 to cell 1 via cell 2: first subtract y = 1, and then either subtract y = 1 again or divide by z = 2.
Therefore, there are five ways in total.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score p_{i} and it takes exactly t_{i} minutes to solve it. Problems are sorted by difficulty — it's guaranteed that p_{i} < p_{i} + 1 and t_{i} < t_{i} + 1.
A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0, p_{i} - c·x) points.
Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by p_{i}). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by p_{i}). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.
You may assume that the duration of the competition is greater or equal than the sum of all t_{i}. That means both Limak and Radewoosh will accept all n problems.
-----Input-----
The first line contains two integers n and c (1 ≤ n ≤ 50, 1 ≤ c ≤ 1000) — the number of problems and the constant representing the speed of loosing points.
The second line contains n integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1000, p_{i} < p_{i} + 1) — initial scores.
The third line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 1000, t_{i} < t_{i} + 1) where t_{i} denotes the number of minutes one needs to solve the i-th problem.
-----Output-----
Print "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points.
-----Examples-----
Input
3 2
50 85 250
10 15 25
Output
Limak
Input
3 6
50 85 250
10 15 25
Output
Radewoosh
Input
8 1
10 20 30 40 50 60 70 80
8 10 58 63 71 72 75 76
Output
Tie
-----Note-----
In the first sample, there are 3 problems. Limak solves them as follows:
Limak spends 10 minutes on the 1-st problem and he gets 50 - c·10 = 50 - 2·10 = 30 points. Limak spends 15 minutes on the 2-nd problem so he submits it 10 + 15 = 25 minutes after the start of the contest. For the 2-nd problem he gets 85 - 2·25 = 35 points. He spends 25 minutes on the 3-rd problem so he submits it 10 + 15 + 25 = 50 minutes after the start. For this problem he gets 250 - 2·50 = 150 points.
So, Limak got 30 + 35 + 150 = 215 points.
Radewoosh solves problem in the reversed order:
Radewoosh solves 3-rd problem after 25 minutes so he gets 250 - 2·25 = 200 points. He spends 15 minutes on the 2-nd problem so he submits it 25 + 15 = 40 minutes after the start. He gets 85 - 2·40 = 5 points for this problem. He spends 10 minutes on the 1-st problem so he submits it 25 + 15 + 10 = 50 minutes after the start. He gets max(0, 50 - 2·50) = max(0, - 50) = 0 points.
Radewoosh got 200 + 5 + 0 = 205 points in total. Limak has 215 points so Limak wins.
In the second sample, Limak will get 0 points for each problem and Radewoosh will first solve the hardest problem and he will get 250 - 6·25 = 100 points for that. Radewoosh will get 0 points for other two problems but he is the winner anyway.
In the third sample, Limak will get 2 points for the 1-st problem and 2 points for the 2-nd problem. Radewoosh will get 4 points for the 8-th problem. They won't get points for other problems and thus there is a tie because 2 + 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.
# Background
My pet bridge-maker ants are marching across a terrain from left to right.
If they encounter a gap, the first one stops and then next one climbs over him, then the next, and the next, until a bridge is formed across the gap.
What clever little things they are!
Now all the other ants can walk over the ant-bridge.
When the last ant is across, the ant-bridge dismantles itself similar to how it was constructed.
This process repeats as many times as necessary (there may be more than one gap to cross) until all the ants reach the right hand side.
# Kata Task
My little ants are marching across the terrain from left-to-right in the order ```A``` then ```B``` then ```C```...
What order do they exit on the right hand side?
# Notes
* ```-``` = solid ground
* ```.``` = a gap
* The number of ants may differ but there are always enough ants to bridge the gaps
* The terrain never starts or ends with a gap
* Ants cannot pass other ants except by going over ant-bridges
* If there is ever ambiguity which ant should move, then the ant at the **back** moves first
# Example
## Input
* ants = ````GFEDCBA````
* terrain = ```------------...-----------```
## Output
* result = ```EDCBAGF```
## Details
Ants moving left to right.
GFEDCBA
------------...-----------
The first one arrives at a gap.
GFEDCB A
------------...-----------
They start to bridge over the gap...
GFED ABC
------------...-----------
...until the ant-bridge is completed!
GF ABCDE
------------...-----------
And then the remaining ants can walk across the bridge.
F
G ABCDE
------------...-----------
And when no more ants need to cross...
ABCDE GF
------------...-----------
... the bridge dismantles itself one ant at a time....
CDE BAGF
------------...-----------
...until all ants get to the other side
EDCBAGF
------------...-----------
Write your solution by modifying this code:
```python
def ant_bridge(ants, terrain):
```
Your solution should implemented in the function "ant_bridge". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is an N-car train.
You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."
-----Constraints-----
- 1 \leq N \leq 100
- 1 \leq i \leq N
-----Input-----
Input is given from Standard Input in the following format:
N i
-----Output-----
Print the answer.
-----Sample Input-----
4 2
-----Sample Output-----
3
The second car from the front of a 4-car train is the third car from the back.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.
Elections are coming. You know the number of voters and the number of parties — $n$ and $m$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $i$-th voter $c_i$ bytecoins you can ask him to vote for any other party you choose.
The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.
-----Input-----
The first line of input contains two integers $n$ and $m$ ($1 \le n, m \le 3000$) — the number of voters and the number of parties respectively.
Each of the following $n$ lines contains two integers $p_i$ and $c_i$ ($1 \le p_i \le m$, $1 \le c_i \le 10^9$) — the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision.
The United Party of Berland has the index $1$.
-----Output-----
Print a single number — the minimum number of bytecoins needed for The United Party of Berland to win the elections.
-----Examples-----
Input
1 2
1 100
Output
0
Input
5 5
2 100
3 200
4 300
5 400
5 900
Output
500
Input
5 5
2 100
3 200
4 300
5 800
5 900
Output
600
-----Note-----
In the first sample, The United Party wins the elections even without buying extra votes.
In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties $3$, $4$ and $5$ get one vote and party number $2$ gets no votes.
In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. <image>. You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).
Your task is to find out if a given integer is a triangular number.
Input
The first line contains the single number n (1 ≤ n ≤ 500) — the given integer.
Output
If the given integer is a triangular number output YES, otherwise output NO.
Examples
Input
1
Output
YES
Input
2
Output
NO
Input
3
Output
YES
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian as well.
Petr, Nikita G. and Nikita are the most influential music critics in Saint-Petersburg. They have recently downloaded their favorite band's new album and going to listen to it. Nikita claims that the songs of entire album should be listened strictly in the same order as they are given, because there is the secret message from the author in the songs' order. Petr, being chaotic, does not think so, hence he loves listening to songs in a random order. Petr is pretty good in convincing other people, so after a two-hours discussion Nikita accepted listening in random order(the discussion's duration was like three times longer thatn the album's one). In this context random order means following: There are N songs in the album. In the very beginning random song is chosen(here and further "random song" means that every song has equal probability to be chosen). After some song is over the next one is chosen randomly and independently of what have been played before.
Nikita G., being the only one who is not going to drop out from the university, wonders, what is the expected number of songs guys have to listen to until every song is played at least once.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single integer N denoting the number of songs in the album.
------ Output ------
For each test case, output a single line containing the expected number of songs the guys will listen to. Your answer will be considered as correct if it has an absolute or relative error less than 10^{−1}. More formally if the expected output is A and your output is B, your output will be considered as correct if and only if
|A − B| ≤ 10^{−1} * max{|A|, |B|, 1}.
------ Constraints ------
1 ≤ T ≤ 100
1 ≤ N ≤ 3000
----- Sample Input 1 ------
3
1
2
3
----- Sample Output 1 ------
1.0
3.0
5.5
------ Explanation 0 ------
Example case 2 After playing the first song there is 1/2 chance to finish the album each time new song is played. So the expected number of songs is 2/2 + 3/4 + 4/8... = 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.
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother.
As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b.
Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.
You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.
-----Input-----
The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 10^5). The second line will contain n space-separated integers representing content of the array a (1 ≤ a_{i} ≤ 10^9). The third line will contain m space-separated integers representing content of the array b (1 ≤ b_{i} ≤ 10^9).
-----Output-----
You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.
-----Examples-----
Input
2 2
2 3
3 5
Output
3
Input
3 2
1 2 3
3 4
Output
4
Input
3 2
4 5 6
1 2
Output
0
-----Note-----
In example 1, you can increase a_1 by 1 and decrease b_2 by 1 and then again decrease b_2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.
In example 3, you don't need to do any operation, Devu's condition is already satisfied.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
VK news recommendation system daily selects interesting publications of one of $n$ disjoint categories for each user. Each publication belongs to exactly one category. For each category $i$ batch algorithm selects $a_i$ publications.
The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of $i$-th category within $t_i$ seconds.
What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.
-----Input-----
The first line of input consists of single integer $n$ — the number of news categories ($1 \le n \le 200\,000$).
The second line of input consists of $n$ integers $a_i$ — the number of publications of $i$-th category selected by the batch algorithm ($1 \le a_i \le 10^9$).
The third line of input consists of $n$ integers $t_i$ — time it takes for targeted algorithm to find one new publication of category $i$ ($1 \le t_i \le 10^5)$.
-----Output-----
Print one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.
-----Examples-----
Input
5
3 7 9 7 8
5 2 5 7 5
Output
6
Input
5
1 2 3 4 5
1 1 1 1 1
Output
0
-----Note-----
In the first example, it is possible to find three publications of the second type, which will take 6 seconds.
In the second example, all news categories contain a different number of publications.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from $1$ to $9$). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, $\ldots$, 9m, 1p, 2p, $\ldots$, 9p, 1s, 2s, $\ldots$, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game: A mentsu, also known as meld, is formed by a koutsu or a shuntsu; A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu; A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples: [2m, 3p, 2s, 4m, 1s, 2s, 4s] — it contains no koutsu or shuntsu, so it includes no mentsu; [4s, 3m, 3p, 4s, 5p, 4s, 5p] — it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu; [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] — it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
-----Input-----
The only line contains three strings — the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from $1$ to $9$ and the second character is m, p or s.
-----Output-----
Print a single integer — the minimum number of extra suited tiles she needs to draw.
-----Examples-----
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
-----Note-----
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile — 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Read the inputs from stdin solve the problem and write the answer to stdout (do 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're given an array $a$ of length $n$. You can perform the following operation on it as many times as you want: Pick two integers $i$ and $j$ $(1 \le i,j \le n)$ such that $a_i+a_j$ is odd, then swap $a_i$ and $a_j$.
What is lexicographically the smallest array you can obtain?
An array $x$ is lexicographically smaller than an array $y$ if there exists an index $i$ such that $x_i<y_i$, and $x_j=y_j$ for all $1 \le j < i$. Less formally, at the first index $i$ in which they differ, $x_i<y_i$
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^5$) — the number of elements in the array $a$.
The second line contains $n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($1 \le a_i \le 10^9$) — the elements of the array $a$.
-----Output-----
The only line contains $n$ space-separated integers, the lexicographically smallest array you can obtain.
-----Examples-----
Input
3
4 1 7
Output
1 4 7
Input
2
1 1
Output
1 1
-----Note-----
In the first example, we can swap $1$ and $4$ since $1+4=5$, which is odd.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least a_{i} candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:
Give m candies to the first child of the line. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. Repeat the first two steps while the line is not empty.
Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?
-----Input-----
The first line contains two integers n, m (1 ≤ n ≤ 100; 1 ≤ m ≤ 100). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100).
-----Output-----
Output a single integer, representing the number of the last child.
-----Examples-----
Input
5 2
1 3 1 4 2
Output
4
Input
6 4
1 1 2 2 3 3
Output
6
-----Note-----
Let's consider the first sample.
Firstly child 1 gets 2 candies and go home. Then child 2 gets 2 candies and go to the end of the line. Currently the line looks like [3, 4, 5, 2] (indices of the children in order of the line). Then child 3 gets 2 candies and go home, and then child 4 gets 2 candies and goes to the end of the line. Currently the line looks like [5, 2, 4]. Then child 5 gets 2 candies and goes home. Then child 2 gets two candies and goes home, and finally child 4 gets 2 candies and goes home.
Child 4 is the last one who goes home.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a function that transforms any positive number to a string representing the number in words. The function should work for all numbers between 0 and 999999.
### Examples
```
number2words(0) ==> "zero"
number2words(1) ==> "one"
number2words(9) ==> "nine"
number2words(10) ==> "ten"
number2words(17) ==> "seventeen"
number2words(20) ==> "twenty"
number2words(21) ==> "twenty-one"
number2words(45) ==> "forty-five"
number2words(80) ==> "eighty"
number2words(99) ==> "ninety-nine"
number2words(100) ==> "one hundred"
number2words(301) ==> "three hundred one"
number2words(799) ==> "seven hundred ninety-nine"
number2words(800) ==> "eight hundred"
number2words(950) ==> "nine hundred fifty"
number2words(1000) ==> "one thousand"
number2words(1002) ==> "one thousand two"
number2words(3051) ==> "three thousand fifty-one"
number2words(7200) ==> "seven thousand two hundred"
number2words(7219) ==> "seven thousand two hundred nineteen"
number2words(8330) ==> "eight thousand three hundred thirty"
number2words(99999) ==> "ninety-nine thousand nine hundred ninety-nine"
number2words(888888) ==> "eight hundred eighty-eight thousand eight hundred eighty-eight"
```
Write your solution by modifying this code:
```python
def number2words(n):
```
Your solution should implemented in the function "number2words". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.
Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 2·10^5) — the number of throws of the first team. Then follow n integer numbers — the distances of throws a_{i} (1 ≤ a_{i} ≤ 2·10^9).
Then follows number m (1 ≤ m ≤ 2·10^5) — the number of the throws of the second team. Then follow m integer numbers — the distances of throws of b_{i} (1 ≤ b_{i} ≤ 2·10^9).
-----Output-----
Print two numbers in the format a:b — the score that is possible considering the problem conditions where the result of subtraction a - b is maximum. If there are several such scores, find the one in which number a is maximum.
-----Examples-----
Input
3
1 2 3
2
5 6
Output
9:6
Input
5
6 7 8 9 10
5
1 2 3 4 5
Output
15: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.
Adilbek was assigned to a special project. For Adilbek it means that he has $n$ days to run a special program and provide its results. But there is a problem: the program needs to run for $d$ days to calculate the results.
Fortunately, Adilbek can optimize the program. If he spends $x$ ($x$ is a non-negative integer) days optimizing the program, he will make the program run in $\left\lceil \frac{d}{x + 1} \right\rceil$ days ($\left\lceil a \right\rceil$ is the ceiling function: $\left\lceil 2.4 \right\rceil = 3$, $\left\lceil 2 \right\rceil = 2$). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to $x + \left\lceil \frac{d}{x + 1} \right\rceil$.
Will Adilbek be able to provide the generated results in no more than $n$ days?
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 50$) — the number of test cases.
The next $T$ lines contain test cases – one per line. Each line contains two integers $n$ and $d$ ($1 \le n \le 10^9$, $1 \le d \le 10^9$) — the number of days before the deadline and the number of days the program runs.
-----Output-----
Print $T$ answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in $n$ days or NO (case insensitive) otherwise.
-----Example-----
Input
3
1 1
4 5
5 11
Output
YES
YES
NO
-----Note-----
In the first test case, Adilbek decides not to optimize the program at all, since $d \le n$.
In the second test case, Adilbek can spend $1$ day optimizing the program and it will run $\left\lceil \frac{5}{2} \right\rceil = 3$ days. In total, he will spend $4$ days and will fit in the limit.
In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program $2$ days, it'll still work $\left\lceil \frac{11}{2+1} \right\rceil = 4$ days.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a string S of length n with each character being one of the first m lowercase English letters.
Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.
Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.
-----Input-----
The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26).
The second line contains string S.
-----Output-----
Print the only line containing the answer.
-----Examples-----
Input
3 3
aaa
Output
6
Input
3 3
aab
Output
11
Input
1 2
a
Output
1
Input
10 9
abacadefgh
Output
789
-----Note-----
For the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa.
For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.
For the third sample, the only possible string T is 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.
In cryptography, Caesar cipher is one of the simplest and most widely known encryption method. Caesar cipher is a type of substitution cipher in which each letter in the text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 1, 'a' would be replaced by 'b', 'b' would become 'c', 'y' would become 'z', 'z' would become 'a', and so on. In that case, a text:
this is a pen
is would become:
uijt jt b qfo
Write a program which reads a text encrypted by Caesar Chipher and prints the corresponding decoded text. The number of shift is secret and it depends on datasets, but you can assume that the decoded text includes any of the following words: "the", "this", or "that".
Input
Input consists of several datasets. Each dataset consists of texts in a line. Input ends with EOF. The text consists of lower-case letters, periods, space, and end-of-lines. Only the letters have been encrypted. A line consists of at most 80 characters.
You may assume that you can create one decoded text which includes any of "the", "this", or "that" from the given input text.
The number of datasets is less than or equal to 20.
Output
Print decoded texts in a line.
Example
Input
xlmw mw xli tmgxyvi xlex m xsso mr xli xvmt.
Output
this is the picture that i took in the trip.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day, early in the morning, you decided to buy yourself a bag of chips in the nearby store. The store has chips of $n$ different flavors. A bag of the $i$-th flavor costs $a_i$ burles.
The store may run out of some flavors, so you'll decide which one to buy after arriving there. But there are two major flaws in this plan:
you have only coins of $1$, $2$ and $3$ burles;
since it's morning, the store will ask you to pay in exact change, i. e. if you choose the $i$-th flavor, you'll have to pay exactly $a_i$ burles.
Coins are heavy, so you'd like to take the least possible number of coins in total. That's why you are wondering: what is the minimum total number of coins you should take with you, so you can buy a bag of chips of any flavor in exact change?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first line of each test case contains the single integer $n$ ($1 \le n \le 100$) — the number of flavors in the store.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$) — the cost of one bag of each flavor.
-----Output-----
For each test case, print one integer — the minimum number of coins you need to buy one bag of any flavor you'll choose in exact change.
-----Examples-----
Input
4
1
1337
3
10 8 10
5
1 2 3 4 5
3
7 77 777
Output
446
4
3
260
-----Note-----
In the first test case, you should, for example, take with you $445$ coins of value $3$ and $1$ coin of value $2$. So, $1337 = 445 \cdot 3 + 1 \cdot 2$.
In the second test case, you should, for example, take $2$ coins of value $3$ and $2$ coins of value $2$. So you can pay either exactly $8 = 2 \cdot 3 + 1 \cdot 2$ or $10 = 2 \cdot 3 + 2 \cdot 2$.
In the third test case, it's enough to take $1$ coin of value $3$ and $2$ coins of value $1$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ of length $2n$. Consider a partition of array $a$ into two subsequences $p$ and $q$ of length $n$ each (each element of array $a$ should be in exactly one subsequence: either in $p$ or in $q$).
Let's sort $p$ in non-decreasing order, and $q$ in non-increasing order, we can denote the sorted versions by $x$ and $y$, respectively. Then the cost of a partition is defined as $f(p, q) = \sum_{i = 1}^n |x_i - y_i|$.
Find the sum of $f(p, q)$ over all correct partitions of array $a$. Since the answer might be too big, print its remainder modulo $998244353$.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 150\,000$).
The second line contains $2n$ integers $a_1, a_2, \ldots, a_{2n}$ ($1 \leq a_i \leq 10^9$) — elements of array $a$.
-----Output-----
Print one integer — the answer to the problem, modulo $998244353$.
-----Examples-----
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
-----Note-----
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence $p$ are different.
In the first example, there are two correct partitions of the array $a$: $p = [1]$, $q = [4]$, then $x = [1]$, $y = [4]$, $f(p, q) = |1 - 4| = 3$; $p = [4]$, $q = [1]$, then $x = [4]$, $y = [1]$, $f(p, q) = |4 - 1| = 3$.
In the second example, there are six valid partitions of the array $a$: $p = [2, 1]$, $q = [2, 1]$ (elements with indices $1$ and $2$ in the original array are selected in the subsequence $p$); $p = [2, 2]$, $q = [1, 1]$; $p = [2, 1]$, $q = [1, 2]$ (elements with indices $1$ and $4$ are selected in the subsequence $p$); $p = [1, 2]$, $q = [2, 1]$; $p = [1, 1]$, $q = [2, 2]$; $p = [2, 1]$, $q = [2, 1]$ (elements with indices $3$ and $4$ are selected in the subsequence $p$).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (x_{i}, y_{i}) and moves with a speed v_{i}.
Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.
-----Input-----
The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home.
The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby.
The i-th of the following n lines contains three integers x_{i}, y_{i} and v_{i} ( - 100 ≤ x_{i}, y_{i} ≤ 100, 1 ≤ v_{i} ≤ 100) — the coordinates of the i-th car and its speed.
It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.
-----Output-----
Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if $\frac{|a - b|}{\operatorname{max}(1, b)} \leq 10^{-6}$.
-----Examples-----
Input
0 0
2
2 0 1
0 2 2
Output
1.00000000000000000000
Input
1 3
3
3 3 2
-2 3 6
-2 7 10
Output
0.50000000000000000000
-----Note-----
In the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.
In the second sample, cars 2 and 3 will arrive simultaneously.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras.
Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now wants to select several consequent (contiguous) pieces of alternating colors to create a zebra. Let's call the number of selected pieces the length of the zebra.
Before assembling the zebra Grisha can make the following operation $0$ or more times. He splits the sequence in some place into two parts, then reverses each of them and sticks them together again. For example, if Grisha has pieces in the order "bwbbw" (here 'b' denotes a black strip, and 'w' denotes a white strip), then he can split the sequence as bw|bbw (here the vertical bar represents the cut), reverse both parts and obtain "wbwbb".
Determine the maximum possible length of the zebra that Grisha can produce.
-----Input-----
The only line contains a string $s$ ($1 \le |s| \le 10^5$, where $|s|$ denotes the length of the string $s$) comprised of lowercase English letters 'b' and 'w' only, where 'w' denotes a white piece and 'b' denotes a black piece.
-----Output-----
Print a single integer — the maximum possible zebra length.
-----Examples-----
Input
bwwwbwwbw
Output
5
Input
bwwbwwb
Output
3
-----Note-----
In the first example one of the possible sequence of operations is bwwwbww|bw $\to$ w|wbwwwbwb $\to$ wbwbwwwbw, that gives the answer equal to $5$.
In the second example no operation can increase the answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You're creating a game level for some mobile game. The level should contain some number of cells aligned in a row from left to right and numbered with consecutive integers starting from $1$, and in each cell you can either put a platform or leave it empty.
In order to pass a level, a player must throw a ball from the left so that it first lands on a platform in the cell $p$, then bounces off it, then bounces off a platform in the cell $(p + k)$, then a platform in the cell $(p + 2k)$, and so on every $k$-th platform until it goes farther than the last cell. If any of these cells has no platform, you can't pass the level with these $p$ and $k$.
You already have some level pattern $a_1$, $a_2$, $a_3$, ..., $a_n$, where $a_i = 0$ means there is no platform in the cell $i$, and $a_i = 1$ means there is one. You want to modify it so that the level can be passed with given $p$ and $k$. In $x$ seconds you can add a platform in some empty cell. In $y$ seconds you can remove the first cell completely, reducing the number of cells by one, and renumerating the other cells keeping their order. You can't do any other operation. You can not reduce the number of cells to less than $p$.
Illustration for the third example test case. Crosses mark deleted cells. Blue platform is the newly added.
What is the minimum number of seconds you need to make this level passable with given $p$ and $k$?
-----Input-----
The first line contains the number of test cases $t$ ($1 \le t \le 100$). Description of test cases follows.
The first line of each test case contains three integers $n$, $p$, and $k$ ($1 \le p \le n \le 10^5$, $1 \le k \le n$) — the number of cells you have, the first cell that should contain a platform, and the period of ball bouncing required.
The second line of each test case contains a string $a_1 a_2 a_3 \ldots a_n$ ($a_i = 0$ or $a_i = 1$) — the initial pattern written without spaces.
The last line of each test case contains two integers $x$ and $y$ ($1 \le x, y \le 10^4$) — the time required to add a platform and to remove the first cell correspondingly.
The sum of $n$ over test cases does not exceed $10^5$.
-----Output-----
For each test case output a single integer — the minimum number of seconds you need to modify the level accordingly.
It can be shown that it is always possible to make the level passable.
-----Examples-----
Input
3
10 3 2
0101010101
2 2
5 4 1
00000
2 10
11 2 3
10110011000
4 3
Output
2
4
10
-----Note-----
In the first test case it's best to just remove the first cell, after that all required platforms are in their places: 0101010101. The stroked out digit is removed, the bold ones are where platforms should be located. The time required is $y = 2$.
In the second test case it's best to add a platform to both cells $4$ and $5$: 00000 $\to$ 00011. The time required is $x \cdot 2 = 4$.
In the third test case it's best to to remove the first cell twice and then add a platform to the cell which was initially $10$-th: 10110011000 $\to$ 10110011010. The time required is $y \cdot 2 + x = 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.
Your task is to return the sum of Triangular Numbers up-to-and-including the `nth` Triangular Number.
Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc."
```
[01]
02 [03]
04 05 [06]
07 08 09 [10]
11 12 13 14 [15]
16 17 18 19 20 [21]
```
e.g. If `4` is given: `1 + 3 + 6 + 10 = 20`.
Triangular Numbers cannot be negative so return 0 if a negative number is given.
Write your solution by modifying this code:
```python
def sum_triangular_numbers(n):
```
Your solution should implemented in the function "sum_triangular_numbers". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice and Bob are controlling a robot. They each have one switch that controls the robot.
Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.
Bob started holding down his button C second after the start-up, and released his button D second after the start-up.
For how many seconds both Alice and Bob were holding down their buttons?
-----Constraints-----
- 0≤A<B≤100
- 0≤C<D≤100
- All input values are integers.
-----Input-----
Input is given from Standard Input in the following format:
A B C D
-----Output-----
Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.
-----Sample Input-----
0 75 25 100
-----Sample Output-----
50
Alice started holding down her button 0 second after the start-up of the robot, and released her button 75 second after the start-up.
Bob started holding down his button 25 second after the start-up, and released his button 100 second after the start-up.
Therefore, the time when both of them were holding down their buttons, is the 50 seconds from 25 seconds after the start-up to 75 seconds after the start-up.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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's a new security company in Paris, and they decided to give their employees an algorithm to make first name recognition faster. In the blink of an eye, they can now detect if a string is a first name, no matter if it is a one-word name or an hyphenated name. They're given this documentation with the algorithm:
*In France, you'll often find people with hyphenated first names. They're called "prénoms composés".
There could be two, or even more words linked to form a new name, quite like jQuery function chaining ;).
They're linked using the - symbol, like Marie-Joelle, Jean-Michel, Jean-Mouloud.
Thanks to this algorithm, you can now recognize hyphenated names quicker than Flash !*
(yeah, their employees know how to use jQuery. Don't ask me why)
Your mission if you accept it, recreate the algorithm.
Using the function **showMe**, which takes a **yourID** argument, you will check if the given argument is a name or not, by returning true or false.
*Note that*
- String will either be a one-word first name, or an hyphenated first name , its words being linked by "-".
- Words can only start with an uppercase letter, and then lowercase letters (from a to z)
Now is your time to help the guards !
Write your solution by modifying this code:
```python
def show_me(name):
```
Your solution should implemented in the function "show_me". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You a captain of a ship. Initially you are standing in a point $(x_1, y_1)$ (obviously, all positions in the sea can be described by cartesian plane) and you want to travel to a point $(x_2, y_2)$.
You know the weather forecast — the string $s$ of length $n$, consisting only of letters U, D, L and R. The letter corresponds to a direction of wind. Moreover, the forecast is periodic, e.g. the first day wind blows to the side $s_1$, the second day — $s_2$, the $n$-th day — $s_n$ and $(n+1)$-th day — $s_1$ again and so on.
Ship coordinates change the following way: if wind blows the direction U, then the ship moves from $(x, y)$ to $(x, y + 1)$; if wind blows the direction D, then the ship moves from $(x, y)$ to $(x, y - 1)$; if wind blows the direction L, then the ship moves from $(x, y)$ to $(x - 1, y)$; if wind blows the direction R, then the ship moves from $(x, y)$ to $(x + 1, y)$.
The ship can also either go one of the four directions or stay in place each day. If it goes then it's exactly 1 unit of distance. Transpositions of the ship and the wind add up. If the ship stays in place, then only the direction of wind counts. For example, if wind blows the direction U and the ship moves the direction L, then from point $(x, y)$ it will move to the point $(x - 1, y + 1)$, and if it goes the direction U, then it will move to the point $(x, y + 2)$.
You task is to determine the minimal number of days required for the ship to reach the point $(x_2, y_2)$.
-----Input-----
The first line contains two integers $x_1, y_1$ ($0 \le x_1, y_1 \le 10^9$) — the initial coordinates of the ship.
The second line contains two integers $x_2, y_2$ ($0 \le x_2, y_2 \le 10^9$) — the coordinates of the destination point.
It is guaranteed that the initial coordinates and destination point coordinates are different.
The third line contains a single integer $n$ ($1 \le n \le 10^5$) — the length of the string $s$.
The fourth line contains the string $s$ itself, consisting only of letters U, D, L and R.
-----Output-----
The only line should contain the minimal number of days required for the ship to reach the point $(x_2, y_2)$.
If it's impossible then print "-1".
-----Examples-----
Input
0 0
4 6
3
UUU
Output
5
Input
0 3
0 0
3
UDD
Output
3
Input
0 0
0 1
1
L
Output
-1
-----Note-----
In the first example the ship should perform the following sequence of moves: "RRRRU". Then its coordinates will change accordingly: $(0, 0)$ $\rightarrow$ $(1, 1)$ $\rightarrow$ $(2, 2)$ $\rightarrow$ $(3, 3)$ $\rightarrow$ $(4, 4)$ $\rightarrow$ $(4, 6)$.
In the second example the ship should perform the following sequence of moves: "DD" (the third day it should stay in place). Then its coordinates will change accordingly: $(0, 3)$ $\rightarrow$ $(0, 3)$ $\rightarrow$ $(0, 1)$ $\rightarrow$ $(0, 0)$.
In the third example the ship can never reach the point $(0, 1)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.
While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one — by value vi - 1, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.
If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.
All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.
Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.
Input
The first line of the input contains a positive integer n (1 ≤ n ≤ 4000) — the number of kids in the line.
Next n lines contain three integers each vi, di, pi (1 ≤ vi, di, pi ≤ 106) — the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.
Output
In the first line print number k — the number of children whose teeth Gennady will cure.
In the second line print k integers — the numbers of the children who will make it to the end of the line in the increasing order.
Examples
Input
5
4 2 2
4 1 2
5 2 4
3 3 5
5 1 2
Output
2
1 3
Input
5
4 5 1
5 3 9
4 1 2
2 1 8
4 1 9
Output
4
1 2 4 5
Note
In the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to - 2, 1, 3, 1, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0, 2, 0. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.
In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5, - 1, 6, 8. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5, 5, 7. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0, 3. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t.
Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
-----Input-----
The first line contains a single integer x (1 ≤ x ≤ 10^18) — the number that Luke Skywalker gave to Chewbacca.
-----Output-----
Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.
-----Examples-----
Input
27
Output
22
Input
4545
Output
4444
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 cities of Byteland and Berland are located on the axis $Ox$. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line $Ox$ there are three types of cities: the cities of Byteland, the cities of Berland, disputed cities.
Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.
The countries agreed to connect the pairs of cities with BNET cables in such a way that: If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables.
Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.
The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.
Each city is a point on the line $Ox$. It is technically possible to connect the cities $a$ and $b$ with a cable so that the city $c$ ($a < c < b$) is not connected to this cable, where $a$, $b$ and $c$ are simultaneously coordinates of the cities $a$, $b$ and $c$.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 2 \cdot 10^{5}$) — the number of cities.
The following $n$ lines contains an integer $x_i$ and the letter $c_i$ ($-10^{9} \le x_i \le 10^{9}$) — the coordinate of the city and its type. If the city belongs to Byteland, $c_i$ equals to 'B'. If the city belongs to Berland, $c_i$ equals to «R». If the city is disputed, $c_i$ equals to 'P'.
All cities have distinct coordinates. Guaranteed, that the cities are given in the increasing order of their coordinates.
-----Output-----
Print the minimal total length of such set of cables, that if we delete all Berland cities ($c_i$='R'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables. Similarly, if we delete all Byteland cities ($c_i$='B'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables.
-----Examples-----
Input
4
-5 R
0 P
3 P
7 B
Output
12
Input
5
10 R
14 B
16 B
21 R
32 R
Output
24
-----Note-----
In the first example, you should connect the first city with the second, the second with the third, and the third with the fourth. The total length of the cables will be $5 + 3 + 4 = 12$.
In the second example there are no disputed cities, so you need to connect all the neighboring cities of Byteland and all the neighboring cities of Berland. The cities of Berland have coordinates $10, 21, 32$, so to connect them you need two cables of length $11$ and $11$. The cities of Byteland have coordinates $14$ and $16$, so to connect them you need one cable of length $2$. Thus, the total length of all cables is $11 + 11 + 2 = 24$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example:
`"dolphin" -> "The Dolphin"`
However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last letter, combined into one word (WITHOUT "The" in front), like this:
`"alaska" -> "Alaskalaska"`
Complete the function that takes a noun as a string, and returns her preferred band name written as a string.
Write your solution by modifying this code:
```python
def band_name_generator(name):
```
Your solution should implemented in the function "band_name_generator". The i
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number n is almost lucky.
Input
The single line contains an integer n (1 ≤ n ≤ 1000) — the number that needs to be checked.
Output
In the only line print "YES" (without the quotes), if number n is almost lucky. Otherwise, print "NO" (without the quotes).
Examples
Input
47
Output
YES
Input
16
Output
YES
Input
78
Output
NO
Note
Note that all lucky numbers are almost lucky as any number is evenly divisible by itself.
In the first sample 47 is a lucky number. In the second sample 16 is divisible by 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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.