question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends.
Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could have formed by the end of the competition.
-----Input-----
The only line of input contains two integers n and m, separated by a single space (1 β€ m β€ n β€ 10^9) β the number of participants and the number of teams respectively.
-----Output-----
The only line of the output should contain two integers k_{min} and k_{max} β the minimum possible number of pairs of friends and the maximum possible number of pairs of friends respectively.
-----Examples-----
Input
5 1
Output
10 10
Input
3 2
Output
1 1
Input
6 3
Output
3 6
-----Note-----
In the first sample all the participants get into one team, so there will be exactly ten pairs of friends.
In the second sample at any possible arrangement one team will always have two participants and the other team will always have one participant. Thus, the number of pairs of friends will always be equal to one.
In the third sample minimum number of newly formed friendships can be achieved if participants were split on teams consisting of 2 people, maximum number can be achieved if participants were split on teams of 1, 1 and 4 people.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length β (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
Input
There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.
Output
Write one line β the corresponding answer. Do not omit the leading 0s.
Examples
Input
1010100
0100101
Output
1110001
Input
000
111
Output
111
Input
1110
1010
Output
0100
Input
01110
01100
Output
00010
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
At the JOI pasta shop, the recommended pasta for lunch and the set menu of freshly squeezed juice are popular. When ordering this set menu, choose one from each of the three pasta and two juices of the day. The price is the total price of pasta and juice minus 50 yen.
Given the price of pasta and juice for a day, create a program to find the minimum price for the set menu for that day.
output
Output the minimum price of the set menu for the day in one line.
Example
Input
800
700
900
198
330
Output
848
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.
Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.
You can consider that the coin shows the heads (or tails) with the probability of 50 percent.
Input
The first line contains integer n (1 β€ n β€ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 β€ pi β€ n) β the permutation p. The numbers are separated by spaces.
Output
In a single line print a single real value β the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
2
1 2
Output
0.000000
Input
5
3 5 2 4 1
Output
13.000000
Note
In the first test the sequence is already sorted, so the answer is 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
An array is called `centered-N` if some `consecutive sequence` of elements of the array sum to `N` and this sequence is preceded and followed by the same number of elements.
Example:
```
[3,2,10,4,1,6,9] is centered-15
because the sequence 10,4,1 sums to 15 and the sequence
is preceded by two elements [3,2] and followed by two elements [6,9]
```
Write a method called `isCenteredN` that returns :
- `true` if its array argument is `not empty` and `centered-N` or empty and centered-0
- otherwise returns `false`.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 Γ n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 β€ di β€ 109) β the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Dreamoon loves summing up something for no reason. One day he obtains two integers a and b occasionally. He wants to calculate the sum of all nice integers. Positive integer x is called nice if <image> and <image>, where k is some integer number in range [1, a].
By <image> we denote the quotient of integer division of x and y. By <image> we denote the remainder of integer division of x and y. You can read more about these operations here: http://goo.gl/AcsXhT.
The answer may be large, so please print its remainder modulo 1 000 000 007 (109 + 7). Can you compute it faster than Dreamoon?
Input
The single line of the input contains two integers a, b (1 β€ a, b β€ 107).
Output
Print a single integer representing the answer modulo 1 000 000 007 (109 + 7).
Examples
Input
1 1
Output
0
Input
2 2
Output
8
Note
For the first sample, there are no nice integers because <image> is always zero.
For the second sample, the set of nice integers is {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.
### Background
In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. It was invented by Lester S. Hill in 1929.
### Task
This cipher involves a text key which has to be turned into a matrix and text which needs to be encoded. The text key can be of any perfect square length but for the sake of this kata we will focus on keys of length 4 forming a 2x2 matrix.
To encrypt a message using the hill cipher, first of all you need to convert the text key into a key matrix. To do that you will convert the key row wise into a 2x2 matrix. Then you will substitute the letters with their respective positions on the alphabet: A=0, B=1,C=2 and so on till Z=25. So for example if we get the key text as ```cats```, the key matrix will be:
[[ 2 0]
[19 18]]
Now the next step is to break the text into pairs of two and convert those pairs into 2x1 matrices. If your text has an odd number of letters then just add a Z next to your last letter. Now again convert those letters into their respective position in the alphabet as above. So for example the text ```Hi``` would be converted into:
[[7]
[8]]
Now we need to [multiply](https://www.mathsisfun.com/algebra/matrix-multiplying.html) the key matrix by the text matrix to get our encrypted matrix and then find out the encrypted matrix [modulo](https://en.wikipedia.org/wiki/Modulo_operation) 26:
[[ 2 0] * [[7] = [[14] = [[14] mod 26
[19 18]] [8]] [277]] [17]]
For the final step we just find out the letters at the alphabet position of 14 and 17 which are ```O``` and ```R```. So ```OR``` is our encrypted message for the message ```Hi```
In this kata you will be given a function named ```encrypt``` with the parameters ```text``` and ```key``` and you have to return the encrypted message in all uppercase letters
``` python
encrypt('','azyb') β ''
encrypt('Hi','cats') β 'OR'
encrypt('This is a good day','bbaa') β 'AAAAAAGACAGAYA'
```
Note:
- The text to encrypt will contain characters other than the alphabets, its your job to clean them before converting text to matrices. Spaces also need to be removed
- The text may contain both uppercase and lowercase alphabets. Its your job to standardize them, the encrypted text however should be returned in uppercase letters.
- The key will always contain 4 lowercase alphabet.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Brown loves games. Today, they will play the following game.
In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:
- Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1β€i) can be freely chosen as long as there is a sufficient number of stones in the pile.
The player who becomes unable to perform the operation, loses the game.
Given X and Y, determine the winner of the game, assuming that both players play optimally.
-----Constraints-----
- 0 β€ X, Y β€ 10^{18}
-----Input-----
Input is given from Standard Input in the following format:
X Y
-----Output-----
Print the winner: either Alice or Brown.
-----Sample Input-----
2 1
-----Sample Output-----
Brown
Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Twin adventurers Rin and Len are searching for treasure in the Mirror Cave. The cave has two pairs of rooms, the Hall of Mirrors, and an expensive treasure lies behind the door of the room.
For convenience, each of the two rooms is considered to have W Γ H cells arranged in a grid pattern. The outside of the room is surrounded by a wall. In addition, walls are installed in places inside the room, and it is not possible to enter the cells where the walls are located. To open the door to the treasure room, the two must move symmetrically to reach a particular cell at the same time. Moreover, if only one arrives first, the door will be locked and will not open.
Symmetrical movement means moving north and north, west and east, east and west, and south and south at the same time. However, it is recognized that the movement is symmetrical even in a situation where one has a wall at the end where it is trying to move and the other has no wall at the end. In this case, those with a wall will stay there, and those without a wall will move to the next cell.
As inputs, the initial position of the twins, the destination, and the placement of obstacles are given. Your job is to write a program to determine if the twins can open the door.
Input
The input consists of multiple datasets. Each dataset is given in the following format.
> W H
> RoomL1 RoomR1
> RoomL2 RoomR2
> ...
> RoomLH RoomRH
The first line gives two positive integers W, H (1 β€ W, H β€ 50) separated by a single space. After that, information on two rooms is given over H lines. RoomLi and RoomRi correspond to the i-th row of the left and right rooms, respectively. Both are strings of length W, with the jth character corresponding to the jth column of the room. Each character is one of the following:
* `.`: Freely moveable cell
* `#`: Cell with wall (cannot enter)
* `%`: Destination
* `R`: Initial position of Rin
* `L`: Initial position of Len
In each room, the first row corresponds to the north end of the room and the first row corresponds to the west end of the room. Also, each room always has exactly one destination, with exactly one initial position for Len in the left room and one for Rin in the right room.
The end of the input is indicated by a line containing two zeros separated by a blank.
Output
For each dataset, print Yes if the twins can open the door, and No if they can't.
Sample Input
5 5
% # ... ... #%
. #. #.. #. #.
. #. #.. #. #.
. #. #.. #. #.
... # L R # ...
3 2
.L. .R #
% .. .%.
4 1
L.%.% .. R
0 0
Output for the Sample Input
Yes
Yes
No
Example
Input
5 5
%#... ...#%
.#.#. .#.#.
.#.#. .#.#.
.#.#. .#.#.
...#L R#...
3 2
.L. .R#
%.. .%.
4 1
L.%. %..R
0 0
Output
Yes
Yes
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Homer has two friends Alice and Bob. Both of them are string fans.
One day, Alice and Bob decide to play a game on a string $s = s_1 s_2 \dots s_n$ of length $n$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.
In a move, a player must choose an index $i$ ($1 \leq i \leq n$) that has not been chosen before, and change $s_i$ to any other lowercase English letter $c$ that $c \neq s_i$.
When all indices have been chosen, the game ends.
The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.
A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:
$a$ is a prefix of $b$, but $a \ne b$;
in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
-----Input-----
Each test contains multiple test cases. The first line contains $t$ ($1 \le t \le 1000$) β the number of test cases. Description of the test cases follows.
The only line of each test case contains a single string $s$ ($1 \leq |s| \leq 50$) consisting of lowercase English letters.
-----Output-----
For each test case, print the final string in a single line.
-----Examples-----
Input
3
a
bbbb
az
Output
b
azaz
by
-----Note-----
In the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.
In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.
In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given a name, turn that name into a perfect square matrix (nested array with the amount of arrays equivalent to the length of each array).
You will need to add periods (`.`) to the end of the name if necessary, to turn it into a matrix.
If the name has a length of 0, return `"name must be at least one letter"`
## Examples
"Bill" ==> [ ["B", "i"],
["l", "l"] ]
"Frank" ==> [ ["F", "r", "a"],
["n", "k", "."],
[".", ".", "."] ]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Vasya has got $n$ books, numbered from $1$ to $n$, arranged in a stack. The topmost book has number $a_1$, the next one β $a_2$, and so on. The book at the bottom of the stack has number $a_n$. All numbers are distinct.
Vasya wants to move all the books to his backpack in $n$ steps. During $i$-th step he wants to move the book number $b_i$ into his backpack. If the book with number $b_i$ is in the stack, he takes this book and all the books above the book $b_i$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $[1, 2, 3]$ (book $1$ is the topmost), and Vasya moves the books in the order $[2, 1, 3]$, then during the first step he will move two books ($1$ and $2$), during the second step he will do nothing (since book $1$ is already in the backpack), and during the third step β one book (the book number $3$). Note that $b_1, b_2, \dots, b_n$ are distinct.
Help Vasya! Tell him the number of books he will put into his backpack during each step.
-----Input-----
The first line contains one integer $n~(1 \le n \le 2 \cdot 10^5)$ β the number of books in the stack.
The second line contains $n$ integers $a_1, a_2, \dots, a_n~(1 \le a_i \le n)$ denoting the stack of books.
The third line contains $n$ integers $b_1, b_2, \dots, b_n~(1 \le b_i \le n)$ denoting the steps Vasya is going to perform.
All numbers $a_1 \dots a_n$ are distinct, the same goes for $b_1 \dots b_n$.
-----Output-----
Print $n$ integers. The $i$-th of them should be equal to the number of books Vasya moves to his backpack during the $i$-th step.
-----Examples-----
Input
3
1 2 3
2 1 3
Output
2 0 1
Input
5
3 1 4 2 5
4 5 1 3 2
Output
3 2 0 0 0
Input
6
6 5 4 3 2 1
6 5 3 4 2 1
Output
1 1 2 0 1 1
-----Note-----
The first example is described in the statement.
In the second example, during the first step Vasya will move the books $[3, 1, 4]$. After that only books $2$ and $5$ remain in the stack ($2$ is above $5$). During the second step Vasya will take the books $2$ and $5$. After that the stack becomes empty, so during next steps Vasya won't move any books.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
D: The Diversity of Prime Factorization
Problem
Ebi-chan has the FACTORIZATION MACHINE, which can factorize natural numbers M (greater than 1) in O ($ \ log $ M) time! But unfortunately, the machine could display only digits and white spaces.
In general, we consider the factorization of M as p_1 ^ {e_1} \ times p_2 ^ {e_2} \ times ... \ times p_K ^ {e_K} where (1) i <j implies p_i <p_j and (2) p_i is prime. Now, she gives M to the machine, and the machine displays according to the following rules in ascending order with respect to i:
* If e_i = 1, then displays p_i,
* otherwise, displays p_i e_i.
For example, if she gives either `22` or` 2048`, then `2 11` is displayed. If either` 24` or `54`, then` 2 3 3`.
Okay, Ebi-chan has written down the output of the machine, but she notices that she has forgotten to write down the input! Now, your task is to count how many natural numbers result in a noted output. Note that Ebi-chan has mistaken writing and no input could result in the output.
The answer could be too large, so, you must output it modulo 10 ^ 9 + 7 (prime number).
Input
N
q_1 q_2 $ \ cdots $ q_N
In the first line, the number of the output of the machine is given. In the second line, the output of the machine is given.
Constraints
* 1 \ leq N \ leq 10 ^ 5
* 2 \ leq q_i \ leq 10 ^ 6 (1 \ leq i \ leq N)
Output
Print the number of the natural numbers that result in the given output of the machine.
Sample Input 1
3
2 3 3
Sample Output for Input 1
2
24 = 2 ^ 3 \ times 3 and 54 = 2 \ times 3 ^ 3 satisfy the condition.
Sample Input 2
3
2 3 4
Sample Output 2 for Input 2
1
Only 162 = 2 \ times 3 ^ 4 satisfies the condition. Note that 4 is not prime.
Sample Input 3
3
3 5 2
Sample Output for Input 3
1
Since 2 <3 <5, only 75 = 3 \ times 5 ^ 2 satisfies the condition.
Sample Input 4
1
Four
Sample Output for Input 4
0
Ebi-chan should have written down it more carefully.
Example
Input
3
2 3 3
Output
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We start with a permutation $a_1, a_2, \ldots, a_n$ and with an empty array $b$. We apply the following operation $k$ times.
On the $i$-th iteration, we select an index $t_i$ ($1 \le t_i \le n-i+1$), remove $a_{t_i}$ from the array, and append one of the numbers $a_{t_i-1}$ or $a_{t_i+1}$ (if $t_i-1$ or $t_i+1$ are within the array bounds) to the right end of the array $b$. Then we move elements $a_{t_i+1}, \ldots, a_n$ to the left in order to fill in the empty space.
You are given the initial permutation $a_1, a_2, \ldots, a_n$ and the resulting array $b_1, b_2, \ldots, b_k$. All elements of an array $b$ are distinct. Calculate the number of possible sequences of indices $t_1, t_2, \ldots, t_k$ modulo $998\,244\,353$.
-----Input-----
Each test contains multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100\,000$), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains two integers $n, k$ ($1 \le k < n \le 200\,000$): sizes of arrays $a$ and $b$.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le n$): elements of $a$. All elements of $a$ are distinct.
The third line of each test case contains $k$ integers $b_1, b_2, \ldots, b_k$ ($1 \le b_i \le n$): elements of $b$. All elements of $b$ are distinct.
The sum of all $n$ among all test cases is guaranteed to not exceed $200\,000$.
-----Output-----
For each test case print one integer: the number of possible sequences modulo $998\,244\,353$.
-----Example-----
Input
3
5 3
1 2 3 4 5
3 2 5
4 3
4 3 2 1
4 3 1
7 4
1 4 7 3 6 2 5
3 2 4 5
Output
2
0
4
-----Note-----
$\require{cancel}$
Let's denote as $a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1}$ an operation over an element with index $i$: removal of element $a_i$ from array $a$ and appending element $a_{i+1}$ to array $b$.
In the first example test, the following two options can be used to produce the given array $b$: $1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2$; $(t_1, t_2, t_3) = (4, 3, 2)$; $1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5$; $(t_1, t_2, t_3) = (4, 1, 2)$.
In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to $4$, namely number $3$, which means that it couldn't be added to array $b$ on the second step.
In the third example test, there are four options to achieve the given array $b$: $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5$; $1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5$; $1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5$;
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
-----Input-----
The first line contains integer n (1 β€ n β€ 10^5) β the number of vertices in the tree.
The second line contains n integers c_{i} (1 β€ c_{i} β€ n), c_{i} β the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers x_{j}, y_{j} (1 β€ x_{j}, y_{j} β€ n) β the edge of the tree. The first vertex is the root of the tree.
-----Output-----
Print n integers β the sums of dominating colours for each vertex.
-----Examples-----
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti:
* If Petya has visited this room before, he writes down the minute he was in this room last time;
* Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i.
Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
Input
The first line contains a single integer n (1 β€ n β€ 2Β·105) β then number of notes in Petya's logbook.
The second line contains n non-negative integers t1, t2, ..., tn (0 β€ ti < i) β notes in the logbook.
Output
In the only line print a single integer β the minimum possible number of rooms in Paris catacombs.
Examples
Input
2
0 0
Output
2
Input
5
0 1 0 1 3
Output
3
Note
In the first sample, sequence of rooms Petya visited could be, for example 1 β 1 β 2, 1 β 2 β 1 or 1 β 2 β 3. The minimum possible number of rooms is 2.
In the second sample, the sequence could be 1 β 2 β 3 β 1 β 2 β 1.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Farmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a_1, a_2, ..., a_{n} of positive integers: Initially, x = 1 and y = 0. If, after any step, x β€ 0 or x > n, the program immediately terminates. The program increases both x and y by a value equal to a_{x} simultaneously. The program now increases y by a_{x} while decreasing x by a_{x}. The program executes steps 2 and 3 (first step 2, then step 3) repeatedly until it terminates (it may never terminate). So, the sequence of executed steps may start with: step 2, step 3, step 2, step 3, step 2 and so on.
The cows are not very good at arithmetic though, and they want to see how the program works. Please help them!
You are given the sequence a_2, a_3, ..., a_{n}. Suppose for each i (1 β€ i β€ n - 1) we run the program on the sequence i, a_2, a_3, ..., a_{n}. For each such run output the final value of y if the program terminates or -1 if it does not terminate.
-----Input-----
The first line contains a single integer, n (2 β€ n β€ 2Β·10^5). The next line contains n - 1 space separated integers, a_2, a_3, ..., a_{n} (1 β€ a_{i} β€ 10^9).
-----Output-----
Output n - 1 lines. On the i-th line, print the requested value when the program is run on the sequence i, a_2, a_3, ...a_{n}.
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.
-----Examples-----
Input
4
2 4 1
Output
3
6
8
Input
3
1 2
Output
-1
-1
-----Note-----
In the first sample For i = 1, x becomes $1 \rightarrow 2 \rightarrow 0$ and y becomes 1 + 2 = 3. For i = 2, x becomes $1 \rightarrow 3 \rightarrow - 1$ and y becomes 2 + 4 = 6. For i = 3, x becomes $1 \rightarrow 4 \rightarrow 3 \rightarrow 7$ and y becomes 3 + 1 + 4 = 8.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an input string.
For each symbol in the string if it's the first character occurrence, replace it with a '1', else replace it with the amount of times you've already seen it...
But will your code be **performant enough**?
___
## Examples:
```
input = "Hello, World!"
result = "1112111121311"
input = "aaaaaaaaaaaa"
result = "123456789101112"
```
There might be some non-ascii characters in the string.
~~~if:java
Note: there will be no int domain overflow (character occurrences will be less than 2 billion).
~~~
~~~if:c
(this does not apply to the C language translation)
~~~
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking device allows one to be placed on an elevating pallet (a flat iron plate on which a car is placed) and parked in the upper tier, and the other to be parked in the lower tier.
In a parking lot that uses such a two-stage parking device, it is necessary to take out the car parked in the lower tier and dismiss it each time to put in and out the car in the upper tier, so be sure to manage it. Keeps the key to the parked car and puts it in and out as needed.
| <image>
--- | ---
Tsuruga Parking Lot is also one of the parking lots equipped with such a two-stage parking device, but due to lack of manpower, the person who cannot drive the car has become the manager. Therefore, once the car was parked, it could not be moved until the customer returned, and the car in the upper tier could not be put out until the owner of the car in the lower tier returned.
Create a program that meets the rules of the Tsuruga parking lot to help the caretaker who has to handle the cars that come to park one after another.
Tsuruga parking lot facilities
* There is one or more parking spaces, all equipped with a two-stage parking device.
* Each parking space is numbered starting from 1.
* Initially, it is assumed that no car is parked in the parking lot.
Tsuruga parking lot adopts the following rules.
When to stop the car
* The caretaker will be informed of the parking time of the car to be parked.
* We will park first in the parking space where no car is parked.
* If there is no parking space where no car is parked, park in an empty parking space. However, if there are multiple such parking spaces, follow the procedure below to park.
1. If the remaining parking time of a parked car is longer than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
2. If the remaining parking time of any parked car is less than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
* If the car is full (no parking space available), the car you are trying to park will wait in turn until the parking space is available. As soon as it becomes available, we will park in order from the first car we were waiting for.
* Under each condition, if there are multiple applicable parking spaces, the parking space number will be the smallest. In addition, if there are cars leaving at the same time, parking will start after all the cars leaving at the same time, and as long as there are cars waiting, the cars that can be parked will be parked at the same time.
When the car leaves
* Cars that have passed the parking time notified by the manager will be shipped.
* If there are cars in multiple parking spaces that have passed the parking time at the same time, the car with the smallest parking space number will be shipped first.
* If the parking time of the car parked in the upper row has expired, you will have to wait until the car in the lower row leaves the garage. The upper car will be delivered at the same time after the lower car is delivered.
The figure below shows an example of how to park at Tsuruga Parking Lot. In this example, the number of parking spaces is 3, and cars B to E are already parked. Consider that car A, which has a parking time of 70 minutes, arrives there. You cannot park because two cars are already parked in parking space 3, and you will have to park in either parking space 1 or parking space 2 that is still vacant. Car B parked in parking space 1 has 50 minutes remaining and car C parked in parking space 2 has 22 minutes remaining, both of which are less than car A's parking time, so car A's parking Park in parking space 1 where car B, which has a smaller time difference, is parked. As a result, car B, which was parked earlier, will be in the upper row.
<image>
Create a program that inputs the number of parking spaces m, the number of cars parked n, and the parking time t of each car, and outputs the car reference numbers in the order in which they come out of the parking lot. However, cars are assigned an integer reference number starting with 1 in the order of input, and cars will come to park one by one every 10 minutes in the order of the reference number.
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:
m n
t1
t2
::
tn
The first line gives the number of two-stage parking devices m (1 β€ m β€ 10) and the number of cars parked n (1 β€ n β€ 100). The next n lines are given the parking time ti (1 β€ ti β€ 120) for the i-th car.
The number of datasets does not exceed 20.
Output
The reference number of the car is output to one line in the order of coming out of the parking lot for each data set. Please output the reference numbers separated by blanks.
Example
Input
3 5
90
52
82
84
70
2 4
10
30
40
60
0 0
Output
2 5 1 4 3
1 2 4 3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!
Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $0$. Also, let's say that the train will visit $n$ stations numbered from $1$ to $n$ along its way, and that Alexey destination is the station $n$.
Alexey learned from the train schedule $n$ integer pairs $(a_i, b_i)$ where $a_i$ is the expected time of train's arrival at the $i$-th station and $b_i$ is the expected time of departure.
Also, using all information he has, Alexey was able to calculate $n$ integers $tm_1, tm_2, \dots, tm_n$ where $tm_i$ is the extra time the train need to travel from the station $i - 1$ to the station $i$. Formally, the train needs exactly $a_i - b_{i-1} + tm_i$ time to travel from station $i - 1$ to station $i$ (if $i = 1$ then $b_0$ is the moment the train leave the terminal, and it's equal to $0$).
The train leaves the station $i$, if both conditions are met:
it's on the station for at least $\left\lceil \frac{b_i - a_i}{2} \right\rceil$ units of time (division with ceiling);
current time $\ge b_i$.
Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of arrival at the station $n$.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) β 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 stations.
Next $n$ lines contain two integers each: $a_i$ and $b_i$ ($1 \le a_i < b_i \le 10^6$). It's guaranteed that $b_i < a_{i+1}$.
Next line contains $n$ integers $tm_1, tm_2, \dots, tm_n$ ($0 \le tm_i \le 10^6$).
-----Output-----
For each test case, print one integer β the time of Alexey's arrival at the last station.
-----Examples-----
Input
2
2
2 4
10 12
0 2
5
1 4
7 8
9 10
13 15
19 20
1 2 3 4 5
Output
12
32
-----Note-----
In the first test case, Alexey arrives at station $1$ without any delay at the moment $a_1 = 2$ (since $tm_1 = 0$). After that, he departs at moment $b_1 = 4$. Finally, he arrives at station $2$ with $tm_2 = 2$ extra time, or at the moment $12$.
In the second test case, Alexey arrives at the first station with $tm_1 = 1$ extra time, or at moment $2$. The train, from one side, should stay at the station at least $\left\lceil \frac{b_1 - a_1}{2} \right\rceil = 2$ units of time and from the other side should depart not earlier than at moment $b_1 = 4$. As a result, the trains departs right at the moment $4$.
Using the same logic, we can figure out that the train arrives at the second station at the moment $9$ and departs at the moment $10$; at the third station: arrives at $14$ and departs at $15$; at the fourth: arrives at $22$ and departs at $23$. And, finally, arrives at the fifth station at $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 an array $a$ of $n$ ($n \geq 2$) positive integers and an integer $p$. Consider an undirected weighted graph of $n$ vertices numbered from $1$ to $n$ for which the edges between the vertices $i$ and $j$ ($i<j$) are added in the following manner:
If $gcd(a_i, a_{i+1}, a_{i+2}, \dots, a_{j}) = min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$, then there is an edge of weight $min(a_i, a_{i+1}, a_{i+2}, \dots, a_j)$ between $i$ and $j$.
If $i+1=j$, then there is an edge of weight $p$ between $i$ and $j$.
Here $gcd(x, y, \ldots)$ denotes the greatest common divisor (GCD) of integers $x$, $y$, ....
Note that there could be multiple edges between $i$ and $j$ if both of the above conditions are true, and if both the conditions fail for $i$ and $j$, then there is no edge between these vertices.
The goal is to find the weight of the minimum spanning tree of this graph.
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 10^4$) β the number of test cases.
The first line of each test case contains two integers $n$ ($2 \leq n \leq 2 \cdot 10^5$) and $p$ ($1 \leq p \leq 10^9$) β the number of nodes and the parameter $p$.
The second line contains $n$ integers $a_1, a_2, a_3, \dots, a_n$ ($1 \leq a_i \leq 10^9$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
Output $t$ lines. For each test case print the weight of the corresponding graph.
-----Examples-----
Input
4
2 5
10 10
2 5
3 3
4 5
5 2 4 9
8 8
5 3 3 6 10 100 9 15
Output
5
3
12
46
-----Note-----
Here are the graphs for the four test cases of the example (the edges of a possible MST of the graphs are marked pink):
For test case 1
For test case 2
For test case 3
For test case 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The goal of this exercise is to convert a string to a new string where each character in the new string is `"("` if that character appears only once in the original string, or `")"` if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
## Examples
```
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
```
**Notes**
Assertion messages may be unclear about what they display in some languages. If you read `"...It Should encode XXX"`, the `"XXX"` is the expected result, not the 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.
You have to restore the wall. The wall consists of $N$ pillars of bricks, the height of the $i$-th pillar is initially equal to $h_{i}$, the height is measured in number of bricks. After the restoration all the $N$ pillars should have equal heights.
You are allowed the following operations: put a brick on top of one pillar, the cost of this operation is $A$; remove a brick from the top of one non-empty pillar, the cost of this operation is $R$; move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is $M$.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes $0$.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
-----Input-----
The first line of input contains four integers $N$, $A$, $R$, $M$ ($1 \le N \le 10^{5}$, $0 \le A, R, M \le 10^{4}$)Β β the number of pillars and the costs of operations.
The second line contains $N$ integers $h_{i}$ ($0 \le h_{i} \le 10^{9}$)Β β initial heights of pillars.
-----Output-----
Print one integerΒ β the minimal cost of restoration.
-----Examples-----
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.
Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.
Now, the following Q operations will be performed:
- Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.
Find the value of the counter on each vertex after all operations.
-----Constraints-----
- 2 \leq N \leq 2 \times 10^5
- 1 \leq Q \leq 2 \times 10^5
- 1 \leq a_i < b_i \leq N
- 1 \leq p_j \leq N
- 1 \leq x_j \leq 10^4
- The given graph is a tree.
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q
-----Output-----
Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.
-----Sample Input-----
4 3
1 2
2 3
2 4
2 10
1 100
3 1
-----Sample Output-----
100 110 111 110
The tree in this input is as follows:
Each operation changes the values of the counters on the vertices as follows:
- Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.
- Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.
- Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have N camels numbered 1,2,\ldots,N. Snuke has decided to make them line up in a row.
The happiness of Camel i will be L_i if it is among the K_i frontmost camels, and R_i otherwise.
Snuke wants to maximize the total happiness of the camels. Find the maximum possible total happiness of the camel.
Solve this problem for each of the T test cases given.
Constraints
* All values in input are integers.
* 1 \leq T \leq 10^5
* 1 \leq N \leq 2 \times 10^{5}
* 1 \leq K_i \leq N
* 1 \leq L_i, R_i \leq 10^9
* The sum of values of N in each input file is at most 2 \times 10^5.
Input
Input is given from Standard Input in the following format:
T
\mathrm{case}_1
\vdots
\mathrm{case}_T
Each case is given in the following format:
N
K_1 L_1 R_1
\vdots
K_N L_N R_N
Output
Print T lines. The i-th line should contain the answer to the i-th test case.
Example
Input
3
2
1 5 10
2 15 5
3
2 93 78
1 71 59
3 57 96
19
19 23 16
5 90 13
12 85 70
19 67 78
12 16 60
18 48 28
5 4 24
12 97 97
4 57 87
19 91 74
18 100 76
7 86 46
9 100 57
3 76 73
6 84 93
1 6 84
11 75 94
19 15 3
12 11 34
Output
25
221
1354
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 naming identifiers (variables and functions) in programming, compound words that concatenate words are used. However, if you concatenate them as they are, you will not be able to understand the word breaks, so in general, select and apply the one that is unified from the following naming conventions:
* Set to Upper CamelCase
Connect words directly to form a compound word, and capitalize only the first letter of each word.
Example: GetUserName
* Set to Lower CamelCase
Connect words directly to form a compound word, and capitalize only the first letter of each word. However, the first letter of the compound word should be lowercase.
Example: getUserName
* Connect with underscore
Words are concatenated with underscores to form a compound word. Make all letters of the word lowercase.
Example: get_user_name
Create a program that outputs the given identifier by applying the specified naming convention. It is assumed that any of the above naming conventions has already been applied to the identifier given.
Input
Multiple datasets are given as input. Each dataset is given in the following format:
name type (identifier, naming convention: space-separated strings and characters)
type is a character indicating the naming convention and is as shown in the table below:
type | Naming convention
--- | ---
U | Upper CamelCase
L | Lower CamelCase
D | Connect with underscore
The number of characters in the given identifier is 1 or more and 100 or less.
End of input when type is'X'. Do not output to this input.
Output
For each dataset, print the identifier with the naming convention on one line.
Example
Input
get_user_name L
getUserName U
GetUserName D
EndOfInput X
Output
getUserName
GetUserName
get_user_name
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $n$ integers, where $n$ is odd. You can make the following operation with it: Choose one of the elements of the array (for example $a_i$) and increase it by $1$ (that is, replace it with $a_i + 1$).
You want to make the median of the array the largest possible using at most $k$ operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $[1, 5, 2, 3, 5]$ is $3$.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $n$ is odd, $1 \le k \le 10^9$)Β β the number of elements in the array and the largest number of operations you can make.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$).
-----Output-----
Print a single integerΒ β the maximum possible median after the operations.
-----Examples-----
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
-----Note-----
In the first example, you can increase the second element twice. Than array will be $[1, 5, 5]$ and it's median is $5$.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $3$.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $[5, 1, 2, 5, 3, 5, 5]$ and the median will be $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.
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with.
Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h Γ w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.
Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 β€ ai β€ 100).
Output
Print the single number β the maximum number of frames Nicholas can make for his future canvases.
Examples
Input
5
2 4 3 2 3
Output
1
Input
13
2 2 4 4 4 4 6 6 6 7 7 9 9
Output
3
Input
4
3 3 3 5
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.
Polycarp's workday lasts exactly $n$ minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has $k$ bars at the beginning of the workday.
In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that $k$ is strictly greater than $1$.
Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.
Consider that Polycarp eats a bar in the minute $x$ and the next bar in the minute $y$ ($x < y$). Then the break time is equal to $y - x - 1$ minutes. It is not necessary for Polycarp to eat all bars he has.
-----Input-----
The first line contains two integers $n$ and $k$ ($2 \le n \le 200\,000$, $2 \le k \le n$) β the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday.
The second line contains the string with length $n$ consisting of zeros and ones. If the $i$-th symbol in the string equals to zero, Polycarp has no important things to do in the minute $i$ and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute $i$ and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.
-----Output-----
Print the minimum possible break in minutes between eating chocolate bars.
-----Examples-----
Input
3 3
010
Output
1
Input
8 3
01010110
Output
3
-----Note-----
In the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.
In the second example Polycarp will eat bars in the minutes $1$ and $8$ anyway, also he needs to eat the chocolate bar in the minute $5$, so that the time of the maximum break will be equal to $3$ minutes.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The executive chef is trying to bring some competitive spirit into his kitchen. He wants to split the chefs into two teams based on their age - he'll form the young and the old team. To make it fair, he will split them evenly or give the young team one person advantage when there is an odd number of chefs. Ages of all employees are unique. The executive chef also rated all chefs according to their cooking skills. Rating of a team is equal to the sum of ratings of its members. The chefs have developed a habit of coming to work late. The executive chef wants to keep the teams as fair as possible at all times and is therefore forced to change the teams each time one of the chefs comes to work in the morning. He needs your help with this task.
------ Input ------
The first line contains the number of chefs N. The following N lines describe the chefs in order as they come to work. Each chef is described by two integers, his or her age A_{i} and rating R_{i}.
------ Output ------
Every time a new chef joins the kitchen, output the absolute difference between team ratings.
------ Constraints ------
$1 β€ N β€ 10^{5}$
$1 β€ A_{i} β€ 10^{9}$
$1 β€ R_{i} β€ 1000$
----- Sample Input 1 ------
5
2 3
1 7
5 5
3 1
8 15
----- Sample Output 1 ------
3
4
5
4
9
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.
Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.
Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
-----Input-----
The first line of the input contains two integers n, kΒ (1 β€ k β€ n β€ 10^5). The second line contains n integers a_1, a_2, ..., a_{n}Β (1 β€ a_{i} β€ 10^3), where a_{i} is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task.
It is guaranteed that n is divisible by k.
-----Output-----
In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.
-----Examples-----
Input
6 2
3 2 1 6 5 4
Output
1
Input
10 5
1 3 5 7 9 9 4 1 8 5
Output
3
-----Note-----
Explanation of the first example.
If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12.
Explanation of the second example.
In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
**Principal Diagonal** -- The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East.
**Secondary Diagonal** -- the secondary diagonal of a matrix identifies those elements of the matrix running from North-East to South-West.
For example:
```
matrix: [1, 2, 3]
[4, 5, 6]
[7, 8, 9]
principal diagonal: [1, 5, 9]
secondary diagonal: [3, 5, 7]
```
## Task
Your task is to find which diagonal is "larger": which diagonal has a bigger sum of their elements.
* If the principal diagonal is larger, return `"Principal Diagonal win!"`
* If the secondary diagonal is larger, return `"Secondary Diagonal win!"`
* If they are equal, return `"Draw!"`
**Note:** You will always receive matrices of the same dimension.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Fair Nut lives in $n$ story house. $a_i$ people live on the $i$-th floor of the house. Every person uses elevator twice a day: to get from the floor where he/she lives to the ground (first) floor and to get from the first floor to the floor where he/she lives, when he/she comes back home in the evening.
It was decided that elevator, when it is not used, will stay on the $x$-th floor, but $x$ hasn't been chosen yet. When a person needs to get from floor $a$ to floor $b$, elevator follows the simple algorithm: Moves from the $x$-th floor (initially it stays on the $x$-th floor) to the $a$-th and takes the passenger. Moves from the $a$-th floor to the $b$-th floor and lets out the passenger (if $a$ equals $b$, elevator just opens and closes the doors, but still comes to the floor from the $x$-th floor). Moves from the $b$-th floor back to the $x$-th. The elevator never transposes more than one person and always goes back to the floor $x$ before transposing a next passenger. The elevator spends one unit of electricity to move between neighboring floors. So moving from the $a$-th floor to the $b$-th floor requires $|a - b|$ units of electricity.
Your task is to help Nut to find the minimum number of electricity units, that it would be enough for one day, by choosing an optimal the $x$-th floor. Don't forget than elevator initially stays on the $x$-th floor.
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 100$)Β β the number of floors.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \leq a_i \leq 100$)Β β the number of people on each floor.
-----Output-----
In a single line, print the answer to the problemΒ β the minimum number of electricity units.
-----Examples-----
Input
3
0 2 1
Output
16
Input
2
1 1
Output
4
-----Note-----
In the first example, the answer can be achieved by choosing the second floor as the $x$-th floor. Each person from the second floor (there are two of them) would spend $4$ units of electricity per day ($2$ to get down and $2$ to get up), and one person from the third would spend $8$ units of electricity per day ($4$ to get down and $4$ to get up). $4 \cdot 2 + 8 \cdot 1 = 16$.
In the second example, the answer can be achieved by choosing the first floor as the $x$-th floor.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.
Given are two integers A and B.
If Takahashi can calculate A \times B, print the result; if he cannot, print -1 instead.
-----Constraints-----
- 1 \leq A \leq 20
- 1 \leq B \leq 20
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
A B
-----Output-----
If Takahashi can calculate A \times B, print the result; if he cannot, print -1.
-----Sample Input-----
2 5
-----Sample Output-----
10
2 \times 5 = 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.
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
Task:
Write
```
smallest(n)
```
that will find the smallest positive number that is evenly divisible by all of the numbers from 1 to n (n <= 40).
E.g
```python
smallest(5) == 60 # 1 to 5 can all divide evenly into 60
smallest(10) == 2520
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $k$ such that Mr. Black can exit the house after opening the first $k$ doors.
We have to note that Mr. Black opened each door at most once, and in the end all doors became open.
-----Input-----
The first line contains integer $n$ ($2 \le n \le 200\,000$)Β β the number of doors.
The next line contains $n$ integers: the sequence in which Mr. Black opened the doors. The $i$-th of these integers is equal to $0$ in case the $i$-th opened door is located in the left exit, and it is equal to $1$ in case it is in the right exit.
It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.
-----Output-----
Print the smallest integer $k$ such that after Mr. Black opened the first $k$ doors, he was able to exit the house.
-----Examples-----
Input
5
0 0 1 0 0
Output
3
Input
4
1 0 0 1
Output
3
-----Note-----
In the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.
When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.
In the second example when the first two doors were opened, there was open closed door in each of the exit.
With three doors opened Mr. Black was able to use the left exit.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
C: Prayer (Pray)
Some twins are famous for praying before the contest.
There are four integers $ H, W, X, Y $, and it seems unlucky if $ H \ times W $ and $ x + y $ are both odd numbers.
input
Four integers $ H, W, X, Y $ are given, separated by spaces.
output
Output "No" if you are unlucky, or "Yes" if not. But don't forget the last line break.
Constraint
* $ H, W, X, Y $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 $
Input example 1
3 5 1 4
Output example 1
No
$ 3 \ times 5 = 15 $, $ 1 + 4 = 5 $, both odd numbers, so it's unlucky.
Input example 2
3 5 2 4
Output example 2
Yes
$ 3 \ times 5 = 15 $ is odd, but $ 2 + 4 = 6 $ is even, so good luck isn't bad.
Example
Input
3 5 1 4
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.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base b_{x} and a number Y represented in base b_{y}. Compare those two numbers.
-----Input-----
The first line of the input contains two space-separated integers n and b_{x} (1 β€ n β€ 10, 2 β€ b_{x} β€ 40), where n is the number of digits in the b_{x}-based representation of X.
The second line contains n space-separated integers x_1, x_2, ..., x_{n} (0 β€ x_{i} < b_{x}) β the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and b_{y} (1 β€ m β€ 10, 2 β€ b_{y} β€ 40, b_{x} β b_{y}), where m is the number of digits in the b_{y}-based representation of Y, and the fourth line contains m space-separated integers y_1, y_2, ..., y_{m} (0 β€ y_{i} < b_{y}) β the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
-----Output-----
Output a single character (quotes for clarity): '<' if X < Y '>' if X > Y '=' if X = Y
-----Examples-----
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
-----Note-----
In the first sample, X = 101111_2 = 47_10 = Y.
In the second sample, X = 102_3 = 21_5 and Y = 24_5 = 112_3, thus X < Y.
In the third sample, $X = FF 4007 A_{16}$ and Y = 4803150_9. We may notice that X starts with much larger digits and b_{x} is much larger than b_{y}, so X is clearly larger than Y.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
X and A are integers between 0 and 9 (inclusive).
If X is less than A, print 0; if X is not less than A, print 10.
-----Constraints-----
- 0 \leq X, A \leq 9
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
X A
-----Output-----
If X is less than A, print 0; if X is not less than A, print 10.
-----Sample Input-----
3 5
-----Sample Output-----
0
3 is less than 5, so we should print 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.
Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted n flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions.
There are m days left to the birthday. The height of the i-th flower (assume that the flowers in the row are numbered from 1 to n from left to right) is equal to a_{i} at the moment. At each of the remaining m days the beaver can take a special watering and water w contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get?
-----Input-----
The first line contains space-separated integers n, m and w (1 β€ w β€ n β€ 10^5;Β 1 β€ m β€ 10^5). The second line contains space-separated integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 10^9).
-----Output-----
Print a single integer β the maximum final height of the smallest flower.
-----Examples-----
Input
6 2 3
2 2 2 2 1 1
Output
2
Input
2 5 1
5 8
Output
9
-----Note-----
In the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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`, return the number of possible ways such that `k` positive integers multiply to `n`. Order matters.
**Examples**
```
n = 24
k = 2
(1, 24), (2, 12), (3, 8), (4, 6), (6, 4), (8, 3), (12, 2), (24, 1) -> 8
n = 100
k = 1
100 -> 1
n = 20
k = 3
(1, 1, 20), (1, 2, 10), (1, 4, 5), (1, 5, 4), (1, 10, 2), (1, 20, 1),
(2, 1, 10), (2, 2, 5), (2, 5, 2), (2, 10, 1), (4, 1, 5), (4, 5, 1),
(5, 1, 4), (5, 2, 2), (5, 4, 1), (10, 1, 2), (10, 2, 1), (20, 1, 1) -> 18
```
**Constraints**
`1 <= n <= 500_000_000`
and `1 <= k <= 1000`
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as v_{i}. The child spend v_{f}_1 + v_{f}_2 + ... + v_{f}_{k} energy for removing part i where f_1, f_2, ..., f_{k} are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
-----Input-----
The first line contains two integers n and m (1 β€ n β€ 1000; 0 β€ m β€ 2000). The second line contains n integers: v_1, v_2, ..., v_{n} (0 β€ v_{i} β€ 10^5). Then followed m lines, each line contains two integers x_{i} and y_{i}, representing a rope from part x_{i} to part y_{i} (1 β€ x_{i}, y_{i} β€ n;Β x_{i} β y_{i}).
Consider all the parts are numbered from 1 to n.
-----Output-----
Output the minimum total energy the child should spend to remove all n parts of the toy.
-----Examples-----
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
-----Note-----
One of the optimal sequence of actions in the first sample is: First, remove part 3, cost of the action is 20. Then, remove part 2, cost of the action is 10. Next, remove part 4, cost of the action is 10. At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
Input
The first line contains two space-separated integers: n and p (1 β€ n β€ 1000; 1 β€ p β€ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
Output
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
Examples
Input
3 3
cba
Output
NO
Input
3 4
cba
Output
cbd
Input
4 4
abcd
Output
abda
Note
String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 > ti + 1.
The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.
A palindrome is a string that reads the same forward or reversed.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Edo has got a collection of n refrigerator magnets!
He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers.
Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.
Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of ββthe door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.
Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x1, y1) and the upper right corner (x2, y2), then its center is located at (<image>, <image>) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.
The sides of the refrigerator door must also be parallel to coordinate axes.
Input
The first line contains two integers n and k (1 β€ n β€ 100 000, 0 β€ k β€ min(10, n - 1)) β the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator.
Next n lines describe the initial plan of placing magnets. Each line contains four integers x1, y1, x2, y2 (1 β€ x1 < x2 β€ 109, 1 β€ y1 < y2 β€ 109) β the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide.
Output
Print a single integer β the minimum area of the door of refrigerator, which can be used to place at least n - k magnets, preserving the relative positions.
Examples
Input
3 1
1 1 2 2
2 2 3 3
3 3 4 4
Output
1
Input
4 1
1 1 2 2
1 9 2 10
9 9 10 10
9 1 10 2
Output
64
Input
3 0
1 1 2 2
1 1 1000000000 1000000000
1 3 8 12
Output
249999999000000001
Note
In the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly.
In the second test sample it doesn't matter which magnet to remove, the answer will not change β we need a fridge with door width 8 and door height 8.
In the third sample you cannot remove anything as k = 0.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.
Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.
Find the inversion number of B, modulo 10^9 + 7.
Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.
Constraints
* All values in input are integers.
* 1 \leq N \leq 2000
* 1 \leq K \leq 10^9
* 1 \leq A_i \leq 2000
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 ... A_{N - 1}
Output
Print the inversion number of B, modulo 10^9 + 7.
Examples
Input
2 2
2 1
Output
3
Input
3 5
1 1 1
Output
0
Input
10 998244353
10 9 8 7 5 6 3 4 2 1
Output
185297239
Read the inputs from stdin solve the problem and write the answer to stdout (do 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. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.
Input
The single line contains an integer n (1 β€ n β€ 106) β the sum of digits of the required lucky number.
Output
Print on the single line the result β the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.
Examples
Input
11
Output
47
Input
10
Output
-1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Problem G Rendezvous on a Tetrahedron
One day, you found two worms $P$ and $Q$ crawling on the surface of a regular tetrahedron with four vertices $A$, $B$, $C$ and $D$. Both worms started from the vertex $A$, went straight ahead, and stopped crawling after a while.
When a worm reached one of the edges of the tetrahedron, it moved on to the adjacent face and kept going without changing the angle to the crossed edge (Figure G.1).
Write a program which tells whether or not $P$ and $Q$ were on the same face of the tetrahedron when they stopped crawling.
You may assume that each of the worms is a point without length, area, or volume.
<image>
Figure G.1. Crossing an edge
Incidentally, lengths of the two trails the worms left on the tetrahedron were exact integral multiples of the unit length. Here, the unit length is the edge length of the tetrahedron. Each trail is more than 0:001 unit distant from any vertices, except for its start point and its neighborhood. This means that worms have crossed at least one edge. Both worms stopped at positions more than 0:001 unit distant from any of the edges.
The initial crawling direction of a worm is specified by two items: the edge $XY$ which is the first edge the worm encountered after its start, and the angle $d$ between the edge $AX$ and the direction of the worm, in degrees.
<image>
Figure G.2. Trails of the worms corresponding to Sample Input 1
Figure G.2 shows the case of Sample Input 1. In this case, $P$ went over the edge $CD$ and stopped on the face opposite to the vertex $A$, while $Q$ went over the edge $DB$ and also stopped on the same face.
Input
The input consists of a single test case, formatted as follows.
$X_PY_P$ $d_P$ $l_P$
$X_QY_Q$ $d_Q$ $l_Q$
$X_WY_W$ ($W = P,Q$) is the first edge the worm $W$ crossed after its start. $X_WY_W$ is one of BC, CD or DB.
An integer $d_W$ ($1 \leq d_W \leq 59$) is the angle in degrees between edge $AX_W$ and the initial direction of the worm $W$ on the face $\triangle AX_WY_W$.
An integer $l_W$ ($1 \leq l_W \leq 20$) is the length of the trail of worm $W$ left on the surface, in unit lengths.
Output
Output YES when and only when the two worms stopped on the same face of the tetrahedron. Otherwise, output NO.
Sample Input 1
CD 30 1
DB 30 1
Sample Output 1
YES
Sample Input 2
BC 1 1
DB 59 1
Sample Output 2
YES
Sample Input 3
BC 29 20
BC 32 20
Sample Output 3
NO
Example
Input
CD 30 1
DB 30 1
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.
Petya recieved a gift of a string s with length up to 10^5 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves: Extract the first character of s and append t with this character. Extract the last character of t and append u with this character.
Petya wants to get strings s and t empty and string u lexicographically minimal.
You should write a program that will help Petya win the game.
-----Input-----
First line contains non-empty string s (1 β€ |s| β€ 10^5), consisting of lowercase English letters.
-----Output-----
Print resulting string u.
-----Examples-----
Input
cab
Output
abc
Input
acdb
Output
abdc
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Zane the wizard is going to perform a magic show shuffling the cups.
There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.
The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = u_{i} and x = v_{i}. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.
Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation. [Image]
Zaneβs puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.
-----Input-----
The first line contains three integers n, m, and k (2 β€ n β€ 10^6, 1 β€ m β€ n, 1 β€ k β€ 3Β·10^5)Β β the number of cups, the number of holes on the table, and the number of swapping operations, respectively.
The second line contains m distinct integers h_1, h_2, ..., h_{m} (1 β€ h_{i} β€ n)Β β the positions along the x-axis where there is a hole on the table.
Each of the next k lines contains two integers u_{i} and v_{i} (1 β€ u_{i}, v_{i} β€ n, u_{i} β v_{i})Β β the positions of the cups to be swapped.
-----Output-----
Print one integerΒ β the final position along the x-axis of the bone.
-----Examples-----
Input
7 3 4
3 4 6
1 2
2 5
5 7
7 1
Output
1
Input
5 1 2
2
1 2
2 4
Output
2
-----Note-----
In the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.
In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties: All the integers in the array were between $l$ and $r$ (inclusive). The sum of all the elements was divisible by $3$.
Unfortunately, Ayoub has lost his array, but he remembers the size of the array $n$ and the numbers $l$ and $r$, so he asked you to find the number of ways to restore the array.
Since the answer could be very large, print it modulo $10^9 + 7$ (i.e. the remainder when dividing by $10^9 + 7$). In case there are no satisfying arrays (Ayoub has a wrong memory), print $0$.
-----Input-----
The first and only line contains three integers $n$, $l$ and $r$ ($1 \le n \le 2 \cdot 10^5 , 1 \le l \le r \le 10^9$)Β β the size of the lost array and the range of numbers in the array.
-----Output-----
Print the remainder when dividing by $10^9 + 7$ the number of ways to restore the array.
-----Examples-----
Input
2 1 3
Output
3
Input
3 2 2
Output
1
Input
9 9 99
Output
711426616
-----Note-----
In the first example, the possible arrays are : $[1,2], [2,1], [3, 3]$.
In the second example, the only possible array is $[2, 2, 2]$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
# Definition
**_Jumping number_** is the number that *All adjacent digits in it differ by 1*.
____
# Task
**_Given_** a number, **_Find if it is Jumping or not_** .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_** .
* **_Return_** *the result as* **_String_** .
* **_The difference between_** *β9β and β0β* is **_not considered as 1_** .
* **_All single digit numbers_** are considered as **_Jumping numbers_**.
___
# Input >> Output Examples
```
jumpingNumber(9) ==> return "Jumping!!"
```
## **_Explanation_**:
* It's **_single-digit number_**
___
```
jumpingNumber(79) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(23) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
```
jumpingNumber(556847) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(4343456) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
```
jumpingNumber(89098) ==> return "Not!!"
```
## **_Explanation_**:
* *Adjacent digits* **_don't differ by 1_**
___
```
jumpingNumber(32) ==> return "Jumping!!"
```
## **_Explanation_**:
* *Adjacent digits* **_differ by 1_**
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays $a$ and $b$ of length $n$. Initially, an $ans$ is equal to $0$ and the following operation is defined: Choose position $i$ ($1 \le i \le n$); Add $a_i$ to $ans$; If $b_i \neq -1$ then add $a_i$ to $a_{b_i}$.
What is the maximum $ans$ you can get by performing the operation on each $i$ ($1 \le i \le n$) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
-----Input-----
The first line contains the integer $n$ ($1 \le n \le 2 \cdot 10^5$)Β β the length of arrays $a$ and $b$.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($β10^6 \le a_i \le 10^6$).
The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$ or $b_i = -1$).
Additional constraint: it's guaranteed that for any $i$ ($1 \le i \le n$) the sequence $b_i, b_{b_i}, b_{b_{b_i}}, \ldots$ is not cyclic, in other words it will always end with $-1$.
-----Output-----
In the first line, print the maximum $ans$ you can get.
In the second line, print the order of operations: $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$). The $p_i$ is the position which should be chosen at the $i$-th step. If there are multiple orders, print any of them.
-----Examples-----
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 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.
We have the first value of a certain sequence, we will name it ```initVal```.
We define pattern list, ```patternL```, an array that has the differences between contiguous terms of the sequence.
``` E.g: patternL = [k1, k2, k3, k4]```
The terms of the sequence will be such values that:
```python
term1 = initVal
term2 - term1 = k1
term3 - term2 = k2
term4 - term3 = k3
term5 - term4 = k4
term6 - term5 = k1
term7 - term6 = k2
term8 - term7 = k3
term9 - term8 = k4
.... - ..... = ...
.... - ..... = ...
```
So the values of the differences between contiguous terms are cyclical and are repeated as the differences values of the pattern list stablishes.
Let's see an example with numbers:
```python
initVal = 10
patternL = [2, 1, 3]
term1 = 10
term2 = 12
term3 = 13
term4 = 16
term5 = 18
term6 = 19
term7 = 22 # and so on...
```
We can easily obtain the next terms of the sequence following the values in the pattern list.
We see that the sixth term of the sequence, ```19```, has the sum of its digits ```10```.
Make a function ```sumDig_nthTerm()```, that receives three arguments in this order
```sumDig_nthTerm(initVal, patternL, nthTerm(ordinal number of the term in the sequence)) ```
This function will output the sum of the digits of the n-th term of the sequence.
Let's see some cases for this function:
```python
sumDig_nthTerm(10, [2, 1, 3], 6) -----> 10 # because the sixth term is 19 sum of Dig = 1 + 9 = 10. The sequence up to the sixth-Term is: 10, 12, 13, 16, 18, 19
sumDig_nthTerm(10, [1, 2, 3], 15) ----> 10 # 37 is the 15-th term, and 3 + 7 = 10
```
Enjoy it and happy coding!!
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Alice received a set of Toy Trainβ’ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described.
Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example.
The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.
Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.
-----Input-----
The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 5\,000$; $1 \leq m \leq 20\,000$) β the number of stations and the number of candies, respectively.
The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) β the station that initially contains candy $i$ and the destination station of the candy, respectively.
-----Output-----
In the first and only line, print $n$ space-separated integers, the $i$-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station $i$.
-----Examples-----
Input
5 7
2 4
5 1
2 3
3 4
4 1
5 3
3 5
Output
10 9 10 10 9
Input
2 3
1 2
1 2
1 2
Output
5 6
-----Note-----
Consider the second sample.
If the train started at station $1$, the optimal strategy is as follows. Load the first candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the first candy. Proceed to station $1$. This step takes $1$ second. Load the second candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the second candy. Proceed to station $1$. This step takes $1$ second. Load the third candy onto the train. Proceed to station $2$. This step takes $1$ second. Deliver the third candy.
Hence, the train needs $5$ seconds to complete the tasks.
If the train were to start at station $2$, however, it would need to move to station $1$ before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is $5+1 = 6$ seconds.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 all know about Roman Numerals, and if not, here's a nice [introduction kata](http://www.codewars.com/kata/5580d8dc8e4ee9ffcb000050). And if you were anything like me, you 'knew' that the numerals were not used for zeroes or fractions; but not so!
I learned something new today: the [Romans did use fractions](https://en.wikipedia.org/wiki/Roman_numerals#Special_values) and there was even a glyph used to indicate zero.
So in this kata, we will be implementing Roman numerals and fractions.
Although the Romans used base 10 for their counting of units, they used base 12 for their fractions. The system used dots to represent twelfths, and an `S` to represent a half like so:
* ^(1)/12 = `.`
* ^(2)/12 = `:`
* ^(3)/12 = `:.`
* ^(4)/12 = `::`
* ^(5)/12 = `:.:`
* ^(6)/12 = `S`
* ^(7)/12 = `S.`
* ^(8)/12 = `S:`
* ^(9)/12 = `S:.`
* ^(10)/12 = `S::`
* ^(11)/12 = `S:.:`
* ^(12)/12 = `I` (as usual)
Further, zero was represented by `N`
## Kata
Complete the method that takes two parameters: an integer component in the range 0 to 5000 inclusive, and an optional fractional component in the range 0 to 11 inclusive.
You must return a string with the encoded value. Any input values outside the ranges given above should return `"NaR"` (i.e. "Not a Roman" :-)
## Examples
```python
roman_fractions(-12) #=> "NaR"
roman_fractions(0, -1) #=> "NaR"
roman_fractions(0, 12) #=> "NaR"
roman_fractions(0) #=> "N"
roman_fractions(0, 3) #=> ":."
roman_fractions(1) #=> "I"
roman_fractions(1, 0) #=> "I"
roman_fractions(1, 5) #=> "I:.:"
roman_fractions(1, 9) #=> "IS:."
roman_fractions(1632, 2) #=> "MDCXXXII:"
roman_fractions(5000) #=> "MMMMM"
roman_fractions(5001) #=> "NaR"
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Well met with Fibonacci bigger brother, AKA Tribonacci.
As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(
So, if we are to start our Tribonacci sequence with `[1, 1, 1]` as a starting input (AKA *signature*), we have this sequence:
```
[1, 1 ,1, 3, 5, 9, 17, 31, ...]
```
But what if we started with `[0, 0, 1]` as a signature? As starting with `[0, 1]` instead of `[1, 1]` basically *shifts* the common Fibonacci sequence by once place, you may be tempted to think that we would get the same sequence shifted by 2 places, but that is not the case and we would get:
```
[0, 0, 1, 1, 2, 4, 7, 13, 24, ...]
```
Well, you may have guessed it by now, but to be clear: you need to create a fibonacci function that given a **signature** array/list, returns **the first n elements - signature included** of the so seeded sequence.
Signature will always contain 3 numbers; n will always be a non-negative number; if `n == 0`, then return an empty array (except in C return NULL) and be ready for anything else which is not clearly specified ;)
If you enjoyed this kata more advanced and generalized version of it can be found in the Xbonacci kata
*[Personal thanks to Professor Jim Fowler on Coursera for his awesome classes that I really recommend to any math enthusiast and for showing me this mathematical curiosity too with his usual contagious passion :)]*
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 string s of length 3 or greater.
No two neighboring characters in s are equal.
Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:
- Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.
The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.
-----Constraints-----
- 3 β€ |s| β€ 10^5
- s consists of lowercase English letters.
- No two neighboring characters in s are equal.
-----Input-----
The input is given from Standard Input in the following format:
s
-----Output-----
If Takahashi will win, print First. If Aoki will win, print Second.
-----Sample Input-----
aba
-----Sample Output-----
Second
Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
We have N integers. The i-th integer is A_i.
Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).What is \mbox{ XOR }?
The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:
- When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.
For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)
-----Constraints-----
- 2 \leq N \leq 3 \times 10^5
- 0 \leq A_i < 2^{60}
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
-----Output-----
Print the value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).
-----Sample Input-----
3
1 2 3
-----Sample Output-----
6
We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=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.
Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it).
It turned out that the operation does exist (however, it is called tor) and it works like this. Suppose that we need to calculate the value of the expression a tor b. Both numbers a and b are written in the ternary notation one under the other one (b under a). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: 1410 tor 5010 = 01123 tor 12123 = 10213 = 3410.
Petya wrote numbers a and c on a piece of paper. Help him find such number b, that a tor b = c. If there are several such numbers, print the smallest one.
Input
The first line contains two integers a and c (0 β€ a, c β€ 109). Both numbers are written in decimal notation.
Output
Print the single integer b, such that a tor b = c. If there are several possible numbers b, print the smallest one. You should print the number in decimal notation.
Examples
Input
14 34
Output
50
Input
50 34
Output
14
Input
387420489 225159023
Output
1000000001
Input
5 5
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.
Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if the sequence consists of at least two elements f_0 and f_1 are arbitrary f_{n} + 2 = f_{n} + 1 + f_{n} for all n β₯ 0.
You are given some sequence of integers a_1, a_2, ..., a_{n}. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.
-----Input-----
The first line of the input contains a single integer n (2 β€ n β€ 1000)Β β the length of the sequence a_{i}.
The second line contains n integers a_1, a_2, ..., a_{n} (|a_{i}| β€ 10^9).
-----Output-----
Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.
-----Examples-----
Input
3
1 2 -1
Output
3
Input
5
28 35 7 14 21
Output
4
-----Note-----
In the first sample, if we rearrange elements of the sequence as - 1, 2, 1, the whole sequence a_{i} would be Fibonacci-ish.
In the second sample, the optimal way to rearrange elements is $7$, $14$, $21$, $35$, 28.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.
For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.
The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.
There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?
Formally, we assume that two words denote the same name, if using the replacements "u"Β [Image]Β "oo" and "h"Β [Image]Β "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.
For example, the following pairs of words denote the same name: "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" $\rightarrow$ "kuuper" and "kuooper" $\rightarrow$ "kuuper". "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" $\rightarrow$ "khoon" and "kkkhoon" $\rightarrow$ "kkhoon" $\rightarrow$ "khoon".
For a given list of words, find the minimal number of groups where the words in each group denote the same name.
-----Input-----
The first line contains integer number n (2 β€ n β€ 400) β number of the words in the list.
The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.
-----Output-----
Print the minimal number of groups where the words in each group denote the same name.
-----Examples-----
Input
10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon
Output
4
Input
9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi
Output
5
Input
2
alex
alex
Output
1
-----Note-----
There are four groups of words in the first example. Words in each group denote same name: "mihail", "mikhail" "oolyana", "ulyana" "kooooper", "koouper" "hoon", "khun", "kkkhoon"
There are five groups of words in the second example. Words in each group denote same name: "hariton", "kkkhariton", "khariton" "hkariton" "buoi", "boooi", "boui" "bui" "boi"
In the third example the words are equal, so they denote the same name.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 n Γ m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
Β
we obtain the table:
acd
efg
hjk
Β
A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
-----Input-----
The first line contains two integers Β β n and m (1 β€ n, m β€ 100).
Next n lines contain m small English letters eachΒ β the characters of the table.
-----Output-----
Print a single numberΒ β the minimum number of columns that you need to remove in order to make the table good.
-----Examples-----
Input
1 10
codeforces
Output
0
Input
4 4
case
care
test
code
Output
2
Input
5 4
code
forc
esco
defo
rces
Output
4
-----Note-----
In the first sample the table is already good.
In the second sample you may remove the first and third column.
In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).
Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length x is such a substring of length 2x, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat.
You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.
Input
The first input line contains integer n (1 β€ n β€ 105) β length of the string. The following line contains n space-separated integer numbers from 0 to 109 inclusive β numbers that stand for the letters of the string. It's guaranteed that each letter can be met in the string at most 10 times.
Output
In the first line output the length of the string's part, left after Bob's deletions. In the second line output all the letters (separated by a space) of the string, left after Bob deleted all the repeats in the described way.
Examples
Input
6
1 2 3 1 2 3
Output
3
1 2 3
Input
7
4 5 6 5 6 7 7
Output
1
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.
Write a program which reads $n$ items and sorts them. Each item has attributes $\\{value, weight, type, date, name\\}$ and they are represented by $\\{$ integer, integer, upper-case letter, integer, string $\\}$ respectively. Sort the items based on the following priorities.
1. first by value (ascending)
2. in case of a tie, by weight (ascending)
3. in case of a tie, by type (ascending in lexicographic order)
4. in case of a tie, by date (ascending)
5. in case of a tie, by name (ascending in lexicographic order)
Constraints
* $1 \leq n \leq 100,000$
* $0 \leq v_i \leq 1,000,000,000$
* $0 \leq w_i \leq 1,000,000,000$
* $t_i$ is a upper-case letter
* $0 \leq d_i \leq 2,000,000,000,000$
* $1 \leq $ size of $s_i \leq 20$
* $s_i \ne s_j$ if $(i \ne j)$
Input
The input is given in the following format.
$n$
$v_0 \; w_0 \; t_0 \; d_0 \; s_0$
$v_1 \; w_1 \; t_1 \; d_1 \; s_1$
:
$v_{n-1} \; w_{n-1} \; t_{n-1} \; d_{n-1} \; s_{n-1}$
In the first line, the number of items $n$. In the following $n$ lines, attributes of each item are given. $v_i \; w_i \; t_i \; d_i \; s_i$ represent value, weight, type, date and name of the $i$-th item respectively.
Output
Print attributes of each item in order. Print an item in a line and adjacency attributes should be separated by a single space.
Example
Input
5
105 24 C 1500000000000 white
100 23 C 1500000000000 blue
105 23 A 1480000000000 pink
110 25 B 1500000000000 black
110 20 A 1300000000000 gree
Output
100 23 C 1500000000000 blue
105 23 A 1480000000000 pink
105 24 C 1500000000000 white
110 20 A 1300000000000 gree
110 25 B 1500000000000 black
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two arrays $a_1, a_2, \dots , a_n$ and $b_1, b_2, \dots , b_m$. Array $b$ is sorted in ascending order ($b_i < b_{i + 1}$ for each $i$ from $1$ to $m - 1$).
You have to divide the array $a$ into $m$ consecutive subarrays so that, for each $i$ from $1$ to $m$, the minimum on the $i$-th subarray is equal to $b_i$. Note that each element belongs to exactly one subarray, and they are formed in such a way: the first several elements of $a$ compose the first subarray, the next several elements of $a$ compose the second subarray, and so on.
For example, if $a = [12, 10, 20, 20, 25, 30]$ and $b = [10, 20, 30]$ then there are two good partitions of array $a$: $[12, 10, 20], [20, 25], [30]$; $[12, 10], [20, 20, 25], [30]$.
You have to calculate the number of ways to divide the array $a$. Since the number can be pretty large print it modulo 998244353.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$)Β β the length of arrays $a$ and $b$ respectively.
The second line contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 10^9$)Β β the array $a$.
The third line contains $m$ integers $b_1, b_2, \dots , b_m$ ($1 \le b_i \le 10^9; b_i < b_{i+1}$)Β β the array $b$.
-----Output-----
In only line print one integer β the number of ways to divide the array $a$ modulo 998244353.
-----Examples-----
Input
6 3
12 10 20 20 25 30
10 20 30
Output
2
Input
4 2
1 3 3 7
3 7
Output
0
Input
8 2
1 2 2 2 2 2 2 2
1 2
Output
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.
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.
Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.
-----Input-----
The first line of the input contains a single integer n (1 β€ n β€ 4)Β β the number of vertices that were not erased by Wilbur's friend.
Each of the following n lines contains two integers x_{i} and y_{i} ( - 1000 β€ x_{i}, y_{i} β€ 1000)Β βthe coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order.
It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes.
-----Output-----
Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print - 1.
-----Examples-----
Input
2
0 0
1 1
Output
1
Input
1
1 1
Output
-1
-----Note-----
In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square.
In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.
Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.
Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.
Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.
Constraints
* 1 β€ N β€ 10^5
* 2 β€ C β€ 10^{14}
* 1 β€ x_1 < x_2 < ... < x_N < C
* 1 β€ v_i β€ 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N C
x_1 v_1
x_2 v_2
:
x_N v_N
Output
If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.
Examples
Input
3 20
2 80
9 120
16 1
Output
191
Input
3 20
2 80
9 1
16 120
Output
192
Input
1 100000000000000
50000000000000 1
Output
0
Input
15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000
Output
6500000000
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function `sumTimesTables` which sums the result of the sums of the elements specified in `tables` multiplied by all the numbers in between `min` and `max` including themselves.
For example, for `sumTimesTables([2,5],1,3)` the result should be the same as
```
2*1 + 2*2 + 2*3 +
5*1 + 5*2 + 5*3
```
i.e. the table of two from 1 to 3 plus the table of five from 1 to 3
All the numbers are integers but you must take in account:
* `tables` could be empty.
* `min` could be negative.
* `max` could be really big.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array $a_1, a_2, \dots, a_n$, you need to handle a total of $q$ updates and queries of two types:
$1$ $l$ $r$ β for each index $i$ with $l \leq i \leq r$, update the value of $a_i$ to the sum of the digits of $a_i$.
$2$ $x$ β output $a_x$.
-----Input-----
The first line of the input contains an integer $t$ ($1 \leq t \leq 1000$) β the number of testcases.
The first line of each test case contains two integers $n$ and $q$ ($1 \le n, q \le 2 \cdot 10^5$) β the size of the array and the number of queries, respectively.
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 next $q$ lines of each test case are of two forms:
$1$ $l$ $r$ ($1 \leq l \leq r \leq n$) β it means, for each index $i$ with $l \leq i \leq r$, you should update the value of $a_i$ to the sum of its digits.
$2$ $x$ ($1 \leq x \leq n$) β it means you should output $a_x$.
There is at least one query of the second type.
The sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
The sum of $q$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output the answers of queries of the second type, in the order they are given.
-----Examples-----
Input
3
5 8
1 420 69 1434 2023
1 2 3
2 2
2 3
2 4
1 2 5
2 1
2 3
2 5
2 3
9999 1000
1 1 2
2 1
2 2
1 1
1
2 1
Output
6
15
1434
1
6
7
36
1
1
-----Note-----
In the first test case, the following process occurs:
Initially, $a = [1, 420, 69, 1434, 2023]$.
The operation is performed for $l=2$, $r=3$, yielding $[1, {6}, {15}, 1434, 2023]$.
We are queried for $x=2$, $x=3$, and $x=4$, and output $6$, $15$, and $1434$.
The operation is performed for $l=2$, $r=5$, yielding $[1, {6}, {6}, {12}, {7}]$.
We are queried for $x=1$, $x=3$, and $x=5$, and output $1$, $6$, and $7$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.
Help guys determine the winner photo by the records of likes.
-----Input-----
The first line of the input contains a single integer n (1 β€ n β€ 1000) β the total likes to the published photoes.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 1 000 000), where a_{i} is the identifier of the photo which got the i-th like.
-----Output-----
Print the identifier of the photo which won the elections.
-----Examples-----
Input
5
1 3 2 2 1
Output
2
Input
9
100 200 300 200 100 300 300 100 200
Output
300
-----Note-----
In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second).
Thus, the winner is the photo with identifier 2, as it got: more likes than the photo with id 3; as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation!
Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.
Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.
According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.
-----Input-----
The only line contains three integers b, d and s (0 β€ b, d, s β€ 10^18, b + d + s β₯ 1)Β β the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium.
-----Output-----
Print single integerΒ β the minimum possible number of meals which Vasiliy could have missed during his vacation.
-----Examples-----
Input
3 2 1
Output
1
Input
1 0 0
Output
0
Input
1 1 1
Output
0
Input
1000000000000000000 0 1000000000000000000
Output
999999999999999999
-----Note-----
In the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day.
In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal.
In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Martian boy is named s β he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=Β«abaΒ», then strings Β«baobabΒ», Β«aabbaaΒ», Β«helloabahelloΒ» make him very happy and strings Β«aabΒ», Β«baaaΒ» and Β«helloabhelloΒ» do not.
However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.
Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.
-----Input-----
The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters.
The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 10^6 letters.
-----Output-----
Print the sought number of ways to cut string t in two so that each part made s happy.
-----Examples-----
Input
aba
baobababbah
Output
2
Input
mars
sunvenusearthmarsjupitersaturnuranusneptune
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.
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
[Image]
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
While watching previous races the organizers have noticed that Willman can perform only steps of length equal to w meters, and Bolt can perform only steps of length equal to b meters. Organizers decided to slightly change the rules of the race. Now, at the end of the racetrack there will be an abyss, and the winner will be declared the athlete, who manages to run farther from the starting point of the the racetrack (which is not the subject to change by any of the athletes).
Note that none of the athletes can run infinitely far, as they both will at some moment of time face the point, such that only one step further will cause them to fall in the abyss. In other words, the athlete will not fall into the abyss if the total length of all his steps will be less or equal to the chosen distance L.
Since the organizers are very fair, the are going to set the length of the racetrack as an integer chosen randomly and uniformly in range from 1 to t (both are included). What is the probability that Willman and Bolt tie again today?
-----Input-----
The first line of the input contains three integers t, w and b (1 β€ t, w, b β€ 5Β·10^18) β the maximum possible length of the racetrack, the length of Willman's steps and the length of Bolt's steps respectively.
-----Output-----
Print the answer to the problem as an irreducible fraction [Image]. Follow the format of the samples output.
The fraction [Image] (p and q are integers, and both p β₯ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1, that both p and q are divisible by d.
-----Examples-----
Input
10 3 2
Output
3/10
Input
7 1 2
Output
3/7
-----Note-----
In the first sample Willman and Bolt will tie in case 1, 6 or 7 are chosen as the length of the racetrack.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Array of integers is unimodal, if:
it is strictly increasing in the beginning; after that it is constant; after that it is strictly decreasing.
The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.
For example, the following three arrays are unimodal: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6].
Write a program that checks if an array is unimodal.
-----Input-----
The first line contains integer n (1 β€ n β€ 100) β the number of elements in the array.
The second line contains n integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 1 000) β the elements of the array.
-----Output-----
Print "YES" if the given array is unimodal. Otherwise, print "NO".
You can output each letter in any case (upper or lower).
-----Examples-----
Input
6
1 5 5 5 4 2
Output
YES
Input
5
10 20 30 20 10
Output
YES
Input
4
1 2 1 2
Output
NO
Input
7
3 3 3 3 3 3 3
Output
YES
-----Note-----
In the first example the array is unimodal, because it is strictly increasing in the beginning (from position 1 to position 2, inclusively), that it is constant (from position 2 to position 4, inclusively) and then it is strictly decreasing (from position 4 to position 6, inclusively).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains a_{i} balls, all of which have color i. You have to write a program that will divide all balls into sets such that: each ball belongs to exactly one of the sets, there are no empty sets, there is no set containing two (or more) balls of different colors (each set contains only balls of one color), there are no two sets such that the difference between their sizes is greater than 1.
Print the minimum possible number of sets.
-----Input-----
The first line contains one integer number n (1 β€ n β€ 500).
The second line contains n integer numbers a_1, a_2, ... , a_{n} (1 β€ a_{i} β€ 10^9).
-----Output-----
Print one integer number β the minimum possible number of sets.
-----Examples-----
Input
3
4 7 8
Output
5
Input
2
2 7
Output
4
-----Note-----
In the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.
Find the total number of biscuits produced within T + 0.5 seconds after activation.
-----Constraints-----
- All values in input are integers.
- 1 \leq A, B, T \leq 20
-----Input-----
Input is given from Standard Input in the following format:
A B T
-----Output-----
Print the total number of biscuits produced within T + 0.5 seconds after activation.
-----Sample Input-----
3 5 7
-----Sample Output-----
10
- Five biscuits will be produced three seconds after activation.
- Another five biscuits will be produced six seconds after activation.
- Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 N. Your task is to divide it into several contiguous subarrays. Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order. At least how many subarrays do you need to divide A into?
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* Each A_i is an integer.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible number of subarrays after division of A.
Examples
Input
6
1 2 3 2 2 1
Output
2
Input
9
1 2 1 2 1 2 1 2 1
Output
5
Input
7
1 2 3 2 1 999999999 1000000000
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.
In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.
Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).
Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.
To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses:
* "Success" if the activation was successful.
* "Already on", if the i-th collider was already activated before the request.
* "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them.
The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program:
* "Success", if the deactivation was successful.
* "Already off", if the i-th collider was already deactivated before the request.
You don't need to print quotes in the output of the responses to the requests.
Input
The first line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the number of colliders and the number of requests, correspondingly.
Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β activate the i-th collider, or "- i" (without the quotes) β deactivate the i-th collider (1 β€ i β€ n).
Output
Print m lines β the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.
Examples
Input
10 10
+ 6
+ 10
+ 5
- 10
- 5
- 6
+ 10
+ 3
+ 6
+ 3
Output
Success
Conflict with 6
Success
Already off
Success
Success
Success
Success
Conflict with 10
Already on
Note
Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 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.
Β«PolygonΒ» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.
You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.
Input
The first line contains one integer n (1 β€ n β€ 3000) β the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 β€ ai β€ 3000) β indexes of these tests.
Output
Output the required default value for the next test index.
Examples
Input
3
1 7 2
Output
3
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawns on you that you have been watching the musician for some 10 odd minutes. You ask, "How much do people normally tip for something like this?" The artist looks up. "Its always gonna be about tree fiddy."
It was then that you realize the musician was a 400 foot tall beast from the paleolithic era. The Loch Ness Monster almost tricked you!
There are only 2 guaranteed ways to tell if you are speaking to The Loch Ness Monster: A.) It is a 400 foot tall beast from the paleolithic era B.) It will ask you for tree fiddy
Since Nessie is a master of disguise, the only way accurately tell is to look for the phrase "tree fiddy". Since you are tired of being grifted by this monster, the time has come to code a solution for finding The Loch Ness Monster.
Note: It can also be written as 3.50 or three fifty.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 fighting with Zmei Gorynich β a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!
$m$
Initially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-th type, you decrease the number of Gorynich's heads by $min(d_i, curX)$, there $curX$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $h_i$ new heads. If $curX = 0$ then Gorynich is defeated.
You can deal each blow any number of times, in any order.
For example, if $curX = 10$, $d = 7$, $h = 10$ then the number of heads changes to $13$ (you cut $7$ heads off, but then Zmei grows $10$ new ones), but if $curX = 10$, $d = 11$, $h = 100$ then number of heads changes to $0$ and Zmei Gorynich is considered defeated.
Calculate the minimum number of blows to defeat Zmei Gorynich!
You have to answer $t$ independent queries.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) β the number of queries.
The first line of each query contains two integers $n$ and $x$ ($1 \le n \le 100$, $1 \le x \le 10^9$) β the number of possible types of blows and the number of heads Zmei initially has, respectively.
The following $n$ lines of each query contain the descriptions of types of blows you can deal. The $i$-th line contains two integers $d_i$ and $h_i$ ($1 \le d_i, h_i \le 10^9$) β the description of the $i$-th blow.
-----Output-----
For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.
If Zmei Gorynuch cannot be defeated print $-1$.
-----Example-----
Input
3
3 10
6 3
8 2
1 4
4 10
4 1
3 2
2 6
1 100
2 15
10 11
14 100
Output
2
3
-1
-----Note-----
In the first query you can deal the first blow (after that the number of heads changes to $10 - 6 + 3 = 7$), and then deal the second blow.
In the second query you just deal the first blow three times, and Zmei is defeated.
In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 board of size $n \times n$, where $n$ is odd (not divisible by $2$). Initially, each cell of the board contains one figure.
In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $(i, j)$ you can move the figure to cells: $(i - 1, j - 1)$; $(i - 1, j)$; $(i - 1, j + 1)$; $(i, j - 1)$; $(i, j + 1)$; $(i + 1, j - 1)$; $(i + 1, j)$; $(i + 1, j + 1)$;
Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.
Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $n^2-1$ cells should contain $0$ figures and one cell should contain $n^2$ figures).
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 200$) β the number of test cases. Then $t$ test cases follow.
The only line of the test case contains one integer $n$ ($1 \le n < 5 \cdot 10^5$) β the size of the board. It is guaranteed that $n$ is odd (not divisible by $2$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $5 \cdot 10^5$ ($\sum n \le 5 \cdot 10^5$).
-----Output-----
For each test case print the answer β the minimum number of moves needed to get all the figures into one cell.
-----Example-----
Input
3
1
5
499993
Output
0
40
41664916690999888
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 set of points $x_1$, $x_2$, ..., $x_n$ on the number line.
Two points $i$ and $j$ can be matched with each other if the following conditions hold: neither $i$ nor $j$ is matched with any other point; $|x_i - x_j| \ge z$.
What is the maximum number of pairs of points you can match with each other?
-----Input-----
The first line contains two integers $n$ and $z$ ($2 \le n \le 2 \cdot 10^5$, $1 \le z \le 10^9$) β the number of points and the constraint on the distance between matched points, respectively.
The second line contains $n$ integers $x_1$, $x_2$, ..., $x_n$ ($1 \le x_i \le 10^9$).
-----Output-----
Print one integer β the maximum number of pairs of points you can match with each other.
-----Examples-----
Input
4 2
1 3 3 7
Output
2
Input
5 5
10 9 5 8 7
Output
1
-----Note-----
In the first example, you may match point $1$ with point $2$ ($|3 - 1| \ge 2$), and point $3$ with point $4$ ($|7 - 3| \ge 2$).
In the second example, you may match point $1$ with point $3$ ($|5 - 10| \ge 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.
# Description
Write a function that checks whether a credit card number is correct or not, using the Luhn algorithm.
The algorithm is as follows:
* From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 Γ 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or alternatively subtract 9 from the product (e.g., 16: 16 - 9 = 7, 18: 18 - 9 = 9).
* Take the sum of all the digits.
* If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.
The input is a string with the full credit card number, in groups of 4 digits separated by spaces, i.e. "1234 5678 9012 3456"
DonΒ΄t worry about wrong inputs, they will always be a string with 4 groups of 4 digits each separated by space.
# Examples
`valid_card?("5457 6238 9823 4311") # True`
`valid_card?("5457 6238 9323 4311") # False`
for reference check: https://en.wikipedia.org/wiki/Luhn_algorithm
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Teddy and Tracy like to play a game based on strings. The game is as follows. Initially, Tracy writes a long random string on a whiteboard. Then, each player starting with Teddy makes turn alternately. Each turn, the player must erase a contiguous substring that exists in the dictionary. The dictionary consists of N words.
Of course, the player that can't erase any substring in his turn loses the game, and the other player is declared the winner.
Note that after a substring R is erased, the remaining substring becomes separated, i.e. they cannot erase a word that occurs partially to the left of R and partially to the right of R.
Determine the winner of the game, assuming that both players play optimally.
------ Input ------
The first line contains a single integer T, the number of test cases. T test cases follow. The first line of each testcase contains a string S, the string Tracy writes on the whiteboard. The next line contains a single integer N. N lines follow. The i-th line contains a single string w_{i}, the i-th word in the dictionary.
------ Output ------
For each test case, output a single line containing the name of the winner of the game.
------ Constraints ------
$1 β€ T β€ 5$
$1 β€ N β€ 30$
$1 β€ |S| β€ 30$
$1 β€ |w_{i}| β€ 30$
$S and w_{i} contain only characters 'a'-'z'$
----- Sample Input 1 ------
3
codechef
2
code
chef
foo
1
bar
mississippi
4
ssissi
mippi
mi
ppi
----- Sample Output 1 ------
Tracy
Tracy
Teddy
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Given an array a_1, a_2, ..., a_{n} of n integers, find the largest number in the array that is not a perfect square.
A number x is said to be a perfect square if there exists an integer y such that x = y^2.
-----Input-----
The first line contains a single integer n (1 β€ n β€ 1000)Β β the number of elements in the array.
The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^6 β€ a_{i} β€ 10^6)Β β the elements of the array.
It is guaranteed that at least one element of the array is not a perfect square.
-----Output-----
Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.
-----Examples-----
Input
2
4 2
Output
2
Input
8
1 2 4 8 16 32 64 576
Output
32
-----Note-----
In the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 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.
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.
You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type).
If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.
Input
The first line contains an integer n (1 β€ n β€ 100) β the number of friends.
Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0 β€ si β€ 100) β the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as "XX-XX-XX", where X is arbitrary digits from 0 to 9.
Output
In the first line print the phrase "If you want to call a taxi, you should call: ". Then print names of all friends whose phone books contain maximal number of taxi phone numbers.
In the second line print the phrase "If you want to order a pizza, you should call: ". Then print names of all friends who have maximal number of pizza phone numbers.
In the third line print the phrase "If you want to go to a cafe with a wonderful girl, you should call: ". Then print names of all friends who have maximal number of girls' phone numbers.
Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.
Examples
Input
4
2 Fedorov
22-22-22
98-76-54
3 Melnikov
75-19-09
23-45-67
99-99-98
7 Rogulenko
22-22-22
11-11-11
33-33-33
44-44-44
55-55-55
66-66-66
95-43-21
3 Kaluzhin
11-11-11
99-99-99
98-65-32
Output
If you want to call a taxi, you should call: Rogulenko.
If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.
If you want to go to a cafe with a wonderful girl, you should call: Melnikov.
Input
3
5 Gleb
66-66-66
55-55-55
01-01-01
65-43-21
12-34-56
3 Serega
55-55-55
87-65-43
65-55-21
5 Melnik
12-42-12
87-73-01
36-04-12
88-12-22
82-11-43
Output
If you want to call a taxi, you should call: Gleb.
If you want to order a pizza, you should call: Gleb, Serega.
If you want to go to a cafe with a wonderful girl, you should call: Melnik.
Input
3
3 Kulczynski
22-22-22
65-43-21
98-12-00
4 Pachocki
11-11-11
11-11-11
11-11-11
98-76-54
0 Smietanka
Output
If you want to call a taxi, you should call: Pachocki.
If you want to order a pizza, you should call: Kulczynski, Pachocki.
If you want to go to a cafe with a wonderful girl, you should call: Kulczynski.
Note
In the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.
Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an integer n. Find any string s of length n consisting only of English lowercase letters such that each non-empty substring of s occurs in s an odd number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
The first line contains a single integer t (1 β€ t β€ 500) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5).
It is guaranteed that the sum of n over all test cases doesn't exceed 3 β
10^5.
Output
For each test case, print a single line containing the string s. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.
Example
Input
4
3
5
9
19
Output
abc
diane
bbcaabbba
youarethecutestuwuu
Note
In the first test case, each substring of "abc" occurs exactly once.
In the third test case, each substring of "bbcaabbba" occurs an odd number of times. In particular, "b" occurs 5 times, "a" and "bb" occur 3 times each, and each of the remaining substrings occurs exactly once.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $n$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.
For example, if $n=6$ and the level is described by the string "**.*..", then the following game scenario is possible:
the sheep at the $4$ position moves to the right, the state of the level: "**..*.";
the sheep at the $2$ position moves to the right, the state of the level: "*.*.*.";
the sheep at the $1$ position moves to the right, the state of the level: ".**.*.";
the sheep at the $3$ position moves to the right, the state of the level: ".*.**.";
the sheep at the $2$ position moves to the right, the state of the level: "..***.";
the sheep are lined up and the game ends.
For a given level, determine the minimum number of moves you need to make to complete the level.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow.
The first line of each test case contains one integer $n$ ($1 \le n \le 10^6$).
The second line of each test case contains a string of length $n$, consisting of the characters '.' (empty space) and '*' (sheep) β the description of the level.
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^6$.
-----Output-----
For each test case output the minimum number of moves you need to make to complete the level.
-----Examples-----
Input
5
6
**.*..
5
*****
3
.*.
3
...
10
*.*...*.**
Output
1
0
0
0
9
-----Note-----
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a stack of N cards, each of which has a non-negative integer written on it. The integer written on the i-th card from the top is A_i.
Snuke will repeat the following operation until two cards remain:
* Choose three consecutive cards from the stack.
* Eat the middle card of the three.
* For each of the other two cards, replace the integer written on it by the sum of that integer and the integer written on the card eaten.
* Return the two cards to the original position in the stack, without swapping them.
Find the minimum possible sum of the integers written on the last two cards remaining.
Constraints
* 2 \leq N \leq 18
* 0 \leq A_i \leq 10^9 (1\leq i\leq N)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
Output
Print the minimum possible sum of the integers written on the last two cards remaining.
Examples
Input
4
3 1 4 2
Output
16
Input
6
5 2 4 1 6 9
Output
51
Input
10
3 1 4 1 5 9 2 6 5 3
Output
115
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Write a function that solves an algebraic expression given as a string.
* The expression can include only sums and products.
* The numbers in the expression are in standard notation (NOT scientific).
* In contrast, the function should return a string with the calculated value given in scientific notation with 5 decimal digits.
# Example:
```python
strexpression = "5 * 4 + 6"
sum_prod(strexpression) = "2.60000e+01"
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant.
A set of directions consists of several instructions. The first instruction is of the form "Begin on XXX", indicating the street that the route begins on. Each subsequent instruction is of the form "Left on XXX" or "Right on XXX", indicating a turn onto the specified road.
When reversing directions, all left turns become right turns and vice versa, and the order of roads and turns is reversed. See the sample input for examples.
------ Input ------
Input will begin with an integer T, the number of test cases that follow. Each test case begins with an integer N, the number of instructions in the route. N lines follow, each with exactly one instruction in the format described above.
------ Output ------
For each test case, print the directions of the reversed route, one instruction per line. Print a blank line after each test case.
------ Constraints ------
$1 β€ T β€ 15$
$2 β€ N β€ 40$
$Each line in the input will contain at most 50 characters, will contain only alphanumeric characters and spaces and will not contain consecutive spaces nor trailing spaces. By alphanumeric characters we mean digits and letters of the English alphabet (lowercase and uppercase).$
----- Sample Input 1 ------
2
4
Begin on Road A
Right on Road B
Right on Road C
Left on Road D
6
Begin on Old Madras Road
Left on Domlur Flyover
Left on 100 Feet Road
Right on Sarjapur Road
Right on Hosur Road
Right on Ganapathi Temple Road
----- Sample Output 1 ------
Begin on Road D
Right on Road C
Left on Road B
Left on Road A
Begin on Ganapathi Temple Road
Left on Hosur Road
Left on Sarjapur Road
Left on 100 Feet Road
Right on Domlur Flyover
Right on Old Madras Road
----- explanation 1 ------
In the first test case, the destination lies on Road D, hence the reversed route begins on Road D. The final turn in the original route is turning left from Road C onto Road D. The reverse of this, turning right from Road D onto Road C, is the first turn in the reversed route.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two integers $A$ and $B$, calculate the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true; $conc(a, b)$ is the concatenation of $a$ and $b$ (for example, $conc(12, 23) = 1223$, $conc(100, 11) = 10011$). $a$ and $b$ should not contain leading zeroes.
-----Input-----
The first line contains $t$ ($1 \le t \le 100$) β the number of test cases.
Each test case contains two integers $A$ and $B$ $(1 \le A, B \le 10^9)$.
-----Output-----
Print one integer β the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true.
-----Example-----
Input
3
1 11
4 2
191 31415926
Output
1
0
1337
-----Note-----
There is only one suitable pair in the first test case: $a = 1$, $b = 9$ ($1 + 9 + 1 \cdot 9 = 19$).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \\{a,b,c,b,d,a,b\\}$ and $Y = \\{b,d,c,a,b,a\\}$, the sequence $\\{b,c,a\\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\\{b,c,a\\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\\{b,c,b,a\\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\\{b,c,b,a\\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.
Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.
Constraints
* $1 \leq q \leq 150$
* $1 \leq$ length of $X$ and $Y$ $\leq 1,000$
* $q \leq 20$ if the dataset includes a sequence whose length is more than 100
Input
The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.
Output
For each dataset, print the length of LCS of $X$ and $Y$ in a line.
Example
Input
3
abcbdab
bdcaba
abc
abc
abc
bc
Output
4
3
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `Ο(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k β€ n` for which `gcd(n, k) = 1`.
The totient function is important in number theory, mainly because it gives the order of the multiplicative group of integers modulo `n`. The totient function also plays a key role in the definition of the RSA encryption system.
For example `let n = 9`.
Then `gcd(9, 3) = gcd(9, 6) = 3` and `gcd(9, 9) = 9`.
The other six numbers in the range `1 β€ k β€ 9` i.e. `1, 2, 4, 5, 7, 8` are relatively prime to `9`.
Therefore, `Ο(9) = 6`.
As another example, `Ο(1) = 1` since `gcd(1, 1) = 1`.
There are generally two approaches to this function:
* Iteratively counting the numbers `k β€ n` such that `gcd(n,k) = 1`.
* Using the Euler product formula.
This is an explicit formula for calculating `Ο(n)` depending on the prime divisor of `n`:
`Ο(n) = n * Product (1 - 1/p)` where the product is taken over the primes `p β€ n` that divide `n`.
For example: `Ο(36) = 36 * (1 - 1/2) * (1 - 1/3) = 36 * 1/2 * 2/3 = 12`.
This second method seems more complex and not likely to be faster, but in practice we will often look for `Ο(n)` with `n` prime. It correctly gives `Ο(n) = n - 1` if `n` is prime.
You have to code the Euler totient function, that takes an integer `1 β€ n` as input and returns `Ο(n)`.
```if:javascript
You do have to check if `n` is a number, is an integer and that `1 β€ n`; if that is not the case, the function should return `0`.
```
```if:python
You do have to check if `n` is a number, is an integer and that `1 β€ n`; if that is not the case, the function should return `0`.
```
```if:racket
`n` is always a positive integer.
```
Input range: `1 β€ n β€ 1e10`
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Suppose I have two vectors: `(a1, a2, a3, ..., aN)` and `(b1, b2, b3, ..., bN)`. The dot product between these two vectors is defined as:
```
a1*b1 + a2*b2 + a3*b3 + ... + aN*bN
```
The vectors are classified as orthogonal if the dot product equals zero.
Complete the function that accepts two sequences as inputs and returns `true` if the vectors are orthogonal, and `false` if they are not. The sequences will always be correctly formatted and of the same length, so there is no need to check them first.
## Examples
```
[1, 1, 1], [2, 5, 7] --> false
[1, 0, 0, 1], [0, 1, 1, 0] --> true
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers from 1 to n was encountered in his array exactly once). If there are multiple ways to do it he wants to find the lexicographically minimal permutation among them.
Thus minimizing the number of changes has the first priority, lexicographical minimizing has the second priority.
In order to determine which of the two permutations is lexicographically smaller, we compare their first elements. If they are equal β compare the second, and so on. If we have two permutations x and y, then x is lexicographically smaller if x_{i} < y_{i}, where i is the first index in which the permutations x and y differ.
Determine the array Ivan will obtain after performing all the changes.
-----Input-----
The first line contains an single integer n (2 β€ n β€ 200 000) β the number of elements in Ivan's array.
The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ n) β the description of Ivan's array.
-----Output-----
In the first line print q β the minimum number of elements that need to be changed in Ivan's array in order to make his array a permutation. In the second line, print the lexicographically minimal permutation which can be obtained from array with q changes.
-----Examples-----
Input
4
3 2 2 3
Output
2
1 2 4 3
Input
6
4 5 6 3 2 1
Output
0
4 5 6 3 2 1
Input
10
6 8 4 6 7 1 6 3 4 5
Output
3
2 8 4 6 7 1 9 3 10 5
-----Note-----
In the first example Ivan needs to replace number three in position 1 with number one, and number two in position 3 with number four. Then he will get a permutation [1, 2, 4, 3] with only two changed numbers β this permutation is lexicographically minimal among all suitable.
In the second example Ivan does not need to change anything because his array already is a permutation.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
For a given array $a$ consisting of $n$ integers and a given integer $m$ find if it is possible to reorder elements of the array $a$ in such a way that $\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$ equals $m$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $\frac{5}{2}=2.5$.
-----Input-----
The first line contains a single integer $t$Β β the number of test cases ($1 \le t \le 100$). The test cases follow, each in two lines.
The first line of a test case contains two integers $n$ and $m$ ($1 \le n \le 100$, $0 \le m \le 10^6$). The second line contains integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^6$)Β β the elements of the array.
-----Output-----
For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.
-----Example-----
Input
2
3 8
2 5 1
4 4
0 1 2 3
Output
YES
NO
-----Note-----
In the first test case one of the reorders could be $[1, 2, 5]$. The sum is equal to $(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$. The brackets denote the inner sum $\sum_{j=i}^{n}{\frac{a_j}{j}}$, while the summation of brackets corresponds to the sum over $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.
Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either
* contains no nodes, or
* is composed of three disjoint sets of nodes:
- a root node.
- a binary tree called its left subtree.
- a binary tree called its right subtree.
Your task is to write a program which perform tree walks (systematically traverse all nodes in a tree) based on the following algorithms:
1. Print the root, the left subtree and right subtree (preorder).
2. Print the left subtree, the root and right subtree (inorder).
3. Print the left subtree, right subtree and the root (postorder).
Here, the given binary tree consists of n nodes and evey node has a unique ID from 0 to n-1.
Constraints
* 1 β€ n β€ 25
Input
The first line of the input includes an integer n, the number of nodes of the tree.
In the next n linen, the information of each node is given in the following format:
id left right
id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1
Output
In the 1st line, print "Preorder", and in the 2nd line print a list of node IDs obtained by the preorder tree walk.
In the 3rd line, print "Inorder", and in the 4th line print a list of node IDs obtained by the inorder tree walk.
In the 5th line, print "Postorder", and in the 6th line print a list of node IDs obtained by the postorder tree walk.
Print a space character before each node ID.
Example
Input
9
0 1 4
1 2 3
2 -1 -1
3 -1 -1
4 5 8
5 6 7
6 -1 -1
7 -1 -1
8 -1 -1
Output
Preorder
0 1 2 3 4 5 6 7 8
Inorder
2 1 3 0 6 5 7 4 8
Postorder
2 3 1 6 7 5 8 4 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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.