task_type stringclasses 4
values | problem stringlengths 14 5.23k | solution stringlengths 1 8.29k | problem_tokens int64 9 1.02k | solution_tokens int64 1 1.98k |
|---|---|---|---|---|
coding | Solve the programming task below in a Python markdown code block.
In a Circular City, there are $n$ houses, numbered from 1 to n and arranged in 1,2,...,n,1,2,...
Chef needs to deliver packages to $m$ (m≤n) houses.
Chef is initially at house 1. Chef decides an integer $x$ and stops after every $x$ houses. i.e- if $n=7$ and $x=2$. He will stop at 1,3,5,7,2,... He may deliver a package when he stops at a house. His work is done when all the packages are delivered.
What is the minimum number of times Chef has to stop, if he can choose any $x$ ?
__Note__: Starting point (1) is also counted in number of stops
------ Input: ------
First line will contain $n, m$, denoting number of houses and number of packages respectively.
Next line contains $m$ distinct space separated integers denoting the houses
------ Output: ------
Single line containing an integer denoting minimum number of stops.
------ Constraints ------
$3 ≤ n ≤ 1000$
$1 ≤ m ≤ n$
----- Sample Input 1 ------
5 3
1 2 4
----- Sample Output 1 ------
3
----- explanation 1 ------
For first input,
If Chef chooses $x=3$, he will stop at 1, 4, 2 before delivering all the packages.
----- Sample Input 2 ------
6 2
3 4
----- Sample Output 2 ------
4
----- explanation 2 ------
For second,
If Chef chooses $x=1$, he will stop at 1, 2, 3, 4 before delivering all the packages. | {"inputs": ["6 2\n3 4", "5 3\n1 2 4"], "outputs": ["4", "3"]} | 381 | 32 |
coding | Solve the programming task below in a Python markdown code block.
# Sort an array by value and index
Your task is to sort an array of integer numbers by the product of the value and the index of the positions.
For sorting the index starts at 1, NOT at 0!
The sorting has to be ascending.
The array will never be null and will always contain numbers.
Example:
```
Input: 23, 2, 3, 4, 5
Product of value and index:
23 => 23 * 1 = 23 -> Output-Pos 4
2 => 2 * 2 = 4 -> Output-Pos 1
3 => 3 * 3 = 9 -> Output-Pos 2
4 => 4 * 4 = 16 -> Output-Pos 3
5 => 5 * 5 = 25 -> Output-Pos 5
Output: 2, 3, 4, 23, 5
```
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have also created other katas. Take a look if you enjoyed this kata!
Also feel free to reuse/extend the following starter code:
```python
def sort_by_value_and_index(arr):
``` | {"functional": "_inputs = [[[1, 2, 3, 4, 5]], [[23, 2, 3, 4, 5]], [[26, 2, 3, 4, 5]], [[9, 5, 1, 4, 3]]]\n_outputs = [[[1, 2, 3, 4, 5]], [[2, 3, 4, 23, 5]], [[2, 3, 4, 5, 26]], [[1, 9, 5, 3, 4]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(sort_by_value_and_index(*i), o[0])"} | 288 | 275 |
coding | Solve the programming task below in a Python markdown code block.
You are given a string $s$ of length $n$ consisting of characters a and/or b.
Let $\operatorname{AB}(s)$ be the number of occurrences of string ab in $s$ as a substring. Analogically, $\operatorname{BA}(s)$ is the number of occurrences of ba in $s$ as a substring.
In one step, you can choose any index $i$ and replace $s_i$ with character a or b.
What is the minimum number of steps you need to make to achieve $\operatorname{AB}(s) = \operatorname{BA}(s)$?
Reminder:
The number of occurrences of string $d$ in $s$ as substring is the number of indices $i$ ($1 \le i \le |s| - |d| + 1$) such that substring $s_i s_{i + 1} \dots s_{i + |d| - 1}$ is equal to $d$. For example, $\operatorname{AB}($aabbbabaa$) = 2$ since there are two indices $i$: $i = 2$ where aabbbabaa and $i = 6$ where aabbbabaa.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 1000$). Description of the test cases follows.
The first and only line of each test case contains a single string $s$ ($1 \le |s| \le 100$, where $|s|$ is the length of the string $s$), consisting only of characters a and/or b.
-----Output-----
For each test case, print the resulting string $s$ with $\operatorname{AB}(s) = \operatorname{BA}(s)$ you'll get making the minimum number of steps.
If there are multiple answers, print any of them.
-----Examples-----
Input
4
b
aabbbabaa
abbb
abbaab
Output
b
aabbbabaa
bbbb
abbaaa
-----Note-----
In the first test case, both $\operatorname{AB}(s) = 0$ and $\operatorname{BA}(s) = 0$ (there are no occurrences of ab (ba) in b), so can leave $s$ untouched.
In the second test case, $\operatorname{AB}(s) = 2$ and $\operatorname{BA}(s) = 2$, so you can leave $s$ untouched.
In the third test case, $\operatorname{AB}(s) = 1$ and $\operatorname{BA}(s) = 0$. For example, we can change $s_1$ to b and make both values zero.
In the fourth test case, $\operatorname{AB}(s) = 2$ and $\operatorname{BA}(s) = 1$. For example, we can change $s_6$ to a and make both values equal to $1$. | {"inputs": ["4\nb\naabbbabaa\nabbb\nabbaab\n", "4\nb\naabbbabaa\nabbb\nabbaab\n", "4\na\naabbbabaa\nabbb\nabbaab\n", "4\nb\naabbbabaa\nabbb\nabbabb\n", "4\na\naabababaa\nabbb\nabbaab\n", "4\nb\naabbbacaa\nabbb\nabbabb\n", "4\nc\naabbbacaa\nabbb\nabbabb\n", "4\nc\naacabbbaa\nabbb\nabbabb\n"], "outputs": ["b\naabbbabaa\nbbbb\nbbbaab\n", "b\naabbbabaa\nbbbb\nbbbaab\n", "a\naabbbabaa\nbbbb\nbbbaab\n", "b\naabbbabaa\nbbbb\nbbbabb\n", "a\naabababaa\nbbbb\nbbbaab\n", "b\naabbbacaa\nbbbb\nbbbabb\n", "c\naabbbacaa\nbbbb\nbbbabb\n", "c\naacabbbaa\nbbbb\nbbbabb\n"]} | 656 | 262 |
coding | Solve the programming task below in a Python markdown code block.
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').
Find the maximum possible score of a'.
-----Constraints-----
- 1 ≤ N ≤ 10^5
- a_i is an integer.
- 1 ≤ a_i ≤ 10^9
-----Partial Score-----
- In the test set worth 300 points, N ≤ 1000.
-----Input-----
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_{3N}
-----Output-----
Print the maximum possible score of a'.
-----Sample Input-----
2
3 1 4 1 5 9
-----Sample Output-----
1
When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1. | {"inputs": ["1\n1 0 5", "1\n0 0 5", "1\n1 3 5", "1\n1 2 5", "1\n0 0 8", "1\n0 0 0", "1\n0 1 0", "1\n1 2 3"], "outputs": ["1\n", "0\n", "-2\n", "-1\n", "0\n", "0\n", "1\n", "-1"]} | 299 | 109 |
coding | Solve the programming task below in a Python markdown code block.
Pak Chanek has a grid that has $N$ rows and $M$ columns. Each row is numbered from $1$ to $N$ from top to bottom. Each column is numbered from $1$ to $M$ from left to right.
Each tile in the grid contains a number. The numbers are arranged as follows:
Row $1$ contains integers from $1$ to $M$ from left to right.
Row $2$ contains integers from $M+1$ to $2 \times M$ from left to right.
Row $3$ contains integers from $2 \times M+1$ to $3 \times M$ from left to right.
And so on until row $N$.
A domino is defined as two different tiles in the grid that touch by their sides. A domino is said to be tight if and only if the two numbers in the domino have a difference of exactly $1$. Count the number of distinct tight dominoes in the grid.
Two dominoes are said to be distinct if and only if there exists at least one tile that is in one domino, but not in the other.
-----Input-----
The only line contains two integers $N$ and $M$ ($1 \leq N, M \leq 10^9$) — the number of rows and columns in the grid.
-----Output-----
An integer representing the number of distinct tight dominoes in the grid.
-----Examples-----
Input
3 4
Output
9
Input
2 1
Output
1
-----Note-----
The picture below is the grid that Pak Chanek has in the first example.
The picture below is an example of a tight domino in the grid. | {"inputs": ["3 4\n", "2 1\n", "1 1\n", "1 2\n", "2 2\n", "1 999999997\n", "1 589284012\n", "999999999 1\n"], "outputs": ["9\n", "1\n", "0\n", "1\n", "2\n", "999999996\n", "589284011\n", "999999998\n"]} | 371 | 134 |
coding | Solve the programming task below in a Python markdown code block.
This is the harder version of the problem. In this version, $1 \le n \le 10^6$ and $0 \leq a_i \leq 10^6$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems
Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $n$ boxes of chocolate, numbered from $1$ to $n$. Initially, the $i$-th box contains $a_i$ chocolate pieces.
Since Bob is a typical nice guy, he will not send Alice $n$ empty boxes. In other words, at least one of $a_1, a_2, \ldots, a_n$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $k > 1$ such that the number of pieces in each box is divisible by $k$. Note that Alice won't mind if there exists some empty boxes.
Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $i$ and put it into either box $i-1$ or box $i+1$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the number of chocolate boxes.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^6$) — the number of chocolate pieces in the $i$-th box.
It is guaranteed that at least one of $a_1, a_2, \ldots, a_n$ is positive.
-----Output-----
If there is no way for Charlie to make Alice happy, print $-1$.
Otherwise, print a single integer $x$ — the minimum number of seconds for Charlie to help Bob make Alice happy.
-----Examples-----
Input
3
4 8 5
Output
9
Input
5
3 10 2 1 5
Output
2
Input
4
0 5 15 10
Output
0
Input
1
1
Output
-1
-----Note-----
In the first example, Charlie can move all chocolate pieces to the second box. Each box will be divisible by $17$.
In the second example, Charlie can move a piece from box $2$ to box $3$ and a piece from box $4$ to box $5$. Each box will be divisible by $3$.
In the third example, each box is already divisible by $5$.
In the fourth example, since Charlie has no available move, he cannot help Bob make Alice happy. | {"inputs": ["1\n1\n", "1\n1\n", "1\n25\n", "1\n835\n", "1\n2103\n", "1\n2103\n", "1\n2140\n", "3\n4 8 5\n"], "outputs": ["-1\n", "-1\n", "0\n", "0\n", "0\n", "0\n", "0\n", "9\n"]} | 678 | 103 |
coding | Solve the programming task below in a Python markdown code block.
You are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations?
Let's assume that the rows of matrix a are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. A matrix cell on the intersection of the i-th row and the j-th column can be represented as (i, j). Formally, a submatrix of matrix a is a group of four integers d, u, l, r (1 ≤ d ≤ u ≤ n; 1 ≤ l ≤ r ≤ m). We will assume that the submatrix contains cells (i, j) (d ≤ i ≤ u; l ≤ j ≤ r). The area of the submatrix is the number of cells it contains.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 5000). Next n lines contain m characters each — matrix a. Matrix a only contains characters: "0" and "1". Note that the elements of the matrix follow without any spaces in the lines.
Output
Print a single integer — the area of the maximum obtained submatrix. If we cannot obtain a matrix of numbers one, print 0.
Examples
Input
1 1
1
Output
1
Input
2 2
10
11
Output
2
Input
4 3
100
011
000
101
Output
2 | {"inputs": ["1 1\n0\n", "1 1\n1\n", "2 2\n10\n11\n", "4 3\n101\n011\n000\n101\n", "4 3\n101\n011\n101\n101\n", "4 3\n101\n011\n100\n101\n", "4 3\n100\n111\n000\n101\n", "4 3\n100\n011\n000\n101\n"], "outputs": ["0\n", "1\n", "2\n", "3\n", "4\n", "3\n", "3\n", "2\n"]} | 357 | 176 |
coding | Solve the programming task below in a Python markdown code block.
Write a program which calculates the area and perimeter of a given rectangle.
Constraints
* 1 ≤ a, b ≤ 100
Input
The length a and breadth b of the rectangle are given in a line separated by a single space.
Output
Print the area and perimeter of the rectangle in a line. The two integers should be separated by a single space.
Example
Input
3 5
Output
15 16 | {"inputs": ["0 5", "1 5", "1 3", "0 3", "0 1", "0 2", "0 4", "1 4"], "outputs": ["0 10\n", "5 12\n", "3 8\n", "0 6\n", "0 2\n", "0 4\n", "0 8\n", "4 10\n"]} | 104 | 97 |
coding | Solve the programming task below in a Python markdown code block.
Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!
The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.
Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!
How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules:
* for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible.
* if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F.
After the values of the error function have been calculated for all the potential addresses the most suitable one is found.
To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck!
Input
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105.
Output
On each n line of the output file print a single number: the value of the error function when the current potential address is chosen.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
2 10
codeforces
codeforces
codehorses
Output
0
12
Input
9 9
vkontakte
vcontacte
vkontrakte
vkollapse
vkrokodile
vtopke
vkapuste
vpechke
vk
vcodeforcese
Output
18
14
36
47
14
29
30
0
84 | {"inputs": ["3 3\nbyg\ndwg\nl\nx\n", "3 3\nbzg\ndwg\nl\nx\n", "4 4\nlocw\na\nr\nba\nxuv\n", "4 4\nlocw\na\ns\nba\nxuv\n", "4 4\nlocw\na\ns\nba\nwuv\n", "4 4\nlocw\na\ns\nba\nwtv\n", "4 4\nlodw\na\nr\nba\nxuv\n", "5 5\nvpjjx\njj\ne\nnor\nuthm\nbf\n"], "outputs": ["6\n1\n1\n", "6\n1\n1\n", "1\n1\n4\n9\n", "1\n1\n4\n9\n", "1\n1\n4\n9\n", "1\n1\n4\n9\n", "1\n1\n4\n9\n", "3\n1\n9\n16\n4\n"]} | 682 | 228 |
coding | Solve the programming task below in a Python markdown code block.
Lucy likes letters. She studied the definition of the lexicographical order at school and plays with it.
At first, she tried to construct the lexicographically smallest word out of given letters. It was so easy! Then she tried to build multiple words and minimize one of them. This was much harder!
Formally, Lucy wants to make n words of length l each out of the given n ⋅ l letters, so that the k-th of them in the lexicographic order is lexicographically as small as possible.
Input
The first line contains three integers n, l, and k (1≤ k ≤ n ≤ 1 000; 1 ≤ l ≤ 1 000) — the total number of words, the length of each word, and the index of the word Lucy wants to minimize.
The next line contains a string of n ⋅ l lowercase letters of the English alphabet.
Output
Output n words of l letters each, one per line, using the letters from the input. Words must be sorted in the lexicographic order, and the k-th of them must be lexicographically as small as possible. If there are multiple answers with the smallest k-th word, output any of them.
Examples
Input
3 2 2
abcdef
Output
af
bc
ed
Input
2 3 1
abcabc
Output
aab
bcc | {"inputs": ["1 1 1\nv\n", "1 1 1\nn\n", "1 1 1\nz\n", "1 1 1\nd\n", "1 1 1\nb\n", "1 1 1\ny\n", "1 1 1\nc\n", "1 1 1\nx\n"], "outputs": ["v\n", "n\n", "z\n", "d\n", "b\n", "y\n", "c\n", "x\n"]} | 306 | 118 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).
Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.
Please complete the following python code precisely:
```python
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
``` | {"functional": "def check(candidate):\n assert candidate(img = [[1,1,1],[1,0,1],[1,1,1]]) == [[0, 0, 0],[0, 0, 0], [0, 0, 0]]\n assert candidate(img = [[100,200,100],[200,50,200],[100,200,100]]) == [[137,141,137],[141,138,141],[137,141,137]]\n\n\ncheck(Solution().imageSmoother)"} | 171 | 155 |
coding | Solve the programming task below in a Python markdown code block.
After completing some serious investigation, Watson and Holmes are now chilling themselves in the Shimla hills. Very soon Holmes became bored. Holmes lived entirely for his profession. We know he is a workaholic. So Holmes wants to stop his vacation and get back to work. But after a tiresome season, Watson is in no mood to return soon. So to keep Holmes engaged, he decided to give Holmes one math problem. And Holmes agreed to solve the problem and said as soon as he solves the problem, they should return back to work. Watson too agreed.
The problem was as follows. Watson knows Holmes’ favorite numbers are 6 and 5. So he decided to give Holmes N single digit numbers. Watson asked Holmes to form a new number with the given N numbers in such a way that the newly formed number should be completely divisible by 5 and 6. Watson told Holmes that he should also form the number from these digits in such a way that the formed number is maximum. He may or may not use all the given numbers. But he is not allowed to use leading zeros. Though he is allowed to leave out some of the numbers, he is not allowed to add any extra numbers, which means the maximum count of each digit in the newly formed number, is the same as the number of times that number is present in those given N digits.
-----Input-----
The first line of input contains one integers T denoting the number of test cases.
Each test case consists of one integer N, number of numbers.
Next line contains contains N single digit integers
-----Output-----
For each test case output a single number, where the above said conditions are satisfied. If it is not possible to create such a number with the given constraints print -1.If there exists a solution, the maximised number should be greater than or equal to 0.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 10000
- 0 ≤ Each digit ≤ 9
-----Subtasks-----
Subtask #1 : (90 points)
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 10000
Subtask 2 : (10 points)
- 1 ≤ T ≤ 10
- 1 ≤ N≤ 10
-----Example-----
Input:
2
12
3 1 2 3 2 0 2 2 2 0 2 3
11
3 9 9 6 4 3 6 4 9 6 0
Output:
33322222200
999666330 | {"inputs": ["2\n12\n3 1 2 3 2 0 2 2 2 0 2 3\n11\n3 9 9 6 4 3 6 4 9 6 0"], "outputs": ["33322222200\n999666330"]} | 578 | 84 |
coding | 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)$. | {"inputs": ["1 1\n1\n", "1 1\n1\n", "2 3\n1 1\n", "2 3\n3 2\n", "2 3\n3 2\n", "2 3\n1 1\n", "2 4\n3 2\n", "2 20\n1 8\n"], "outputs": ["1\n", "1\n", "6\n", "5\n", "5\n", "6\n", "8\n", "210\n"]} | 461 | 117 |
coding | Solve the programming task below in a Python markdown code block.
Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key!
Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It doesn't matter if the ```A``` in the string is capitalized or not. When CapsLock is enabled, capitalization is reversed, but punctuation is not affected.
Examples:
```
"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."
"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."
"aAaaaaAaaaAAaAa"
-> ""
```
**Note!**
If (Caps Lock is Enabled) and then you (HOLD Shift + alpha character) it will always be the reverse
Examples:
```
(Caps Lock Enabled) + (HOLD Shift + Press 'b') = b
(Caps Lock Disabled) + (HOLD Shift + Press 'b') = B
```
If the given string is `""`, the answer should be evident.
Happy coding!
~~~if:fortran
*NOTE: In Fortran, your returned string is* **not** *permitted to contain any unnecessary leading/trailing whitespace.*
~~~
(Adapted from https://codegolf.stackexchange.com/questions/158132/no-a-just-caps-lock)
Also feel free to reuse/extend the following starter code:
```python
def fat_fingers(string):
``` | {"functional": "_inputs = [['aAaaaaAaaaAAaAa'], ['The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness.'], ['a99&a6/<a}']]\n_outputs = [[''], ['The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS.'], ['99&6/<}']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(fat_fingers(*i), o[0])"} | 554 | 405 |
coding | Solve the programming task below in a Python markdown code block.
Polycarp is a great fan of television.
He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment l_{i} and ends at moment r_{i}.
Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.
Polycarp wants to check out all n shows. Are two TVs enough to do so?
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 2·10^5) — the number of shows.
Each of the next n lines contains two integers l_{i} and r_{i} (0 ≤ l_{i} < r_{i} ≤ 10^9) — starting and ending time of i-th show.
-----Output-----
If Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).
-----Examples-----
Input
3
1 2
2 3
4 5
Output
YES
Input
4
1 2
2 3
2 3
1 2
Output
NO | {"inputs": ["2\n0 1\n0 1\n", "2\n0 4\n0 4\n", "2\n0 2\n0 6\n", "2\n2 5\n0 5\n", "2\n0 2\n0 6\n", "2\n0 1\n0 1\n", "2\n0 4\n0 4\n", "2\n2 5\n0 5\n"], "outputs": ["YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES"]} | 298 | 133 |
coding | Solve the programming task below in a Python markdown code block.
You are given $a$ uppercase Latin letters 'A' and $b$ letters 'B'.
The period of the string is the smallest such positive integer $k$ that $s_i = s_{i~mod~k}$ ($0$-indexed) for each $i$. Note that this implies that $k$ won't always divide $a+b = |s|$.
For example, the period of string "ABAABAA" is $3$, the period of "AAAA" is $1$, and the period of "AABBB" is $5$.
Find the number of different periods over all possible strings with $a$ letters 'A' and $b$ letters 'B'.
-----Input-----
The first line contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$) — the number of letters 'A' and 'B', respectively.
-----Output-----
Print the number of different periods over all possible strings with $a$ letters 'A' and $b$ letters 'B'.
-----Examples-----
Input
2 4
Output
4
Input
5 3
Output
5
-----Note-----
All the possible periods for the first example: $3$ "BBABBA" $4$ "BBAABB" $5$ "BBBAAB" $6$ "AABBBB"
All the possible periods for the second example: $3$ "BAABAABA" $5$ "BAABABAA" $6$ "BABAAABA" $7$ "BAABAAAB" $8$ "AAAAABBB"
Note that these are not the only possible strings for the given periods. | {"inputs": ["2 4\n", "5 3\n", "1 1\n", "1 2\n", "2 1\n", "1 3\n", "3 1\n", "2 2\n"], "outputs": ["4\n", "5\n", "1\n", "2\n", "2\n", "2\n", "2\n", "3\n"]} | 378 | 86 |
coding | Solve the programming task below in a Python markdown code block.
Chef is good at making pancakes. Generally he gets requests to serve N pancakes at once.
He serves them in the form of a stack.
A pancake can be treated as a circular disk with some radius.
Chef needs to take care that when he places a pancake on the top of the stack the radius of the pancake should not exceed the radius of the largest pancake in the stack by more than 1.
Additionally all radii should be positive integers, and the bottom most pancake should have its radius as 1.
Chef wants you to find out in how many ways can he create a stack containing N pancakes.
------ Input Format ------
First line of the input contains T (T ≤ 1000) denoting the number of test cases.
T lines follow each containing a single integer N (1 ≤ N ≤ 1000) denoting the size of the required stack.
------ Output Format ------
For each case the output should be a single integer representing the number of ways a stack of size N can be created. As the answer can be large print it modulo 1000000007.
----- Sample Input 1 ------
2
1
2
----- Sample Output 1 ------
1
2 | {"inputs": ["2\n1\n2", "2\n0\n2", "2\n0\n4", "2\n0\n5", "2\n0\n6", "2\n0\n8", "2\n1\n8", "2\n2\n8"], "outputs": ["1\n2", "0\n2\n", "0\n15\n", "0\n52\n", "0\n203\n", "0\n4140\n", "1\n4140\n", "2\n4140\n"]} | 272 | 122 |
coding | Solve the programming task below in a Python markdown code block.
You receive the name of a city as a string, and you need to return a string that shows how many times each letter shows up in the string by using an asterisk (`*`).
For example:
```
"Chicago" --> "c:**,h:*,i:*,a:*,g:*,o:*"
```
As you can see, the letter `c` is shown only once, but with 2 asterisks.
The return string should include **only the letters** (not the dashes, spaces, apostrophes, etc). There should be no spaces in the output, and the different letters are separated by a comma (`,`) as seen in the example above.
Note that the return string must list the letters in order of their first appearence in the original string.
More examples:
```
"Bangkok" --> "b:*,a:*,n:*,g:*,k:**,o:*"
"Las Vegas" --> "l:*,a:**,s:**,v:*,e:*,g:*"
```
Have fun! ;)
Also feel free to reuse/extend the following starter code:
```python
def get_strings(city):
``` | {"functional": "_inputs = [['Chicago'], ['Bangkok'], ['Las Vegas'], ['Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch']]\n_outputs = [['c:**,h:*,i:*,a:*,g:*,o:*'], ['b:*,a:*,n:*,g:*,k:**,o:*'], ['l:*,a:**,s:**,v:*,e:*,g:*'], ['l:***********,a:***,n:****,f:*,i:***,r:****,p:*,w:****,g:*******,y:*****,o:******,e:*,c:**,h:**,d:*,b:*,t:*,s:*']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(get_strings(*i), o[0])"} | 263 | 309 |
coding | Solve the programming task below in a Python markdown code block.
You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.
Here, a correct bracket sequence is defined as follows:
- () is a correct bracket sequence.
- If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.
- If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.
- Every correct bracket sequence can be derived from the rules above.
Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.
-----Constraints-----
- The length of S is N.
- 1 ≤ N ≤ 100
- S consists of ( and ).
-----Input-----
Input is given from Standard Input in the following format:
N
S
-----Output-----
Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.
-----Sample Input-----
3
())
-----Sample Output-----
(()) | {"inputs": ["3\n)()", "3\n)))", "3\n))(", "3\n(()", "3\n())", "3\n())\n", "6\n)())))", "6\n())())"], "outputs": ["()()\n", "((()))\n", "(())()\n", "(())\n", "(())", "(())\n", "(((()())))\n", "((())())\n"]} | 254 | 93 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).
For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even index but is not even.
Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.
A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Please complete the following python code precisely:
```python
class Solution:
def countGoodNumbers(self, n: int) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(n = 1) == 5\n assert candidate(n = 4) == 400\n assert candidate(n = 50) == 564908303\n\n\ncheck(Solution().countGoodNumbers)"} | 206 | 67 |
coding | Solve the programming task below in a Python markdown code block.
Since I got tired to write long problem statements, I decided to make this problem statement short. For given positive integer L, how many pairs of positive integers a, b (a ≤ b) such that LCM(a, b) = L are there? Here, LCM(a, b) stands for the least common multiple of a and b.
Constraints
* 1 ≤ L ≤ 1012
Input
For each dataset, an integer L is given in a line. Input terminates when L = 0.
Output
For each dataset, output the number of pairs of a and b.
Example
Input
12
9
2
0
Output
8
3
2 | {"inputs": ["12\n9\n3\n0", "12\n8\n2\n0", "12\n9\n0\n0", "12\n0\n3\n0", "12\n9\n1\n0", "12\n8\n1\n0", "12\n9\n4\n0", "12\n8\n0\n0"], "outputs": ["8\n3\n2\n", "8\n4\n2\n", "8\n3\n", "8\n", "8\n3\n1\n", "8\n4\n1\n", "8\n3\n3\n", "8\n4\n"]} | 157 | 142 |
coding | Solve the programming task below in a Python markdown code block.
Chef has recently learnt some new facts about the famous number π. For example, he was surprised that ordinary fractions are sometimes used to represent this number approximately. For example, 22/7, 355/113 or even 103993/33102.
Soon, by calculating the value of 22/7 and 355/113 on paper Chef became quite disappointed because these values are not precise enough. For example, 22/7 differs in the third digit after the decimal point. So, these values are definitely should not be used for serious calculations.
However, Chef doesn't know anything about 103993/33102. This fraction is quite inconvenient to calculate on paper. Chef is curious how precise this value is. So he asks you to help him and to calculate the first K digits after the decimal point of such an approximation of π. He consider this ordinary fraction as infinite decimal fraction so formally he asks you to calculate this approximation truncated to the first K digits after the decimal point.
------ Input ------
The first line of the input contains an integer T, denoting the number of test cases. The description of T test cases follows. The only line of each test case contains a single integer K.
------ Output ------
For each test case output a single line containing the value of 103993/33102 truncated to the first K digits after the decimal point. Note that for K = 0 you should output just "3" without decimal point (quotes are for clarity).
------ Constraints ------
$0 ≤ K ≤ 10^{6}$
$1 ≤ T ≤ 2000$
$The sum of K over the input does not exceed 10^{6}$
----- Sample Input 1 ------
3
0
6
20
----- Sample Output 1 ------
3
3.141592
3.14159265301190260407
----- explanation 1 ------
Example case 1. Here K = 0 so we don't need to output any digits after the decimal point. The decimal point itself also should not be output.
Example case 2. Note that here we truncate (not round) the actual value of 103993/33102 to 6 digits after the decimal point. As you see from example case 3 rounded value here differs from truncated one.
Example case 3. This example is only to show that this approximation of ? is also far from perfect :) | {"inputs": ["3\n1\n0\n0", "3\n1\n1\n0", "3\n2\n1\n0", "3\n2\n1\n1", "3\n0\n1\n1", "3\n1\n1\n1", "3\n1\n1\n2", "3\n1\n0\n1"], "outputs": ["3.1\n3\n3\n", "3.1\n3.1\n3\n", "3.14\n3.1\n3\n", "3.14\n3.1\n3.1\n", "3\n3.1\n3.1\n", "3.1\n3.1\n3.1\n", "3.1\n3.1\n3.14\n", "3.1\n3\n3.1\n"]} | 566 | 181 |
coding | Solve the programming task below in a Python markdown code block.
You are given an array $a$ consisting of $n$ integers. Let's denote monotonic renumeration of array $a$ as an array $b$ consisting of $n$ integers such that all of the following conditions are met:
$b_1 = 0$; for every pair of indices $i$ and $j$ such that $1 \le i, j \le n$, if $a_i = a_j$, then $b_i = b_j$ (note that if $a_i \ne a_j$, it is still possible that $b_i = b_j$); for every index $i \in [1, n - 1]$ either $b_i = b_{i + 1}$ or $b_i + 1 = b_{i + 1}$.
For example, if $a = [1, 2, 1, 2, 3]$, then two possible monotonic renumerations of $a$ are $b = [0, 0, 0, 0, 0]$ and $b = [0, 0, 0, 0, 1]$.
Your task is to calculate the number of different monotonic renumerations of $a$. The answer may be large, so print it modulo $998244353$.
-----Input-----
The first line contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of elements in $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).
-----Output-----
Print one integer — the number of different monotonic renumerations of $a$, taken modulo $998244353$.
-----Examples-----
Input
5
1 2 1 2 3
Output
2
Input
2
100 1
Output
2
Input
4
1 3 3 7
Output
4 | {"inputs": ["2\n100 1\n", "2\n000 1\n", "2\n000 2\n", "2\n010 2\n", "2\n011 2\n", "2\n100 1\n", "4\n1 3 3 7\n", "4\n1 3 1 7\n"], "outputs": ["2\n", "2\n", "2\n", "2\n", "2\n", "2\n", "4\n", "2\n"]} | 461 | 122 |
coding | Solve the programming task below in a Python markdown code block.
# Task
Write a function `deNico`/`de_nico()` that accepts two parameters:
- `key`/`$key` - string consists of unique letters and digits
- `message`/`$message` - string with encoded message
and decodes the `message` using the `key`.
First create a numeric key basing on the provided `key` by assigning each letter position in which it is located after setting the letters from `key` in an alphabetical order.
For example, for the key `crazy` we will get `23154` because of `acryz` (sorted letters from the key).
Let's decode `cseerntiofarmit on ` using our `crazy` key.
```
1 2 3 4 5
---------
c s e e r
n t i o f
a r m i t
o n
```
After using the key:
```
2 3 1 5 4
---------
s e c r e
t i n f o
r m a t i
o n
```
# Notes
- The `message` is never shorter than the `key`.
- Don't forget to remove trailing whitespace after decoding the message
# Examples
Check the test cases for more examples.
# Related Kata
[Basic Nico - encode](https://www.codewars.com/kata/5968bb83c307f0bb86000015)
Also feel free to reuse/extend the following starter code:
```python
def de_nico(key,msg):
``` | {"functional": "_inputs = [['crazy', 'cseerntiofarmit on '], ['crazy', 'cseerntiofarmit on'], ['abc', 'abcd'], ['ba', '2143658709'], ['a', 'message'], ['key', 'eky']]\n_outputs = [['secretinformation'], ['secretinformation'], ['abcd'], ['1234567890'], ['message'], ['key']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(de_nico(*i), o[0])"} | 359 | 242 |
coding | Solve the programming task below in a Python markdown code block.
A product-sum number is a natural number N which can be expressed as both the product and the sum of the same set of numbers.
N = a1 × a2 × ... × ak = a1 + a2 + ... + ak
For example, 6 = 1 × 2 × 3 = 1 + 2 + 3.
For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. The minimal product-sum numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows.
```
k=2: 4 = 2 × 2 = 2 + 2
k=3: 6 = 1 × 2 × 3 = 1 + 2 + 3
k=4: 8 = 1 × 1 × 2 × 4 = 1 + 1 + 2 + 4
k=5: 8 = 1 × 1 × 2 × 2 × 2 = 1 + 1 + 2 + 2 + 2
k=6: 12 = 1 × 1 × 1 × 1 × 2 × 6 = 1 + 1 + 1 + 1 + 2 + 6
```
Hence for 2 ≤ k ≤ 6, the sum of all the minimal product-sum numbers is 4+6+8+12 = 30; note that 8 is only counted once in the sum.
Your task is to write an algorithm to compute the sum of all minimal product-sum numbers where 2 ≤ k ≤ n.
Courtesy of ProjectEuler.net
Also feel free to reuse/extend the following starter code:
```python
def productsum(n):
``` | {"functional": "_inputs = [[3], [6], [12], [2]]\n_outputs = [[10], [30], [61], [4]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(productsum(*i), o[0])"} | 401 | 176 |
coding | Solve the programming task below in a Python markdown code block.
DNA sequencing data can be stored in many different formats. In this Kata, we will be looking at SAM formatting. It is a plain text file where every line (excluding the first header lines) contains data about a "read" from whatever sample the file comes from. Rather than focusing on the whole read, we will take two pieces of information: the cigar string and the nucleotide sequence.
The cigar string is composed of numbers and flags. It represents how the read aligns to what is known as a reference genome. A reference genome is an accepted standard for mapping the DNA.
The nucleotide sequence shows us what bases actually make up that section of DNA. They can be represented with the letters A, T, C, or G.
Example Read: ('36M', 'ACTCTTCTTGCGAAAGTTCGGTTAGTAAAGGGGATG')
The M in the above cigar string stands for "match", and the 36 stands for the length of the nucleotide sequence. Since all 36 bases are given the 'M' distinction, we know they all matched the reference.
Example Read: ('20M10S', 'ACTCTTCTTGCGAAAGTTCGGTTAGTAAAG')
In the above cigar string, only 20 have the "M" distinction, but the length of the actual string of nucleotides is 30. Therefore we know that read did not match the reference. (Don't worry about what the other letters mean. That will be covered in a later kata.)
Your job for this kata is to create a function that determines whether a cigar string fully matches the reference and accounts for all bases. If it does fully match, return True. If the numbers in the string do not match the full length of the string, return 'Invalid cigar'. If it does not fully match, return False.
*Note for C++: Return True, False, or Invalid cigar as strings*
Also feel free to reuse/extend the following starter code:
```python
def is_matched(read):
``` | {"functional": "_inputs = [[['36M', 'CATAATACTTTACCTACTCTCAACAAATGCGGGAGA']], [['10M6H', 'GAGCGAGTGCGCCTTAC']], [['12S', 'TGTTTCTCCAAG']]]\n_outputs = [[True], ['Invalid cigar'], [False]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(is_matched(*i), o[0])"} | 440 | 217 |
coding | Solve the programming task below in a Python markdown code block.
Consider a table of size $n \times m$, initially fully white. Rows are numbered $1$ through $n$ from top to bottom, columns $1$ through $m$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 115$) — the number of rows and the number of columns in the table.
The $i$-th of the next $n$ lines contains a string of $m$ characters $s_{i1} s_{i2} \ldots s_{im}$ ($s_{ij}$ is 'W' for white cells and 'B' for black cells), describing the $i$-th row of the table.
-----Output-----
Output two integers $r$ and $c$ ($1 \le r \le n$, $1 \le c \le m$) separated by a space — the row and column numbers of the center of the black square.
-----Examples-----
Input
5 6
WWBBBW
WWBBBW
WWBBBW
WWWWWW
WWWWWW
Output
2 4
Input
3 3
WWW
BWW
WWW
Output
2 1 | {"inputs": ["1 1\nB\n", "1 1\nB\n", "1 1\nB\n", "1 4\nWWBW\n", "1 4\nWWBW\n", "1 4\nWWWB\n", "1 4\nBWWW\n", "1 4\nWBWW\n"], "outputs": ["1 1\n", "1 1\n", "1 1\n", "1 3\n", "1 3\n", "1 4\n", "1 1\n", "1 2\n"]} | 295 | 123 |
coding | Solve the programming task below in a Python markdown code block.
A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input
The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).
Output
Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print - 1.
Examples
Input
1033
Output
33
Input
10
Output
0
Input
11
Output
-1
Note
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | {"inputs": ["7\n", "3\n", "5\n", "4\n", "2\n", "1\n", "74\n", "88\n"], "outputs": ["-1\n", "3\n", "-1\n", "-1\n", "-1\n", "-1\n", "-1\n", "-1\n"]} | 361 | 73 |
coding | Solve the programming task below in a Python markdown code block.
Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $q$ questions about this song. Each question is about a subsegment of the song starting from the $l$-th letter to the $r$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $k$ times, where $k$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $10$. Vasya is interested about the length of the resulting string.
Help Petya find the length of each string obtained by Vasya.
-----Input-----
The first line contains two integers $n$ and $q$ ($1\leq n\leq 100000$, $1\leq q \leq 100000$) — the length of the song and the number of questions.
The second line contains one string $s$ — the song, consisting of $n$ lowercase letters of English letters.
Vasya's questions are contained in the next $q$ lines. Each line contains two integers $l$ and $r$ ($1 \leq l \leq r \leq n$) — the bounds of the question.
-----Output-----
Print $q$ lines: for each question print the length of the string obtained by Vasya.
-----Examples-----
Input
7 3
abacaba
1 3
2 5
1 7
Output
4
7
11
Input
7 4
abbabaa
1 3
5 7
6 6
2 4
Output
5
4
1
5
Input
13 7
sonoshikumiwo
1 5
2 10
7 7
1 13
4 8
2 5
3 9
Output
82
125
9
191
62
63
97
-----Note-----
In the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to $4$. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is $7$. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length $11$. | {"inputs": ["7 3\nabacaba\n1 3\n2 5\n1 7\n", "7 3\nabacaba\n2 3\n2 5\n1 7\n", "7 3\nabacaba\n2 6\n2 5\n1 7\n", "7 3\nabacaba\n2 6\n2 6\n1 7\n", "7 3\nabacaba\n2 3\n4 5\n1 7\n", "7 1\nabacaba\n2 6\n2 5\n1 7\n", "7 2\nabacaba\n2 6\n2 6\n1 7\n", "7 3\nabacaba\n2 3\n4 5\n2 7\n"], "outputs": ["4\n7\n11\n", "3\n7\n11\n", "9\n7\n11\n", "9\n9\n11\n", "3\n4\n11\n", "9\n", "9\n9\n", "3\n4\n10\n"]} | 613 | 246 |
coding | Solve the programming task below in a Python markdown code block.
Find the intersection of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$.
Constraints
* $1 \leq n, m \leq 200,000$
* $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$
* $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$
Input
The input is given in the following format.
$n$
$a_0 \; a_1 \; ... \; a_{n-1}$
$m$
$b_0 \; b_1 \; ... \; b_{m-1}$
Elements of $A$ and $B$ are given in ascending order respectively. There are no duplicate elements in each set.
Output
Print elements in the intersection in ascending order. Print an element in a line.
Example
Input
4
1 2 5 8
5
2 3 5 9 11
Output
2
5 | {"inputs": ["4\n1 3 5 8\n5\n1 3 5 9 7", "4\n1 2 5 8\n5\n2 3 5 9 7", "4\n1 2 5 8\n7\n0 3 5 9 9", "4\n1 2 0 8\n9\n1 3 5 9 6", "4\n1 2 5 8\n5\n4 3 5 9 11", "4\n1 2 5 8\n9\n2 3 5 9 11", "4\n1 2 9 8\n5\n4 3 5 9 11", "4\n1 2 5 8\n9\n1 3 5 9 11"], "outputs": ["1\n3\n5\n", "2\n5\n", "5\n", "1\n", "5\n", "2\n5\n", "9\n", "1\n5\n"]} | 278 | 236 |
coding | Solve the programming task below in a Python markdown code block.
# Write Number in Expanded Form - Part 2
This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form).
You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/decimals.php#writing-a-decimal-in-expanded-form). For example:
```python
expanded_form(1.24) # Should return '1 + 2/10 + 4/100'
expanded_form(7.304) # Should return '7 + 3/10 + 4/1000'
expanded_form(0.04) # Should return '4/100'
```
Also feel free to reuse/extend the following starter code:
```python
def expanded_form(num):
``` | {"functional": "_inputs = [[1.24], [7.304], [0.04], [1.04], [7.3004], [0.004], [693.230459]]\n_outputs = [['1 + 2/10 + 4/100'], ['7 + 3/10 + 4/1000'], ['4/100'], ['1 + 4/100'], ['7 + 3/10 + 4/10000'], ['4/1000'], ['600 + 90 + 3 + 2/10 + 3/100 + 4/10000 + 5/100000 + 9/1000000']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(expanded_form(*i), o[0])"} | 202 | 332 |
coding | Solve the programming task below in a Python markdown code block.
You are given a positive integer N and an array A of size N. There are N lists L_{1}, L_{2} \ldots L_{N}. Initially, L_{i} = [A_{i}].
You can perform the following operation any number of times as long as there are at least 2 lists:
Select 2 (non-empty) lists L_{i} and L_{j} (i \neq j)
Append L_{j} to L_{i} and remove the list L_{j}. Note that this means L_{j} cannot be chosen in any future operation.
Find the minimum number of operations required to obtain a set of lists that satisfies the following conditions:
The first element and last element of each list are equal.
The first element of all the lists is the same.
Print -1 if it is not possible to achieve this via any sequence of operations.
------ Input Format ------
- The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains an integer N.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, print a single line containing one integer: the minimum number of operations required to obtain an array of lists that satisfies the given conditions.
Print -1 if it is impossible to achieve such an array of lists.
------ Constraints ------
$1 ≤ T ≤ 10^{5}$
$1 ≤ N ≤ 2 \cdot 10^{5}$
$1 ≤ A_{i} ≤ N$
- Sum of $N$ over all test cases doesn't exceed $2 \cdot 10^{5}$
------ subtasks ------
Subtask 1(100 points): Original constraints
----- Sample Input 1 ------
3
1
1
2
1 2
3
1 1 2
----- Sample Output 1 ------
0
-1
2
----- explanation 1 ------
Test case $1$: There is only one list $[1]$, and it trivially satisfies the condition so no operations are required.
Test case $2$: There are only $2$ ways to do an operation - either take list $[1]$ and append it to list $[2]$ or take list $[2]$ and append it to list $[1]$. In both cases, it is not possible to satisfy both given conditions at the same time. Hence, the answer is $-1$.
Test case $3$: Here is one possible order of operations:
- Select the $3$rd list $[2]$ and append it to the $1$st list $[1]$.
- Then, select the $2$nd list $[1]$ and append it to the $1$st list $[1, 2]$.
Finally, we are left with the single list $[1, 2, 1]$ which satisfies the given conditions. It can be verified that it is impossible to do this using less than $2$ operations. | {"inputs": ["3\n1\n1\n2\n1 2\n3\n1 1 2\n"], "outputs": ["0\n-1\n2\n"]} | 678 | 37 |
coding | Solve the programming task below in a Python markdown code block.
*Shamelessly stolen from Here :)*
Your server has sixteen memory banks; each memory bank can hold any number of blocks. You must write a routine to balance the blocks between the memory banks.
The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lowest-numbered memory bank) and redistributes those blocks among the banks. To do this, it removes all of the blocks from the selected bank, then moves to the next (by index) memory bank and inserts one of the blocks. It continues doing this until it runs out of blocks; if it reaches the last memory bank, it wraps around to the first one.
We need to know how many redistributions can be done before a blocks-in-banks configuration is produced that has been seen before.
For example, imagine a scenario with only four memory banks:
* The banks start with 0, 2, 7, and 0 blocks (`[0,2,7,0]`). The third bank has the most blocks (7), so it is chosen for redistribution.
* Starting with the next bank (the fourth bank) and then continuing one block at a time, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2.
* Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3.
* Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4.
* The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1.
* The third bank is chosen, and the same thing happens: 2 4 1 2.
At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite loop is detected after the fifth block redistribution cycle, and so the answer in this example is 5.
Return the number of redistribution cycles completed before a configuration is produced that has been seen before.
People seem to be struggling, so here's a visual walkthrough of the above example: http://oi65.tinypic.com/dmshls.jpg
Note: Remember, memory access is very fast. Yours should be too.
**Hint for those who are timing out:** Look at the number of cycles happening even in the sample tests. That's a _lot_ of different configurations, and a lot of different times you're going to be searching for a matching sequence. Think of ways to cut down on the time this searching process takes.
Please upvote if you enjoyed! :)
Also feel free to reuse/extend the following starter code:
```python
def mem_alloc(banks):
``` | {"functional": "_inputs = [[[5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 600]], [[53, 21, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 60]], [[14, 21, 10, 0, 1, 7, 0, 14, 3, 12, 8, 10, 17, 12, 0, 19]], [[5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 6]], [[17, 17, 3, 5, 1, 10, 6, 2, 0, 12, 8, 11, 16, 2, 1, 6]]]\n_outputs = [[70], [316], [826], [5042], [158378]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(mem_alloc(*i), o[0])"} | 668 | 454 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.
Return a list answer of size 2 where:
answer[0] is a list of all players that have not lost any matches.
answer[1] is a list of all players that have lost exactly one match.
The values in the two lists should be returned in increasing order.
Note:
You should only consider the players that have played at least one match.
The testcases will be generated such that no two matches will have the same outcome.
Please complete the following python code precisely:
```python
class Solution:
def findWinners(self, matches: List[List[int]]) -> List[List[int]]:
``` | {"functional": "def check(candidate):\n assert candidate(matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]) == [[1,2,10],[4,5,7,8]]\n assert candidate(matches = [[2,3],[1,3],[5,4],[6,4]]) == [[1,2,5,6],[]]\n\n\ncheck(Solution().findWinners)"} | 175 | 122 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.
Please complete the following python code precisely:
```python
class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(startTime = [1,2,3], endTime = [3,2,7], queryTime = 4) == 1\n assert candidate(startTime = [4], endTime = [4], queryTime = 4) == 1\n assert candidate(startTime = [4], endTime = [4], queryTime = 5) == 0\n assert candidate(startTime = [1,1,1,1], endTime = [1,3,2,4], queryTime = 7) == 0\n assert candidate(startTime = [9,8,7,6,5,4,3,2,1], endTime = [10,10,10,10,10,10,10,10,10], queryTime = 5) == 5\n\n\ncheck(Solution().busyStudent)"} | 130 | 195 |
coding | Solve the programming task below in a Python markdown code block.
Chef Zidane likes the number 9. He has a number N, and he wants to turn it into a multiple of 9. He cannot add or remove digits, and he can only change one digit at a time. The only allowed operation is to increment or decrement a digit by one, and doing this takes exactly one second. Note that he cannot increase a digit 9 or decrease a digit 0, and the resulting number must not contain any leading zeroes unless N has a single digit.
Chef Zidane wants to know the minimum amount of time (in seconds) needed to accomplish this. Please help him, before his kitchen gets overwhelmed with mist!
-----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 one line containing a single positive integer N.
-----Output-----
For each test case, output a single line containing the answer.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ N ≤ 10105
- N will not contain leading zeroes.
- Each test file is at most 3Mb in size.
-----Example-----
Input:4
1989
86236
90210
99999999999999999999999999999999999999988
Output:0
2
3
2
-----Explanation-----
Example case 1. 1989 is already divisible by 9, so no operations are needed to be performed.
Example case 2. 86236 can be turned into a multiple of 9 by incrementing the first and third digit (from the left), to get 96336. This takes 2 seconds.
Example case 3. 90210 can be turned into a multiple of 9 by decrementing the third digit twice and the fourth digit once, to get 90000. This takes 3 seconds. | {"inputs": ["4\n1989\n86236\n90210\n99999999999999999999999999999999999999988"], "outputs": ["0\n2\n3\n2"]} | 456 | 77 |
coding | Solve the programming task below in a Python markdown code block.
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In an operation, you select a prefix of a, and simultaneously invert the bits in the prefix (0 changes to 1 and 1 changes to 0) and reverse the order of the bits in the prefix.
For example, if a=001011 and you select the prefix of length 3, it becomes 011011. Then if you select the entire string, it becomes 001001.
Your task is to transform the string a into b in at most 3n operations. It can be proved that it is always possible.
Input
The first line contains a single integer t (1≤ t≤ 1000) — the number of test cases. Next 3t lines contain descriptions of test cases.
The first line of each test case contains a single integer n (1≤ n≤ 1000) — the length of the binary strings.
The next two lines contain two binary strings a and b of length n.
It is guaranteed that the sum of n across all test cases does not exceed 1000.
Output
For each test case, output an integer k (0≤ k≤ 3n), followed by k integers p_1,…,p_k (1≤ p_i≤ n). Here k is the number of operations you use and p_i is the length of the prefix you flip in the i-th operation.
Example
Input
5
2
01
10
5
01011
11100
2
01
01
10
0110011011
1000110100
1
0
1
Output
3 1 2 1
6 5 2 5 3 1 2
0
9 4 1 2 10 4 1 2 1 5
1 1
Note
In the first test case, we have 01→ 11→ 00→ 10.
In the second test case, we have 01011→ 00101→ 11101→ 01000→ 10100→ 00100→ 11100.
In the third test case, the strings are already the same. Another solution is to flip the prefix of length 2, which will leave a unchanged. | {"inputs": ["5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n", "5\n2\n01\n10\n5\n01011\n11110\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n", "5\n2\n01\n10\n5\n01001\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n", "5\n2\n01\n10\n5\n01011\n11100\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n0\n", "5\n2\n01\n10\n5\n01011\n11000\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n0\n", "5\n2\n01\n10\n5\n01011\n11000\n2\n01\n01\n10\n1110011011\n1000110100\n1\n0\n0\n", "5\n2\n01\n10\n5\n01011\n11101\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n1\n", "5\n2\n01\n10\n5\n01011\n11101\n2\n01\n01\n10\n0110011011\n1000110100\n1\n0\n0\n"], "outputs": ["3 1 2 1 \n3 1 5 2 \n0 \n7 1 10 8 7 1 2 1 \n1 1 \n", "3 1 2 1 \n5 1 5 4 1 2 \n0 \n7 1 10 8 7 1 2 1 \n1 1 \n", "3 1 2 1 \n3 1 5 1 \n0 \n7 1 10 8 7 1 2 1 \n1 1 \n", "3 1 2 1 \n3 1 5 2 \n0 \n7 1 10 8 7 1 2 1 \n0 \n", "3 1 2 1 \n5 1 5 1 3 1 \n0 \n7 1 10 8 7 1 2 1 \n0 \n", "3 1 2 1 \n5 1 5 1 3 1 \n0 \n6 10 8 7 1 2 1 \n0 \n", "3 1 2 1 \n5 1 4 3 1 2 \n0 \n7 1 10 8 7 1 2 1 \n1 1 \n", "3 1 2 1 \n5 1 4 3 1 2 \n0 \n7 1 10 8 7 1 2 1 \n0 \n"]} | 605 | 904 |
coding | Solve the programming task below in a Python markdown code block.
# Your Task
You have a Petri dish with bacteria, and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have `n` bacteria in the Petri dish and size of the i-th bacteria is bacteriai. Also you know intergalactic positive integer constant `K`.
The i-th bacteria can swallow the j-th bacteria if and only if bacteriai > bacteriaj and bacteriai ≤ bacteriaj + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size.
Since you don't have a microscope, you can only guess the minimal possible number of bacteria that will remain in your Petri dish when you finally find a microscope.
```python
micro_world([101, 53, 42, 102, 101, 55, 54], 1) == 3
micro_world([20, 15, 10, 15, 20, 25], 5) == 1
```
___
# Explanation
```python
bacteria = [101, 53, 42, 102, 101, 55, 54]
K = 1
```
```if:cpp
The one of possible sequences of swallows is: {101,53,42,102,101,55,54} → {101,53,42,102,55,54} → {101,42,102,55,54} → {42,102,55,54} → {42,102,55}. In total there are 3 bacteria remaining.
```
```if:python,ruby,javascript
The one of possible sequences of swallows is: [101,53,42,102,101,55,54] → [101,53,42,102,55,54] → [101,42,102,55,54] → [42,102,55,54] → [42,102,55]. In total there are 3 bacteria remaining.
```
Also feel free to reuse/extend the following starter code:
```python
def micro_world(bacteria, k):
``` | {"functional": "_inputs = [[[101, 53, 42, 102, 101, 55, 54], 1], [[20, 15, 10, 15, 20, 25], 5], [[5, 3, 1, 5], 1]]\n_outputs = [[3], [1], [4]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(micro_world(*i), o[0])"} | 564 | 234 |
coding | Solve the programming task below in a Python markdown code block.
A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_i < a_j$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1)$, $(4, 3)$.
You are given a permutation $p$ of size $n$. However, the numbers on some positions are replaced by $-1$. Let the valid permutation be such a replacement of $-1$ in this sequence back to numbers from $1$ to $n$ in such a way that the resulting sequence is a permutation of size $n$.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the sequence.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($-1 \le p_i \le n$, $p_i \ne 0$) — the initial sequence.
It is guaranteed that all elements not equal to $-1$ are pairwise distinct.
-----Output-----
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$.
-----Examples-----
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
-----Note-----
In the first example two resulting valid permutations are possible:
$[3, 1, 2]$ — $2$ inversions; $[3, 2, 1]$ — $3$ inversions.
The expected value is $\frac{2 \cdot 1 + 3 \cdot 1}{2} = 2.5$.
In the second example no $-1$ are present, thus the only valid permutation is possible — the given one. It has $0$ inversions.
In the third example there are two resulting valid permutations — one with $0$ inversions and one with $1$ inversion. | {"inputs": ["1\n1\n", "1\n1\n", "1\n-1\n", "1\n-1\n", "2\n1 2\n", "2\n2 1\n", "2\n1 2\n", "2\n-1 2\n"], "outputs": ["0\n", " 0", "0\n", " 0", "0\n", "1\n", " 0", "0\n"]} | 688 | 100 |
coding | Solve the programming task below in a Python markdown code block.
There is an easy way to obtain a new task from an old one called "Inverse the problem": we give an output of the original task, and ask to generate an input, such that solution to the original problem will produce the output we provided. The hard task of Topcoder Open 2014 Round 2C, InverseRMQ, is a good example.
Now let's create a task this way. We will use the task: you are given a tree, please calculate the distance between any pair of its nodes. Yes, it is very easy, but the inverse version is a bit harder: you are given an n × n distance matrix. Determine if it is the distance matrix of a weighted tree (all weights must be positive integers).
Input
The first line contains an integer n (1 ≤ n ≤ 2000) — the number of nodes in that graph.
Then next n lines each contains n integers di, j (0 ≤ di, j ≤ 109) — the distance between node i and node j.
Output
If there exists such a tree, output "YES", otherwise output "NO".
Examples
Input
3
0 2 7
2 0 9
7 9 0
Output
YES
Input
3
1 2 7
2 0 9
7 9 0
Output
NO
Input
3
0 2 2
7 0 9
7 9 0
Output
NO
Input
3
0 1 1
1 0 1
1 1 0
Output
NO
Input
2
0 0
0 0
Output
NO
Note
In the first example, the required tree exists. It has one edge between nodes 1 and 2 with weight 2, another edge between nodes 1 and 3 with weight 7.
In the second example, it is impossible because d1, 1 should be 0, but it is 1.
In the third example, it is impossible because d1, 2 should equal d2, 1. | {"inputs": ["1\n0\n", "1\n1\n", "1\n2\n", "1\n4\n", "1\n6\n", "1\n5\n", "1\n7\n", "1\n3\n"], "outputs": ["YES\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]} | 458 | 86 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Please complete the following python code precisely:
```python
class Solution:
def maxProduct(self, nums: List[int]) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(nums = [3,4,5,2]) == 12 \n assert candidate(nums = [1,5,4,5]) == 16\n assert candidate(nums = [3,7]) == 12\n\n\ncheck(Solution().maxProduct)"} | 84 | 73 |
coding | Solve the programming task below in a Python markdown code block.
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.
The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
Input
The first line contains the only integer q (1 ≤ q ≤ 1013).
Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
Output
In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.
Examples
Input
6
Output
2
Input
30
Output
1
6
Input
1
Output
1
0
Note
Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory. | {"inputs": ["9\n", "5\n", "2\n", "8\n", "3\n", "4\n", "7\n", "1\n"], "outputs": ["2\n", "1\n0\n", "1\n0\n", "1\n4\n", "1\n0\n", "2\n", "1\n0\n", "1\n0\n"]} | 418 | 82 |
coding | Solve the programming task below in a Python markdown code block.
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.
Input
The only line contains three integers n, a and b (0 ≤ a, b < n ≤ 100).
Output
Print the single number — the number of the sought positions.
Examples
Input
3 1 1
Output
2
Input
5 2 3
Output
3
Note
The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1).
In the second sample they are 3, 4 and 5. | {"inputs": ["9 4 3\n", "1 0 0\n", "6 5 5\n", "5 4 0\n", "9 4 4\n", "6 0 5\n", "3 0 1\n", "9 3 4\n"], "outputs": ["4", "1", "1", "1", "5\n", "6\n", "2\n", "5\n"]} | 178 | 98 |
coding | Solve the programming task below in a Python markdown code block.
Given are three positive integers A, B, and C. Compute the following value modulo 998244353:
\sum_{a=1}^{A} \sum_{b=1}^{B} \sum_{c=1}^{C} abc
-----Constraints-----
- 1 \leq A, B, C \leq 10^9
-----Input-----
Input is given from standard input in the following format:
A B C
-----Output-----
Print the value modulo 998244353.
-----Sample Input-----
1 2 3
-----Sample Output-----
18
We have: (1 \times 1 \times 1) + (1 \times 1 \times 2) + (1 \times 1 \times 3) + (1 \times 2 \times 1) + (1 \times 2 \times 2) + (1 \times 2 \times 3) = 1 + 2 + 3 + 2 + 4 + 6 = 18. | {"inputs": ["1 2 3\n", "88 395 518\n", "693 299 737\n", "198 235 277\n", "682152024 451794315 2028038\n", "192279221 156648747 154396385\n", "264704198 120999147 136987925\n", "1000000000 987654321 123456789\n"], "outputs": ["18\n", "572699487\n", "373149185\n", "518269127\n", "579633067\n", "152138957\n", "24444247\n", "951633476\n"]} | 246 | 270 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:
The 1st place athlete's rank is "Gold Medal".
The 2nd place athlete's rank is "Silver Medal".
The 3rd place athlete's rank is "Bronze Medal".
For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is "x").
Return an array answer of size n where answer[i] is the rank of the ith athlete.
Please complete the following python code precisely:
```python
class Solution:
def findRelativeRanks(self, score: List[int]) -> List[str]:
``` | {"functional": "def check(candidate):\n assert candidate(score = [5,4,3,2,1]) == [\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]\n assert candidate(score = [10,3,8,9,4]) == [\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]\n\n\ncheck(Solution().findRelativeRanks)"} | 226 | 92 |
coding | Solve the programming task below in a Python markdown code block.
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $i$-th page contains some mystery that will be explained on page $a_i$ ($a_i \ge i$).
Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $i$ such that Ivan already has read it, but hasn't read page $a_i$). After that, he closes the book and continues to read it on the following day from the next page.
How many days will it take to read the whole book?
-----Input-----
The first line contains single integer $n$ ($1 \le n \le 10^4$) — the number of pages in the book.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($i \le a_i \le n$), where $a_i$ is the number of page which contains the explanation of the mystery on page $i$.
-----Output-----
Print one integer — the number of days it will take to read the whole book.
-----Example-----
Input
9
1 3 3 6 7 6 8 8 9
Output
4
-----Note-----
Explanation of the example test:
During the first day Ivan will read only the first page. During the second day Ivan will read pages number $2$ and $3$. During the third day — pages $4$-$8$. During the fourth (and the last) day Ivan will read remaining page number $9$. | {"inputs": ["1\n1\n", "1\n1\n", "4\n1 2 4 4\n", "4\n1 2 4 4\n", "4\n2 2 4 4\n", "4\n2 4 4 4\n", "9\n1 3 3 6 7 6 8 8 9\n", "9\n1 3 3 6 7 6 8 8 9\n"], "outputs": ["1\n", "1\n", "3\n", "3\n", "2\n", "1\n", "4\n", "4\n"]} | 393 | 142 |
coding | Solve the programming task below in a Python markdown code block.
Alice is visiting New York City. To make the trip fun, Alice will take photos of the city skyline and give the set of photos as a present to Bob. However, she wants to find the set of photos with maximum beauty and she needs your help.
There are $n$ buildings in the city, the $i$-th of them has positive height $h_i$. All $n$ building heights in the city are different. In addition, each building has a beauty value $b_i$. Note that beauty can be positive or negative, as there are ugly buildings in the city too.
A set of photos consists of one or more photos of the buildings in the skyline. Each photo includes one or more buildings in the skyline that form a contiguous segment of indices. Each building needs to be in exactly one photo. This means that if a building does not appear in any photo, or if a building appears in more than one photo, the set of pictures is not valid.
The beauty of a photo is equivalent to the beauty $b_i$ of the shortest building in it. The total beauty of a set of photos is the sum of the beauty of all photos in it. Help Alice to find the maximum beauty a valid set of photos can have.
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 3 \cdot 10^5$), the number of buildings on the skyline.
The second line contains $n$ distinct integers $h_1, h_2, \ldots, h_n$ ($1 \le h_i \le n$). The $i$-th number represents the height of building $i$.
The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($-10^9 \le b_i \le 10^9$). The $i$-th number represents the beauty of building $i$.
-----Output-----
Print one number representing the maximum beauty Alice can achieve for a valid set of photos of the skyline.
-----Examples-----
Input
5
1 2 3 5 4
1 5 3 2 4
Output
15
Input
5
1 4 3 2 5
-3 4 -10 2 7
Output
10
Input
2
2 1
-2 -3
Output
-3
Input
10
4 7 3 2 5 1 9 10 6 8
-4 40 -46 -8 -16 4 -10 41 12 3
Output
96
-----Note-----
In the first example, Alice can achieve maximum beauty by taking five photos, each one containing one building.
In the second example, Alice can achieve a maximum beauty of $10$ by taking four pictures: three just containing one building, on buildings $1$, $2$ and $5$, each photo with beauty $-3$, $4$ and $7$ respectively, and another photo containing building $3$ and $4$, with beauty $2$.
In the third example, Alice will just take one picture of the whole city.
In the fourth example, Alice can take the following pictures to achieve maximum beauty: photos with just one building on buildings $1$, $2$, $8$, $9$, and $10$, and a single photo of buildings $3$, $4$, $5$, $6$, and $7$. | {"inputs": ["2\n2 1\n-2 -3\n", "1\n1\n1000000000\n", "1\n1\n-1000000000\n", "5\n1 2 3 5 4\n1 5 3 2 4\n", "5\n1 4 3 2 5\n-3 4 -10 2 7\n", "8\n8 7 3 2 6 4 1 5\n4 -1 4 -1 -1 2 2 3\n", "10\n5 1 6 2 8 3 4 10 9 7\n1 1 -1 -1 -1 1 -1 1 -1 1\n", "10\n4 7 3 2 5 1 9 10 6 8\n-4 40 -46 -8 -16 4 -10 41 12 3\n"], "outputs": ["-3\n", "1000000000\n", "-1000000000\n", "15\n", "10\n", "14\n", "5\n", "96\n"]} | 754 | 294 |
coding | Solve the programming task below in a Python markdown code block.
Give me Chocolate
Anushka wants to buy chocolates.there are many chocolates in front of her, tagged with their prices.
Anushka has only a certain amount to spend, and she wants to maximize the number of chocolates she buys with this money.
Given a list of prices and an amount to spend, what is the maximum number of chocolates Anushka can buy?
For example,
if prices =[1,2,3,4]
and Anushka has k=7 to spend, she can buy items [1,2,3] for 6 , or [3,4] for 7 units of currency. she would choose the first group of 3 items.
Input Format
The first line contains two integers, n and k , the number of priced chocolates and the amount Anushka has to spend.
The next line contains n space-separated integers prices[i]
Constraints
1<= n <= 105
1<= k <= 109
1<= prices[i] <= 109
A chocolate can't be bought multiple times.
Output Format
An integer that denotes the maximum number of chocolates Anushka can buy for her.
Sample Input
7 50
1 12 5 111 200 1000 10
Sample Output
4
Explanation
she can buy only 4 chocolatess at most. These chocolates have the following prices: 1, 12, 5, 10. | {"inputs": ["7 50\n1 12 5 111 200 1000 10"], "outputs": ["4"]} | 326 | 38 |
coding | Solve the programming task below in a Python markdown code block.
# The die is cast!
Your task in this kata is to write a "dice roller" that interprets a subset of [dice notation](http://en.wikipedia.org/wiki/Dice_notation).
# Description
In most role-playing games, die rolls required by the system are given in the form `AdX`. `A` and `X` are variables, separated by the letter **d**, which stands for *die* or *dice*.
- `A` is the number of dice to be rolled (usually omitted if 1).
- `X` is the number of faces of each die.
Here are some examples of input:
# Modifiers
As an addition to the above rules the input may also contain modifiers in the form `+N` or `-N` where `N` is an integer.
Here are some examples of input containing modifiers:
*Modifiers must be applied **after** all dice has been summed up.*
# Output
Your function must support two types of output depending on the second argument; *verbose* and *summed*.
## Summed output
If the verbose flag isn't set your function should sum up all the dice and modifiers and return the result as an integer.
## Verbose output
With the verbose flag your function should return an object/hash containing an array (`dice`) with all the dice rolls, and a integer (`modifier`) containing the sum of the modifiers which defaults to zero.
Example of verbose output:
# Invalid input
Here are some examples of invalid inputs:
# Additional information
- Your solution should ignore all whitespace.
- `roll` should return `false` for invalid input.
Also feel free to reuse/extend the following starter code:
```python
def roll(desc, verbose=False):
``` | {"functional": "_inputs = [[''], [{}], ['abc'], ['2d6+3 abc'], ['abc 2d6+3'], ['2d6++4']]\n_outputs = [[False], [False], [False], [False], [False], [False]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(roll(*i), o[0])"} | 370 | 198 |
coding | Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types:
* replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4);
* swap any pair of digits in string a.
Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.
Input
The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.
Output
Print on the single line the single number — the minimum number of operations needed to convert string a into string b.
Examples
Input
47
74
Output
1
Input
774
744
Output
1
Input
777
444
Output
3
Note
In the first sample it is enough simply to swap the first and the second digit.
In the second sample we should replace the second digit with its opposite.
In the third number we should replace all three digits with their opposites. | {"inputs": ["7\n4\n", "7\n7\n", "4\n7\n", "4\n4\n", "4\n46\n", "47\n77\n", "47\n47\n", "47\n44\n"], "outputs": ["1\n", "0\n", "1\n", "0\n", "0\n", "1\n", "0\n", "1\n"]} | 342 | 93 |
coding | Solve the programming task below in a Python markdown code block.
Limak can repeatedly remove one of the first two characters of a string, for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.
You are given N different strings S_1, S_2, \ldots, S_N. Among N \cdot (N-1) / 2 pairs (S_i, S_j), in how many pairs could Limak obtain one string from the other?
Constraints
* 2 \leq N \leq 200\,000
* S_i consists of lowercase English letters `a`-`z`.
* S_i \neq S_j
* 1 \leq |S_i|
* |S_1| + |S_2| + \ldots + |S_N| \leq 10^6
Input
Input is given from Standard Input in the following format.
N
S_1
S_2
\vdots
S_N
Output
Print the number of unordered pairs (S_i, S_j) where i \neq j and Limak can obtain one string from the other.
Examples
Input
3
abcxyx
cyx
abc
Output
1
Input
6
b
a
abc
c
d
ab
Output
5 | {"inputs": ["3\nabcxyx\ncyx\nabb", "3\nabxxyc\ncyx\nabb", "6\nb\na\nabb\nc\nd\nab", "6\nb\na\nabb\nc\nd\nba", "3\naxxbyc\ncyx\nabb", "3\naxxbyc\ncyx\naab", "3\naxxbyc\ncyw\naab", "3\naxxbyc\ncyw\nbaa"], "outputs": ["1\n", "0\n", "5\n", "4\n", "0\n", "0\n", "0\n", "0\n"]} | 289 | 145 |
coding | Solve the programming task below in a Python markdown code block.
A binary string is called *alternating* if no two adjacent characters of the string are equal. Formally, a binary string T of length M is called alternating if T_{i} \neq T_{i +1} for each 1 ≤ i < M.
For example, 0, 1, 01, 10, 101, 010, 1010 are alternating strings while 11, 001, 1110 are not.
You are given a binary string S of length N. You would like to rearrange the characters of S such that the length of the longest alternating substring of S is maximum. Find this maximum value.
A binary string is a string that consists of characters 0 and 1. A string a is a [substring] of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
------ Input Format ------
- The first line of input contains an integer T, denoting the number of test cases. The T test cases then follow:
- The first line of each test case contains an integer N.
- The second line of each test case contains the binary string S.
------ Output Format ------
For each test case, output the maximum possible length of the longest alternating substring of S after rearrangement.
------ Constraints ------
$1 ≤ T ≤ 10^{4}$
$1 ≤ N ≤ 10^{5}$
$S$ contains only the characters 0 and 1.
- Sum of $N$ over all test cases does not exceed $2 \cdot 10^{5}$.
----- Sample Input 1 ------
4
3
110
4
1010
4
0000
7
1101101
----- Sample Output 1 ------
3
4
1
5
----- explanation 1 ------
Test case $1$: Swapping the second and third characters makes $S=101$. Hence the length of the longest alternating substring is $3$ (choosing the entire string as a substring).
Test case $2$: The given string $S=1010$ is an alternating string of length $4$.
Test case $3$: The length of the longest alternating substring is $1$ for any rearrangement of $S=0000$.
Test case $4$: One possible rearrangement of $S$ is $1\underline{10101}1$, which has an alternating substring of length $5$ (the substring starting at index $2$ and ending at index $6$). | {"inputs": ["4\n3\n110\n4\n1010\n4\n0000\n7\n1101101\n"], "outputs": ["3\n4\n1\n5\n"]} | 590 | 50 |
coding | Solve the programming task below in a Python markdown code block.
For a collection of integers $S$, define $\operatorname{mex}(S)$ as the smallest non-negative integer that does not appear in $S$.
NIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times.
The universe can be represented as a 1-indexed array $a$ of length $n$. When NIT snaps his fingers, he does the following operation on the array:
He selects positive integers $l$ and $r$ such that $1\le l\le r\le n$. Let $w=\operatorname{mex}(\{a_l,a_{l+1},\dots,a_r\})$. Then, for all $l\le i\le r$, set $a_i$ to $w$.
We say the universe is destroyed if and only if for all $1\le i\le n$, $a_i=0$ holds.
Find the minimum number of times NIT needs to snap his fingers to destroy the universe. That is, find the minimum number of operations NIT needs to perform to make all elements in the array equal to $0$.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). Description of the test cases follows.
The first line of each test case contains one integer $n$ ($1\le n\le 10^5$).
The second line of each test case contains $n$ integers $a_1$, $a_2$, $\ldots$, $a_n$ ($0\le a_i\le 10^9$).
It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot 10^5$.
-----Output-----
For each test case, print one integer — the answer to the problem.
-----Examples-----
Input
4
4
0 0 0 0
5
0 1 2 3 4
7
0 2 3 0 1 2 0
1
1000000000
Output
0
1
2
1
-----Note-----
In the first test case, we do $0$ operations and all elements in the array are already equal to $0$.
In the second test case, one optimal way is doing the operation with $l=2$, $r=5$.
In the third test case, one optimal way is doing the operation twice, respectively with $l=4$, $r=4$ and $l=2$, $r=6$.
In the fourth test case, one optimal way is doing the operation with $l=1$, $r=1$. | {"inputs": ["4\n4\n0 0 0 0\n5\n0 1 2 3 4\n7\n0 2 3 0 1 2 0\n1\n1000000000\n"], "outputs": ["0\n1\n2\n1\n"]} | 613 | 71 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.
You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.
It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.
Return the original array nums. If there are multiple solutions, return any of them.
Please complete the following python code precisely:
```python
class Solution:
def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
``` | {"functional": "def check(candidate):\n assert candidate(adjacentPairs = [[2,1],[3,4],[3,2]]) == [1,2,3,4]\n assert candidate(adjacentPairs = [[4,-2],[1,4],[-3,1]]) == [-2,4,1,-3]\n assert candidate(adjacentPairs = [[100000,-100000]]) == [100000,-100000]\n\n\ncheck(Solution().restoreArray)"} | 194 | 120 |
coding | Solve the programming task below in a Python markdown code block.
You have two arrays A and B of size N and M respectively. You have to merge both the arrays to form a new array C of size N + M (the relative order of elements in the original arrays A and B should not change in the array C).
For e.g. if A = [{\color{blue}1}, {\color{blue}2}, {\color{blue}7} ] and B = [{\color{red}3}, {\color{red}6}, {\color{red}5}], one possible way to merge them to form C is: C = [{\color{blue}1}, {\color{red}3}, {\color{red}6}, {\color{blue}2}, {\color{red}5}, {\color{blue}7}].
Maximize the length of longest non-decreasing subsequence of the merged array C.
As a reminder, a non-decreasing subsequence of some array X is a sequence of indices i_{1}, i_{2}, ..., i_{k}, such that i_{1} < i_{2} < ... < i_{k} and X_{i_{1}} ≤ X_{i_{2}} ≤ ... ≤ X_{i_{k}}
------ Input Format ------
- The first line contains T - the number of test cases. Then the test cases follow.
- The first line of each test case contains two integers N and M - the size of the array A and B respectively.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \dots, A_{N} denoting the array A.
- The third line of each test case contains M space-separated integers B_{1}, B_{2}, \dots, B_{M} denoting the array B.
------ Output Format ------
For each test case, output the maximum possible length of longest non-decreasing subsequence in the merged array.
------ Constraints ------
$1 ≤ T ≤ 1000$
$1 ≤ N, M ≤ 10^{5}$
$1 ≤ A_{i}, B_{i} ≤ 10^{9}$
- It is guaranteed that the sum of $N$ over all test cases does not exceed $4 \cdot 10^{5}$.
- It is guaranteed that the sum of $M$ over all test cases does not exceed $4 \cdot 10^{5}$.
----- Sample Input 1 ------
2
3 2
6 4 5
1 3
2 3
1 3
2 2 4
----- Sample Output 1 ------
4
5
----- explanation 1 ------
Test Case-1: We can merge the arrays in the following way: $C = [{\color{blue}6}, {\color{red}1}, {\color{red}3}, {\color{blue}4}, {\color{blue}5}]$. The length of longest non-decreasing subsequence in this case is $4$.
Test Case-2: We can merge the arrays in the following way: $C = [{\color{blue}1}, {\color{red}2}, {\color{red}2}, {\color{blue}3}, {\color{red}4}]$. The length of longest non-decreasing subsequence in this case is $5$. | {"inputs": ["2\n3 2\n6 4 5\n1 3\n2 3\n1 3\n2 2 4\n"], "outputs": ["4\n5\n"]} | 715 | 44 |
coding | Solve the programming task below in a Python markdown code block.
Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.
Output
Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.
Examples
Input
2 2
1 0
1 1
1 1
Output
0
Input
4 5
0 0 1 0 1
0 1 1 1 0
1 0 1 0 1
1 1 1 1 1
2 3
Output
2
Note
In the second example the upper left square is (1,1) and the lower right is (3,2). | {"inputs": ["1 1\n1\n1 1\n", "1 1\n0\n1 1\n", "2 2\n1 1\n1 1\n1 1\n", "2 2\n1 0\n1 1\n1 1\n", "2 3\n1 0 1\n0 1 0\n3 2\n", "3 2\n1 1\n1 1\n1 0\n2 1\n", "2 3\n0 0 1\n0 1 0\n3 2\n", "2 3\n0 0 1\n1 1 0\n3 2\n"], "outputs": ["1", "0", "1\n", "0", "3", "1", "2\n", "3\n"]} | 606 | 181 |
coding | Solve the programming task below in a Python markdown code block.
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight: the queen's weight is 9, the rook's weight is 5, the bishop's weight is 3, the knight's weight is 3, the pawn's weight is 1, the king's weight isn't considered in evaluating position.
The player's weight equals to the sum of weights of all his pieces on the board.
As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
-----Input-----
The input contains eight lines, eight characters each — the board's description.
The white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters.
The white pieces are denoted as follows: the queen is represented is 'Q', the rook — as 'R', the bishop — as'B', the knight — as 'N', the pawn — as 'P', the king — as 'K'.
The black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively.
An empty square of the board is marked as '.' (a dot).
It is not guaranteed that the given chess position can be achieved in a real game. Specifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.
-----Output-----
Print "White" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, print "Black" if the weight of the black pieces is more than the weight of the white pieces and print "Draw" if the weights of the white and black pieces are equal.
-----Examples-----
Input
...QK...
........
........
........
........
........
........
...rk...
Output
White
Input
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR
Output
Draw
Input
rppppppr
...k....
........
........
........
........
K...Q...
........
Output
Black
-----Note-----
In the first test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals 5.
In the second test sample the weights of the positions of the black and the white pieces are equal to 39.
In the third test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals to 16. | {"inputs": ["...QK...\n........\n........\n........\n........\n........\n........\n...rk...\n", "rnbqkbnr\npppppppp\n........\n........\n........\n........\nPPPPPPPP\nRNBQKBNR\n", "rppppppr\n...k....\n........\n........\n........\n........\nK...Q...\n........\n", "....bQ.K\n.B......\n.....P..\n........\n........\n........\n...N.P..\n.....R..\n", "b....p..\nR.......\n.pP...b.\npp......\nq.PPNpPR\n..K..rNn\nP.....p.\n...Q..B.\n", "...Nn...\n........\n........\n........\n.R....b.\n........\n........\n......p.\n", "...p..Kn\n.....Pq.\n.R.rN...\n...b.PPr\np....p.P\n...B....\np.b.....\n..N.....\n", "q.......\nPPPPPPPP\n........\n........\n........\n........\n........\n........\n"], "outputs": ["White\n", "Draw\n", "Black\n", "White\n", "White\n", "White\n", "Black\n", "Black\n"]} | 596 | 315 |
coding | Solve the programming task below in a Python markdown code block.
Following on from [Part 1](http://www.codewars.com/kata/filling-an-array-part-1/), part 2 looks at some more complicated array contents.
So let's try filling an array with...
## ...square numbers
The numbers from `1` to `n*n`
## ...a range of numbers
A range of numbers starting from `start` and increasing by `step`
## ...random numbers
A bunch of random integers between `min` and `max`
## ...prime numbers
All primes starting from `2` (obviously)...
HOTE: All the above functions should take as their first parameter a number that determines the length of the returned array.
Also feel free to reuse/extend the following starter code:
```python
def squares(n):
``` | {"functional": "_inputs = [[5]]\n_outputs = [[[1, 4, 9, 16, 25]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(squares(*i), o[0])"} | 176 | 168 |
coding | Solve the programming task below in a Python markdown code block.
Given is a md5 hash of a five digits long PIN. It is given as string.
Md5 is a function to hash your password:
"password123" ===> "482c811da5d5b4bc6d497ffa98491e38"
Why is this useful?
Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only got the hash. The only way is cracking it, means try every combination, hash it and compare it with the hash you want to crack. (There are also other ways of attacking md5 but that's another story)
Every Website and OS is storing their passwords as hashes, so if a hacker gets access to the database, he can do nothing, as long the password is safe enough.
What is a hash:
https://en.wikipedia.org/wiki/Hash_function#:~:text=A%20hash%20function%20is%20any,table%20called%20a%20hash%20table.
What is md5:
https://en.wikipedia.org/wiki/MD5
Note: Many languages have build in tools to hash md5. If not, you can write your own md5 function or google for an example.
Here is another kata on generating md5 hashes:
https://www.codewars.com/kata/password-hashes
Your task is to return the cracked PIN as string.
This is a little fun kata, to show you, how weak PINs are and how important a bruteforce protection is, if you create your own login.
If you liked this kata, here is an extension with short passwords:
https://www.codewars.com/kata/59146f7b4670ba520900000a
Also feel free to reuse/extend the following starter code:
```python
def crack(hash):
``` | {"functional": "_inputs = [['827ccb0eea8a706c4c34a16891f84e7b'], ['86aa400b65433b608a9db30070ec60cd']]\n_outputs = [['12345'], ['00078']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(crack(*i), o[0])"} | 425 | 222 |
coding | Solve the programming task below in a Python markdown code block.
You are given three integers A, B and C.
Determine if there exists an equilateral triangle whose sides have lengths A, B and C.
Constraints
* All values in input are integers.
* 1 \leq A,B,C \leq 100
Input
Input is given from Standard Input in the following format:
A B C
Output
If there exists an equilateral triangle whose sides have lengths A, B and C, print `Yes`; otherwise, print `No`.
Examples
Input
2 2 2
Output
Yes
Input
3 4 5
Output
No | {"inputs": ["2 4 2", "0 0 0", "3 4 2", "2 6 2", "3 4 1", "2 7 2", "3 0 1", "1 7 2"], "outputs": ["No\n", "Yes\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]} | 141 | 94 |
coding | Solve the programming task below in a Python markdown code block.
Remember the movie with David Bowie: 'The Labyrinth'?
You can remember your childhood here: https://www.youtube.com/watch?v=2dgmgub8mHw
In this scene the girl is faced with two 'Knights" and two doors. One door leads the castle where the Goblin King and her kid brother is, the other leads to certain death. She can ask the 'Knights' a question to find out which door is the right one to go in. But...
One of them always tells the truth, and the other one always lies.
In this Kata one of the 'Knights' is on a coffee break, leaving the other one to watch the doors. You have to determine if the one there is the Knight(Truth teller) or Knave(Liar) based off of what he ```says```
Create a function:
```
def knight_or_knave(says):
# returns if knight or knave
```
Your function should determine if the input '''says''' is True or False and then return:
```'Knight!'``` if True or ```'Knave! Do not trust.'``` if False
Input will be either boolean values, or strings.
The strings will be simple statements that will be either true or false, or evaluate to True or False.
See example test cases for, well... examples
You will porbably need to ```eval(says)```
But note: Eval is evil, and is only here for this Kata as a game.
And remember the number one rule of The Labyrinth, even if it is easy, Don't ever say 'that was easy.'
Also feel free to reuse/extend the following starter code:
```python
def knight_or_knave(said):
``` | {"functional": "_inputs = [[True], [False], ['4+2==5'], ['2+2==4'], ['not True and False or False or False'], ['3 is 3'], ['True'], ['not True'], ['2+2==5'], ['4+1==5'], ['4 is 3'], ['9+2==3'], ['105+30076==30181'], ['3 is 3 is 3 is 9'], ['False'], ['\"orange\" is not \"red\"'], ['4 is \"blue\"'], ['True is not False']]\n_outputs = [['Knight!'], ['Knave! Do not trust.'], ['Knave! Do not trust.'], ['Knight!'], ['Knave! Do not trust.'], ['Knight!'], ['Knight!'], ['Knave! Do not trust.'], ['Knave! Do not trust.'], ['Knight!'], ['Knave! Do not trust.'], ['Knave! Do not trust.'], ['Knight!'], ['Knave! Do not trust.'], ['Knave! Do not trust.'], ['Knight!'], ['Knave! Do not trust.'], ['Knight!']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(knight_or_knave(*i), o[0])"} | 376 | 399 |
coding | Solve the programming task below in a Python markdown code block.
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.
The shop sells N kinds of cakes.
Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.
These values may be zero or negative.
Ringo has decided to have M pieces of cakes here. He will choose the set of cakes as follows:
- Do not have two or more pieces of the same kind of cake.
- Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity).
Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.
-----Constraints-----
- N is an integer between 1 and 1 \ 000 (inclusive).
- M is an integer between 0 and N (inclusive).
- x_i, y_i, z_i \ (1 \leq i \leq N) are integers between -10 \ 000 \ 000 \ 000 and 10 \ 000 \ 000 \ 000 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
N M
x_1 y_1 z_1
x_2 y_2 z_2
: :
x_N y_N z_N
-----Output-----
Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.
-----Sample Input-----
5 3
3 1 4
1 5 9
2 6 5
3 5 8
9 7 9
-----Sample Output-----
56
Consider having the 2-nd, 4-th and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:
- Beauty: 1 + 3 + 9 = 13
- Tastiness: 5 + 5 + 7 = 17
- Popularity: 9 + 8 + 9 = 26
The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 13 + 17 + 26 = 56. This is the maximum value. | {"inputs": ["5 3\n3 1 4\n1 5 9\n2 6 5\n3 5 8\n9 6 9", "5 3\n3 1 4\n1 5 9\n2 6 5\n3 5 1\n7 7 9", "5 3\n3 1 4\n1 5 9\n2 6 5\n3 5 8\n9 7 9", "5 3\n3 1 4\n1 5 9\n2 6 5\n3 5 8\n9 7 9\n", "5 3\n3 0 4\n1 5 18\n2 6 5\n3 5 8\n7 7 9", "5 3\n3 0 4\n1 5 18\n2 6 5\n3 5 4\n7 7 9", "5 5\n1 -2 4\n0 5 -6\n7 -8 -16\n-10 7 -12\n13 -3 15", "5 5\n1 -2 4\n-4 5 -9\n7 -8 -16\n-10 7 -12\n13 -3 15"], "outputs": ["55\n", "51\n", "56", "56\n", "63\n", "60\n", "27\n", "26\n"]} | 611 | 341 |
coding | Solve the programming task below in a Python markdown code block.
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into a pieces, and the second one — into b pieces.
Ivan knows that there will be n people at the celebration (including himself), so Ivan has set n plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met: Each piece of each cake is put on some plate; Each plate contains at least one piece of cake; No plate contains pieces of both cakes.
To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number x such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least x pieces of cake.
Help Ivan to calculate this number x!
-----Input-----
The first line contains three integers n, a and b (1 ≤ a, b ≤ 100, 2 ≤ n ≤ a + b) — the number of plates, the number of pieces of the first cake, and the number of pieces of the second cake, respectively.
-----Output-----
Print the maximum possible number x such that Ivan can distribute the cake in such a way that each plate will contain at least x pieces of cake.
-----Examples-----
Input
5 2 3
Output
1
Input
4 7 10
Output
3
-----Note-----
In the first example there is only one way to distribute cakes to plates, all of them will have 1 cake on it.
In the second example you can have two plates with 3 and 4 pieces of the first cake and two plates both with 5 pieces of the second cake. Minimal number of pieces is 3. | {"inputs": ["5 2 3\n", "5 5 6\n", "2 4 3\n", "2 1 1\n", "5 6 7\n", "5 2 8\n", "3 2 3\n", "5 7 8\n"], "outputs": ["1\n", "2\n", "3\n", "1\n", "2\n", "2\n", "1\n", "2\n"]} | 419 | 102 |
coding | Solve the programming task below in a Python markdown code block.
Switch/Case - Bug Fixing #6
Oh no! Timmy's evalObject function doesn't work. He uses Switch/Cases to evaluate the given properties of an object, can you fix timmy's function?
Also feel free to reuse/extend the following starter code:
```python
def eval_object(v):
``` | {"functional": "_inputs = [[{'a': 1, 'b': 1, 'operation': '+'}], [{'a': 1, 'b': 1, 'operation': '-'}], [{'a': 1, 'b': 1, 'operation': '/'}], [{'a': 1, 'b': 1, 'operation': '*'}], [{'a': 1, 'b': 1, 'operation': '%'}], [{'a': 1, 'b': 1, 'operation': '**'}]]\n_outputs = [[2], [0], [1], [1], [0], [1]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(eval_object(*i), o[0])"} | 79 | 274 |
coding | Solve the programming task below in a Python markdown code block.
Chef has an array A of size N and an integer K. He can perform the following operation on A any number of times:
Select any K distinct indices i_{1}, i_{2}, \ldots, i_{K} and increment the array elements at these K indices by 1.
Formally, set A_{i_{j}} := A_{i_{j}} + 1 for all 1 ≤ j ≤ K.
For example, if A = [3, 2, 8, 4, 6] and we select the indices 2, 3, 5, then A becomes [3, 2 + 1, 8 + 1, 4, 6 + 1] i.e. [3, 3, 9, 4, 7].
Determine if Chef can make the array A palindromic by applying the given operation any number of times.
Note: An array is called palindrome if it reads the same backwards and forwards, for e.g. [4, 10, 10, 4] and [7, 1, 7] are palindromic arrays.
------ Input Format ------
- The first line contains a single integer T — the number of test cases. Then the test cases follow.
- The first line of each test case contains two integers N and K — the size of the array A and the parameter mentioned in the statement.
- The second line of each test case contains N space-separated integers A_{1}, A_{2}, \dots, A_{N} denoting the array A.
------ Output Format ------
For each test case, output YES if we can make A palindromic by applying the given operation. Otherwise, output NO.
You may print each character of YES and NO in uppercase or lowercase (for example, yes, yEs, Yes will be considered identical).
------ Constraints ------
$1 ≤ T ≤ 10^{5}$
$1 ≤K ≤N ≤10^{5}$
$1 ≤A_{i} ≤10^{6}$
- Sum of $N$ over all test cases does not exceed $2 \cdot 10^{5}$.
----- Sample Input 1 ------
4
5 3
2 4 5 4 2
6 1
4 5 5 4 6 4
6 2
4 5 5 4 6 4
4 2
1 2 3 3
----- Sample Output 1 ------
YES
YES
YES
NO
----- explanation 1 ------
Test case $1$: The given array $A$ is already palindromic.
Test case $2$: We can apply the following operations:
- Select index $[4]$: $A$ becomes $[4, 5, 5, 5, 6, 4]$
- Select index $[2]$: $A$ becomes $[4, 6, 5, 5, 6, 4]$
Test case $3$: We can apply the following operations:
- Select index $[2, 4]$: $A$ becomes $[4, 6, 5, 5, 6, 4]$
Test case $4$: It can be proven that $A$ can not be converted into a palindrome using the given operations. | {"inputs": ["4\n5 3\n2 4 5 4 2\n6 1\n4 5 5 4 6 4\n6 2\n4 5 5 4 6 4\n4 2\n1 2 3 3\n"], "outputs": ["YES\nYES\nYES\nNO\n"]} | 728 | 78 |
coding | Solve the programming task below in a Python markdown code block.
Berland annual chess tournament is coming!
Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.
Thus, organizers should divide all 2·n players into two teams with n people each in such a way that the first team always wins.
Every chess player has its rating r_{i}. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win.
After teams assignment there will come a drawing to form n pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.
Is it possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing?
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 100).
The second line contains 2·n integers a_1, a_2, ... a_2n (1 ≤ a_{i} ≤ 1000).
-----Output-----
If it's possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing, then print "YES". Otherwise print "NO".
-----Examples-----
Input
2
1 3 2 4
Output
YES
Input
1
3 3
Output
NO | {"inputs": ["1\n3 3\n", "1\n2 3\n", "1\n2 1\n", "1\n8 6\n", "1\n2 3\n", "1\n2 1\n", "1\n8 6\n", "1\n2 5\n"], "outputs": ["NO\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n"]} | 378 | 102 |
coding | Solve the programming task below in a Python markdown code block.
Mislove had an array $a_1$, $a_2$, $\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it:
The number of different numbers in the array is not less than $l$ and is not greater than $r$;
For each array's element $a_i$ either $a_i = 1$ or $a_i$ is even and there is a number $\dfrac{a_i}{2}$ in the array.
For example, if $n=5$, $l=2$, $r=3$ then an array could be $[1,2,2,4,4]$ or $[1,1,1,1,2]$; but it couldn't be $[1,2,2,4,8]$ because this array contains $4$ different numbers; it couldn't be $[1,2,2,3,3]$ because $3$ is odd and isn't equal to $1$; and it couldn't be $[1,1,2,2,16]$ because there is a number $16$ in the array but there isn't a number $\frac{16}{2} = 8$.
According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array.
-----Input-----
The only input line contains three integers $n$, $l$ and $r$ ($1 \leq n \leq 1\,000$, $1 \leq l \leq r \leq \min(n, 20)$) — an array's size, the minimal number and the maximal number of distinct elements in an array.
-----Output-----
Output two numbers — the minimal and the maximal possible sums of all elements in an array.
-----Examples-----
Input
4 2 2
Output
5 7
Input
5 1 5
Output
5 31
-----Note-----
In the first example, an array could be the one of the following: $[1,1,1,2]$, $[1,1,2,2]$ or $[1,2,2,2]$. In the first case the minimal sum is reached and in the last case the maximal sum is reached.
In the second example, the minimal sum is reached at the array $[1,1,1,1,1]$, and the maximal one is reached at the array $[1,2,4,8,16]$. | {"inputs": ["4 2 2\n", "5 1 5\n", "1 1 1\n", "1 1 1\n", "2 1 1\n", "2 1 2\n", "2 2 2\n", "3 1 2\n"], "outputs": ["5 7\n", "5 31\n", "1 1\n", "1 1\n", "2 2\n", "2 3\n", "3 3\n", "3 5\n"]} | 561 | 119 |
coding | Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.
Alice has quarreled with Berta recently. Now she doesn't want to have anything in common with her!
Recently, they've received two collections of positive integers. The Alice's integers were A_{1}, A_{2}, ..., A_{N}, while Berta's were B_{1}, B_{2}, ..., B_{M}.
Now Alice wants to throw away the minimal amount of number from her collection so that their collections would have no common numbers, i.e. there won't be any number which is present in both collections. Please help Alice to find the minimal amount of numbers she would need to throw away.
------ Input ------
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two space-separated integer numbers N and M denoting the amount of numbers in Alice's and Berta's collections respectively.
The second line contains N space-separated integers A_{1}, A_{2}, ..., A_{N} denoting the numbers of Alice.
The third line contains M space-separated integers B_{1}, B_{2}, ..., B_{M} denoting the numbers of Berta.
------ Output ------
For each test case, output a single line containing the minimal amount of numbers Alice needs to throw away from her collection so that she wouldn't have any numbers in common with Berta.
------ Constraints ------
$1 ≤ A_{i}, B_{i} ≤ 10^{6}$
$All numbers are distinct within a single girl's collection.$
------ Subtasks ------
$Subtask #1 (47 points): T = 25, 1 ≤ N, M ≤ 1000$
$Subtask #2 (53 points): T = 5, 1 ≤ N, M ≤ 100000$
----- Sample Input 1 ------
2
3 4
1 2 3
3 4 5 6
3 3
1 2 3
4 5 6
----- Sample Output 1 ------
1
0
----- explanation 1 ------
Example case 1. If Alice throws away the number 3 from her collection, she would obtain {1, 2} which is disjoint with {3, 4, 5, 6}.
Example case 2. Girls don't have any number in common initially. So there is no need to throw away any number. | {"inputs": ["2\n3 4\n1 2 3\n3 4 5 6\n3 3\n1 2 3\n4 5 6"], "outputs": ["1\n0"]} | 545 | 48 |
coding | Solve the programming task below in a Python markdown code block.
Chef's current score is X. Each second, Chef will find the smallest [prime factor] of his score and add it to his score.
Determine the minimum time in seconds, after which his score becomes ≥ Y.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- Each test case consists of a single line containing two integers X and Y, the initial and required score of Chef.
------ Output Format ------
For each test case, output the minimum time in seconds, after which Chef's score becomes ≥ Y.
------ Constraints ------
$1 ≤ T ≤ 1000$
$2 ≤ X ≤ 10$
$20 ≤ Y ≤ 10^{9}$
----- Sample Input 1 ------
4
2 23
9 20
5 100
6 89
----- Sample Output 1 ------
11
5
46
42
----- explanation 1 ------
Test case $1$: The initial score is $2$. Chef needs the score to be at least $23$.
- The smallest prime factor of $2$ is $2$. Thus, the score increase to $2+2 = 4$.
- The smallest prime factor of $4$ is $2$. Thus, the score increase to $4+2 = 6$.
- Similarly, each time the score would be increased by $2$. Thus, after $11$ seconds, the score becomes $24$, which is $≥ 23$.
Test case $2$: The initial score is $9$. Chef needs the score to be at least $20$.
- The smallest prime factor of $9$ is $3$. Thus, the score increase to $9+3 = 12$.
- The smallest prime factor of $12$ is $2$. Thus, the score increase to $12+2 = 14$.
- The smallest prime factor of $14$ is $2$. Thus, the score increase to $14+2 = 16$.
- The smallest prime factor of $16$ is $2$. Thus, the score increase to $16+2 = 18$.
- The smallest prime factor of $18$ is $2$. Thus, the score increase to $18+2 = 20$.
Thus, after $5$ seconds, the score becomes $20$, which is $≥ 20$. | {"inputs": ["4\n2 23\n9 20\n5 100\n6 89\n"], "outputs": ["11\n5\n46\n42\n"]} | 546 | 44 |
coding | Solve the programming task below in a Python markdown code block.
Coders is about to start and Ram has not done dinner yet. So, he quickly goes to hostel mess and finds a long queue in front of food counter. But somehow he manages to take the food plate and reaches in front of the queue. The plates are divided into sections such that it has 2 rows and N columns.
Due to the crowd Ram knows that when he will get out of the queue the food will get mixed. So, he don't want to put food in two consecutive sections column wise
but he can put food in two consecutive sections row wise as spacing between the rows is good enough to take food out of the queue safely. If he doesn't like the food, he will not take food. You are given N and you have to tell the number of ways in which food can be taken without getting it mixed.
Input Format:
First line contains T which denotes number of test cases and each test case represents a single line containing the value of N.
Output Format
Output the total ways for each input.
SAMPLE INPUT
2
1
3
SAMPLE OUTPUT
4
25
Explanation
Explanation:
Case 1:
Plate has 2 rows and 1 column each. So, Ram can
Put food in upper section.
Put food in lower section.
Put food in both section.
Do Not food in either section.
Case 2:
Plate has 2 rows and 3 columns. So, possible ways for one row are PNN, PNP, NNN, NPN, NNP where P represents food taken and N represents food not taken.
Total possible ways are 25 because a way to put food in 1 row can correspond
to any of 5 ways on other row. | {"inputs": ["19\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19"], "outputs": ["4\n9\n25\n64\n169\n441\n1156\n3025\n7921\n20736\n54289\n142129\n372100\n974169\n2550409\n6677056\n17480761\n45765225\n119814916"]} | 367 | 169 |
coding | Solve the programming task below in a Python markdown code block.
Pushkar is very good in Number Theory. He takes two numbers $A\ and\ B$ and declares them a Pushkar Pair. Pushkar Pair has a property that $A$ has a $Modular\ Inverse$ modulo $B$.
He asks you to tell him the largest number $L$ that divides both of them.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers $A, B$.
-----Output:-----
For each testcase, output in a single line the integer $L$.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq A,B \leq 10^4$
-----Sample Input:-----
1
3 4
-----Sample Output:-----
1 | {"inputs": ["1\n3 4"], "outputs": ["1"]} | 199 | 16 |
coding | Solve the programming task below in a Python markdown code block.
John is very good in shooting. We wants to get admitted in HackerEarth Shooting Academy (HESA). But HESA take very hard interview process to select the candidates. In the Interview process, an assignment is given to John.
In this assignment, some amount X will be given to John. There are some targets to shoot and to fire a bullet there is some cost P is associated. When John will fire a bullet, P amount will be divided from its amount X.
NOTE: The amount will be divided if and only if P completely divides X.
At last, John will have to tell, On now many targets he shoot i.e. N and as well as remaining amount of the John. Help John to get selected in HESA.
INPUT:
First line contains number of test cases T.
For each test case, a single line represents two space separated integers X and P.
OUTPUT:
For each test case, print the value of N.
Constraints:
1 ≤ T ≤ 10
1 ≤ X , P ≤ 100000
SAMPLE INPUT
1
4 2
SAMPLE OUTPUT
2 0 | {"inputs": ["5\n27 3\n64 4\n23 5\n10 2\n12 4"], "outputs": ["3 0\n3 0\n0 23\n1 5\n1 3"]} | 244 | 56 |
coding | Solve the programming task below in a Python markdown code block.
You are given a string $s$, consisting only of Latin letters 'a', and a string $t$, consisting of lowercase Latin letters.
In one move, you can replace any letter 'a' in the string $s$ with a string $t$. Note that after the replacement string $s$ might contain letters other than 'a'.
You can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.
Two strings are considered different if they have different length, or they differ at some index.
-----Input-----
The first line contains a single integer $q$ ($1 \le q \le 10^4$) — the number of testcases.
The first line of each testcase contains a non-empty string $s$, consisting only of Latin letters 'a'. The length of $s$ doesn't exceed $50$.
The second line contains a non-empty string $t$, consisting of lowercase Latin letters. The length of $t$ doesn't exceed $50$.
-----Output-----
For each testcase, print the number of different strings $s$ that can be obtained after an arbitrary amount of moves (including zero). If the number is infinitely large, print -1. Otherwise, print the number.
-----Examples-----
Input
3
aaaa
a
aa
abc
a
b
Output
1
-1
2
-----Note-----
In the first example, you can replace any letter 'a' with the string "a", but that won't change the string. So no matter how many moves you make, you can't obtain a string other than the initial one.
In the second example, you can replace the second letter 'a' with "abc". String $s$ becomes equal to "aabc". Then the second letter 'a' again. String $s$ becomes equal to "aabcbc". And so on, generating infinitely many different strings.
In the third example, you can either leave string $s$ as is, performing zero moves, or replace the only 'a' with "b". String $s$ becomes equal to "b", so you can't perform more moves on it. | {"inputs": ["3\naaaa\na\naa\nabc\na\nb\n"], "outputs": ["1\n-1\n2\n"]} | 469 | 31 |
coding | Solve the programming task below in a Python markdown code block.
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by $i \operatorname{mod} j$. A Modular Equation, as Hamed's teacher described, is an equation of the form $a \operatorname{mod} x = b$ in which a and b are two non-negative integers and x is a variable. We call a positive integer x for which $a \operatorname{mod} x = b$ a solution of our equation.
Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations.
Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers a and b determines how many answers the Modular Equation $a \operatorname{mod} x = b$ has.
-----Input-----
In the only line of the input two space-separated integers a and b (0 ≤ a, b ≤ 10^9) are given.
-----Output-----
If there is an infinite number of answers to our equation, print "infinity" (without the quotes). Otherwise print the number of solutions of the Modular Equation $a \operatorname{mod} x = b$.
-----Examples-----
Input
21 5
Output
2
Input
9435152 272
Output
282
Input
10 10
Output
infinity
-----Note-----
In the first sample the answers of the Modular Equation are 8 and 16 since $21 \operatorname{mod} 8 = 21 \operatorname{mod} 16 = 5$ | {"inputs": ["1 0\n", "0 0\n", "5 2\n", "2 0\n", "2 0\n", "5 2\n", "1 0\n", "0 0\n"], "outputs": ["1\n", "infinity\n", "1\n", "2\n", "2", "1", "1", "infinity"]} | 407 | 82 |
coding | Solve the programming task below in a Python markdown code block.
Define a "prime prime" number to be a rational number written as one prime number over another prime number: `primeA / primeB` (e.g. `7/31`)
Given a whole number `N`, generate the number of "prime prime" rational numbers less than 1, using only prime numbers between `0` and `N` (non inclusive).
Return the count of these "prime primes", and the integer part of their sum.
## Example
```python
N = 6
# The "prime primes" less than 1 are:
2/3, 2/5, 3/5 # count: 3
2/3 + 2/5 + 3/5 = 1.6667 # integer part: 1
Thus, the function should return 3 and 1.
```
Also feel free to reuse/extend the following starter code:
```python
def prime_primes(N):
``` | {"functional": "_inputs = [[6], [4], [10], [65], [0], [1000], [666]]\n_outputs = [[[3, 1]], [[1, 0]], [[6, 3]], [[153, 63]], [[0, 0]], [[14028, 6266]], [[7260, 3213]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(prime_primes(*i), o[0])"} | 217 | 236 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a 0-indexed array of strings details. Each element of details provides information about a given passenger compressed into a string of length 15. The system is such that:
The first ten characters consist of the phone number of passengers.
The next character denotes the gender of the person.
The following two characters are used to indicate the age of the person.
The last two characters determine the seat allotted to that person.
Return the number of passengers who are strictly more than 60 years old.
Please complete the following python code precisely:
```python
class Solution:
def countSeniors(self, details: List[str]) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(details = [\"7868190130M7522\",\"5303914400F9211\",\"9273338290F4010\"]) == 2\n assert candidate(details = [\"1313579440F2036\",\"2921522980M5644\"]) == 0\n\n\ncheck(Solution().countSeniors)"} | 152 | 124 |
coding | Solve the programming task below in a Python markdown code block.
KISS stands for Keep It Simple Stupid.
It is a design principle for keeping things simple rather than complex.
You are the boss of Joe.
Joe is submitting words to you to publish to a blog. He likes to complicate things.
Define a function that determines if Joe's work is simple or complex.
Input will be non emtpy strings with no punctuation.
It is simple if:
``` the length of each word does not exceed the amount of words in the string ```
(See example test cases)
Otherwise it is complex.
If complex:
```python
return "Keep It Simple Stupid"
```
or if it was kept simple:
```python
return "Good work Joe!"
```
Note: Random test are random and nonsensical. Here is a silly example of a random test:
```python
"jump always mostly is touchy dancing choice is pineapples mostly"
```
Also feel free to reuse/extend the following starter code:
```python
def is_kiss(words):
``` | {"functional": "_inputs = [['Joe had a bad day'], ['Joe had some bad days'], ['Joe is having no fun'], ['Sometimes joe cries for hours'], ['Joe is having lots of fun'], ['Joe is working hard a lot'], ['Joe listened to the noise and it was an onamonapia'], ['Joe listened to the noises and there were some onamonapias']]\n_outputs = [['Good work Joe!'], ['Good work Joe!'], ['Keep It Simple Stupid'], ['Keep It Simple Stupid'], ['Good work Joe!'], ['Keep It Simple Stupid'], ['Good work Joe!'], ['Keep It Simple Stupid']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(is_kiss(*i), o[0])"} | 218 | 274 |
coding | Solve the programming task below in a Python markdown code block.
Chef found N magical cards in his drawer. Each card has a number written on each of its faces. He places all the cards on the table in a front face-up manner.
Chef denotes the numbers on the front face by A_{1}, A_{2},..., A_{N} and on the back face by B_{1}, B_{2},..., B_{N}. Chef can choose some (possibly zero or all) cards and flip them, then he will calculate the [bitwise AND] of all the numbers currently in a face-up manner.
Now Chef wonders what is the *maximum* bitwise AND that he can achieve and what is the *minimum* number of cards he has to flip to achieve this value. Can you help him find it?
------ Input Format ------
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- Each test case contains three lines of input.
- The first line contains a single integer N - the number of cards.
- The second line contains N space-separated integers A_{1}, A_{2},..., A_{N} - the numbers on the front face of the cards
- The third line contains N space-separated integers B_{1}, B_{2},..., B_{N} - the numbers on the back face of the cards
------ Output Format ------
For each test case, print a single line containing two space-separated integers, first denoting the maximum bitwise AND possible and second denoting the minimum number of flips required to achieve it.
------ Constraints ------
$1 ≤ T ≤ 10^{4}$
$1 ≤ N ≤ 10^{5}$
$0 ≤ A_{i} ≤ 2^{30} - 1$
$0 ≤ B_{i} ≤ 2^{30} - 1$
- Sum of $N$ over all testcases does not exceeds $10^{5}$.
----- Sample Input 1 ------
3
3
4 6 8
2 1 2
3
0 2 0
2 0 8
3
1 2 1
2 3 6
----- Sample Output 1 ------
2 2
0 0
2 2
----- explanation 1 ------
Test case $1$: The maximum AND is obtained after flipping the first and third cards achieving a configuration of $[2, 6, 2]$ which yields a bitwise AND of $2$.
Test case $2$: Every possible configuration of the cards yields a bitwise AND equal to $0$. So to ensure the minimum number of operations, Chef performs no flip. | {"inputs": ["3\n3\n4 6 8\n2 1 2\n3\n0 2 0\n2 0 8\n3\n1 2 1\n2 3 6"], "outputs": ["2 2\n0 0\n2 2"]} | 568 | 64 |
coding | Solve the programming task below in a Python markdown code block.
You are parking at a parking lot. You can choose from the following two fee plans:
- Plan 1: The fee will be A×T yen (the currency of Japan) when you park for T hours.
- Plan 2: The fee will be B yen, regardless of the duration.
Find the minimum fee when you park for N hours.
-----Constraints-----
- 1≤N≤20
- 1≤A≤100
- 1≤B≤2000
- All input values are integers.
-----Input-----
Input is given from Standard Input in the following format:
N A B
-----Output-----
When the minimum fee is x yen, print the value of x.
-----Sample Input-----
7 17 120
-----Sample Output-----
119
- If you choose Plan 1, the fee will be 7×17=119 yen.
- If you choose Plan 2, the fee will be 120 yen.
Thus, the minimum fee is 119 yen. | {"inputs": ["7 17 120\n", "5 20 100\n", "6 18 100\n"], "outputs": ["119\n", "100\n", "100\n"]} | 234 | 57 |
coding | Solve the programming task below in a Python markdown code block.
In this task Anna and Maria play the following game. Initially they have a checkered piece of paper with a painted n × m rectangle (only the border, no filling). Anna and Maria move in turns and Anna starts. During each move one should paint inside the last-painted rectangle a new lesser rectangle (along the grid lines). The new rectangle should have no common points with the previous one. Note that when we paint a rectangle, we always paint only the border, the rectangles aren't filled.
Nobody wins the game — Anna and Maria simply play until they have done k moves in total. Count the number of different ways to play this game.
Input
The first and only line contains three integers: n, m, k (1 ≤ n, m, k ≤ 1000).
Output
Print the single number — the number of the ways to play the game. As this number can be very big, print the value modulo 1000000007 (109 + 7).
Examples
Input
3 3 1
Output
1
Input
4 4 1
Output
9
Input
6 7 2
Output
75
Note
Two ways to play the game are considered different if the final pictures are different. In other words, if one way contains a rectangle that is not contained in the other way.
In the first sample Anna, who performs her first and only move, has only one possible action plan — insert a 1 × 1 square inside the given 3 × 3 square.
In the second sample Anna has as much as 9 variants: 4 ways to paint a 1 × 1 square, 2 ways to insert a 1 × 2 rectangle vertically, 2 more ways to insert it horizontally and one more way is to insert a 2 × 2 square. | {"inputs": ["5 5 3\n", "5 7 2\n", "2 2 1\n", "3 5 1\n", "3 6 1\n", "1 5 3\n", "5 4 2\n", "2 2 2\n"], "outputs": ["0\n", "15\n", "0\n", "6\n", "10\n", "0\n", "0\n", "0\n"]} | 401 | 104 |
coding | Solve the programming task below in a Python markdown code block.
Problem
One day, mo3tthi and tubuann decided to play a game with magic pockets and biscuits.
Now there are $ K $ pockets, numbered $ 1,2, \ ldots, K $.
The capacity of the $ i $ th pocket is $ M_i $, which initially contains $ N_i $ biscuits.
mo3tthi and tubuann start with mo3tthi and perform the following series of operations alternately.
* Choose one pocket.
* Perform one of the following operations only once. However, if the number of biscuits in the pocket selected as a result of the operation exceeds the capacity of the pocket, the operation cannot be performed.
* Stroking the selected pocket. Magical power increases the number of biscuits in your chosen pocket by $ 1 $.
* Hit the selected pocket. The number of biscuits in the pocket chosen by magical power is doubled by $ 2 $.
The game ends when you can't operate it, the person who can't operate loses, and the person who doesn't can win.
You, a friend of mo3tthi, were asked by mo3tthi in advance if you could decide if you could win this game.
For mo3tthi, make a program to determine if mo3tthi can definitely win this game.
Constraints
The input satisfies the following conditions.
* $ 1 \ leq K \ leq 10 ^ 5 $
* $ 1 \ leq N_i \ leq M_i \ leq 10 ^ {18} $
* All inputs are integers
Input
The input is given in the following format.
$ K $
$ N_1 $ $ M_1 $
$ \ vdots $
$ N_K $ $ M_K $
Output
When mo3tthi acts optimally, "mo3tthi" is output on one line if he can win, and "tubuann" is output otherwise.
Examples
Input
1
2 4
Output
mo3tthi
Input
2
2 3
3 8
Output
tubuann
Input
10
2 8
5 9
7 20
8 41
23 48
90 112
4 5
7 7
2344 8923
1 29
Output
mo3tthi | {"inputs": ["1\n2 5", "1\n2 6", "1\n2 7", "1\n1 6", "1\n4 5", "1\n4 6", "1\n3 5", "1\n2 3"], "outputs": ["mo3tthi\n", "mo3tthi\n", "mo3tthi\n", "tubuann\n", "mo3tthi\n", "tubuann\n", "tubuann\n", "mo3tthi\n"]} | 528 | 123 |
coding | Solve the programming task below in a Python markdown code block.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
-----Input-----
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10^6) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
-----Output-----
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
-----Examples-----
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
-----Note-----
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | {"inputs": ["1 1 1\nX\n", "1 1 1\nX\n", "1 1 2\nX\n", "1 1 1\nX\n", "1 1 2\nX\n", "1 2 2\nX.\n", "1 2 2\n.X\n", "1 2 2\nX*\n"], "outputs": ["IMPOSSIBLE\n", "IMPOSSIBLE\n", "IMPOSSIBLE\n", "IMPOSSIBLE\n", "IMPOSSIBLE\n", "RL\n", "LR\n", "IMPOSSIBLE\n"]} | 595 | 138 |
coding | Solve the programming task below in a Python markdown code block.
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s_1 = a), and the difference between any two neighbouring elements is equal to c (s_{i} - s_{i} - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that s_{i} = b. Of course, you are the person he asks for a help.
-----Input-----
The first line of the input contain three integers a, b and c ( - 10^9 ≤ a, b, c ≤ 10^9) — the first element of the sequence, Vasya's favorite number and the difference between any two neighbouring elements of the sequence, respectively.
-----Output-----
If b appears in the sequence s print "YES" (without quotes), otherwise print "NO" (without quotes).
-----Examples-----
Input
1 7 3
Output
YES
Input
10 10 0
Output
YES
Input
1 -4 5
Output
NO
Input
0 60 50
Output
NO
-----Note-----
In the first sample, the sequence starts from integers 1, 4, 7, so 7 is its element.
In the second sample, the favorite integer of Vasya is equal to the first element of the sequence.
In the third sample all elements of the sequence are greater than Vasya's favorite integer.
In the fourth sample, the sequence starts from 0, 50, 100, and all the following elements are greater than Vasya's favorite integer. | {"inputs": ["1 7 3\n", "0 1 0\n", "0 0 0\n", "0 0 1\n", "0 0 2\n", "0 1 0\n", "0 1 1\n", "0 1 2\n"], "outputs": ["YES\n", "NO\n", "YES\n", "YES\n", "YES\n", "NO\n", "YES\n", "NO\n"]} | 378 | 102 |
coding | Solve the programming task below in a Python markdown code block.
# Problem
In China,there is an ancient mathematical book, called "The Mathematical Classic of Sun Zi"(《孙子算经》). In the book, there is a classic math problem: “今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?”
Ahh, Sorry. I forgot that you don't know Chinese. Let's translate it to English:
There is a unkown positive integer `n`. We know:
`n % 3 = 2`, and `n % 5 = 3`, and `n % 7 = 2`.
What's the minimum possible positive integer `n`?
The correct answer is `23`.
# Task
You are given three non-negative integers `x,y,z`. They represent the remainders of the unknown positive integer `n` divided by 3,5,7.
That is: `n % 3 = x, n % 5 = y, n % 7 = z`
Your task is to find the minimum possible positive integer `n` and return it.
# Example
For `x = 2, y = 3, z = 2`, the output should be `23`
`23 % 3 = 2, 23 % 5 = 3, 23 % 7 = 2`
For `x = 1, y = 2, z = 3`, the output should be `52`
`52 % 3 = 1, 52 % 5 = 2, 52 % 7 = 3`
For `x = 1, y = 3, z = 5`, the output should be `103`
`103 % 3 = 1, 103 % 5 = 3, 103 % 7 = 5`
For `x = 0, y = 0, z = 0`, the output should be `105`
For `x = 1, y = 1, z = 1`, the output should be `1`
# Note
- `0 <= x < 3, 0 <= y < 5, 0 <= z < 7`
- Happy Coding `^_^`
Also feel free to reuse/extend the following starter code:
```python
def find_unknown_number(x,y,z):
``` | {"functional": "_inputs = [[2, 3, 2], [1, 2, 3], [1, 3, 5], [0, 0, 0], [1, 1, 1]]\n_outputs = [[23], [52], [103], [105], [1]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(find_unknown_number(*i), o[0])"} | 530 | 215 |
coding | Solve the programming task below in a Python markdown code block.
You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color?
Your task is to write a program that for given values r, g and b will find the maximum number t of tables, that can be decorated in the required manner.
-----Input-----
The single line contains three integers r, g and b (0 ≤ r, g, b ≤ 2·10^9) — the number of red, green and blue baloons respectively. The numbers are separated by exactly one space.
-----Output-----
Print a single integer t — the maximum number of tables that can be decorated in the required manner.
-----Examples-----
Input
5 4 3
Output
4
Input
1 1 1
Output
1
Input
2 3 3
Output
2
-----Note-----
In the first sample you can decorate the tables with the following balloon sets: "rgg", "gbb", "brr", "rrg", where "r", "g" and "b" represent the red, green and blue balls, respectively. | {"inputs": ["5 4 3\n", "1 1 1\n", "2 3 3\n", "0 1 0\n", "0 3 3\n", "4 0 4\n", "0 0 0\n", "3 5 2\n"], "outputs": ["4\n", "1\n", "2\n", "0\n", "2\n", "2\n", "0\n", "3\n"]} | 276 | 102 |
coding | Solve the programming task below in a Python markdown code block.
Concatenation of two integers is obtained as follows: First, convert both integers to strings. Then concatenate both strings into one and convert this concatenated string back to integer.
For example, concatenation of 6 and 7 is CONC(6, 7) = 67, concatenation of 123 and 45 is CONC(123, 45) = 12345.
You are given an array A consisting of N integers. You are also given two integers L and R. Find the number of pairs (i, j) such that 1 ≤ i, j ≤ N and L ≤ CONC(A_{i}, A_{j}) ≤ R
Note: Since the size of the input and output is large, please use fast input-output methods.
------ Input Format ------
- The first line will contain T, the number of test cases. Then T test cases follow.
- The first line of each test case contains three integers N, L, R.
- The second line of each test case line contains N integers A_{1}, A_{2},\dots, A_{N}.
------ Output Format ------
For each testcase, output in a single line the number of suitable pairs.
------ Constraints ------
$1 ≤ T ≤ 10^{4}$
$1 ≤ N ≤ 10^{5}$
$1 ≤ L ≤ R ≤ 10^{15}$
$1 ≤ A_{i} ≤ 10^{7}$
- Sum of $N$ over all test cases does not exceed $10^{6}$.
----- Sample Input 1 ------
4
2 10 52
2 5
3 58 100
4 2 3
4 100 1000
1 10 100 1000
5 28 102
3 2 1 9 10
----- Sample Output 1 ------
3
0
2
11
----- explanation 1 ------
Test case 1:
- $(i = 1, j = 1)$: $CONC(A_{1}, A_{1}) = 22$ and $10 ≤ 22 ≤ 52$.
- $(i = 1, j = 2)$: $CONC(A_{1}, A_{2}) = 25$ and $10 ≤ 25 ≤ 52$.
- $(i = 2, j = 1)$: $CONC(A_{2}, A_{1}) = 52$ and $10 ≤ 52 ≤ 52$.
- $(i = 2, j = 2)$: $CONC(A_{2}, A_{2}) = 55$ and $10 ≤ 55$ but $ 55 \nleq 52$.
So there are three suitable pairs.
Test case 2: There is no suitable pair.
Test case 3: The suitable pairs are $(2, 1)$ and $(1, 2)$. | {"inputs": ["4\n2 10 52\n2 5\n3 58 100\n4 2 3\n4 100 1000\n1 10 100 1000\n5 28 102\n3 2 1 9 10\n"], "outputs": ["3\n0\n2\n11\n"]} | 681 | 93 |
coding | Solve the programming task below in a Python markdown code block.
There is Chef and Chef’s Crush who are playing a game of numbers.
Chef’s crush has a number $A$ and Chef has a number $B$.
Now, Chef wants Chef’s crush to win the game always, since she is his crush. The game ends when the greatest value of A^B is reached after performing some number of operations (possibly zero), Where ^ is Bitwise XOR.
Before performing any operation you have to ensure that both $A$ and $B$ have the same number of bits without any change in the values. It is not guaranteed that $A$ and $B$ should have same number of bits in the input.
For example, if $A$ is $2$ and $B$ is $15$, then the binary representation of both the numbers will have to be $0010$ and $1111$ respectively, before performing any operation.
The operation is defined as :
- Right circular shift of the bits of only $B$ from MSB$_B$ to LSB$_B$ i.e. if we consider $B_1 B_2 B_3 B_4$ as binary number, then after one circular right shift, it would be $B_4 B_1 B_2 B_3$
They both are busy with themselves, can you find the number of operations to end the game?
-----Input :-----
- The first line of input contains $T$, (number of test cases)
- Then each of the next $T$ lines contain : two integers $A$ and $B$ respectively.
-----Output :-----
For each test case print two space-separated integers, The number of operations to end the game and value of A^B when the game ends.
-----Constraints :-----
- $1 \leq T \leq100$
- $1\leq A,B \leq 10^{18}$
-----Subtasks :-----
- 30 Points: $1\leq A,B \leq 10^5$
- 70 Points: Original Constraints
-----Sample Input :-----
1
4 5
-----Sample Output :-----
2 7
-----Explanation :-----
Binary representation of $4$ is $100$ and binary representation $5$ is $101$.
- After operation $1$ : $B$ $=$ $110$, so A^B $=$ $2$
- After operation $2$ : $B$ $=$ $011$, so A^B $=$ $7$
So, the value of A^B will be $7$. Which is the greatest possible value for A^B and the number of operations are $2$. | {"inputs": ["1\n4 5"], "outputs": ["2 7"]} | 590 | 18 |
coding | Solve the programming task below in a Python markdown code block.
# Definition (Primorial Of a Number)
*Is similar to factorial of a number*, **_In primorial_**, not all the natural numbers get multiplied, **_only prime numbers are multiplied to calculate the primorial of a number_**. It's denoted with **_P_****_#_** and it is the product of the first n prime numbers.
___
# Task
**_Given_** *a number N* , **_calculate its primorial_**.  
___
# Notes
* **_Only positive_** numbers *will be passed (N > 0)* .
___
# Input >> Output Examples:
``` cpp
1- numPrimorial (3) ==> return (30)
```
## **_Explanation_**:
**_Since_** *the passed number is (3)* ,**_Then_** **_the primorial_** *should obtained by multiplying* ```2 * 3 * 5 = 30 .```
### Mathematically written as , **_P_**3**_#_** = 30 .
___
## **_Explanation_**:
**_Since_** *the passed number is (5)* ,**_Then_** **_the primorial_** *should obtained by multiplying* ``` 2 * 3 * 5 * 7 * 11 = 2310 .```
### Mathematically written as , **_P_**5**_#_** = 2310 .
___
## **_Explanation_**:
**_Since_** *the passed number is (6)* ,**_Then_** **_the primorial_** *should obtained by multiplying* ``` 2 * 3 * 5 * 7 * 11 * 13 = 30030 .```
### Mathematically written as , **_P_**6**_#_** = 30030 .
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
Also feel free to reuse/extend the following starter code:
```python
def num_primorial(n):
``` | {"functional": "_inputs = [[3], [4], [5], [8], [9]]\n_outputs = [[30], [210], [2310], [9699690], [223092870]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(num_primorial(*i), o[0])"} | 585 | 199 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.
Return the number of consistent strings in the array words.
Please complete the following python code precisely:
```python
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]) == 2\n assert candidate(allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]) == 7\n assert candidate(allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]) == 4\n\n\ncheck(Solution().countConsistentStrings)"} | 98 | 118 |
coding | Solve the programming task below in a Python markdown code block.
Tsetso likes to play with arrays.
An Array A[1,2,\ldots,N] is said to be a Tsetso array if A[1] \cdot A[N] = max(A_{1},A_{2},\ldots,A_{N-1},A_{N}).
Bedo, his teammate, likes to solve problems so much, so Tsetso gave him an array A of N \bf{distinct} integers A_{1}, A_{2}, \ldots, A_{N} and Q queries of the form [L, R] and asked him to count the number of Tsetso subarrays in the given range.
A subarray[L,R] is to be a Tsetso subarray if A[L] \cdot A[R] = max(A_{L},A_{L+1},....,A_{R-1},A_{R}).
Bedo spent a lot of time trying to solve it, but he couldn't, can you?
\bf{Note}: A sequence a is a subarray of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
------ Input Format ------
- First-line will contain T, the number of test cases. Then the test cases follow.
- The first line of input contains two space-separated integers N and Q, the number of elements in the array, and the number of queries.
- The second line contains N \bf{distinct} space-separated integers A_{1}, A_{2}, \ldots, A_{N}.
- Then Q lines follow each line containing two space-separated integers L, R.
------ Output Format ------
For each query, output in a single line the number of Tsetso subarrays in the given range [L, R].
------ Constraints ------
$1 ≤ T ≤ 10$
$2 ≤ N ≤ 10^{5}$
$1 ≤ A_{i} ≤ 10^{18} $
$1 ≤ Q ≤ 5 \cdot 10^{5}$
$1 ≤L ≤R ≤N$
- Sum of $N$ over all testcases is atmost $10^{5}$.
- Sum of $Q$ over all testcases is atmost $5 \cdot 10^{5}$.
----- Sample Input 1 ------
1
7 3
3 6 24 4 1 8 2
1 7
2 5
4 7
----- Sample Output 1 ------
7
4
4
----- explanation 1 ------
- All the valid subarrays are $[1,6],[2,4],[3,5],[4,5],[5,5],[5,6],[4,7]$.
- One of the invalid subarrays is $[1,3] , 3 \cdot 24 \neq max(3,6,24) $ | {"inputs": ["1\n7 3\n3 6 24 4 1 8 2\n1 7\n2 5\n4 7"], "outputs": ["7\n4\n4"]} | 648 | 47 |
coding | Solve the programming task below in a Python markdown code block.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 ≤ l ≤ r ≤ n and there is at least one pair of integers x, k such that 1 ≤ x, k ≤ n, l ≤ x < x + 2k ≤ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 ≤ |s| ≤ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 ≤ l ≤ r ≤ n and there is at least one pair of integers x, k such that 1 ≤ x, k ≤ n, l ≤ x < x + 2k ≤ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0. | {"inputs": ["0\n", "1\n", "01\n", "00\n", "100\n", "101\n", "001\n", "000\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "1\n"]} | 326 | 80 |
coding | Solve the programming task below in a Python markdown code block.
There are N events (numbered from 1 to N) and M contestants (numbered from 1 to M). For each event i, contestant j receives a predetermined number of points A_{i, j}.
A [subset] of these events will be selected, and the final score of contestant j, denoted s_{j}, will be the sum of their points for each event selected.
Formally, if S denotes the set of events chosen, then \displaystyle s_{j} = \sum_{x \in S} A_{x, j} for each 1 ≤ j ≤ M. If S is empty, we define s_{j} = 0 for each j.
The *differentiation* of the final scoreboard is equal to
\max_{i=1}^M (\sum_{j=1}^M |s_{j} - s_{i}|)
Find the maximum possible differentiation over all subsets of events.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- Each test case consists of several lines.
- The first line of each test case contains two space-separated integers N and M — the number of events and contestants, respectively.
- The next N lines describe the events. The i-th of these N lines contains M space-separated integers A_{i, 1}, A_{i, 2}, \ldots, A_{i, M} — the j-th of which describes the number of points the j-th contestant earns for event i.
------ Output Format ------
For each test case, output on a new line the maximum differentiation over all subsets of events.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 10^{5}$
$1 ≤ M ≤ 10^{5}$
$0 ≤ A_{i, j} ≤ 10^{5}$
- The sum of $N\cdot M$ over all test cases won't exceed $10^{5}$.
----- Sample Input 1 ------
3
1 1
1
3 3
1 0 1
1 2 1
1 2 1
4 2
1 3
5 1
6 8
2 1
----- Sample Output 1 ------
0
4
5
----- explanation 1 ------
Test case $1$: There are two possible subsets of events — either take the only event, or don't. In either case, the differentiation will be $0$.
Test case $2$: Take events $2$ and $3$ for a final scoreboard of $(2, 4, 2)$. The differentiation of this scoreboard is $4$, and it can be proven that this is the maximum.
Test case $3$: Take events $3$ and $5$, for a final scoreboard of $(7, 2)$, which has a differentiation of $5$. | {"inputs": ["3\n1 1\n1\n3 3\n1 0 1\n1 2 1\n1 2 1\n4 2\n1 3\n5 1\n6 8\n2 1\n"], "outputs": ["0\n4\n5"]} | 634 | 65 |
coding | Solve the programming task below in a Python markdown code block.
On March 14, the day of the number $\pi$ is celebrated all over the world. This is a very important mathematical constant equal to the ratio of the circumference of a circle to its diameter.
Polycarp was told at school that the number $\pi$ is irrational, therefore it has an infinite number of digits in decimal notation. He wanted to prepare for the Day of the number $\pi$ by memorizing this number as accurately as possible.
Polycarp wrote out all the digits that he managed to remember. For example, if Polycarp remembered $\pi$ as $3.1415$, he wrote out 31415.
Polycarp was in a hurry and could have made a mistake, so you decided to check how many first digits of the number $\pi$ Polycarp actually remembers correctly.
-----Input-----
The first line of the input data contains the single integer $t$ ($1 \le t \le 10^3$) — the number of test cases in the test.
Each test case is described by a single string of digits $n$, which was written out by Polycarp.
The string $n$ contains up to $30$ digits.
-----Output-----
Output $t$ integers, each of which is the answer to the corresponding test case, that is how many first digits of the number $\pi$ Polycarp remembers correctly.
-----Examples-----
Input
9
000
3
4141592653
141592653589793238462643383279
31420
31415
314159265358
27182
314159265358979323846264338327
Output
0
1
0
0
3
5
12
0
30
-----Note-----
None | {"inputs": ["1\n1\n", "1\n3\n", "1\n0\n", "1\n00\n", "1\n31\n", "2\n0\n0\n", "1\n3444\n", "3\n8\n5\n8\n"], "outputs": ["0\n", "1\n", "0\n", "0\n", "2\n", "0\n0\n", "1\n", "0\n0\n0\n"]} | 446 | 103 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
Let's play the minesweeper game (Wikipedia, online game)!
You are given an m x n char matrix board representing the game board where:
'M' represents an unrevealed mine,
'E' represents an unrevealed empty square,
'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
digit ('1' to '8') represents how many mines are adjacent to this revealed square, and
'X' represents a revealed mine.
You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E').
Return the board after revealing this position according to the following rules:
If a mine 'M' is revealed, then the game is over. You should change it to 'X'.
If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively.
If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
Return the board when no more squares will be revealed.
Please complete the following python code precisely:
```python
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
``` | {"functional": "def check(candidate):\n assert candidate(board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]) == [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\n assert candidate(board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]) == [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\n\n\ncheck(Solution().updateBoard)"} | 324 | 243 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an integer array nums, which contains distinct elements and an integer k.
A subset is called a k-Free subset if it contains no two elements with an absolute difference equal to k. Notice that the empty set is a k-Free subset.
Return the number of k-Free subsets of nums.
A subset of an array is a selection of elements (possibly none) of the array.
Please complete the following python code precisely:
```python
class Solution:
def countTheNumOfKFreeSubsets(self, nums: List[int], k: int) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(nums = [5,4,6], k = 1) == 5\n assert candidate(nums = [2,3,5,8], k = 5) == 12\n assert candidate(nums = [10,5,9,11], k = 20) == 16\n\n\ncheck(Solution().countTheNumOfKFreeSubsets)"} | 137 | 97 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an array nums of size n, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.
Please complete the following python code precisely:
```python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(nums = [3,2,3]) == 3\n assert candidate(nums = [2,2,1,1,1,2,2]) == 2\n\n\ncheck(Solution().majorityElement)"} | 94 | 60 |
coding | Solve the programming task below in a Python markdown code block.
Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
There are $N$ students standing in a row and numbered $1$ through $N$ from left to right. You are given a string $S$ with length $N$, where for each valid $i$, the $i$-th character of $S$ is 'x' if the $i$-th student is a girl or 'y' if this student is a boy. Students standing next to each other in the row are friends.
The students are asked to form pairs for a dance competition. Each pair must consist of a boy and a girl. Two students can only form a pair if they are friends. Each student can only be part of at most one pair. What is the maximum number of pairs that can be formed?
------ Input ------
The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
The first and only line of each test case contains a single string $S$.
------ Output ------
For each test case, print a single line containing one integer ― the maximum number of pairs.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 10^{5}$
$|S| = N$
$S$ contains only characters 'x' and 'y'
the sum of $N$ over all test cases does not exceed $3 \cdot 10^{5}$
------ Subtasks ------
Subtask #1 (100 points): original constraints
----- Sample Input 1 ------
3
xy
xyxxy
yy
----- Sample Output 1 ------
1
2
0
----- explanation 1 ------
Example case 1: There is only one possible pair: (first student, second student).
Example case 2: One of the ways to form two pairs is: (first student, second student) and (fourth student, fifth student).
Another way to form two pairs is: (second student, third student) and (fourth student, fifth student). | {"inputs": ["3\nxy\nxyxxy\nyy"], "outputs": ["1\n2\n0"]} | 473 | 24 |
coding | Solve the programming task below in a Python markdown code block.
Ignoring the air resistance, velocity of a freely falling object $v$ after $t$ seconds and its drop $y$ in $t$ seconds are represented by the following formulas:
$ v = 9.8 t $
$ y = 4.9 t^2 $
A person is trying to drop down a glass ball and check whether it will crack. Your task is to write a program to help this experiment.
You are given the minimum velocity to crack the ball. Your program should print the lowest possible floor of a building to crack the ball. The height of the $N$ floor of the building is defined by $5 \times N - 5$.
Input
The input consists of multiple datasets. Each dataset, a line, consists of the minimum velocity v (0 < v < 200) to crack the ball. The value is given by a decimal fraction, with at most 4 digits after the decimal point. The input ends with EOF. The number of datasets is less than or equal to 50.
Output
For each dataset, print the lowest possible floor where the ball cracks.
Example
Input
25.4
25.4
Output
8
8 | {"inputs": ["25.4\n25.4", "26.000450676027395\n25.4", "26.601491934975797\n25.4", "44.72115406668142\n44.101745823639", "38.4955310270825\n37.15642943049945", "60.63345250628777\n63.4141206664841", "73.9111092448129\n75.52007039121814", "35.31260445827307\n34.47301494550142"], "outputs": ["8\n8", "8\n8\n", "9\n8\n", "22\n21\n", "17\n16\n", "39\n43\n", "57\n60\n", "14\n14\n"]} | 262 | 304 |
coding | Please solve the programming task below using a self-contained code snippet in a markdown code block.
There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by an n x k cost matrix costs.
For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on...
Return the minimum cost to paint all houses.
Please complete the following python code precisely:
```python
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
``` | {"functional": "def check(candidate):\n assert candidate(costs = [[1,5,3],[2,9,4]]) == 5\n assert candidate(costs = [[1,3],[2,4]]) == 5\n\n\ncheck(Solution().minCostII)"} | 176 | 62 |
coding | Solve the programming task below in a Python markdown code block.
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforces^{ω} that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.
There is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.
Help the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.
-----Input-----
The single line of the input contains the word written on the banner. The word only consists of upper-case English letters. The word is non-empty and its length doesn't exceed 100 characters. It is guaranteed that the word isn't word CODEFORCES.
-----Output-----
Print 'YES', if there exists a way to cut out the substring, and 'NO' otherwise (without the quotes).
-----Examples-----
Input
CODEWAITFORITFORCES
Output
YES
Input
BOTTOMCODER
Output
NO
Input
DECODEFORCES
Output
YES
Input
DOGEFORCES
Output
NO | {"inputs": ["C\n", "C\n", "D\n", "B\n", "ABACABA\n", "ABACABA\n", "AABCABA\n", "CODEFORCE\n"], "outputs": ["NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]} | 427 | 77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.