question
large_stringlengths 265
13.2k
|
|---|
Solve the programming task below in a Python markdown code block.
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part.
[Image]
After making a paper ship from the square piece, Vasya looked on the remaining (a - b) mm × b mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.
Can you determine how many ships Vasya will make during the lesson?
-----Input-----
The first line of the input contains two integers a, b (1 ≤ b < a ≤ 10^12) — the sizes of the original sheet of paper.
-----Output-----
Print a single integer — the number of ships that Vasya will make.
-----Examples-----
Input
2 1
Output
2
Input
10 7
Output
6
Input
1000000000000 1
Output
1000000000000
-----Note-----
Pictures to the first and second sample test.
[Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.
The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 2^30.
-----Output-----
Print a single integer — the required maximal xor of a segment of consecutive elements.
-----Examples-----
Input
5
1 2 1 1 2
Output
3
Input
3
1 2 7
Output
7
Input
4
4 2 4 8
Output
14
-----Note-----
In the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.
The second sample contains only one optimal segment, which contains exactly one array element (element with index three).
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Consider the array `[3,6,9,12]`. If we generate all the combinations with repetition that sum to `12`, we get `5` combinations: `[12], [6,6], [3,9], [3,3,6], [3,3,3,3]`. The length of the sub-arrays (such as `[3,3,3,3]` should be less than or equal to the length of the initial array (`[3,6,9,12]`).
Given an array of positive integers and a number `n`, count all combinations with repetition of integers that sum to `n`. For example:
```Haskell
find([3,6,9,12],12) = 5.
```
More examples in the test cases.
Good luck!
If you like this Kata, please try:
[Array combinations](https://www.codewars.com/kata/59e66e48fc3c499ec5000103)
[Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b)
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
-----Output-----
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
-----Examples-----
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
-----Note-----
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 is the leader of the State Refactoring Party, and she is about to become the prime minister.
The elections have just taken place. There are $n$ parties, numbered from $1$ to $n$. The $i$-th party has received $a_i$ seats in the parliament.
Alice's party has number $1$. In order to become the prime minister, she needs to build a coalition, consisting of her party and possibly some other parties. There are two conditions she needs to fulfil: The total number of seats of all parties in the coalition must be a strict majority of all the seats, i.e. it must have strictly more than half of the seats. For example, if the parliament has $200$ (or $201$) seats, then the majority is $101$ or more seats. Alice's party must have at least $2$ times more seats than any other party in the coalition. For example, to invite a party with $50$ seats, Alice's party must have at least $100$ seats.
For example, if $n=4$ and $a=[51, 25, 99, 25]$ (note that Alice'a party has $51$ seats), then the following set $[a_1=51, a_2=25, a_4=25]$ can create a coalition since both conditions will be satisfied. However, the following sets will not create a coalition:
$[a_2=25, a_3=99, a_4=25]$ since Alice's party is not there; $[a_1=51, a_2=25]$ since coalition should have a strict majority; $[a_1=51, a_2=25, a_3=99]$ since Alice's party should have at least $2$ times more seats than any other party in the coalition.
Alice does not have to minimise the number of parties in a coalition. If she wants, she can invite as many parties as she wants (as long as the conditions are satisfied). If Alice's party has enough people to create a coalition on her own, she can invite no parties.
Note that Alice can either invite a party as a whole or not at all. It is not possible to invite only some of the deputies (seats) from another party. In other words, if Alice invites a party, she invites all its deputies.
Find and print any suitable coalition.
-----Input-----
The first line contains a single integer $n$ ($2 \leq n \leq 100$) — the number of parties.
The second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq 100$) — the number of seats the $i$-th party has.
-----Output-----
If no coalition satisfying both conditions is possible, output a single line with an integer $0$.
Otherwise, suppose there are $k$ ($1 \leq k \leq n$) parties in the coalition (Alice does not have to minimise the number of parties in a coalition), and their indices are $c_1, c_2, \dots, c_k$ ($1 \leq c_i \leq n$). Output two lines, first containing the integer $k$, and the second the space-separated indices $c_1, c_2, \dots, c_k$.
You may print the parties in any order. Alice's party (number $1$) must be on that list. If there are multiple solutions, you may print any of them.
-----Examples-----
Input
3
100 50 50
Output
2
1 2
Input
3
80 60 60
Output
0
Input
2
6 5
Output
1
1
Input
4
51 25 99 25
Output
3
1 2 4
-----Note-----
In the first example, Alice picks the second party. Note that she can also pick the third party or both of them. However, she cannot become prime minister without any of them, because $100$ is not a strict majority out of $200$.
In the second example, there is no way of building a majority, as both other parties are too large to become a coalition partner.
In the third example, Alice already has the majority.
The fourth example is described in the problem statement.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:$f(p) = \sum_{i = 1}^{n} \sum_{j = i}^{n} \operatorname{min}(p_{i}, p_{i + 1}, \ldots p_{j})$
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
-----Input-----
The single line of input contains two integers n and m (1 ≤ m ≤ cnt_{n}), where cnt_{n} is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold. In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
-----Output-----
Output n number forming the required permutation.
-----Examples-----
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
-----Note-----
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
**Introduction**
Little Petya very much likes sequences. However, recently he received a sequence as a gift from his mother.
Petya didn't like it at all! He decided to make a single replacement. After this replacement, Petya would like to the sequence in increasing order.
He asks himself: What is the lowest possible value I could have got after making the replacement and sorting the sequence?
**About the replacement**
Choose exactly one element from the sequence and replace it with another integer > 0. You are **not allowed** to replace a number with itself, or to change no number at all.
**Task**
Find the lowest possible sequence after performing a valid replacement, and sorting the sequence.
**Input:**
Input contains sequence with `N` integers. All elements of the sequence > 0. The sequence will never be empty.
**Output:**
Return sequence with `N` integers — which includes the lowest possible values of each sequence element, after the single replacement and sorting has been performed.
**Examples**:
```
([1,2,3,4,5]) => [1,1,2,3,4]
([4,2,1,3,5]) => [1,1,2,3,4]
([2,3,4,5,6]) => [1,2,3,4,5]
([2,2,2]) => [1,2,2]
([42]) => [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.
Playing with Stones
Koshiro and Ukiko are playing a game with black and white stones. The rules of the game are as follows:
1. Before starting the game, they define some small areas and place "one or more black stones and one or more white stones" in each of the areas.
2. Koshiro and Ukiko alternately select an area and perform one of the following operations.
(a) Remove a white stone from the area
(b) Remove one or more black stones from the area. Note, however, that the number of the black stones must be less than or equal to white ones in the area.
(c) Pick up a white stone from the stone pod and replace it with a black stone. There are plenty of white stones in the pod so that there will be no shortage during the game.
3. If either Koshiro or Ukiko cannot perform 2 anymore, he/she loses.
They played the game several times, with Koshiro’s first move and Ukiko’s second move, and felt the winner was determined at the onset of the game. So, they tried to calculate the winner assuming both players take optimum actions.
Given the initial allocation of black and white stones in each area, make a program to determine which will win assuming both players take optimum actions.
Input
The input is given in the following format.
$N$
$w_1$ $b_1$
$w_2$ $b_2$
:
$w_N$ $b_N$
The first line provides the number of areas $N$ ($1 \leq N \leq 10000$). Each of the subsequent $N$ lines provides the number of white stones $w_i$ and black stones $b_i$ ($1 \leq w_i, b_i \leq 100$) in the $i$-th area.
Output
Output 0 if Koshiro wins and 1 if Ukiko wins.
Examples
Input
4
24 99
15 68
12 90
95 79
Output
0
Input
3
2 46
94 8
46 57
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.
A text editor is a useful software tool that can help people in various situations including writing and programming. Your job in this problem is to construct an offline text editor, i.e., to write a program that first reads a given text and a sequence of editing commands and finally reports the text obtained by performing successively the commands in the given sequence.
The editor has a text buffer and a cursor. The target text is stored in the text buffer and most editing commands are performed around the cursor. The cursor has its position that is either the beginning of the text, the end of the text, or between two consecutive characters in the text. The initial cursor position (i.e., the cursor position just after reading the initial text) is the beginning of the text.
A text manipulated by the editor is a single line consisting of a sequence of characters, each of which must be one of the following: 'a' through 'z', 'A' through 'Z', '0' through '9', '.' (period), ',' (comma), and ' ' (blank). You can assume that any other characters never occur in the text buffer. You can also assume that the target text consists of at most 1,000 characters at any time. The definition of words in this problem is a little strange: a word is a non-empty character sequence delimited by not only blank characters but also the cursor. For instance, in the following text with a cursor represented as '^',
He^llo, World.
the words are the following.
He
llo,
World.
Notice that punctuation characters may appear in words as shown in this example.
The editor accepts the following set of commands. In the command list, "any-text" represents any text surrounded by a pair of double quotation marks such as "abc" and "Co., Ltd.".
Command |
Descriptions
---|---
forward char |
Move the cursor by one character to the right, unless the cursor is already at the end of the text.
forward word |
Move the cursor to the end of the leftmost word in the right. If no words occur in the right, move it to the end of the text.
backward char |
Move the cursor by one character to the left, unless the cursor is already at the beginning of the text.
backward word |
Move the cursor to the beginning of the rightmost word in the left. If no words occur in the left, move it to the beginning of the text.
insert "any-text" |
Insert any-text (excluding double quotation marks) at the position specified by the cursor. After performing this command, the new cursor position is at the end of the inserted text. The length of any-text is less than or equal to 100.
delete char |
Delete the character that is right next to the cursor, if it exists.
delete word |
Delete the leftmost word in the right of the cursor. If one or more blank characters occur between the cursor and the word before performing this command, delete these blanks, too. If no words occur in the right, delete no characters in the text buffer.
Input
The first input line contains a positive integer, which represents the number of texts the editor will edit. For each text, the input contains the following descriptions:
* The first line is an initial text whose length is at most 100.
* The second line contains an integer M representing the number of editing commands.
* Each of the third through the M+2nd lines contains an editing command.
You can assume that every input line is in a proper format or has no syntax errors. You can also assume that every input line has no leading or trailing spaces and that just a single blank character occurs between a command name (e.g., forward) and its argument (e.g., char).
Output
For each input text, print the final text with a character '^' representing the cursor position. Each output line shall contain exactly a single text with a character '^'.
Examples
Input
Output
Input
3
A sample input
9
forward word
delete char
forward word
delete char
forward word
delete char
backward word
backward word
forward word
Hallow, Word.
7
forward char
delete word
insert "ello, "
forward word
backward char
backward char
insert "l"
3
forward word
backward word
delete word
Output
Asampleinput^
Hello, Worl^d.
^
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?
Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.
Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.
-----Input-----
The first line contains two integers n and m (1 ≤ n ≤ m ≤ 1000) — the length of the string s and the length of the string t correspondingly.
The second line contains n lowercase English letters — string s.
The third line contains m lowercase English letters — string t.
-----Output-----
In the first line print single integer k — the minimal number of symbols that need to be replaced.
In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.
-----Examples-----
Input
3 5
abc
xaybz
Output
2
2 3
Input
4 10
abcd
ebceabazcd
Output
1
2
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Polycarp likes squares and cubes of positive integers. Here is the beginning of the sequence of numbers he likes: $1$, $4$, $8$, $9$, ....
For a given number $n$, count the number of integers from $1$ to $n$ that Polycarp likes. In other words, find the number of such $x$ that $x$ is a square of a positive integer number or a cube of a positive integer number (or both a square and a cube simultaneously).
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 20$) — the number of test cases.
Then $t$ lines contain the test cases, one per line. Each of the lines contains one integer $n$ ($1 \le n \le 10^9$).
-----Output-----
For each test case, print the answer you are looking for — the number of integers from $1$ to $n$ that Polycarp likes.
-----Examples-----
Input
6
10
1
25
1000000000
999999999
500000000
Output
4
1
6
32591
32590
23125
-----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.
You are given two arrays `arr1` and `arr2`, where `arr2` always contains integers.
Write the function `find_array(arr1, arr2)` such that:
For `arr1 = ['a', 'a', 'a', 'a', 'a']`, `arr2 = [2, 4]`
`find_array returns ['a', 'a']`
For `arr1 = [0, 1, 5, 2, 1, 8, 9, 1, 5]`, `arr2 = [1, 4, 7]`
`find_array returns [1, 1, 1]`
For `arr1 = [0, 3, 4]`, `arr2 = [2, 6]`
`find_array returns [4]`
For `arr1=["a","b","c","d"]` , `arr2=[2,2,2]`,
`find_array returns ["c","c","c"]`
For `arr1=["a","b","c","d"]`, `arr2=[3,0,2]`
`find_array returns ["d","a","c"]`
If either `arr1` or `arr2` is empty, you should return an empty arr (empty list in python,
empty vector in c++). Note for c++ use std::vector arr1, arr2.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Mr. Chanek has an integer represented by a string $s$. Zero or more digits have been erased and are denoted by the character _. There are also zero or more digits marked by the character X, meaning they're the same digit.
Mr. Chanek wants to count the number of possible integer $s$, where $s$ is divisible by $25$. Of course, $s$ must not contain any leading zero. He can replace the character _ with any digit. He can also replace the character X with any digit, but it must be the same for every character X.
As a note, a leading zero is any 0 digit that comes before the first nonzero digit in a number string in positional notation. For example, 0025 has two leading zeroes. An exception is the integer zero, (0 has no leading zero, but 0000 has three leading zeroes).
-----Input-----
One line containing the string $s$ ($1 \leq |s| \leq 8$). The string $s$ consists of the characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, _, and X.
-----Output-----
Output an integer denoting the number of possible integer $s$.
-----Examples-----
Input
25
Output
1
Input
_00
Output
9
Input
_XX
Output
9
Input
0
Output
1
Input
0_25
Output
0
-----Note-----
In the first example, the only possible $s$ is $25$.
In the second and third example, $s \in \{100, 200,300,400,500,600,700,800,900\}$.
In the fifth example, all possible $s$ will have at least one leading zero.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Princess Rupsa saw one of her friends playing a special game. The game goes as follows:
N+1 numbers occur sequentially (one at a time) from A_{0} to A_{N}.
You must write the numbers on a sheet of paper, such that A_{0} is written first. The other numbers are written according to an inductive rule — after A_{i-1} numbers have been written in a row, then A_{i} can be written at either end of the row. That is, you first write A_{0}, and then A_{1} can be written on its left or right to make A_{0}A_{1} or A_{1}A_{0}, and so on.
A_{i} must be written before writing A_{j}, for every i < j.
For a move in which you write a number A_{i} (i>0), your points increase by the product of A_{i} and its neighbour. (Note that for any move it will have only one neighbour as you write the number at an end).
Total score of a game is the score you attain after placing all the N + 1 numbers.
Princess Rupsa wants to find out the sum of scores obtained by all possible different gameplays. Two gameplays are different, if after writing down all N + 1 numbers, when we read from left to right, there exists some position i, at which the gameplays have a_{j} and a_{k} written at the i^{th} position such that j ≠ k. But since she has recently found her true love, a frog Prince, and is in a hurry to meet him, you must help her solve the problem as fast as possible. Since the answer can be very large, print the answer modulo 10^{9} + 7.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains a single integer N.
The second line contains N + 1 space-separated integers denoting A_{0} to A_{N}.
------ Output ------
For each test case, output a single line containing an integer denoting the answer.
------ Constraints ------
1 ≤ T ≤ 10
1 ≤ N ≤ 10^{5}
1 ≤ A_{i} ≤ 10^{9}
------ Sub tasks ------
Subtask #1: 1 ≤ N ≤ 10 (10 points)
Subtask #2: 1 ≤ N ≤ 1000 (20 points)
Subtask #3: Original Constraints (70 points)
----- Sample Input 1 ------
2
1
1 2
2
1 2 1
----- Sample Output 1 ------
4
14
----- explanation 1 ------
There are 2 possible gameplays. A0A1 which gives score of 2 and A1A0 which also gives score of 2. So the answer is 2 + 2 = 4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Aizu Gakuen High School holds a school festival every year. The most popular of these is the haunted house. The most popular reason is that 9 classes do haunted houses instead of 1 or 2 classes. Each one has its own unique haunted house. Therefore, many visitors come from the neighborhood these days.
Therefore, the school festival executive committee decided to unify the admission fee for the haunted house in the school as shown in the table below, and based on this, total the total number of visitors and income for each class.
Admission fee list (admission fee per visitor)
Morning Afternoon
200 yen 300 yen
Enter the number of visitors in the morning and afternoon for each class, and create a program that creates a list of the total number of visitors and income for each class.
Input
The input is given in the following format:
name1 a1 b1
name2 a2 b2
::
name9 a9 b9
The input consists of 9 lines, the class name of the i-th class on the i-line namei (a half-width character string of 1 to 15 characters including numbers and alphabets), the number of visitors in the morning ai (0 ≤ ai ≤ 400) , Afternoon attendance bi (0 ≤ bi ≤ 400) is given.
Output
On the i-line, output the class name of the i-class, the total number of visitors, and the fee income on one line separated by blanks.
Example
Input
1a 132 243
1c 324 183
1f 93 199
2b 372 163
2c 229 293
2e 391 206
3a 118 168
3b 263 293
3d 281 102
Output
1a 375 99300
1c 507 119700
1f 292 78300
2b 535 123300
2c 522 133700
2e 597 140000
3a 286 74000
3b 556 140500
3d 383 86800
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 statement
When you heard that this year's KUPC can be joined as a team, you decided to talk to your friends and join as a team.
Eventually, $ 4 $ people, including you, got together.
Individual strength is expressed in ratings, and $ 4 $ person ratings are $ a $, $ b $, $ c $, and $ d $, respectively.
You decided to split into $ 2 $ teams of $ 2 $ people each.
At this time, the strength of the team is defined by the sum of the ratings of the $ 2 $ people who make up the team. In addition, the difference in ability between teams is defined by the absolute value of the difference in strength of each team.
You want to divide the teams so that the difference in ability between the teams is as small as possible.
Find the minimum value of the difference in ability between teams when the teams are divided successfully.
Constraint
* $ 1 \ leq a, b, c, d \ leq 2799 $
* All inputs are integers
* * *
input
Input is given from standard input in the following format.
$ a $ $ b $ $ c $ $ d $
output
Output the minimum difference in ability between teams in an integer $ 1 $ line.
* * *
Input example 1
2 1 3 4
Output example 1
0
If you team up with the $ 1 $ and $ 3 $ people, and the $ 2 $ and $ 4 $ people, the strength of the team will be $ 5 $ and the difference in ability will be $ 0 $. Obviously this is the smallest.
* * *
Input example 2
64 224 239 1024
Output example 2
625
Example
Input
2 1 3 4
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.
Petya is preparing for his birthday. He decided that there would be $n$ different dishes on the dinner table, numbered from $1$ to $n$. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.
Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from $n$ different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it: the dish will be delivered by a courier from the restaurant $i$, in this case the courier will arrive in $a_i$ minutes, Petya goes to the restaurant $i$ on his own and picks up the dish, he will spend $b_i$ minutes on this.
Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.
For example, if Petya wants to order $n = 4$ dishes and $a = [3, 7, 4, 5]$, and $b = [2, 1, 2, 4]$, then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in $3$ minutes, the courier of the fourth restaurant will bring the order in $5$ minutes, and Petya will pick up the remaining dishes in $1 + 2 = 3$ minutes. Thus, in $5$ minutes all the dishes will be at Petya's house.
Find the minimum time after which all the dishes can be at Petya's home.
-----Input-----
The first line contains one positive integer $t$ ($1 \le t \le 2 \cdot 10^5$) — the number of test cases. Then $t$ test cases follow.
Each test case begins with a line containing one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of dishes that Petya wants to order.
The second line of each test case contains $n$ integers $a_1 \ldots a_n$ ($1 \le a_i \le 10^9$) — the time of courier delivery of the dish with the number $i$.
The third line of each test case contains $n$ integers $b_1 \ldots b_n$ ($1 \le b_i \le 10^9$) — the time during which Petya will pick up the dish with the number $i$.
The sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case output one integer — the minimum time after which all dishes can be at Petya's home.
-----Example-----
Input
4
4
3 7 4 5
2 1 2 4
4
1 2 3 4
3 3 3 3
2
1 2
10 10
2
10 10
1 2
Output
5
3
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.
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.
Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.
Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.
Input
The first line contains integer n (1 ≤ n ≤ 100 000) — the length of words S and T.
The second line contains word S.
The third line contains word T.
Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words.
Output
Print a single integer — the number of distinct words W that can be transformed to S and T due to a typo.
Examples
Input
7
reading
trading
Output
1
Input
5
sweet
sheep
Output
0
Input
3
toy
try
Output
2
Note
In the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).
In the second sample test the two given words couldn't be obtained from the same word by removing one letter.
In the third sample test the two given words could be obtained from either word "tory" or word "troy".
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $n$ days of summer. On the $i$-th day, $a_i$ millimeters of rain will fall. All values $a_i$ are distinct.
The mayor knows that citizens will watch the weather $x$ days before the celebration and $y$ days after. Because of that, he says that a day $d$ is not-so-rainy if $a_d$ is smaller than rain amounts at each of $x$ days before day $d$ and and each of $y$ days after day $d$. In other words, $a_d < a_j$ should hold for all $d - x \le j < d$ and $d < j \le d + y$. Citizens only watch the weather during summer, so we only consider such $j$ that $1 \le j \le n$.
Help mayor find the earliest not-so-rainy day of summer.
-----Input-----
The first line contains three integers $n$, $x$ and $y$ ($1 \le n \le 100\,000$, $0 \le x, y \le 7$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after.
The second line contains $n$ distinct integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 10^9$), where $a_i$ denotes the rain amount on the $i$-th day.
-----Output-----
Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.
-----Examples-----
Input
10 2 2
10 9 6 7 8 3 2 1 4 5
Output
3
Input
10 2 3
10 9 6 7 8 3 2 1 4 5
Output
8
Input
5 5 5
100000 10000 1000 100 10
Output
5
-----Note-----
In the first example days $3$ and $8$ are not-so-rainy. The $3$-rd day is earlier.
In the second example day $3$ is not not-so-rainy, because $3 + y = 6$ and $a_3 > a_6$. Thus, day $8$ is the answer. Note that $8 + y = 11$, but we don't consider day $11$, because it is not summer.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 ```x(n)``` that takes in a number ```n``` and returns an ```nxn``` array with an ```X``` in the middle. The ```X``` will be represented by ```1's``` and the rest will be ```0's```.
E.g.
```python
x(5) == [[1, 0, 0, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 0, 1]];
x(6) == [[1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 1, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 1]];
```
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where a_{i}, j = 1 if the i-th switch turns on the j-th lamp and a_{i}, j = 0 if the i-th switch is not connected to the j-th lamp.
Initially all m lamps are turned off.
Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.
It is guaranteed that if you push all n switches then all m lamps will be turned on.
Your think that you have too many switches and you would like to ignore one of them.
Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n - 1 switches then all the m lamps will be turned on.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000) — the number of the switches and the number of the lamps.
The following n lines contain m characters each. The character a_{i}, j is equal to '1' if the i-th switch turns on the j-th lamp and '0' otherwise.
It is guaranteed that if you press all n switches all m lamps will be turned on.
-----Output-----
Print "YES" if there is a switch that if you will ignore it and press all the other n - 1 switches then all m lamps will be turned on. Print "NO" if there is no such switch.
-----Examples-----
Input
4 5
10101
01000
00111
10000
Output
YES
Input
4 5
10100
01000
00110
00101
Output
NO
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points.
Each of the next n lines contains two integers (x_{i}, y_{i}) (0 ≤ x_{i}, y_{i} ≤ 10^9) — the coordinates of the i-th point.
-----Output-----
Print the only integer c — the number of parallelograms with the vertices at the given points.
-----Example-----
Input
4
0 1
1 0
1 1
2 0
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.
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.
Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter t_{ij} units of time.
Order is important everywhere, so the painters' work is ordered by the following rules: Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n); each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter.
Given that the painters start working at time 0, find for each picture the time when it is ready for sale.
-----Input-----
The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers t_{i}1, t_{i}2, ..., t_{in} (1 ≤ t_{ij} ≤ 1000), where t_{ij} is the time the j-th painter needs to work on the i-th picture.
-----Output-----
Print the sequence of m integers r_1, r_2, ..., r_{m}, where r_{i} is the moment when the n-th painter stopped working on the i-th picture.
-----Examples-----
Input
5 1
1
2
3
4
5
Output
1 3 6 10 15
Input
4 2
2 5
3 1
5 3
10 1
Output
7 8 13 21
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a simple weighted connected undirected graph, consisting of $n$ vertices and $m$ edges.
A path in the graph of length $k$ is a sequence of $k+1$ vertices $v_1, v_2, \dots, v_{k+1}$ such that for each $i$ $(1 \le i \le k)$ the edge $(v_i, v_{i+1})$ is present in the graph. A path from some vertex $v$ also has vertex $v_1=v$. Note that edges and vertices are allowed to be included in the path multiple times.
The weight of the path is the total weight of edges in it.
For each $i$ from $1$ to $q$ consider a path from vertex $1$ of length $i$ of the maximum weight. What is the sum of weights of these $q$ paths?
Answer can be quite large, so print it modulo $10^9+7$.
-----Input-----
The first line contains a three integers $n$, $m$, $q$ ($2 \le n \le 2000$; $n - 1 \le m \le 2000$; $m \le q \le 10^9$) — the number of vertices in the graph, the number of edges in the graph and the number of lengths that should be included in the answer.
Each of the next $m$ lines contains a description of an edge: three integers $v$, $u$, $w$ ($1 \le v, u \le n$; $1 \le w \le 10^6$) — two vertices $v$ and $u$ are connected by an undirected edge with weight $w$. The graph contains no loops and no multiple edges. It is guaranteed that the given edges form a connected graph.
-----Output-----
Print a single integer — the sum of the weights of the paths from vertex $1$ of maximum weights of lengths $1, 2, \dots, q$ modulo $10^9+7$.
-----Examples-----
Input
7 8 25
1 2 1
2 3 10
3 4 2
1 5 2
5 6 7
6 4 15
5 3 1
1 7 3
Output
4361
Input
2 1 5
1 2 4
Output
60
Input
15 15 23
13 10 12
11 14 12
2 15 5
4 10 8
10 2 4
10 7 5
3 10 1
5 6 11
1 13 8
9 15 4
4 2 9
11 15 1
11 12 14
10 8 12
3 6 11
Output
3250
Input
5 10 10000000
2 4 798
1 5 824
5 2 558
4 1 288
3 4 1890
3 1 134
2 3 1485
4 5 284
3 5 1025
1 2 649
Output
768500592
-----Note-----
Here is the graph for the first example: [Image]
Some maximum weight paths are: length $1$: edges $(1, 7)$ — weight $3$; length $2$: edges $(1, 2), (2, 3)$ — weight $1+10=11$; length $3$: edges $(1, 5), (5, 6), (6, 4)$ — weight $2+7+15=24$; length $4$: edges $(1, 5), (5, 6), (6, 4), (6, 4)$ — weight $2+7+15+15=39$; $\dots$
So the answer is the sum of $25$ terms: $3+11+24+39+\dots$
In the second example the maximum weight paths have weights $4$, $8$, $12$, $16$ and $20$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The following problem is well-known: given integers n and m, calculate $2^{n} \operatorname{mod} m$,
where 2^{n} = 2·2·...·2 (n factors), and $x \operatorname{mod} y$ denotes the remainder of division of x by y.
You are asked to solve the "reverse" problem. Given integers n and m, calculate $m \operatorname{mod} 2^{n}$.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^8).
The second line contains a single integer m (1 ≤ m ≤ 10^8).
-----Output-----
Output a single integer — the value of $m \operatorname{mod} 2^{n}$.
-----Examples-----
Input
4
42
Output
10
Input
1
58
Output
0
Input
98765432
23456789
Output
23456789
-----Note-----
In the first example, the remainder of division of 42 by 2^4 = 16 is equal to 10.
In the second example, 58 is divisible by 2^1 = 2 without remainder, and 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.
The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.
R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.
The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.
-----Input-----
The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 2·10^4; 1 ≤ m ≤ 10; 1 ≤ k ≤ 2·10^5) — the number of the employees, the number of chats and the number of events in the log, correspondingly.
Next n lines contain matrix a of size n × m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as a_{ij}) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m.
Next k lines contain the description of the log events. The i-th line contains two space-separated integers x_{i} and y_{i} (1 ≤ x_{i} ≤ n; 1 ≤ y_{i} ≤ m) which mean that the employee number x_{i} sent one message to chat number y_{i}. It is guaranteed that employee number x_{i} is a participant of chat y_{i}. It is guaranteed that each chat contains at least two employees.
-----Output-----
Print in the single line n space-separated integers, where the i-th integer shows the number of message notifications the i-th employee receives.
-----Examples-----
Input
3 4 5
1 1 1 1
1 0 1 1
1 1 0 0
1 1
3 1
1 3
2 4
3 2
Output
3 3 1
Input
4 3 4
0 1 1
1 0 1
1 1 1
0 0 0
1 2
2 1
3 1
1 3
Output
0 2 3 0
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The Little Elephant loves to play with color cards.
He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).
Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card.
The numbers in the lines are separated by single spaces.
Output
On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.
Examples
Input
3
4 7
4 7
7 4
Output
0
Input
5
4 7
7 4
2 11
9 7
1 1
Output
2
Note
In the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.
In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 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.
There is a vampire family of N members. Vampires are also known as extreme gourmets. Of course vampires' foods are human blood. However, not all kinds of blood is acceptable for them. Vampires drink blood that K blood types of ones are mixed, and each vampire has his/her favorite amount for each blood type.
You, cook of the family, are looking inside a fridge to prepare dinner. Your first task is to write a program that judges if all family members' dinner can be prepared using blood in the fridge.
Constraints
* Judge data includes at most 100 data sets.
* 1 ≤ N ≤ 100
* 1 ≤ K ≤ 100
* 0 ≤ Si ≤ 100000
* 0 ≤ Bij ≤ 1000
Input
Input file consists of a number of data sets. One data set is given in following format:
N K
S1 S2 ... SK
B11 B12 ... B1K
B21 B22 ... B2K
:
BN1 BN2 ... BNK
N and K indicate the number of family members and the number of blood types respectively.
Si is an integer that indicates the amount of blood of the i-th blood type that is in a fridge.
Bij is an integer that indicates the amount of blood of the j-th blood type that the i-th vampire uses.
The end of input is indicated by a case where N = K = 0. You should print nothing for this data set.
Output
For each set, print "Yes" if everyone's dinner can be prepared using blood in a fridge, "No" otherwise (without quotes).
Example
Input
2 3
5 4 5
1 2 3
3 2 1
3 5
1 2 3 4 5
0 1 0 1 2
0 1 1 2 2
1 0 3 1 1
0 0
Output
Yes
No
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR.
Find the maximum possible value of <image> after performing at most k operations optimally.
Input
The first line contains three integers n, k and x (1 ≤ n ≤ 200 000, 1 ≤ k ≤ 10, 2 ≤ x ≤ 8).
The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).
Output
Output the maximum value of a bitwise OR of sequence elements after performing operations.
Examples
Input
3 1 2
1 1 1
Output
3
Input
4 2 3
1 2 4 8
Output
79
Note
For the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is <image>.
For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Long time ago there was a symmetric array $a_1,a_2,\ldots,a_{2n}$ consisting of $2n$ distinct integers. Array $a_1,a_2,\ldots,a_{2n}$ is called symmetric if for each integer $1 \le i \le 2n$, there exists an integer $1 \le j \le 2n$ such that $a_i = -a_j$.
For each integer $1 \le i \le 2n$, Nezzar wrote down an integer $d_i$ equal to the sum of absolute differences from $a_i$ to all integers in $a$, i. e. $d_i = \sum_{j = 1}^{2n} {|a_i - a_j|}$.
Now a million years has passed and Nezzar can barely remember the array $d$ and totally forget $a$. Nezzar wonders if there exists any symmetric array $a$ consisting of $2n$ distinct integers that generates the array $d$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$).
The second line of each test case contains $2n$ integers $d_1, d_2, \ldots, d_{2n}$ ($0 \le d_i \le 10^{12}$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case, print "YES" in a single line if there exists a possible array $a$. Otherwise, print "NO".
You can print letters in any case (upper or lower).
-----Examples-----
Input
6
2
8 12 8 12
2
7 7 9 11
2
7 11 7 11
1
1 1
4
40 56 48 40 80 56 80 48
6
240 154 210 162 174 154 186 240 174 186 162 210
Output
YES
NO
NO
NO
NO
YES
-----Note-----
In the first test case, $a=[1,-3,-1,3]$ is one possible symmetric array that generates the array $d=[8,12,8,12]$.
In the second test case, it can be shown that there is no symmetric array consisting of distinct integers that can generate array $d$.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 consisting of $n$ integers $a_1, a_2, \dots , a_n$ and an integer $x$. It is guaranteed that for every $i$, $1 \le a_i \le x$.
Let's denote a function $f(l, r)$ which erases all values such that $l \le a_i \le r$ from the array $a$ and returns the resulting array. For example, if $a = [4, 1, 1, 4, 5, 2, 4, 3]$, then $f(2, 4) = [1, 1, 5]$.
Your task is to calculate the number of pairs $(l, r)$ such that $1 \le l \le r \le x$ and $f(l, r)$ is sorted in non-descending order. Note that the empty array is also considered sorted.
-----Input-----
The first line contains two integers $n$ and $x$ ($1 \le n, x \le 10^6$) — the length of array $a$ and the upper limit for its elements, respectively.
The second line contains $n$ integers $a_1, a_2, \dots a_n$ ($1 \le a_i \le x$).
-----Output-----
Print the number of pairs $1 \le l \le r \le x$ such that $f(l, r)$ is sorted in non-descending order.
-----Examples-----
Input
3 3
2 3 1
Output
4
Input
7 4
1 3 1 2 2 4 3
Output
6
-----Note-----
In the first test case correct pairs are $(1, 1)$, $(1, 2)$, $(1, 3)$ and $(2, 3)$.
In the second test case correct pairs are $(1, 3)$, $(1, 4)$, $(2, 3)$, $(2, 4)$, $(3, 3)$ and $(3, 4)$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The princess is going to escape the dragon's cave, and she needs to plan it carefully.
The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess noticed that the dragon is very greedy and not too smart. To delay him, the princess decides to borrow a couple of bijous from his treasury. Once the dragon overtakes the princess, she will drop one bijou to distract him. In this case he will stop, pick up the item, return to the cave and spend f hours to straighten the things out in the treasury. Only after this will he resume the chase again from the very beginning.
The princess is going to run on the straight. The distance between the cave and the king's castle she's aiming for is c miles. How many bijous will she need to take from the treasury to be able to reach the castle? If the dragon overtakes the princess at exactly the same moment she has reached the castle, we assume that she reached the castle before the dragon reached her, and doesn't need an extra bijou to hold him off.
Input
The input data contains integers vp, vd, t, f and c, one per line (1 ≤ vp, vd ≤ 100, 1 ≤ t, f ≤ 10, 1 ≤ c ≤ 1000).
Output
Output the minimal number of bijous required for the escape to succeed.
Examples
Input
1
2
1
1
10
Output
2
Input
1
2
1
1
8
Output
1
Note
In the first case one hour after the escape the dragon will discover it, and the princess will be 1 mile away from the cave. In two hours the dragon will overtake the princess 2 miles away from the cave, and she will need to drop the first bijou. Return to the cave and fixing the treasury will take the dragon two more hours; meanwhile the princess will be 4 miles away from the cave. Next time the dragon will overtake the princess 8 miles away from the cave, and she will need the second bijou, but after this she will reach the castle without any further trouble.
The second case is similar to the first one, but the second time the dragon overtakes the princess when she has reached the castle, and she won't need the second bijou.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 takes one or more arrays and returns a new array of unique values in the order of the original provided arrays.
In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
Check the assertion tests for examples.
*Courtesy of [FreeCodeCamp](https://www.freecodecamp.com/challenges/sorted-union), a great place to learn web-dev; plus, its founder Quincy Larson is pretty cool and amicable. I made the original one slightly more tricky ;)*
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Devu is a class teacher of a class of n students. One day, in the morning prayer of the school, all the students of his class were standing in a line. You are given information of their arrangement by a string s. The string s consists of only letters 'B' and 'G', where 'B' represents a boy and 'G' represents a girl.
Devu wants inter-gender interaction among his class should to be maximum. So he does not like seeing two or more boys/girls standing nearby (i.e. continuous) in the line. e.g. he does not like the arrangements BBG and GBB, but he likes BG, GBG etc.
Now by seeing the initial arrangement s of students, Devu may get furious and now he wants to change this arrangement into a likable arrangement. For achieving that, he can swap positions of any two students (not necessary continuous). Let the cost of swapping people from position i with position j (i ≠ j) be c(i, j). You are provided an integer variable type, then the cost of the the swap will be defined by c(i, j) = |j − i|type.
Please help Devu in finding minimum cost of swaps needed to convert the current arrangement into a likable one.
-----Input-----
The first line of input contains an integer T, denoting the number of test cases. Then T test cases are follow.
The first line of each test case contains an integer type, denoting the type of the cost function. Then the next line contains string s of length n, denoting the initial arrangement s of students.
Note that the integer n is not given explicitly in input.
-----Output-----
For each test case, print a single line containing the answer of the test case, that is, the minimum cost to convert the current arrangement into a likable one. If it is not possible to convert the current arrangement into a likable one, then print -1 instead of the minimum cost.
-----Constraints and Subtasks-----Subtask 1: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 0
- Sum of n over all the test cases in one test file does not exceed 106.
Subtask 2: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 1
- Sum of n over all the test cases in one test file does not exceed 106.
Subtask 3: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 2
- Sum of n over all the test cases in one test file does not exceed 106.
Subtask 4: 25 points
- 1 ≤ T ≤ 102
- 1 ≤ n ≤ 103
- type can be 0, 1 or 2, that is type ∈ {0, 1, 2}.
-----Example-----
Input:
8
0
BB
0
BG
0
BBGG
1
BGG
1
BGGB
1
BBBGG
2
BBGG
2
BGB
Output:
-1
0
1
1
1
3
1
0
-----Explanation-----
Note type of the first 3 test cases is 0. So c(i, j) = 1. Hence we just have to count minimum number of swaps needed.
Example case 1. There is no way to make sure that both the boys does not stand nearby. So answer is -1.
Example case 2. Arrangement is already valid. No swap is needed. So answer is 0.
Example case 3. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is 1.
Now type of the next 3 test cases is 1. So c(i, j) = |j − i|, that is, the absolute value of the difference between i and j.
Example case 4. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBG which is a valid arrangement. So answer is |1 - 0| = 1.
Example case 5. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBGB which is a valid arrangement. So answer is |1 - 0| = 1.
Example case 6. Swap boy at position 1 with girl at position 4. After swap the arrangement will be BGBGB which is a valid arrangement. So answer is |4 - 1| = 3.
Then type of the last 2 test cases is 2. So c(i, j) = (j − i)2
Example case 7. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is (2 - 1)2 = 1.
Example case 8. Arrangement is already valid. No swap is needed. So 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.
Problem:
You are given n natural numbers a1,a2,a3…… an. Let SOD of a number be defined as the Sum of Digits of that number. Compute the value of
{ [ SOD(a1) + SOD(a2) + …….. SOD(an) ] % 9 } – { [ SOD( a1 + a2 + ….. an ) ] % 9 }
Input:
The first line consists of the value of n. Next n lines are such that the i th line consists of a single natural number ai.
Output:
Print a single line consisting of the computed value.
Constraints:
2 ≤ n ≤ 10000
1 ≤ ai ≤ 10^10000
Problem Setter : Shreyans
Problem Tester : Sandeep
(By IIT Kgp HackerEarth Programming Club)
SAMPLE INPUT
3
1
2
3
SAMPLE OUTPUT
0
Explanation
(SOD(1)+SOD(2)+SOD(3))%9=(1+2+3)%9=6 and (SOD(1+2+3))%9=SOD(6)%9=6. So, 6-6=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.
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a k-tree.
A k-tree is an infinite rooted tree where:
each vertex has exactly k children; each edge has some weight; if we look at the edges that goes from some vertex to its children (exactly k edges), then their weights will equal 1, 2, 3, ..., k.
The picture below shows a part of a 3-tree.
[Image]
As soon as Dima, a good friend of Lesha, found out about the tree, he immediately wondered: "How many paths of total weight n (the sum of all weights of the edges in the path) are there, starting from the root of a k-tree and also containing at least one edge of weight at least d?".
Help Dima find an answer to his question. As the number of ways can be rather large, print it modulo 1000000007 (10^9 + 7).
-----Input-----
A single line contains three space-separated integers: n, k and d (1 ≤ n, k ≤ 100; 1 ≤ d ≤ k).
-----Output-----
Print a single integer — the answer to the problem modulo 1000000007 (10^9 + 7).
-----Examples-----
Input
3 3 2
Output
3
Input
3 3 3
Output
1
Input
4 3 2
Output
6
Input
4 5 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.
You are given a string $t$ consisting of $n$ lowercase Latin letters and an integer number $k$.
Let's define a substring of some string $s$ with indices from $l$ to $r$ as $s[l \dots r]$.
Your task is to construct such string $s$ of minimum possible length that there are exactly $k$ positions $i$ such that $s[i \dots i + n - 1] = t$. In other words, your task is to construct such string $s$ of minimum possible length that there are exactly $k$ substrings of $s$ equal to $t$.
It is guaranteed that the answer is always unique.
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 50$) — the length of the string $t$ and the number of substrings.
The second line of the input contains the string $t$ consisting of exactly $n$ lowercase Latin letters.
-----Output-----
Print such string $s$ of minimum possible length that there are exactly $k$ substrings of $s$ equal to $t$.
It is guaranteed that the answer is always unique.
-----Examples-----
Input
3 4
aba
Output
ababababa
Input
3 2
cat
Output
catcat
Read the inputs from stdin solve the problem and write the answer to stdout (do 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
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
[Image]
As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore.
A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.
Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length l_{i}.
The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle $180^{\circ}$.
Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing.
Help sculptor!
-----Input-----
The first line contains an integer n (3 ≤ n ≤ 10^5) — a number of rod-blanks.
The second line contains n integers l_{i} (1 ≤ l_{i} ≤ 10^9) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.
-----Output-----
Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.
-----Examples-----
Input
3
1 2 1
Output
1
Input
5
20 4 3 2 1
Output
11
-----Note-----
In the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}.
In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Create a program that reads poker hand data and outputs the role for each. However, this issue follows the rules below.
* Poker is a competition with 5 playing cards.
* No more than 5 cards with the same number.
* There is no joker.
* Suppose you only consider the following poker roles: (The higher the number, the higher the role.)
1. No role (does not apply to any of the following)
2. One pair (two cards with the same number)
3. Two pairs (two pairs of cards with the same number)
4. Three cards (one set of three cards with the same number)
5. Straight (the numbers on 5 cards are consecutive)
However, in the case of a straight containing A, the sequence ending with A is also straight. In other words, there are two types of straights containing A: A 2 3 4 5 and 10 J Q K A. Lines that straddle A, such as J Q K A 2, are not straight. (In this case, it will be "no role").
6. Full House (one set of three cards with the same number and the other two cards with the same number)
7. Four Cards (one set of four cards with the same number)
Input
The input consists of multiple datasets. Each dataset is given in the following format:
Hand 1, Hand 2, Hand 3, Hand 4, Hand 5
In your hand, Trump's J (jack) is 11, Q (queen) is 12, K (king) is 13, A (ace) is 1, and the others are represented by their respective numbers.
The number of datasets does not exceed 50.
Output
For each dataset, output one of the highest roles you can play in your hand. Follow the output example for the notation of the role.
Example
Input
1,2,3,4,1
2,3,2,3,12
12,13,11,12,12
7,6,7,6,7
3,3,2,3,3
6,7,8,9,10
11,12,10,1,13
11,12,13,1,2
Output
one pair
two pair
three card
full house
four card
straight
straight
null
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Description
THE BY DOLM @ STER is a training simulation game scheduled to be released on EXIDNA by 1rem on April 1, 2010. For the time being, it probably has nothing to do with an arcade game where the network connection service stopped earlier this month.
This game is a game in which members of the unit (formation) to be produced are selected from the bidders, and through lessons and communication with the members, they (they) are raised to the top of the bidders, the top biddles.
Each bidle has three parameters, vocal, dance, and looks, and the unit's ability score is the sum of all the parameters of the biddles that belong to the unit. The highest of the three stats of a unit is the rank of the unit.
There is no limit to the number of people in a unit, and you can work as a unit with one, three, or 100 members. Of course, you can hire more than one of the same bidle, but hiring a bidle is expensive and must be taken into account.
As a producer, you decided to write and calculate a program to make the best unit.
Input
The input consists of multiple test cases.
The first line of each test case is given the number N of bid dollars and the available cost M. (1 <= N, M <= 300) The next 2 * N lines contain information about each bidle.
The name of the bidle is on the first line of the bidle information. Biddle names consist of alphabets and spaces, with 30 characters or less. Also, there is no bidle with the same name.
The second line is given the integers C, V, D, L. C is the cost of hiring one Biddle, V is the vocal, D is the dance, and L is the stat of the looks. (1 <= C, V, D, L <= 300)
Input ends with EOF.
Output
Answer the maximum rank of units that can be made within the given cost.
If you cannot make a unit, output 0.
Example
Input
3 10
Dobkeradops
7 5 23 10
PataPata
1 1 2 1
dop
5 3 11 14
2 300
Bydo System Alpha
7 11 4 7
Green Inferno
300 300 300 300
Output
29
462
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Tokitsukaze and CSL are playing a little game of stones.
In the beginning, there are $n$ piles of stones, the $i$-th pile of which has $a_i$ stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?
Consider an example: $n=3$ and sizes of piles are $a_1=2$, $a_2=3$, $a_3=0$. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be $[1, 3, 0]$ and it is a good move. But if she chooses the second pile then the state will be $[2, 2, 0]$ and she immediately loses. So the only good move for her is to choose the first pile.
Supposing that both players always take their best moves and never make mistakes, who will win the game?
Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of piles.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_1, a_2, \ldots, a_n \le 10^9$), which mean the $i$-th pile has $a_i$ stones.
-----Output-----
Print "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.
-----Examples-----
Input
1
0
Output
cslnb
Input
2
1 0
Output
cslnb
Input
2
2 2
Output
sjfnb
Input
3
2 3 1
Output
sjfnb
-----Note-----
In the first example, Tokitsukaze cannot take any stone, so CSL will win.
In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.
In the third example, Tokitsukaze will win. Here is one of the optimal ways:
Firstly, Tokitsukaze can choose the first pile and take a stone from that pile. Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately. Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose.
In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 $n$ and $k$. Your task is to find if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers or not.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 10^5$) — the number of test cases.
The next $t$ lines describe test cases. The only line of the test case contains two integers $n$ and $k$ ($1 \le n, k \le 10^7$).
-----Output-----
For each test case, print the answer — "YES" (without quotes) if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers and "NO" otherwise.
-----Example-----
Input
6
3 1
4 2
10 3
10 2
16 4
16 5
Output
YES
YES
NO
YES
YES
NO
-----Note-----
In the first test case, you can represent $3$ as $3$.
In the second test case, the only way to represent $4$ is $1+3$.
In the third test case, you cannot represent $10$ as the sum of three distinct positive odd integers.
In the fourth test case, you can represent $10$ as $3+7$, for example.
In the fifth test case, you can represent $16$ as $1+3+5+7$.
In the sixth test case, you cannot represent $16$ as the sum of five distinct positive odd integers.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time t_{i} needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed.
Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^5).
The next line contains n integers t_{i} (1 ≤ t_{i} ≤ 10^9), separated by spaces.
-----Output-----
Print a single number — the maximum number of not disappointed people in the queue.
-----Examples-----
Input
5
15 2 1 5 3
Output
4
-----Note-----
Value 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 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.
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.
Therefore, Sasha decided to upsolve the following problem:
You have an array a with n integers. You need to count the number of funny pairs (l, r) (l ≤ r). To check if a pair (l, r) is a funny pair, take mid = (l + r - 1)/(2), then if r - l + 1 is an even number and a_l ⊕ a_{l+1} ⊕ … ⊕ a_{mid} = a_{mid + 1} ⊕ a_{mid + 2} ⊕ … ⊕ a_r, then the pair is funny. In other words, ⊕ of elements of the left half of the subarray from l to r should be equal to ⊕ of elements of the right half. Note that ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
It is time to continue solving the contest, so Sasha asked you to solve this task.
Input
The first line contains one integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the size of the array.
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i < 2^{20}) — array itself.
Output
Print one integer — the number of funny pairs. You should consider only pairs where r - l + 1 is even number.
Examples
Input
5
1 2 3 4 5
Output
1
Input
6
3 2 2 3 7 6
Output
3
Input
3
42 4 2
Output
0
Note
Be as cool as Sasha, upsolve problems!
In the first example, the only funny pair is (2, 5), as 2 ⊕ 3 = 4 ⊕ 5 = 1.
In the second example, funny pairs are (2, 3), (1, 4), and (3, 6).
In the third example, there are no funny pairs.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This is yet another problem on regular bracket sequences.
A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.
For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.
Input
The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.
Output
Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.
Print -1, if there is no answer. If the answer is not unique, print any of them.
Examples
Input
(??)
1 2
2 8
Output
4
()()
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.
Consider n distinct points on a line. Let the i-th point have the coordinate x_{i} and weight w_{i}. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |x_{i} - x_{j}| ≥ w_{i} + w_{j}.
Find the size of the maximum clique in such graph.
-----Input-----
The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points.
Each of the next n lines contains two numbers x_{i}, w_{i} (0 ≤ x_{i} ≤ 10^9, 1 ≤ w_{i} ≤ 10^9) — the coordinate and the weight of a point. All x_{i} are different.
-----Output-----
Print a single number — the number of vertexes in the maximum clique of the given graph.
-----Examples-----
Input
4
2 3
3 1
6 1
0 2
Output
3
-----Note-----
If you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!
The picture for the sample test. [Image]
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves: "010210" $\rightarrow$ "100210"; "010210" $\rightarrow$ "001210"; "010210" $\rightarrow$ "010120"; "010210" $\rightarrow$ "010201".
Note than you cannot swap "02" $\rightarrow$ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String $a$ is lexicographically less than string $b$ (if strings $a$ and $b$ have the same length) if there exists some position $i$ ($1 \le i \le |a|$, where $|s|$ is the length of the string $s$) such that for every $j < i$ holds $a_j = b_j$, and $a_i < b_i$.
-----Input-----
The first line of the input contains the string $s$ consisting only of characters '0', '1' and '2', its length is between $1$ and $10^5$ (inclusive).
-----Output-----
Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
-----Examples-----
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Yaroslav likes algorithms. We'll describe one of his favorite algorithms.
1. The algorithm receives a string as the input. We denote this input string as a.
2. The algorithm consists of some number of command. Сommand number i looks either as si >> wi, or as si <> wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?".
3. At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates.
4. Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk >> wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates.
5. The value of string a after algorithm termination is considered to be the output of the algorithm.
Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.
Help Yaroslav.
Input
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.
Output
Print the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces.
Your algorithm will be launched for each of these numbers. The answer will be considered correct if:
* Each line will a correct algorithm command (see the description in the problem statement).
* The number of commands should not exceed 50.
* The algorithm will increase each of the given numbers by one.
* To get a respond, the algorithm will perform no more than 200 iterations for each number.
Examples
Input
2
10
79
Output
10<>11
79<>80
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$. You may perform any number of operations on them (possibly zero).
During each operation you should choose any positive integer $x$ and set $a := a - x$, $b := b - 2x$ or $a := a - 2x$, $b := b - x$. Note that you may choose different values of $x$ in different operations.
Is it possible to make $a$ and $b$ equal to $0$ simultaneously?
Your program should answer $t$ independent test cases.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.
Then the test cases follow, each test case is represented by one line containing two integers $a$ and $b$ for this test case ($0 \le a, b \le 10^9$).
-----Output-----
For each test case print the answer to it — YES if it is possible to make $a$ and $b$ equal to $0$ simultaneously, and NO otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).
-----Example-----
Input
3
6 9
1 1
1 2
Output
YES
NO
YES
-----Note-----
In the first test case of the example two operations can be used to make both $a$ and $b$ equal to zero: choose $x = 4$ and set $a := a - x$, $b := b - 2x$. Then $a = 6 - 4 = 2$, $b = 9 - 8 = 1$; choose $x = 1$ and set $a := a - 2x$, $b := b - x$. Then $a = 2 - 2 = 0$, $b = 1 - 1 = 0$.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Not to be confused with chessboard.
[Image]
-----Input-----
The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have.
The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.
-----Output-----
Output a single number.
-----Examples-----
Input
9
brie soft
camembert soft
feta soft
goat soft
muenster soft
asiago hard
cheddar hard
gouda hard
swiss hard
Output
3
Input
6
parmesan hard
emmental hard
edam hard
colby hard
gruyere hard
asiago hard
Output
4
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
If we multiply the integer `717 (n)` by `7 (k)`, the result will be equal to `5019`.
Consider all the possible ways that this last number may be split as a string and calculate their corresponding sum obtained by adding the substrings as integers. When we add all of them up,... surprise, we got the original number `717`:
```
Partitions as string Total Sums
['5', '019'] 5 + 19 = 24
['50', '19'] 50 + 19 = 69
['501', '9'] 501 + 9 = 510
['5', '0', '19'] 5 + 0 + 19 = 24
['5', '01', '9'] 5 + 1 + 9 = 15
['50', '1', '9'] 50 + 1 + 9 = 60
['5', '0', '1', '9'] 5 + 0 + 1 + 9 = 15
____________________
Big Total: 717
____________________
```
In fact, `717` is one of the few integers that has such property with a factor `k = 7`.
Changing the factor `k`, for example to `k = 3`, we may see that the integer `40104` fulfills this property.
Given an integer `start_value` and an integer `k`, output the smallest integer `n`, but higher than `start_value`, that fulfills the above explained properties.
If by chance, `start_value`, fulfills the property, do not return `start_value` as a result, only the next integer. Perhaps you may find this assertion redundant if you understood well the requirement of the kata: "output the smallest integer `n`, but higher than `start_value`"
The values for `k` in the input may be one of these: `3, 4, 5, 7`
### Features of the random tests
If you want to understand the style and features of the random tests, see the *Notes* at the end of these instructions.
The random tests are classified in three parts.
- Random tests each with one of the possible values of `k` and a random `start_value` in the interval `[100, 1300]`
- Random tests each with a `start_value` in a larger interval for each value of `k`, as follows:
- for `k = 3`, a random `start value` in the range `[30000, 40000]`
- for `k = 4`, a random `start value` in the range `[2000, 10000]`
- for `k = 5`, a random `start value` in the range `[10000, 20000]`
- for `k = 7`, a random `start value` in the range `[100000, 130000]`
- More challenging tests, each with a random `start_value` in the interval `[100000, 110000]`.
See the examples tests.
Enjoy it.
# Notes:
- As these sequences are finite, in other words, they have a maximum term for each value of k, the tests are prepared in such way that the `start_value` will always be less than this maximum term. So you may be confident that your code will always find an integer.
- The values of `k` that generate sequences of integers, for the constrains of this kata are: 2, 3, 4, 5, and 7. The case `k = 2` was not included because it generates only two integers.
- The sequences have like "mountains" of abundance of integers but also have very wide ranges like "valleys" of scarceness. Potential solutions, even the fastest ones, may time out searching the next integer due to an input in one of these valleys. So it was intended to avoid these ranges.
Javascript and Ruby versions will be released soon.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.
The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.
An Example of some correct logos:
[Image]
An Example of some incorrect logos:
[Image]
Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of $n$ rows and $m$ columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').
Adhami gave Warawreh $q$ options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is $0$.
Warawreh couldn't find the best option himself so he asked you for help, can you help him?
-----Input-----
The first line of input contains three integers $n$, $m$ and $q$ $(1 \leq n , m \leq 500, 1 \leq q \leq 3 \cdot 10^{5})$ — the number of row, the number columns and the number of options.
For the next $n$ lines, every line will contain $m$ characters. In the $i$-th line the $j$-th character will contain the color of the cell at the $i$-th row and $j$-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.
For the next $q$ lines, the input will contain four integers $r_1$, $c_1$, $r_2$ and $c_2$ $(1 \leq r_1 \leq r_2 \leq n, 1 \leq c_1 \leq c_2 \leq m)$. In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell $(r_1, c_1)$ and with the bottom-right corner in the cell $(r_2, c_2)$.
-----Output-----
For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print $0$.
-----Examples-----
Input
5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5
Output
16
4
4
4
0
Input
6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10
Output
36
4
16
16
16
Input
8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5
Output
64
0
16
4
16
4
36
0
-----Note-----
Picture for the first test:
[Image]
The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let us call two integers $x$ and $y$ adjacent if $\frac{lcm(x, y)}{gcd(x, y)}$ is a perfect square. For example, $3$ and $12$ are adjacent, but $6$ and $9$ are not.
Here $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$, and $lcm(x, y)$ denotes the least common multiple (LCM) of integers $x$ and $y$.
You are given an array $a$ of length $n$. Each second the following happens: each element $a_i$ of the array is replaced by the product of all elements of the array (including itself), that are adjacent to the current value.
Let $d_i$ be the number of adjacent elements to $a_i$ (including $a_i$ itself). The beauty of the array is defined as $\max_{1 \le i \le n} d_i$.
You are given $q$ queries: each query is described by an integer $w$, and you have to output the beauty of the array after $w$ seconds.
-----Input-----
The first input line contains a single integer $t$ ($1 \le t \le 10^5)$ — the number of test cases.
The first line of each test case contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the length of the array.
The following line contains $n$ integers $a_1, \ldots, a_n$ ($1 \le a_i \le 10^6$) — array elements.
The next line contain a single integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of queries.
The following $q$ lines contain a single integer $w$ each ($0 \le w \le 10^{18}$) — the queries themselves.
It is guaranteed that the sum of values $n$ over all test cases does not exceed $3 \cdot 10^5$, and the sum of values $q$ over all test cases does not exceed $3 \cdot 10^5$
-----Output-----
For each query output a single integer — the beauty of the array at the corresponding moment.
-----Examples-----
Input
2
4
6 8 4 2
1
0
6
12 3 20 5 80 1
1
1
Output
2
3
-----Note-----
In the first test case, the initial array contains elements $[6, 8, 4, 2]$. Element $a_4=2$ in this array is adjacent to $a_4=2$ (since $\frac{lcm(2, 2)}{gcd(2, 2)}=\frac{2}{2}=1=1^2$) and $a_2=8$ (since $\frac{lcm(8,2)}{gcd(8, 2)}=\frac{8}{2}=4=2^2$). Hence, $d_4=2$, and this is the maximal possible value $d_i$ in this array.
In the second test case, the initial array contains elements $[12, 3, 20, 5, 80, 1]$. The elements adjacent to $12$ are $\{12, 3\}$, the elements adjacent to $3$ are $\{12, 3\}$, the elements adjacent to $20$ are $\{20, 5, 80\}$, the elements adjacent to $5$ are $\{20, 5, 80\}$, the elements adjacent to $80$ are $\{20, 5, 80\}$, the elements adjacent to $1$ are $\{1\}$. After one second, the array is transformed into $[36, 36, 8000, 8000, 8000, 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.
Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is a_{i}, and after a week of discounts its price will be b_{i}.
Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.
Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.
-----Input-----
In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·10^5, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now.
The second line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^4) — prices of items during discounts (i.e. right now).
The third line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^4) — prices of items after discounts (i.e. after a week).
-----Output-----
Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.
-----Examples-----
Input
3 1
5 4 6
3 1 5
Output
10
Input
5 3
3 4 7 10 3
4 5 5 12 5
Output
25
-----Note-----
In the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.
In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two arrays of length $n$: $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$.
You can perform the following operation any number of times:
Choose integer index $i$ ($1 \le i \le n$);
Swap $a_i$ and $b_i$.
What is the minimum possible sum $|a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n|$ $+$ $|b_1 - b_2| + |b_2 - b_3| + \dots + |b_{n-1} - b_n|$ (in other words, $\sum\limits_{i=1}^{n - 1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$) you can achieve after performing several (possibly, zero) operations?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 4000$) — the number of test cases. Then, $t$ test cases follow.
The first line of each test case contains the single integer $n$ ($2 \le n \le 25$) — the length of arrays $a$ and $b$.
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 array $a$.
The third line of each test case contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 10^9$) — the array $b$.
-----Output-----
For each test case, print one integer — the minimum possible sum $\sum\limits_{i=1}^{n-1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$.
-----Examples-----
Input
3
4
3 3 10 10
10 10 3 3
5
1 2 3 4 5
6 7 8 9 10
6
72 101 108 108 111 44
10 87 111 114 108 100
Output
0
8
218
-----Note-----
In the first test case, we can, for example, swap $a_3$ with $b_3$ and $a_4$ with $b_4$. We'll get arrays $a = [3, 3, 3, 3]$ and $b = [10, 10, 10, 10]$ with sum $3 \cdot |3 - 3| + 3 \cdot |10 - 10| = 0$.
In the second test case, arrays already have minimum sum (described above) equal to $|1 - 2| + \dots + |4 - 5| + |6 - 7| + \dots + |9 - 10|$ $= 4 + 4 = 8$.
In the third test case, we can, for example, swap $a_5$ and $b_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.
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?
-----Constraints-----
- All values in input are integers.
- 0 \leq A, B, C
- 1 \leq K \leq A + B + C \leq 2 \times 10^9
-----Input-----
Input is given from Standard Input in the following format:
A B C K
-----Output-----
Print the maximum possible sum of the numbers written on the cards chosen.
-----Sample Input-----
2 1 1 3
-----Sample Output-----
2
Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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$ seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from $1$ to $n$ from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat $i$ ($1 \leq i \leq n$) will decide to go for boiled water at minute $t_i$.
Tank with a boiled water is located to the left of the $1$-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly $p$ minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small.
Nobody likes to stand in a queue. So when the passenger occupying the $i$-th seat wants to go for a boiled water, he will first take a look on all seats from $1$ to $i - 1$. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than $i$ are busy, he will go to the tank.
There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.
Your goal is to find for each passenger, when he will receive the boiled water for his noodles.
-----Input-----
The first line contains integers $n$ and $p$ ($1 \leq n \leq 100\,000$, $1 \leq p \leq 10^9$) — the number of people and the amount of time one person uses the tank.
The second line contains $n$ integers $t_1, t_2, \dots, t_n$ ($0 \leq t_i \leq 10^9$) — the moments when the corresponding passenger will go for the boiled water.
-----Output-----
Print $n$ integers, where $i$-th of them is the time moment the passenger on $i$-th seat will receive his boiled water.
-----Example-----
Input
5 314
0 310 942 628 0
Output
314 628 1256 942 1570
-----Note-----
Consider the example.
At the $0$-th minute there were two passengers willing to go for a water, passenger $1$ and $5$, so the first passenger has gone first, and returned at the $314$-th minute. At this moment the passenger $2$ was already willing to go for the water, so the passenger $2$ has gone next, and so on. In the end, $5$-th passenger was last to receive the boiled water.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 got many presents these days. So she decided to pack them into boxes and send them to her friends.
There are $n$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.
Also, there are $m$ boxes. All of them are for different people, so they are pairwise distinct (consider that the names of $m$ friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.
Alice wants to pack presents with the following rules: She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of $n$ kinds, empty boxes are allowed); For each kind at least one present should be packed into some box.
Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo $10^9+7$.
See examples and their notes for clarification.
-----Input-----
The first line contains two integers $n$ and $m$, separated by spaces ($1 \leq n,m \leq 10^9$) — the number of kinds of presents and the number of boxes that Alice has.
-----Output-----
Print one integer — the number of ways to pack the presents with Alice's rules, calculated by modulo $10^9+7$
-----Examples-----
Input
1 3
Output
7
Input
2 2
Output
9
-----Note-----
In the first example, there are seven ways to pack presents:
$\{1\}\{\}\{\}$
$\{\}\{1\}\{\}$
$\{\}\{\}\{1\}$
$\{1\}\{1\}\{\}$
$\{\}\{1\}\{1\}$
$\{1\}\{\}\{1\}$
$\{1\}\{1\}\{1\}$
In the second example there are nine ways to pack presents:
$\{\}\{1,2\}$
$\{1\}\{2\}$
$\{1\}\{1,2\}$
$\{2\}\{1\}$
$\{2\}\{1,2\}$
$\{1,2\}\{\}$
$\{1,2\}\{1\}$
$\{1,2\}\{2\}$
$\{1,2\}\{1,2\}$
For example, the way $\{2\}\{2\}$ is wrong, because presents of the first kind should be used in the least one box.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 several queries. Each query consists of three integers $p$, $q$ and $b$. You need to answer whether the result of $p/q$ in notation with base $b$ is a finite fraction.
A fraction in notation with base $b$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of queries.
Next $n$ lines contain queries, one per line. Each line contains three integers $p$, $q$, and $b$ ($0 \le p \le 10^{18}$, $1 \le q \le 10^{18}$, $2 \le b \le 10^{18}$). All numbers are given in notation with base $10$.
-----Output-----
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
-----Examples-----
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
-----Note-----
$\frac{6}{12} = \frac{1}{2} = 0,5_{10}$
$\frac{4}{3} = 1,(3)_{10}$
$\frac{9}{36} = \frac{1}{4} = 0,01_2$
$\frac{4}{12} = \frac{1}{3} = 0,1_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 know that the Martians use a number system with base k. Digit b (0 ≤ b < k) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology).
A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of all digits of number x. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.
For example, d(35047) = d((3 + 5 + 0 + 4)7) = d(157) = d((1 + 5)7) = d(67) = 67. In this sample the calculations are performed in the 7-base notation.
If a number's digital root equals b, the Martians also call this number lucky.
You have string s, which consists of n digits in the k-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.
Note that substring s[i... j] of the string s = a1a2... an (1 ≤ i ≤ j ≤ n) is the string aiai + 1... aj. Two substrings s[i1... j1] and s[i2... j2] of the string s are different if either i1 ≠ i2 or j1 ≠ j2.
Input
The first line contains three integers k, b and n (2 ≤ k ≤ 109, 0 ≤ b < k, 1 ≤ n ≤ 105).
The second line contains string s as a sequence of n integers, representing digits in the k-base notation: the i-th integer equals ai (0 ≤ ai < k) — the i-th digit of string s. The numbers in the lines are space-separated.
Output
Print a single integer — the number of substrings that are lucky numbers.
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
10 5 6
3 2 0 5 6 1
Output
5
Input
7 6 4
3 5 0 4
Output
1
Input
257 0 3
0 0 256
Output
3
Note
In the first sample the following substrings have the sought digital root: s[1... 2] = "3 2", s[1... 3] = "3 2 0", s[3... 4] = "0 5", s[4... 4] = "5" and s[2... 6] = "2 0 5 6 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.
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.
Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.
It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.
Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.
Input
The first line contains two space-separated integers: n (2 ≤ n ≤ 105), the number of planets in the galaxy, and m (0 ≤ m ≤ 105) — the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 ≤ ci ≤ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection.
Then n lines follow: the i-th line contains an integer ki (0 ≤ ki ≤ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 ≤ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.
Output
Print a single number — the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.
Examples
Input
4 6
1 2 2
1 3 3
1 4 8
2 3 4
2 4 5
3 4 3
0
1 3
2 3 4
0
Output
7
Input
3 1
1 2 3
0
1 3
0
Output
-1
Note
In the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then — to planet 4, then he spends a total of only 2 + 5 = 7 seconds.
In the second sample one can't get from planet 1 to planet 3 by moving through stargates.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 integers N and M.
Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 10^5
- N \leq M \leq 10^9
-----Input-----
Input is given from Standard Input in the following format:
N M
-----Output-----
Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.
-----Sample Input-----
3 14
-----Sample Output-----
2
Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Let's define $S(x)$ to be the sum of digits of number $x$ written in decimal system. For example, $S(5) = 5$, $S(10) = 1$, $S(322) = 7$.
We will call an integer $x$ interesting if $S(x + 1) < S(x)$. In each test you will be given one integer $n$. Your task is to calculate the number of integers $x$ such that $1 \le x \le n$ and $x$ is interesting.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — number of test cases.
Then $t$ lines follow, the $i$-th line contains one integer $n$ ($1 \le n \le 10^9$) for the $i$-th test case.
-----Output-----
Print $t$ integers, the $i$-th should be the answer for the $i$-th test case.
-----Examples-----
Input
5
1
9
10
34
880055535
Output
0
1
1
3
88005553
-----Note-----
The first interesting number is equal to $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.
The alphabetized kata
---------------------
Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!
The input is restricted to contain no numerals and only words containing the english alphabet letters.
Example:
```python
alphabetized("The Holy Bible") # "BbeehHilloTy"
```
_Inspired by [Tauba Auerbach](http://www.taubaauerbach.com/view.php?id=73)_
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least $3$ (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself $k$-multihedgehog.
Let us define $k$-multihedgehog as follows: $1$-multihedgehog is hedgehog: it has one vertex of degree at least $3$ and some vertices of degree 1. For all $k \ge 2$, $k$-multihedgehog is $(k-1)$-multihedgehog in which the following changes has been made for each vertex $v$ with degree 1: let $u$ be its only neighbor; remove vertex $v$, create a new hedgehog with center at vertex $w$ and connect vertices $u$ and $w$ with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby $k$-multihedgehog is a tree. Ivan made $k$-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed $k$-multihedgehog.
-----Input-----
First line of input contains $2$ integers $n$, $k$ ($1 \le n \le 10^{5}$, $1 \le k \le 10^{9}$) — number of vertices and hedgehog parameter.
Next $n-1$ lines contains two integers $u$ $v$ ($1 \le u, \,\, v \le n; \,\, u \ne v$) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
-----Output-----
Print "Yes" (without quotes), if given graph is $k$-multihedgehog, and "No" (without quotes) otherwise.
-----Examples-----
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
-----Note-----
2-multihedgehog from the first example looks like this:
[Image]
Its center is vertex $13$. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least $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 have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 3^2 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 2^2 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.
-----Input-----
The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
-----Output-----
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
-----Examples-----
Input
4
2 2 1
2 2 3
2 2 2
2 2 4
Output
5
5
4
0
-----Note-----
In the first query of the sample one needs to perform two breaks: to split 2 × 2 bar into two pieces of 2 × 1 (cost is 2^2 = 4), to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 1^2 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ consisting of $n$ integers. In one move, you can jump from the position $i$ to the position $i - a_i$ (if $1 \le i - a_i$) or to the position $i + a_i$ (if $i + a_i \le n$).
For each position $i$ from $1$ to $n$ you want to know the minimum the number of moves required to reach any position $j$ such that $a_j$ has the opposite parity from $a_i$ (i.e. if $a_i$ is odd then $a_j$ has to be even and vice versa).
-----Input-----
The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$.
-----Output-----
Print $n$ integers $d_1, d_2, \dots, d_n$, where $d_i$ is the minimum the number of moves required to reach any position $j$ such that $a_j$ has the opposite parity from $a_i$ (i.e. if $a_i$ is odd then $a_j$ has to be even and vice versa) or -1 if it is impossible to reach such a position.
-----Example-----
Input
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
What is the minimum number of operations you need to make all of the elements equal to 1?
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array.
The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.
Output
Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.
Examples
Input
5
2 2 3 4 6
Output
5
Input
4
2 4 6 8
Output
-1
Input
3
2 6 9
Output
4
Note
In the first sample you can turn all numbers to 1 using the following 5 moves:
* [2, 2, 3, 4, 6].
* [2, 1, 3, 4, 6]
* [2, 1, 3, 1, 6]
* [2, 1, 1, 1, 6]
* [1, 1, 1, 1, 6]
* [1, 1, 1, 1, 1]
We can prove that in this case it is not possible to make all numbers one using less than 5 moves.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.
Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (10^9 + 9).
-----Input-----
The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 10^9; 0 ≤ m ≤ n).
-----Output-----
Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (10^9 + 9).
-----Examples-----
Input
5 3 2
Output
3
Input
5 4 2
Output
6
-----Note-----
Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points.
Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4.
Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N.
There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island a_i and Island b_i.
Cat Snuke is on Island 1 now, and wants to go to Island N. However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.
Help him.
Constraints
* 3 ≤ N ≤ 200 000
* 1 ≤ M ≤ 200 000
* 1 ≤ a_i < b_i ≤ N
* (a_i, b_i) \neq (1, N)
* If i \neq j, (a_i, b_i) \neq (a_j, b_j).
Input
Input is given from Standard Input in the following format:
N M
a_1 b_1
a_2 b_2
:
a_M b_M
Output
If it is possible to go to Island N by using two boat services, print `POSSIBLE`; otherwise, print `IMPOSSIBLE`.
Examples
Input
3 2
1 2
2 3
Output
POSSIBLE
Input
4 3
1 2
2 3
3 4
Output
IMPOSSIBLE
Input
100000 1
1 99999
Output
IMPOSSIBLE
Input
5 5
1 3
4 5
2 3
2 4
1 4
Output
POSSIBLE
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
-----Input-----
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 10^5, $1 \leq d \leq 10^{9}$) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type m_{i}, s_{i} (0 ≤ m_{i}, s_{i} ≤ 10^9) — the amount of money and the friendship factor, respectively.
-----Output-----
Print the maximum total friendship factir that can be reached.
-----Examples-----
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
-----Note-----
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.
First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.
Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.
-----Input-----
First line of the input contains the string s — the coating that is present in the shop. Second line contains the string t — the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.
-----Output-----
The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating.
If the answer is not -1, then the following n lines should contain two integers x_{i} and y_{i} — numbers of ending blocks in the corresponding piece. If x_{i} ≤ y_{i} then this piece is used in the regular order, and if x_{i} > y_{i} piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.
-----Examples-----
Input
abc
cbaabc
Output
2
3 1
1 3
Input
aaabrytaaa
ayrat
Output
3
1 1
6 5
8 7
Input
ami
no
Output
-1
-----Note-----
In the first sample string "cbaabc" = "cba" + "abc".
In the second sample: "ayrat" = "a" + "yr" + "at".
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.
The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.
The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.
Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.
The traffic light on the crosswalk from the j-th house of the i-th row to the (j + 1)-th house of the same row has waiting time equal to a_{ij} (1 ≤ i ≤ 2, 1 ≤ j ≤ n - 1). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals b_{j} (1 ≤ j ≤ n). The city doesn't have any other crossings.
The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing. [Image] Figure to the first sample.
Help Laurenty determine the minimum total time he needs to wait at the crossroads.
-----Input-----
The first line of the input contains integer n (2 ≤ n ≤ 50) — the number of houses in each row.
Each of the next two lines contains n - 1 space-separated integer — values a_{ij} (1 ≤ a_{ij} ≤ 100).
The last line contains n space-separated integers b_{j} (1 ≤ b_{j} ≤ 100).
-----Output-----
Print a single integer — the least total time Laurenty needs to wait at the crossroads, given that he crosses the avenue only once both on his way to the store and on his way back home.
-----Examples-----
Input
4
1 2 3
3 2 1
3 2 2 3
Output
12
Input
3
1 2
3 3
2 1 3
Output
11
Input
2
1
1
1 1
Output
4
-----Note-----
The first sample is shown on the figure above.
In the second sample, Laurenty's path can look as follows: Laurenty crosses the avenue, the waiting time is 3; Laurenty uses the second crossing in the first row, the waiting time is 2; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty crosses the avenue, the waiting time is 1; Laurenty uses the second crossing in the second row, the waiting time is 3. In total we get that the answer equals 11.
In the last sample Laurenty visits all the crossings, so the answer is 4.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a3. A tower consisting of blocks with sides a1, a2, ..., ak has the total volume a13 + a23 + ... + ak3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
Input
The only line of the input contains one integer m (1 ≤ m ≤ 1015), meaning that Limak wants you to choose X between 1 and m, inclusive.
Output
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
Examples
Input
48
Output
9 42
Input
6
Output
6 6
Note
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is:
* Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15.
* The second added block has side 2, so the remaining volume is 15 - 8 = 7.
* Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 33 + 23 + 7·13 = 27 + 8 + 7 = 42.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 [Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers:
```math
3≺5≺7≺9≺ ...\\
≺2·3≺2·5≺2·7≺2·9≺...\\
≺2^n·3≺2^n·5≺2^n·7≺2^n·9≺...\\
≺2^{(n+1)}·3≺2^{(n+1)}·5≺2^{(n+1)}·7≺2^{(n+1)}·9≺...\\
≺2^n≺2^{(n-1)}≺...\\
≺4≺2≺1\\
```
Your task is to complete the function which returns `true` if `$a≺b$` according to this ordering, and `false` otherwise.
You may assume both `$a$` and `$b$` are non-zero positive integers.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.
She has $n$ friends who are also grannies (Maria is not included in this number). The $i$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $a_i$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $i$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $a_i$.
Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $1$). All the remaining $n$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $a_i$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $i$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $a_i$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance.
Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!
Consider an example: if $n=6$ and $a=[1,5,4,5,1,9]$, then: at the first step Maria can call grannies with numbers $1$ and $5$, each of them will see two grannies at the moment of going out into the yard (note that $a_1=1 \le 2$ and $a_5=1 \le 2$); at the second step, Maria can call grannies with numbers $2$, $3$ and $4$, each of them will see five grannies at the moment of going out into the yard (note that $a_2=5 \le 5$, $a_3=4 \le 5$ and $a_4=5 \le 5$); the $6$-th granny cannot be called into the yard — therefore, the answer is $6$ (Maria herself and another $5$ grannies).
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then test cases follow.
The first line of a test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of grannies (Maria is not included in this number).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 2\cdot10^5$).
It is guaranteed that the sum of the values $n$ over all test cases of the input does not exceed $10^5$.
-----Output-----
For each test case, print a single integer $k$ ($1 \le k \le n + 1$) — the maximum possible number of grannies in the courtyard.
-----Example-----
Input
4
5
1 1 2 2 1
6
2 3 4 5 6 7
6
1 5 4 5 1 9
5
1 2 3 5 6
Output
6
1
6
4
-----Note-----
In the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.
In the second test case in the example, no one can be in the yard, so Maria will remain there alone.
The third test case in the example is described in the details above.
In the fourth test case in the example, on the first step Maria can call grannies with numbers $1$, $2$ and $3$. If on the second step Maria calls $4$ or $5$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $4$-th granny or the $5$-th granny separately (one of them). If she calls both: $4$ and $5$, then when they appear, they will see $4+1=5$ grannies. Despite the fact that it is enough for the $4$-th granny, the $5$-th granny is not satisfied. So, Maria cannot call both the $4$-th granny and the $5$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You like the card board game "Set". Each card contains $k$ features, each of which is equal to a value from the set $\{0, 1, 2\}$. The deck contains all possible variants of cards, that is, there are $3^k$ different cards in total.
A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $k$ features are good for them.
For example, the cards $(0, 0, 0)$, $(0, 2, 1)$, and $(0, 1, 2)$ form a set, but the cards $(0, 2, 2)$, $(2, 1, 2)$, and $(1, 2, 0)$ do not, as, for example, the last feature is not good.
A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $n$ distinct cards?
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le n \le 10^3$, $1 \le k \le 20$) — the number of cards on a table and the number of card features. The description of the cards follows in the next $n$ lines.
Each line describing a card contains $k$ integers $c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$ ($0 \le c_{i, j} \le 2$) — card features. It is guaranteed that all cards are distinct.
-----Output-----
Output one integer — the number of meta-sets.
-----Examples-----
Input
8 4
0 0 0 0
0 0 0 1
0 0 0 2
0 0 1 0
0 0 2 0
0 1 0 0
1 0 0 0
2 2 0 0
Output
1
Input
7 4
0 0 0 0
0 0 0 1
0 0 0 2
0 0 1 0
0 0 2 0
0 1 0 0
0 2 0 0
Output
3
Input
9 2
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
Output
54
Input
20 4
0 2 0 0
0 2 2 2
0 2 2 1
0 2 0 1
1 2 2 0
1 2 1 0
1 2 2 1
1 2 0 1
1 1 2 2
1 1 0 2
1 1 2 1
1 1 1 1
2 1 2 0
2 1 1 2
2 1 2 1
2 1 1 1
0 1 1 2
0 0 1 0
2 2 0 0
2 0 0 2
Output
0
-----Note-----
Let's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $1$, $2$, $3$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.
You can see the first three tests below. For the first two tests, the meta-sets are highlighted.
In the first test, the only meta-set is the five cards $(0000,\ 0001,\ 0002,\ 0010,\ 0020)$. The sets in it are the triples $(0000,\ 0001,\ 0002)$ and $(0000,\ 0010,\ 0020)$. Also, a set is the triple $(0100,\ 1000,\ 2200)$ which does not belong to any meta-set.
In the second test, the following groups of five cards are meta-sets: $(0000,\ 0001,\ 0002,\ 0010,\ 0020)$, $(0000,\ 0001,\ 0002,\ 0100,\ 0200)$, $(0000,\ 0010,\ 0020,\ 0100,\ 0200)$.
In there third test, there are $54$ meta-sets.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given two strings s and t consisting of lowercase Latin letters. The length of t is 2 (i.e. this string consists only of two characters).
In one move, you can choose any character of s and replace it with any lowercase Latin letter. More formally, you choose some i and replace s_i (the character at the position i) with some character from 'a' to 'z'.
You want to do no more than k replacements in such a way that maximizes the number of occurrences of t in s as a subsequence.
Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.
Input
The first line of the input contains two integers n and k (2 ≤ n ≤ 200; 0 ≤ k ≤ n) — the length of s and the maximum number of moves you can make. The second line of the input contains the string s consisting of n lowercase Latin letters. The third line of the input contains the string t consisting of two lowercase Latin letters.
Output
Print one integer — the maximum possible number of occurrences of t in s as a subsequence if you replace no more than k characters in s optimally.
Examples
Input
4 2
bbaa
ab
Output
3
Input
7 3
asddsaf
sd
Output
10
Input
15 6
qwertyhgfdsazxc
qa
Output
16
Input
7 2
abacaba
aa
Output
15
Note
In the first example, you can obtain the string "abab" replacing s_1 with 'a' and s_4 with 'b'. Then the answer is 3.
In the second example, you can obtain the string "ssddsdd" and get the answer 10.
In the fourth example, you can obtain the string "aaacaaa" and get the answer 15.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
ButCoder Inc. runs a programming competition site called ButCoder. In this site, a user is given an integer value called rating that represents his/her skill, which changes each time he/she participates in a contest. The initial value of a new user's rating is 0, and a user whose rating reaches K or higher is called Kaiden ("total transmission"). Note that a user's rating may become negative.
Hikuhashi is a new user in ButCoder. It is estimated that, his rating increases by A in each of his odd-numbered contests (first, third, fifth, ...), and decreases by B in each of his even-numbered contests (second, fourth, sixth, ...).
According to this estimate, after how many contests will he become Kaiden for the first time, or will he never become Kaiden?
Constraints
* 1 ≤ K, A, B ≤ 10^{18}
* All input values are integers.
Input
Input is given from Standard Input in the following format:
K A B
Output
If it is estimated that Hikuhashi will never become Kaiden, print `-1`. Otherwise, print the estimated number of contests before he become Kaiden for the first time.
Examples
Input
4000 2000 500
Output
5
Input
4000 500 2000
Output
-1
Input
1000000000000000000 2 1
Output
1999999999999999997
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $v$ (different from root) is the previous to $v$ vertex on the shortest path from the root to the vertex $v$. Children of the vertex $v$ are all vertices for which $v$ is the parent.
A vertex is a leaf if it has no children. We call a vertex a bud, if the following three conditions are satisfied:
it is not a root,
it has at least one child, and
all its children are leaves.
You are given a rooted tree with $n$ vertices. The vertex $1$ is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud.
What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of the vertices in the given tree.
Each of the next $n-1$ lines contains two integers $u$ and $v$ ($1 \le u, v \le n$, $u \neq v$) meaning that there is an edge between vertices $u$ and $v$ in the tree.
It is guaranteed that the given graph is a tree.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case print a single integer — the minimal number of leaves that is possible to get after some operations.
-----Examples-----
Input
5
7
1 2
1 3
1 4
2 5
2 6
4 7
6
1 2
1 3
2 4
2 5
3 6
2
1 2
7
7 3
1 5
1 3
4 6
4 7
2 1
6
2 1
2 3
4 5
3 4
3 6
Output
2
2
1
2
1
-----Note-----
In the first test case the tree looks as follows:
Firstly you can choose a bud vertex $4$ and re-hang it to vertex $3$. After that you can choose a bud vertex $2$ and re-hang it to vertex $7$. As a result, you will have the following tree with $2$ leaves:
It can be proved that it is the minimal number of leaves possible to get.
In the second test case the tree looks as follows:
You can choose a bud vertex $3$ and re-hang it to vertex $5$. As a result, you will have the following tree with $2$ leaves:
It can be proved that it is the minimal number of leaves possible to get.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 been assigned to develop a filter for bad messages in the in-game chat. A message is a string $S$ of length $n$, consisting of lowercase English letters and characters ')'. The message is bad if the number of characters ')' at the end of the string strictly greater than the number of remaining characters. For example, the string ")bc)))" has three parentheses at the end, three remaining characters, and is not considered bad.
-----Input-----
The first line contains the number of test cases $t$ ($1 \leq t \leq 100$). Description of the $t$ test cases follows.
The first line of each test case contains an integer $n$ ($1 \leq n \leq 100$). The second line of each test case contains a string $S$ of length $n$, consisting of lowercase English letters and characters ')'.
-----Output-----
For each of $t$ test cases, print "Yes" if the string is bad. Otherwise, print "No".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
5
2
))
12
gl))hf))))))
9
gege)))))
14
)aa))b))))))))
1
)
Output
Yes
No
Yes
Yes
Yes
-----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.
Implement a function, so it will produce a sentence out of the given parts.
Array of parts could contain:
- words;
- commas in the middle;
- multiple periods at the end.
Sentence making rules:
- there must always be a space between words;
- there must not be a space between a comma and word on the left;
- there must always be one and only one period at the end of a sentence.
**Example:**
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given n integers a_1, a_2, ..., a_{n}. Find the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2 (i. e. some integer x exists so that a_{i} + a_{j} = 2^{x}).
-----Input-----
The first line contains the single positive integer n (1 ≤ n ≤ 10^5) — the number of integers.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print the number of pairs of indexes i, j (i < j) that a_{i} + a_{j} is a power of 2.
-----Examples-----
Input
4
7 3 2 1
Output
2
Input
3
1 1 1
Output
3
-----Note-----
In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).
In the second example all pairs of indexes (i, j) (where i < j) include in answer.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.
Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:
* Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.
For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure. If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward. Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.
864abc2e4a08c26015ffd007a30aab03.png
Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.
Constraints
* 1 ≦ x ≦ 10^{15}
* x is an integer.
Input
The input is given from Standard Input in the following format:
x
Output
Print the answer.
Examples
Input
7
Output
2
Input
149696127901
Output
27217477801
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 pair of positive integers $(a,b)$ is called special if $\lfloor \frac{a}{b} \rfloor = a mod b$. Here, $\lfloor \frac{a}{b} \rfloor$ is the result of the integer division between $a$ and $b$, while $a mod b$ is its remainder.
You are given two integers $x$ and $y$. Find the number of special pairs $(a,b)$ such that $1\leq a \leq x$ and $1 \leq b \leq y$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases.
The only line of the description of each test case contains two integers $x$, $y$ ($1 \le x,y \le 10^9$).
-----Output-----
For each test case print the answer on a single line.
-----Examples-----
Input
9
3 4
2 100
4 3
50 3
12 4
69 420
12345 6789
123456 789
12345678 9
Output
1
0
2
3
5
141
53384
160909
36
-----Note-----
In the first test case, the only special pair is $(3, 2)$.
In the second test case, there are no special pairs.
In the third test case, there are two special pairs: $(3, 2)$ and $(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.
Heidi the Cow is aghast: cracks in the northern Wall? Zombies gathering outside, forming groups, preparing their assault? This must not happen! Quickly, she fetches her HC^2 (Handbook of Crazy Constructions) and looks for the right chapter:
How to build a wall: Take a set of bricks. Select one of the possible wall designs. Computing the number of possible designs is left as an exercise to the reader. Place bricks on top of each other, according to the chosen design.
This seems easy enough. But Heidi is a Coding Cow, not a Constructing Cow. Her mind keeps coming back to point 2b. Despite the imminent danger of a zombie onslaught, she wonders just how many possible walls she could build with up to n bricks.
A wall is a set of wall segments as defined in the easy version. How many different walls can be constructed such that the wall consists of at least 1 and at most n bricks? Two walls are different if there exist a column c and a row r such that one wall has a brick in this spot, and the other does not.
Along with n, you will be given C, the width of the wall (as defined in the easy version). Return the number of different walls modulo 10^6 + 3.
-----Input-----
The first line contains two space-separated integers n and C, 1 ≤ n ≤ 500000, 1 ≤ C ≤ 200000.
-----Output-----
Print the number of different walls that Heidi could build, modulo 10^6 + 3.
-----Examples-----
Input
5 1
Output
5
Input
2 2
Output
5
Input
3 2
Output
9
Input
11 5
Output
4367
Input
37 63
Output
230574
-----Note-----
The number 10^6 + 3 is prime.
In the second sample case, the five walls are:
B B
B., .B, BB, B., and .B
In the third sample case, the nine walls are the five as in the second sample case and in addition the following four:
B B
B B B B
B., .B, BB, and BB
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books).
# Zero Terminated Sum
Mary has another puzzle book, and it's up to you to help her out! This book is filled with zero-terminated substrings, and you have to find the substring with the largest sum of its digits. For example, one puzzle looks like this:
```
"72102450111111090"
```
Here, there are 4 different substrings: `721`, `245`, `111111`, and `9`. The sums of their digits are `10`, `11`, `6`, and `9` respectively. Therefore, the substring with the largest sum of its digits is `245`, and its sum is `11`.
Write a function `largest_sum` which takes a string and returns the maximum of the sums of the substrings. In the example above, your function should return `11`.
### Notes:
- A substring can have length 0. For example, `123004560` has three substrings, and the middle one has length 0.
- All inputs will be valid strings of digits, and the last digit will always be `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.
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
Input
The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.
Output
In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds.
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
3
3 2 2
Output
4
Input
4
2 2 2 2
Output
3
Note
You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Al Gorithm was reading a book about climate and oceans when he encountered the word “glaciological”. He thought it was quite curious, because it has the following interesting property: For every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ 1.
Chef Al was happy about this and called such words 1-good words. He also generalized the concept: He said a word was K-good if for every two letters in the word, if the first appears x times and the second appears y times, then |x - y| ≤ K.
Now, the Chef likes K-good words a lot and so was wondering: Given some word w, how many letters does he have to remove to make it K-good?
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of a single line containing two things: a word w and an integer K, separated by a space.
-----Output-----
For each test case, output a single line containing a single integer: the minimum number of letters he has to remove to make the word K-good.
-----Constraints-----
- 1 ≤ T ≤ 30
- 1 ≤ |w| ≤ 105
- 0 ≤ K ≤ 105
- w contains only lowercase English letters.
-----Example-----
Input:
4
glaciological 1
teammate 0
possessions 3
defenselessness 3
Output:
0
0
1
2
-----Explanation-----
Example case 1. The word “glaciological” is already 1-good, so the Chef doesn't have to remove any letter.
Example case 2. Similarly, “teammate” is already 0-good.
Example case 3. The word “possessions” is 4-good. To make it 3-good, the Chef can remove the last s to make “possession”.
Example case 4. The word “defenselessness” is 4-good. To make it 3-good, Chef Al can remove an s and an e to make, for example, “defenslesness”. Note that the word doesn't have to be a valid English word.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible — he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
Input
The first line contains six integers n, m, x1, y1, x2, y2 — the board sizes and the coordinates of the first and second chips, correspondingly (1 ≤ n, m ≤ 100; 2 ≤ n × m; 1 ≤ x1, x2 ≤ n; 1 ≤ y1, y2 ≤ m). The numbers in the line are separated by single spaces.
It is guaranteed that the chips are located in different squares.
Output
If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.
Examples
Input
1 6 1 2 1 6
Output
First
Input
6 5 4 3 2 1
Output
First
Input
10 10 1 1 10 10
Output
Second
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Generalized leap year
Normally, whether or not the year x is a leap year is defined as follows.
1. If x is a multiple of 400, it is a leap year.
2. Otherwise, if x is a multiple of 100, it is not a leap year.
3. Otherwise, if x is a multiple of 4, it is a leap year.
4. If not, it is not a leap year.
This can be generalized as follows. For a sequence A1, ..., An, we define whether the year x is a "generalized leap year" as follows.
1. For the smallest i (1 ≤ i ≤ n) such that x is a multiple of Ai, if i is odd, it is a generalized leap year, and if it is even, it is not a generalized leap year.
2. When such i does not exist, it is not a generalized leap year if n is odd, but a generalized leap year if n is even.
For example, when A = [400, 100, 4], the generalized leap year for A is equivalent to a normal leap year.
Given the sequence A1, ..., An and the positive integers l, r. Answer the number of positive integers x such that l ≤ x ≤ r such that year x is a generalized leap year for A.
Input
The input consists of up to 50 datasets. Each dataset is represented in the following format.
> n l r A1 A2 ... An
The integer n satisfies 1 ≤ n ≤ 50. The integers l and r satisfy 1 ≤ l ≤ r ≤ 4000. For each i, the integer Ai satisfies 1 ≤ Ai ≤ 4000.
The end of the input is represented by a line of three zeros.
Output
Print the answer in one line for each dataset.
Sample Input
3 1988 2014
400
100
Four
1 1000 1999
1
2 1111 3333
2
2
6 2000 3000
Five
7
11
9
3
13
0 0 0
Output for the Sample Input
7
1000
2223
785
Example
Input
3 1988 2014
400
100
4
1 1000 1999
1
2 1111 3333
2
2
6 2000 3000
5
7
11
9
3
13
0 0 0
Output
7
1000
2223
785
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 Hitachi string is a concatenation of one or more copies of the string `hi`.
For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not.
Given a string S, determine whether S is a Hitachi string.
Constraints
* The length of S is between 1 and 10 (inclusive).
* S is a string consisting of lowercase English letters.
Input
Input is given from Standard Input in the following format:
S
Output
If S is a Hitachi string, print `Yes`; otherwise, print `No`.
Examples
Input
hihi
Output
Yes
Input
hi
Output
Yes
Input
ha
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.
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.
At first day Mister B read v_0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v_0 pages, at second — v_0 + a pages, at third — v_0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v_1 pages per day.
Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.
Help Mister B to calculate how many days he needed to finish the book.
-----Input-----
First and only line contains five space-separated integers: c, v_0, v_1, a and l (1 ≤ c ≤ 1000, 0 ≤ l < v_0 ≤ v_1 ≤ 1000, 0 ≤ a ≤ 1000) — the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.
-----Output-----
Print one integer — the number of days Mister B needed to finish the book.
-----Examples-----
Input
5 5 10 5 4
Output
1
Input
12 4 12 4 1
Output
3
Input
15 1 100 0 0
Output
15
-----Note-----
In the first sample test the book contains 5 pages, so Mister B read it right at the first day.
In the second sample test at first day Mister B read pages number 1 - 4, at second day — 4 - 11, at third day — 11 - 12 and finished the book.
In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Binary with 0 and 1 is good, but binary with only 0 is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages.
Can you write a program that can send and receive this messages?
Rules
The input message consists of ASCII characters between 32 and 127 (7-bit)
The encoded output message consists of blocks of 0
A block is separated from another block by a space
Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):
First block is always 0 or 00. If it is 0, then the series contains 1, if not, it contains 0
The number of 0 in the second block is the number of bits in the series
Example
Let’s take a simple example with a message which consists of only one character (Letter 'C').'C' in binary is represented as 1000011, so with Chuck Norris’ technique this gives:
0 0 - the first series consists of only a single 1
00 0000 - the second series consists of four 0
0 00 - the third consists of two 1
So 'C' is coded as: 0 0 00 0000 0 00
Second example, we want to encode the message "CC" (i.e. the 14 bits 10000111000011) :
0 0 - one single 1
00 0000 - four 0
0 000 - three 1
00 0000 - four 0
0 00 - two 1
So "CC" is coded as: 0 0 00 0000 0 000 00 0000 0 00
Note of thanks
Thanks to the author of the original kata. I really liked this kata. I hope that other warriors will enjoy it too.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
Attention: we lost all the test cases for this problem, so instead of solving the problem, we need you to generate test cases. We're going to give you the answer, and you need to print a test case that produces the given answer. The original problem is in the following paragraph.
People don't use cash as often as they used to. Having a credit card solves some of the hassles of cash, such as having to receive change when you can't form the exact amount of money needed to purchase an item. Typically cashiers will give you as few coins as possible in change, but they don't have to. For example, if your change is 30 cents, a cashier could give you a 5 cent piece and a 25 cent piece, or they could give you three 10 cent pieces, or ten 1 cent pieces, two 5 cent pieces, and one 10 cent piece. Altogether there are 18 different ways to make 30 cents using only 1 cent pieces, 5 cent pieces, 10 cent pieces, and 25 cent pieces. Two ways are considered different if they contain a different number of at least one type of coin. Given the denominations of the coins and an amount of change to be made, how many different ways are there to make change?
As we mentioned before, we lost all the test cases for this problem, so we're actually going to give you the number of ways, and want you to produce a test case for which the number of ways is the given number. There could be many ways to achieve this (we guarantee there's always at least one), so you can print any, as long as it meets the constraints described below.
Input
Input will consist of a single integer A (1 ≤ A ≤ 105), the desired number of ways.
Output
In the first line print integers N and M (1 ≤ N ≤ 106, 1 ≤ M ≤ 10), the amount of change to be made, and the number of denominations, respectively.
Then print M integers D1, D2, ..., DM (1 ≤ Di ≤ 106), the denominations of the coins. All denominations must be distinct: for any i ≠ j we must have Di ≠ Dj.
If there are multiple tests, print any of them. You can print denominations in atbitrary order.
Examples
Input
18
Output
30 4
1 5 10 25
Input
3
Output
20 2
5 2
Input
314
Output
183 4
6 5 2 139
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.
Sometimes the government makes payouts to the poor: all citizens who have strictly less money than x are paid accordingly so that after the payout they have exactly x money. In this case the citizens don't send a receipt.
You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^{5}) — the numer of citizens.
The next line contains n integers a_1, a_2, ..., a_n (0 ≤ a_{i} ≤ 10^{9}) — the initial balances of citizens.
The next line contains a single integer q (1 ≤ q ≤ 2 ⋅ 10^{5}) — the number of events.
Each of the next q lines contains a single event. The events are given in chronological order.
Each event is described as either 1 p x (1 ≤ p ≤ n, 0 ≤ x ≤ 10^{9}), or 2 x (0 ≤ x ≤ 10^{9}). In the first case we have a receipt that the balance of the p-th person becomes equal to x. In the second case we have a payoff with parameter x.
Output
Print n integers — the balances of all citizens after all events.
Examples
Input
4
1 2 3 4
3
2 3
1 2 2
2 1
Output
3 2 3 4
Input
5
3 50 2 1 10
3
1 2 0
2 8
1 3 20
Output
8 8 20 8 10
Note
In the first example the balances change as follows: 1 2 3 4 → 3 3 3 4 → 3 2 3 4 → 3 2 3 4
In the second example the balances change as follows: 3 50 2 1 10 → 3 0 2 1 10 → 8 8 8 8 10 → 8 8 20 8 10
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?
He needs your help to check it.
A Minesweeper field is a rectangle $n \times m$, where each cell is either empty, or contains a digit from $1$ to $8$, or a bomb. The field is valid if for each cell: if there is a digit $k$ in the cell, then exactly $k$ neighboring cells have bombs. if the cell is empty, then all neighboring cells have no bombs.
Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $8$ neighboring cells).
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 100$) — the sizes of the field.
The next $n$ lines contain the description of the field. Each line contains $m$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $1$ to $8$, inclusive.
-----Output-----
Print "YES", if the field is valid and "NO" otherwise.
You can choose the case (lower or upper) for each letter arbitrarily.
-----Examples-----
Input
3 3
111
1*1
111
Output
YES
Input
2 4
*.*.
1211
Output
NO
-----Note-----
In the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.
You can read more about Minesweeper in Wikipedia's article.
Read the inputs from stdin solve the problem and write the answer to stdout (do 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 k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
All the numbers in the lines are separated by single spaces.
Output
On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.
Examples
Input
6 2
2 3 6 5 4 10
Output
3
Note
In the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.
Read the inputs from stdin solve the problem and write the answer to stdout (do not directly test on the sample inputs). Enclose your code within ```python delimiters.
|
Solve the programming task below in a Python markdown code block.
You are given N integers. The i-th integer is a_i. Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:
* Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.
Constraints
* 3 \leq N \leq 300
* 1 \leq a_i \leq 300(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_N
Output
Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.
Examples
Input
4
1
1
1
2
Output
18
Input
6
1
3
2
3
5
2
Output
150
Input
20
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
2
3
8
4
Output
563038556
Read the inputs from 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.