task_type
stringclasses 1
value | problem
stringlengths 261
3.34k
| answer
stringlengths 35
6.15k
| problem_tokens
int64 62
774
| answer_tokens
int64 12
2.04k
|
|---|---|---|---|---|
coding
|
Solve the programming task below in a Python markdown code block.
Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won $x$ rounds in a row. For example, if Bob won five rounds in a row and $x = 2$, then two sets ends.
You know that Alice and Bob have already played $n$ rounds, and you know the results of some rounds. For each $x$ from $1$ to $n$, calculate the maximum possible number of sets that could have already finished if each set lasts until one of the players wins $x$ rounds in a row. It is possible that the last set is still not finished β in that case, you should not count it in the answer.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 10^6$)Β β the number of rounds.
The second line contains one string $s$ of length $n$ β the descriptions of rounds. If the $i$-th element of the string is 0, then Alice won the $i$-th round; if it is 1, then Bob won the $i$-th round, and if it is ?, then you don't know who won the $i$-th round.
-----Output-----
In the only line print $n$ integers. The $i$-th integer should be equal to the maximum possible number of sets that could have already finished if each set lasts until one of the players wins $i$ rounds in a row.
-----Examples-----
Input
6
11?000
Output
6 3 2 1 0 0
Input
5
01?01
Output
5 1 0 0 0
Input
12
???1??????1?
Output
12 6 4 3 2 2 1 1 1 1 1 1
-----Note-----
Let's consider the first test case:
if $x = 1$ and $s = 110000$ or $s = 111000$ then there are six finished sets; if $x = 2$ and $s = 110000$ then there are three finished sets; if $x = 3$ and $s = 111000$ then there are two finished sets; if $x = 4$ and $s = 110000$ then there is one finished set; if $x = 5$ then there are no finished sets; if $x = 6$ then there are no finished sets.
|
{"inputs": ["1\n0\n", "1\n1\n", "1\n?\n", "1\n0\n", "1\n1\n", "1\n?\n", "5\n01?01\n", "5\n10?10\n"], "outputs": ["1 \n", "1 \n", "1 \n", "1\n", "1\n", "1\n", "5 1 0 0 0 \n", "5 1 0 0 0\n"]}
| 597
| 114
|
coding
|
Solve the programming task below in a Python markdown code block.
Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $1$. Each person is looking through the circle's center at the opposite person.
A sample of a circle of $6$ persons. The orange arrows indicate who is looking at whom.
You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $a$ is looking at the person with the number $b$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $c$? If, for the specified $a$, $b$, and $c$, no such circle exists, output -1.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 10^4$) β the number of test cases. Then $t$ test cases follow.
Each test case consists of one line containing three distinct integers $a$, $b$, $c$ ($1 \le a,b,c \le 10^8$).
-----Output-----
For each test case output in a separate line a single integer $d$ β the number of the person being looked at by the person with the number $c$ in a circle such that the person with the number $a$ is looking at the person with the number $b$. If there are multiple solutions, print any of them. Output $-1$ if there's no circle meeting the given conditions.
-----Examples-----
Input
7
6 2 4
2 3 1
2 4 10
5 3 4
1 3 2
2 5 4
4 3 2
Output
8
-1
-1
-1
4
1
-1
-----Note-----
In the first test case, there's a desired circle of $8$ people. The person with the number $6$ will look at the person with the number $2$ and the person with the number $8$ will look at the person with the number $4$.
In the second test case, there's no circle meeting the conditions. If the person with the number $2$ is looking at the person with the number $3$, the circle consists of $2$ people because these persons are neighbors. But, in this case, they must have the numbers $1$ and $2$, but it doesn't meet the problem's conditions.
In the third test case, the only circle with the persons with the numbers $2$ and $4$ looking at each other consists of $4$ people. Therefore, the person with the number $10$ doesn't occur in the circle.
|
{"inputs": ["1\n1 2 3\n", "1\n2 3 4\n", "1\n1 2 3\n", "1\n2 3 4\n", "1\n1 3 4\n", "1\n1 7 4\n", "1\n9 10 1\n", "1\n9 10 1\n"], "outputs": ["-1\n", "-1\n", "-1\n", "-1\n", "2\n", "10\n", "-1\n", "-1\n"]}
| 605
| 122
|
coding
|
Solve the programming task below in a Python markdown code block.
Alice has an array of N integers β A_{1}, A_{2}, \ldots, A_{N}. She wants the product of all the elements of the array to be a non-negative integer. That is, it can be either 0 or positive. But she doesn't want it to be negative.
To do this, she is willing to remove some elements of the array. Determine the minimum number of elements that she will have to remove to make the product of the array's elements non-negative.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- The first line of each test case contains a single integer N β the number of elements in the array originally.
- The next line contains N space-separated integers β A_{1}, A_{2}, \ldots, A_{N}, which are the original array elements.
------ Output Format ------
For each test case, output on a new line the minimum number of elements that she has to remove from the array.
------ Constraints ------
$1 β€ T β€ 100$
$2 β€ N β€ 10000$
$-1000 β€ A_{i} β€ 1000$
----- Sample Input 1 ------
4
3
1 9 8
4
2 -1 9 100
4
2 -1 0 100
4
2 -1 -1 100
----- Sample Output 1 ------
0
1
0
0
----- explanation 1 ------
Test case $1$: The product of the elements of the array is $1 \times 9 \times 8 = 72$, which is already non-negative. Hence no element needs to be removed, and so the answer is $0$.
Test case $2$: The product of the elements of the array is $2 \times -1 \times 9 \times 100 = -1800$, which is negative. Alice can remove the element $-1$, and the product then becomes non-negative. Hence the answer is $1$.
Test case $3$: The product of the elements of the array is $2 \times -1 \times 0 \times 100 = 0$, which is already non-negative. Hence no element needs to be removed, and so the answer is $0$.
Test case $4$: The product of the elements of the array is $2 \times -1 \times -1 \times 100 = 200$, which is already non-negative. Hence no element needs to be removed, and so the answer is $0$.
|
{"inputs": ["4\n3\n1 9 8\n4\n2 -1 9 100\n4\n2 -1 0 100\n4\n2 -1 -1 100\n"], "outputs": ["0\n1\n0\n0\n"]}
| 579
| 64
|
coding
|
Solve the programming task below in a Python markdown code block.
## Task:
You have to create a function `isPronic` to check whether the argument passed is a Pronic Number and return true if it is & false otherwise.
### Description:
`Pronic Number` -A pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers, that is, n(n + 1).
> The first few Pronic Numbers are - 0, 2, 6, 12, 20, 30, 42...
### Explanation:
0 = 0 Γ 1 // β΄ 0 is a Pronic Number
2 = 1 Γ 2 // β΄ 2 is a Pronic Number
6 = 2 Γ 3 // β΄ 6 is a Pronic Number
12 = 3 Γ 4 // β΄ 12 is a Pronic Number
20 = 4 Γ 5 // β΄ 20 is a Pronic Number
30 = 5 Γ 6 // β΄ 30 is a Pronic Number
42 = 6 Γ 7 // β΄ 42 is a Pronic Number
Also feel free to reuse/extend the following starter code:
```python
def is_pronic(n):
```
|
{"functional": "_inputs = [[2], [3], [4], [5], [6], [-3], [-27]]\n_outputs = [[True], [False], [False], [False], [True], [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(is_pronic(*i), o[0])"}
| 314
| 192
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Β
Please complete the following python code precisely:
```python
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
```
|
{"functional": "def check(candidate):\n assert candidate(rec1 = [0,0,2,2], rec2 = [1,1,3,3]) == True\n assert candidate(rec1 = [0,0,1,1], rec2 = [1,0,2,1]) == False\n assert candidate(rec1 = [0,0,1,1], rec2 = [2,2,3,3]) == False\n\n\ncheck(Solution().isRectangleOverlap)"}
| 188
| 110
|
coding
|
Solve the programming task below in a Python markdown code block.
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!
A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system.
There are n booking requests received by now. Each request is characterized by two numbers: c_{i} and p_{i} β the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.
We know that for each request, all c_{i} people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.
Unfortunately, there only are k tables in the restaurant. For each table, we know r_{i} β the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.
Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.
-----Input-----
The first line of the input contains integer n (1 β€ n β€ 1000) β the number of requests from visitors. Then n lines follow. Each line contains two integers: c_{i}, p_{i} (1 β€ c_{i}, p_{i} β€ 1000) β the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly.
The next line contains integer k (1 β€ k β€ 1000) β the number of tables in the restaurant. The last line contains k space-separated integers: r_1, r_2, ..., r_{k} (1 β€ r_{i} β€ 1000) β the maximum number of people that can sit at each table.
-----Output-----
In the first line print two integers: m, s β the number of accepted requests and the total money you get from these requests, correspondingly.
Then print m lines β each line must contain two space-separated integers: the number of the accepted request and the number of the table to seat people who come via this request. The requests and the tables are consecutively numbered starting from 1 in the order in which they are given in the input.
If there are multiple optimal answers, print any of them.
-----Examples-----
Input
3
10 50
2 100
5 30
3
4 6 9
Output
2 130
2 1
3 2
|
{"inputs": ["1\n1 1\n1\n1\n", "1\n2 1\n1\n1\n", "1\n2 1\n1\n1\n", "1\n1 1\n1\n1\n", "1\n0 1\n1\n1\n", "1\n0 1\n1\n2\n", "1\n0 1\n1\n3\n", "1\n0 1\n1\n5\n"], "outputs": ["1 1\n1 1\n", "0 0\n", "0 0\n", "1 1\n1 1\n", "1 1\n1 1\n", "1 1\n1 1\n", "1 1\n1 1\n", "1 1\n1 1\n"]}
| 592
| 174
|
coding
|
Solve the programming task below in a Python markdown code block.
One of the first algorithm used for approximating the integer square root of a positive integer `n` is known as "Hero's method",
named after the first-century Greek mathematician Hero of Alexandria who gave the first description
of the method. Hero's method can be obtained from Newton's method which came 16 centuries after.
We approximate the square root of a number `n` by taking an initial guess `x`, an error `e` and repeatedly calculating a new approximate *integer* value `x` using: `(x + n / x) / 2`; we are finished when the previous `x` and the `new x` have an absolute difference less than `e`.
We supply to a function (int_rac) a number `n` (positive integer) and a parameter `guess` (positive integer) which will be our initial `x`. For this kata the parameter 'e' is set to `1`.
Hero's algorithm is not always going to come to an exactly correct result! For instance: if n = 25 we get 5 but for n = 26 we also get 5. Nevertheless `5` is the *integer* square root of `26`.
The kata is to return the count of the progression of integer approximations that the algorithm makes.
Reference:
Some examples:
```
int_rac(25,1): follows a progression of [1,13,7,5] so our function should return 4.
int_rac(125348,300): has a progression of [300,358,354] so our function should return 3.
int_rac(125348981764,356243): has a progression of [356243,354053,354046] so our function should return 3.
```
#
You can use Math.floor (or similar) for each integer approximation.
#
Note for JavaScript, Coffescript, Typescript:
Don't use the double bitwise NOT ~~ at each iteration if you want to have the same results as in the tests and the other languages.
Also feel free to reuse/extend the following starter code:
```python
def int_rac(n, guess):
```
|
{"functional": "_inputs = [[25, 1], [125348, 300], [125348981764, 356243], [236, 12], [48981764, 8000], [6999, 700], [16000, 400], [16000, 100], [2500, 60], [250000, 600], [95367431640625, 1], [9094947017729282379150390625, 1], [835871232077058, 1], [246391990316004, 1], [403832254158749, 1], [217414278071071, 1], [639593178334873, 1], [646895994940989, 1], [346147532294375, 1], [871397668454373, 1], [711652869429165, 1], [828061341209011, 1]]\n_outputs = [[4], [3], [3], [2], [3], [6], [5], [3], [2], [3], [28], [52], [30], [29], [29], [29], [29], [29], [29], [30], [29], [30]]\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(int_rac(*i), o[0])"}
| 501
| 604
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
The valid operators are '+', '-', '*', and '/'.
Each operand may be an integer or another expression.
The division between two integers always truncates toward zero.
There will not be any division by zero.
The input represents a valid arithmetic expression in a reverse polish notation.
The answer and all the intermediate calculations can be represented in a 32-bit integer.
Β
Please complete the following python code precisely:
```python
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]) == 9\n assert candidate(tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]) == 6\n assert candidate(tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]) == 22\n\n\ncheck(Solution().evalRPN)"}
| 159
| 105
|
coding
|
Solve the programming task below in a Python markdown code block.
# Covfefe
Your are given a string. You must replace the word(s) `coverage` by `covfefe`, however, if you don't find the word `coverage` in the string, you must add `covfefe` at the end of the string with a leading space.
For the languages where the string is not immutable (such as ruby), don't modify the given string, otherwise this will break the test cases.
Also feel free to reuse/extend the following starter code:
```python
def covfefe(s):
```
|
{"functional": "_inputs = [['coverage'], ['coverage coverage'], ['nothing'], ['double space '], ['covfefe']]\n_outputs = [['covfefe'], ['covfefe covfefe'], ['nothing covfefe'], ['double space covfefe'], ['covfefe covfefe']]\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(covfefe(*i), o[0])"}
| 126
| 205
|
coding
|
Solve the programming task below in a Python markdown code block.
Today there is going to be an unusual performance at the circus β hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.
Input
The first line contains number n (2 β€ n β€ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one.
Output
Print the single number which is the minimal number of swaps that let the trainer to achieve his goal.
Examples
Input
3
HTH
Output
0
Input
9
HTHTHTHHT
Output
2
Note
In the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then β the tiger in position 9 with the hamster in position 7.
|
{"inputs": ["2\nTH\n", "2\nHT\n", "3\nHHT\n", "3\nTHH\n", "3\nHTH\n", "4\nHTHT\n", "4\nHTTH\n", "4\nTTHH\n"], "outputs": ["0", "0\n", "0\n", "0\n", "0", "1", "0", "0\n"]}
| 419
| 89
|
coding
|
Solve the programming task below in a Python markdown code block.
### Background
In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. It was invented by Lester S. Hill in 1929.
### Task
This cipher involves a text key which has to be turned into a matrix and text which needs to be encoded. The text key can be of any perfect square length but for the sake of this kata we will focus on keys of length 4 forming a 2x2 matrix.
To encrypt a message using the hill cipher, first of all you need to convert the text key into a key matrix. To do that you will convert the key row wise into a 2x2 matrix. Then you will substitute the letters with their respective positions on the alphabet: A=0, B=1,C=2 and so on till Z=25. So for example if we get the key text as ```cats```, the key matrix will be:
[[ 2 0]
[19 18]]
Now the next step is to break the text into pairs of two and convert those pairs into 2x1 matrices. If your text has an odd number of letters then just add a Z next to your last letter. Now again convert those letters into their respective position in the alphabet as above. So for example the text ```Hi``` would be converted into:
[[7]
[8]]
Now we need to [multiply](https://www.mathsisfun.com/algebra/matrix-multiplying.html) the key matrix by the text matrix to get our encrypted matrix and then find out the encrypted matrix [modulo](https://en.wikipedia.org/wiki/Modulo_operation) 26:
[[ 2 0] * [[7] = [[14] = [[14] mod 26
[19 18]] [8]] [277]] [17]]
For the final step we just find out the letters at the alphabet position of 14 and 17 which are ```O``` and ```R```. So ```OR``` is our encrypted message for the message ```Hi```
In this kata you will be given a function named ```encrypt``` with the parameters ```text``` and ```key``` and you have to return the encrypted message in all uppercase letters
``` python
encrypt('','azyb') β ''
encrypt('Hi','cats') β 'OR'
encrypt('This is a good day','bbaa') β 'AAAAAAGACAGAYA'
```
Note:
- The text to encrypt will contain characters other than the alphabets, its your job to clean them before converting text to matrices. Spaces also need to be removed
- The text may contain both uppercase and lowercase alphabets. Its your job to standardize them, the encrypted text however should be returned in uppercase letters.
- The key will always contain 4 lowercase alphabet.
Also feel free to reuse/extend the following starter code:
```python
def encrypt(text,key):
```
|
{"functional": "_inputs = [['', 'azyb'], ['hello', 'hill'], ['This is a good day', 'bbaa'], ['CODEWARS IS GREAT', 'wxyz'], ['Five + Seven = Twelve', 'math'], ['+-*/ &*%^$', 'azyb']]\n_outputs = [[''], ['DRJIMN'], ['AAAAAAGACAGAYA'], ['CICQQIIASSDXKSFP'], ['IVSLIGSLAQEECSWR'], ['']]\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(encrypt(*i), o[0])"}
| 648
| 243
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a string, message, and a positive integer, limit.
You must split message into one or more parts based on limit. Each resulting part should have the suffix "<a/b>", where "b" is to be replaced with the total number of parts and "a" is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.
The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.
Return the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.
Β
Please complete the following python code precisely:
```python
class Solution:
def splitMessage(self, message: str, limit: int) -> List[str]:
```
|
{"functional": "def check(candidate):\n assert candidate(message = \"this is really a very awesome message\", limit = 9) == [\"thi<1/14>\",\"s i<2/14>\",\"s r<3/14>\",\"eal<4/14>\",\"ly <5/14>\",\"a v<6/14>\",\"ery<7/14>\",\" aw<8/14>\",\"eso<9/14>\",\"me<10/14>\",\" m<11/14>\",\"es<12/14>\",\"sa<13/14>\",\"ge<14/14>\"]\n assert candidate(message = \"short message\", limit = 15) == [\"short mess<1/2>\",\"age<2/2>\"]\n\n\ncheck(Solution().splitMessage)"}
| 232
| 214
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array.
Β
Please complete the following python code precisely:
```python
class Solution:
def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums1 = [4,1,3], nums2 = [5,7]) == 15\n assert candidate(nums1 = [3,5,2,6], nums2 = [3,1,7]) == 3\n\n\ncheck(Solution().minNumber)"}
| 81
| 74
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given an array $a_1, a_2, \dots, a_n$ consisting of $n$ distinct integers. Count the number of pairs of indices $(i, j)$ such that $i < j$ and $a_i \cdot a_j = i + j$.
-----Input-----
The first line contains one integer $t$ ($1 \leq t \leq 10^4$) β the number of test cases. Then $t$ cases follow.
The first line of each test case contains one integer $n$ ($2 \leq n \leq 10^5$) β the length of array $a$.
The second line of each test case contains $n$ space separated integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 2 \cdot n$) β the array $a$. It is guaranteed that all elements are distinct.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output the number of pairs of indices $(i, j)$ such that $i < j$ and $a_i \cdot a_j = i + j$.
-----Examples-----
Input
3
2
3 1
3
6 1 5
5
3 1 5 9 2
Output
1
1
3
-----Note-----
For the first test case, the only pair that satisfies the constraints is $(1, 2)$, as $a_1 \cdot a_2 = 1 + 2 = 3$
For the second test case, the only pair that satisfies the constraints is $(2, 3)$.
For the third test case, the pairs that satisfy the constraints are $(1, 2)$, $(1, 5)$, and $(2, 3)$.
|
{"inputs": ["3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 2\n", "3\n2\n3 1\n3\n4 1 5\n5\n3 1 5 9 2\n", "3\n2\n3 1\n3\n6 1 5\n5\n3 1 5 9 4\n", "3\n2\n2 1\n3\n4 1 5\n5\n3 1 4 9 2\n", "3\n2\n3 1\n3\n4 2 5\n5\n3 1 4 5 2\n", "3\n2\n3 2\n3\n2 1 5\n5\n3 1 5 9 4\n", "3\n2\n3 1\n3\n4 1 5\n5\n6 1 5 9 4\n", "3\n2\n3 2\n3\n4 1 5\n5\n6 1 5 9 4\n"], "outputs": ["1\n1\n3\n", "1\n1\n3\n", "1\n1\n2\n", "0\n1\n3\n", "1\n0\n3\n", "0\n1\n2\n", "1\n1\n1\n", "0\n1\n1\n"]}
| 426
| 310
|
coding
|
Solve the programming task below in a Python markdown code block.
Mr. Square is going on a holiday. He wants to bring 2 of his favorite squares with him, so he put them in his rectangle suitcase.
Write a function that, given the size of the squares and the suitcase, return whether the squares can fit inside the suitcase.
```Python
fit_in(a,b,m,n)
a,b are the sizes of the 2 squares
m,n are the sizes of the suitcase
```
# Example
```Python
fit_in(1,2,3,2) should return True
fit_in(1,2,2,1) should return False
fit_in(3,2,3,2) should return False
fit_in(1,2,1,2) should return False
```
Also feel free to reuse/extend the following starter code:
```python
def fit_in(a,b,m,n):
```
|
{"functional": "_inputs = [[1, 2, 3, 2], [1, 2, 2, 1], [3, 2, 3, 2], [1, 2, 1, 2], [6, 5, 8, 7], [6, 6, 12, 6], [7, 1, 7, 8], [10, 10, 11, 11], [7, 2, 9, 7], [7, 2, 8, 7], [4, 1, 5, 3], [1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 2, 1, 4], [3, 2, 4, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 4, 2, 1], [3, 4, 1, 2], [4, 2, 3, 1], [4, 2, 1, 3], [4, 3, 2, 1], [4, 3, 1, 2], [4, 1, 2, 3], [4, 1, 3, 2]]\n_outputs = [[True], [False], [False], [False], [False], [True], [True], [False], [True], [False], [False], [True], [True], [False], [False], [False], [False], [True], [True], [False], [False], [False], [False], [False], [False], [False], [False], [False], [False], [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(fit_in(*i), o[0])"}
| 193
| 679
|
coding
|
Solve the programming task below in a Python markdown code block.
Initially, Chef had an array A of length N. Chef performs the following operation on A at most once:
Select L and R such that 1 β€ L β€ R β€ N and set A_{i} := A_{i} + 1 for all L β€ i β€ R.
Determine the maximum number of *inversions* Chef can decrease from the array A by applying the operation at most once.
More formally, let the final array obtained after applying the operation at most once be B. You need to determine the maximum value of inv(A) - inv(B) (where inv(X) denotes the number of *inversions* in array X).
Note: The number of *inversions* in an array X is the number of pairs (i, j) such that 1 β€ i < j β€ N and X_{i} > X_{j}.
------ 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 an integer N β the size of the array A.
- 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 the maximum value of inv(A) - inv(B) which can be obtained after applying at most one operation.
------ Constraints ------
$1 β€ T β€ 10^{5}$
$1 β€N β€10^{5}$
$1 β€A_{i} β€N$
- Sum of $N$ over all test cases does not exceed $2 \cdot 10^{5}$.
----- Sample Input 1 ------
3
5
4 2 3 1 5
6
1 2 3 4 5 6
4
2 1 1 1
----- Sample Output 1 ------
2
0
3
----- explanation 1 ------
Test case $1$: The initial array $A$ is $[4, 2, 3, 1, 5]$ which has $5$ inversions. We can perform operation on $L = 3, R = 4$. The resultant array will be $[4, 2, 4, 2, 5]$ which has $3$ inversions. Therefore we reduce the number of inversion by $2$ which is the maximum decrement possible.
Test case $2$: The initial array $A$ is $[1, 2, 3, 4, 5, 6]$ which has $0$ inversions. In this case, we do not need to apply any operation and the final array $B$ will be same as the initial array $A$. Therefore the maximum possible decrement in inversions is $0$.
Test case $3$: The initial array $A$ is $[2, 1, 1, 1]$ which has $3$ inversions. We can perform operation on $L = 2, R = 4$. The resultant array will be $[2, 2, 2, 2]$ which has $0$ inversions. Therefore we reduce the number of inversion by $3$ which is the maximum decrement possible.
|
{"inputs": ["3\n5\n4 2 3 1 5\n6\n1 2 3 4 5 6\n4\n2 1 1 1\n"], "outputs": ["2\n0\n3\n"]}
| 704
| 54
|
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 two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Β
Please complete the following python code precisely:
```python
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
```
|
{"functional": "def check(candidate):\n assert candidate(num1 = \"11\", num2 = \"123\") == \"134\"\n assert candidate(num1 = \"456\", num2 = \"77\") == \"533\"\n assert candidate(num1 = \"0\", num2 = \"0\") == \"0\"\n\n\ncheck(Solution().addStrings)"}
| 112
| 89
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given an array $a$ consisting of $n$ integers. In one move, you can jump from the position $i$ to the position $i - a_i$ (if $1 \le i - a_i$) or to the position $i + a_i$ (if $i + a_i \le n$).
For each position $i$ from $1$ to $n$ you want to know the minimum the number of moves required to reach any position $j$ such that $a_j$ has the opposite parity from $a_i$ (i.e. if $a_i$ is odd then $a_j$ has to be even and vice versa).
-----Input-----
The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) β the number of elements in $a$.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the $i$-th element of $a$.
-----Output-----
Print $n$ integers $d_1, d_2, \dots, d_n$, where $d_i$ is the minimum the number of moves required to reach any position $j$ such that $a_j$ has the opposite parity from $a_i$ (i.e. if $a_i$ is odd then $a_j$ has to be even and vice versa) or -1 if it is impossible to reach such a position.
-----Example-----
Input
10
4 5 7 6 7 5 4 4 6 4
Output
1 1 1 2 -1 1 1 3 1 1
|
{"inputs": ["10\n4 5 7 6 7 5 4 4 6 4\n", "10\n4 9 7 6 7 5 4 4 6 4\n", "10\n4 9 7 6 7 5 4 4 6 0\n", "10\n4 9 7 6 7 5 4 4 6 1\n", "10\n4 5 7 6 7 5 4 4 6 4\n", "10\n4 17 7 6 7 5 4 4 6 1\n", "10\n4 17 7 6 7 5 4 4 12 1\n", "10\n4 17 1 6 7 5 4 4 12 1\n"], "outputs": ["1 1 1 2 -1 1 1 3 1 1 \n", "1 -1 1 2 -1 1 1 3 1 1\n", "1 -1 1 -1 -1 1 1 -1 1 -1\n", "1 -1 2 1 -1 1 1 2 1 1\n", "1 1 1 2 -1 1 1 3 1 1 \n", "1 -1 2 1 -1 1 1 2 1 1\n", "1 -1 2 1 -1 1 1 2 -1 1\n", "1 -1 1 1 -1 1 1 2 -1 1\n"]}
| 397
| 389
|
coding
|
Solve the programming task below in a Python markdown code block.
A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:
- The first term s is given as input.
- Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.
- a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.
Find the minimum integer m that satisfies the following condition:
- There exists an integer n such that a_m = a_n (m > n).
-----Constraints-----
- 1 \leq s \leq 100
- All values in input are integers.
- It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.
-----Input-----
Input is given from Standard Input in the following format:
s
-----Output-----
Print the minimum integer m that satisfies the condition.
-----Sample Input-----
8
-----Sample Output-----
5
a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.
|
{"inputs": ["2", "6", "5", "9", "8", "7", "8\n", "7\n"], "outputs": ["4\n", "10\n", "7\n", "21\n", "5", "18", "5\n", "18\n"]}
| 276
| 66
|
coding
|
Solve the programming task below in a Python markdown code block.
In discus throw, a player is given 3 throws and the throw with the longest distance is regarded as their final score.
You are given the distances for all 3 throws of a player. Determine the final score of the player.
------ Input Format ------
- First line will contain T, number of test cases. Then the test cases follow.
- Each test case contains of a single line of input, three integers A, B, and C denoting the distances in each throw.
------ Output Format ------
For each test case, output the final score of the player.
------ Constraints ------
$1 β€ T β€ 100$
$1 β€ A,B,C β€ 100$
----- Sample Input 1 ------
3
10 15 8
32 32 32
82 45 54
----- Sample Output 1 ------
15
32
82
----- explanation 1 ------
Test Case $1$: The longest distance is achieved in the second throw, which is equal to $15$ units. Thus, the answer is $15$.
Test Case $2$: In all throws, the distance is $32$ units. Thus, the final score is $32$.
Test Case $3$: The longest distance is achieved in the first throw which is equal to $82$ units. Thus, the answer is $82$.
|
{"inputs": ["3\n10 15 8\n32 32 32\n82 45 54\n"], "outputs": ["15\n32\n82\n"]}
| 310
| 47
|
coding
|
Solve the programming task below in a Python markdown code block.
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces:
* Form groups consisting of A_i children each!
Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at most one group. Those who are left without a group leave the game. The others proceed to the next round. Note that it's possible that nobody leaves the game in some round.
In the end, after the K-th round, there are exactly two children left, and they are declared the winners.
You have heard the values of A_1, A_2, ..., A_K. You don't know N, but you want to estimate it.
Find the smallest and the largest possible number of children in the game before the start, or determine that no valid values of N exist.
Constraints
* 1 \leq K \leq 10^5
* 2 \leq A_i \leq 10^9
* All input values are integers.
Input
Input is given from Standard Input in the following format:
K
A_1 A_2 ... A_K
Output
Print two integers representing the smallest and the largest possible value of N, respectively, or a single integer -1 if the described situation is impossible.
Examples
Input
4
3 4 3 2
Output
6 8
Input
5
3 4 100 3 2
Output
-1
Input
10
2 2 2 2 2 2 2 2 2 2
Output
2 3
|
{"inputs": ["4\n3 3 2 2", "4\n4 3 2 2", "4\n3 5 3 2", "4\n1 1 2 2", "4\n3 4 2 2", "4\n3 6 2 2", "4\n3 6 4 2", "4\n3 4 3 2"], "outputs": ["3 5\n", "4 7\n", "6 11\n", "2 3\n", "-1\n", "-1\n", "-1\n", "6 8"]}
| 372
| 136
|
coding
|
Solve the programming task below in a Python markdown code block.
One day the Codeforces round author sat exams. He had n exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2.
The author would need to spend too much time and effort to make the sum of his marks strictly more than k. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than k, the author's mum won't be pleased at all.
The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams.
Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all n exams equal exactly k.
Input
The single input line contains space-separated integers n and k (1 β€ n β€ 50, 1 β€ k β€ 250) β the number of exams and the required sum of marks.
It is guaranteed that there exists a way to pass n exams in the way that makes the sum of marks equal exactly k.
Output
Print the single number β the minimum number of exams that the author will get a 2 for, considering that the sum of marks for all exams must equal k.
Examples
Input
4 8
Output
4
Input
4 10
Output
2
Input
1 3
Output
0
Note
In the first sample the author has to get a 2 for all his exams.
In the second sample he should get a 3 for two exams and a 2 for two more.
In the third sample he should get a 3 for one exam.
|
{"inputs": ["1 2\n", "1 5\n", "3 7\n", "4 9\n", "2 5\n", "2 6\n", "3 8\n", "1 4\n"], "outputs": ["1\n", "0\n", "2\n", "3\n", "1\n", "0\n", "1\n", "0\n"]}
| 390
| 86
|
coding
|
Solve the programming task below in a Python markdown code block.
Chef is given two arrays A and B of length N each.
In one operation Chef can choose one element of A and one element of B and increase them by 1.
More formally:
Chef can pick two integers i, j (1β€ i, j β€ N) and increment A_{i} and B_{j} by 1.
Determine the minimum number of operations required to make A and B equal.
Output -1 if it is not possible to make A and B equal.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- Each test case consists of multiple lines of input.
- The first line of each test case contains a single integer N - denoting the length of arrays A and B.
- The second line of each test case contains N space separated integers A_{1}, A_{2}, A_{3}, \dots A_{N} - denoting the array A.
- The third line of each test case contains N space separated integers B_{1}, B_{2}, B_{3}, \dots B_{N} - denoting the array B.
------ Output Format ------
For each test case, output the minimum number of operations to make A and B equal or -1 if they cannot be made equal.
------ Constraints ------
$1 β€ T β€ 2 \cdot 10^{4}$
$2 β€ N β€ 10^{5}$
$1 β€ A_{i}, B_{i} β€ 10^{9}$
- Sum of $N$ over all test cases do not exceed $10^{5}$.
----- Sample Input 1 ------
3
2
1 2
2 1
3
1 1 2
2 2 1
3
4 6 8
5 7 6
----- Sample Output 1 ------
1
-1
2
----- explanation 1 ------
Test case $1$: We can choose $i = 1$ and $j = 2$ and increment $A_{i}$ and $B_{j}$ by $1$. Thus, both arrays become $[2, 2]$ and are equal. We require only $1$ operation to make these arrays equal. It can be proven that the arrays cannot be made equal in less than one operation.
Test case $2$: Both the arrays cannot be made equal using any number of operations.
Test case $3$: We perform $2$ operations as follows:
- Choose $i = 1, j = 3$: The arrays become $A = [5, 6, 8]$ and $B = [5, 7, 7]$.
- Choose $i = 2, j = 3$: The arrays become $A = [5, 7, 8]$ and $B = [5, 7, 8]$.
Thus, both arrays can be made equal using $2$ operations.
|
{"inputs": ["3\n2\n1 2\n2 1\n3\n1 1 2\n2 2 1\n3\n4 6 8\n5 7 6\n"], "outputs": ["1\n-1\n2\n"]}
| 634
| 57
|
coding
|
Solve the programming task below in a Python markdown code block.
Given a string, turn each letter into its ASCII character code and join them together to create a number - let's call this number `total1`:
```
'ABC' --> 'A' = 65, 'B' = 66, 'C' = 67 --> 656667
```
Then replace any incidence of the number `7` with the number `1`, and call this number 'total2':
```
total1 = 656667
^
total2 = 656661
^
```
Then return the difference between the sum of the digits in `total1` and `total2`:
```
(6 + 5 + 6 + 6 + 6 + 7)
- (6 + 5 + 6 + 6 + 6 + 1)
-------------------------
6
```
Also feel free to reuse/extend the following starter code:
```python
def calc(x):
```
|
{"functional": "_inputs = [['abcdef'], ['ifkhchlhfd'], ['aaaaaddddr'], ['jfmgklf8hglbe'], ['jaam'], ['abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ']]\n_outputs = [[6], [6], [30], [6], [12], [96]]\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(calc(*i), o[0])"}
| 227
| 202
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a string S of length N.
You can apply the following operation on the string any number of times:
Choose an index i (1β€ i < N), and swap S_{i} with S_{i+1}, if S_{i} and S_{i+1} contain adjacent characters.
For example, a and b are adjacent, z and y are adjacent, x and y are adjacent, while c and e are not adjacent. Note that a and z are not considered adjacent.
Find the lexicographically smallest string you can obtain, by applying the above operation any number of times.
Note: String X is lexicographically smaller than string Y if X_{i} < Y_{i}, where i is the first index where X and Y differ.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- Each test case consists of multiple lines of input.
- The first line of each test case contains an integer N β the length of the string.
- The second line contains the string S, consisting of lowercase english alphabets.
------ Output Format ------
For each test case, output on a new line - the lexicographically smallest string that we can obtain from the given string using any number of operations.
------ Constraints ------
$1 β€ T β€ 10^{4}$
$1 β€ N β€ 2\cdot 10^{5}$
$S$ consists of lowercase english alphabets only.
- The sum of $N$ over all test cases won't exceed $2\cdot 10^{5}$.
----- Sample Input 1 ------
2
5
cbaba
6
dbbced
----- Sample Output 1 ------
bbcaa
cdbbde
----- explanation 1 ------
Test case $1$: For the given string cbaba:
- We swap c and b at indices $1$ and $2$ and the string becomes: bcaba.
- Swap a and b at indices $3$ and $4$ and the string becomes: bcbaa.
- Finally swap c and b at indices $2$ and $3$ and the string becomes: bbcaa.
Note that this is the lexicographically smallest string we can obtain using any number of operations.
Test case $2$: For the given string dbbced:
- We swap b and c at indices $3$ and $4$ and the string becomes: dbcbed.
- Swap b and c at indices $2$ and $3$ and the string becomes: dcbbed.
- Swap d and c at indices $1$ and $2$ and the string becomes: cdbbed.
- Finally swap e and d at indices $5$ and $6$ and the string becomes: cdbbde.
Note that this is the lexicographically smallest string we can obtain using any number of operations.
|
{"inputs": ["2\n5\ncbaba\n6\ndbbced"], "outputs": ["bbcaa\ncdbbde"]}
| 619
| 30
|
coding
|
Solve the programming task below in a Python markdown code block.
Same as [the original](https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6) (same rules, really, go there for example and I strongly recommend completing it first), but with more than one asterisk (but always at least one).
For example, `"*2"` should return `["12", "42", "72"]`.
Similarly, `"*2*"` should return `["024", "120", "126", "222", "228", "324", "420", "426", "522", "528", "624", "720", "726", "822", "828", "924"]`. Order matters and returning the right one is part of the challenge itself, yep!
More examples in the test codes and, of course, if you cannot generate any number divisible by 6, just return `[]` (or `[] of String` in Crystal).
Also feel free to reuse/extend the following starter code:
```python
def is_divisible_by_6(s):
```
|
{"functional": "_inputs = [['*2'], ['*21'], ['**1'], ['*2*'], ['***']]\n_outputs = [[['12', '42', '72']], [[]], [[]], [['024', '120', '126', '222', '228', '324', '420', '426', '522', '528', '624', '720', '726', '822', '828', '924']], [['000', '006', '012', '018', '024', '030', '036', '042', '048', '054', '060', '066', '072', '078', '084', '090', '096', '102', '108', '114', '120', '126', '132', '138', '144', '150', '156', '162', '168', '174', '180', '186', '192', '198', '204', '210', '216', '222', '228', '234', '240', '246', '252', '258', '264', '270', '276', '282', '288', '294', '300', '306', '312', '318', '324', '330', '336', '342', '348', '354', '360', '366', '372', '378', '384', '390', '396', '402', '408', '414', '420', '426', '432', '438', '444', '450', '456', '462', '468', '474', '480', '486', '492', '498', '504', '510', '516', '522', '528', '534', '540', '546', '552', '558', '564', '570', '576', '582', '588', '594', '600', '606', '612', '618', '624', '630', '636', '642', '648', '654', '660', '666', '672', '678', '684', '690', '696', '702', '708', '714', '720', '726', '732', '738', '744', '750', '756', '762', '768', '774', '780', '786', '792', '798', '804', '810', '816', '822', '828', '834', '840', '846', '852', '858', '864', '870', '876', '882', '888', '894', '900', '906', '912', '918', '924', '930', '936', '942', '948', '954', '960', '966', '972', '978', '984', '990', '996']]]\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_divisible_by_6(*i), o[0])"}
| 268
| 1,106
|
coding
|
Solve the programming task below in a Python markdown code block.
```if-not:rust
Your task is to write a function `toLeetSpeak` that converts a regular english sentence to Leetspeak.
```
```if:rust
Your task is to write a function `to_leet_speak` that converts a regular english sentence to Leetspeak.
```
More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet
Consider only uppercase letters (no lowercase letters, no numbers) and spaces.
For example:
```if-not:rust
~~~
toLeetSpeak("LEET") returns "1337"
~~~
```
```if:rust
~~~
to_leet_speak("LEET") returns "1337"
~~~
```
In this kata we use a simple LeetSpeak dialect. Use this alphabet:
```
{
A : '@',
B : '8',
C : '(',
D : 'D',
E : '3',
F : 'F',
G : '6',
H : '#',
I : '!',
J : 'J',
K : 'K',
L : '1',
M : 'M',
N : 'N',
O : '0',
P : 'P',
Q : 'Q',
R : 'R',
S : '$',
T : '7',
U : 'U',
V : 'V',
W : 'W',
X : 'X',
Y : 'Y',
Z : '2'
}
```
Also feel free to reuse/extend the following starter code:
```python
def to_leet_speak(str):
```
|
{"functional": "_inputs = [['LEET'], ['CODEWARS'], ['HELLO WORLD'], ['LOREM IPSUM DOLOR SIT AMET'], ['THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG']]\n_outputs = [['1337'], ['(0D3W@R$'], ['#3110 W0R1D'], ['10R3M !P$UM D010R $!7 @M37'], ['7#3 QU!(K 8R0WN F0X JUMP$ 0V3R 7#3 1@2Y D06']]\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(to_leet_speak(*i), o[0])"}
| 367
| 279
|
coding
|
Solve the programming task below in a Python markdown code block.
The new PIN is hard to remember. I was told that I shouldn't take notes, but I don't think I can remember them. Therefore, I decided to embed a numerical value in the text and make a note of the PIN. Here, the sum of all the numbers is the PIN.
Create a program that reads the memorandum and outputs the PIN code.
Input
Sentences with embedded positive integers are given over multiple lines. Each line is a character string containing single-byte alphanumeric characters, symbols, and spaces, or a blank line. However, you are guaranteed to enter no more than 80 characters per line and a PIN of 10,000 or less.
Output
The PIN (the sum of positive integers in the text) is output on one line.
Example
Input
Thereare100yenonthetable.Iam17yearsold.
Ishouldgohomeat6pm.
Output
123
|
{"inputs": ["Thereare100yenonthetable.Iam17yearsold.\n.mp6taemohogdluohsI", ".dlosr`ey71maI.elbasehtnoney001eraerehT\n.mp6taelohdgoltohsI", ".closr`ey71maI-elbasegtnoney001eragrehT\nIshptkogdhomemt5q`.", "Thergarn100yeeontgesable-Iam17ye`rsolc.\nIshptkogdhomemt5q`.", "Thergarn10Iyeeontgesable-0am17ye`rsolc.\nIshptkogdhomemt5q`.", "Thergarno0Iyee1mtgesable-0al17ye`rsolc.\nqI.otmemohdg5ktpis`", ".closr`ez61la0-egbaseltl1epyI0enragrehT\n`singk5sdholfpso/Iq", "ThIrgarne0eype1ltlesabge-0al16ze`rsolc.\nqI/ospflnhds5kgnis`"], "outputs": ["123\n", "78\n", "77\n", "122\n", "32\n", "23\n", "67\n", "22\n"]}
| 205
| 332
|
coding
|
Solve the programming task below in a Python markdown code block.
# Task
John is an orchard worker.
There are `n` piles of fruits waiting to be transported. Each pile of fruit has a corresponding weight. John's job is to combine the fruits into a pile and wait for the truck to take them away.
Every time, John can combine any two piles(`may be adjacent piles, or not`), and the energy he costs is equal to the weight of the two piles of fruit.
For example, if there are two piles, pile1's weight is `1` and pile2's weight is `2`. After merging, the new pile's weight is `3`, and he consumed 3 units of energy.
John wants to combine all the fruits into 1 pile with the least energy.
Your task is to help John, calculate the minimum energy he costs.
# Input
- `fruits`: An array of positive integers. Each element represents the weight of a pile of fruit.
Javascript:
- 1 <= fruits.length <= 10000
- 1 <= fruits[i] <= 10000
Python:
- 1 <= len(fruits) <= 5000
- 1 <= fruits[i] <= 10000
# Output
An integer. the minimum energy John costs.
# Examples
For `fruits = [1,2,9]`, the output should be `15`.
```
3 piles: 1 2 9
combine 1 and 2 to 3, cost 3 units of energy.
2 piles: 3 9
combine 3 and 9 to 12, cost 12 units of energy.
1 pile: 12
The total units of energy is 3 + 12 = 15 units
```
For `fruits = [100]`, the output should be `0`.
There's only 1 pile. So no need combine it.
Also feel free to reuse/extend the following starter code:
```python
def comb(fruits):
```
|
{"functional": "_inputs = [[[1, 2, 9]], [[100]], [[1, 2]], [[4, 3, 5, 6, 10, 20]], [[87, 84, 42, 34, 24, 81, 60, 48, 75]], [[11, 9, 20, 10, 21, 35, 15, 34, 48, 76, 94, 28, 79, 16, 4, 41, 98, 30, 35, 92, 93, 33, 100, 93, 64, 23, 37, 6, 86, 27, 48, 16, 66, 99, 61, 83, 3, 5, 95]]]\n_outputs = [[15], [0], [3], [111], [1663], [9056]]\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(comb(*i), o[0])"}
| 452
| 402
|
coding
|
Solve the programming task below in a Python markdown code block.
Two words are anagrams of one another if their letters can be rearranged to form the other word.
Given a string, split it into two contiguous substrings of equal length. Determine the minimum number of characters to change to make the two substrings into anagrams of one another.
Example
$s=\textbf{abccde}$
Break $\boldsymbol{\mathrm{~S~}}$ into two parts: 'abc' and 'cde'. Note that all letters have been used, the substrings are contiguous and their lengths are equal. Now you can change 'a' and 'b' in the first substring to 'd' and 'e' to have 'dec' and 'cde' which are anagrams. Two changes were necessary.
Function Description
Complete the anagram function in the editor below.
anagram has the following parameter(s):
string s: a string
Returns
int: the minimum number of characters to change or -1.
Input Format
The first line will contain an integer, $\textit{q}$, the number of test cases.
Each test case will contain a string $\boldsymbol{\mathrm{~S~}}$.
Constraints
$1\leq q\leq100$
$1\leq|s|\leq10^4$
$\boldsymbol{\mathrm{~S~}}$ consists only of characters in the range ascii[a-z].
Sample Input
6
aaabbb
ab
abc
mnop
xyyx
xaxbbbxx
Sample Output
3
1
-1
2
0
1
Explanation
Test Case #01: We split $\boldsymbol{\mathrm{~S~}}$ into two strings $\mbox{S1}$='aaa' and $\mbox{S2}$='bbb'. We have to replace all three characters from the first string with 'b' to make the strings anagrams.
Test Case #02: You have to replace 'a' with 'b', which will generate "bb".
Test Case #03: It is not possible for two strings of unequal length to be anagrams of one another.
Test Case #04: We have to replace both the characters of first string ("mn") to make it an anagram of the other one.
Test Case #05: $\mbox{S1}$ and $\mbox{S2}$ are already anagrams of one another.
Test Case #06: Here S1 = "xaxb" and S2 = "bbxx". You must replace 'a' from S1 with 'b' so that S1 = "xbxb".
|
{"inputs": ["6\naaabbb\nab\nabc\nmnop\nxyyx\nxaxbbbxx\n"], "outputs": ["3\n1\n-1\n2\n0\n1\n"]}
| 581
| 43
|
coding
|
Solve the programming task below in a Python markdown code block.
Given is a string S. Replace every character in S with x and print the result.
-----Constraints-----
- S is a string consisting of lowercase English letters.
- The length of S is between 1 and 100 (inclusive).
-----Input-----
Input is given from Standard Input in the following format:
S
-----Output-----
Replace every character in S with x and print the result.
-----Sample Input-----
sardine
-----Sample Output-----
xxxxxxx
Replacing every character in S with x results in xxxxxxx.
|
{"inputs": ["x\n", "a\n", "z\n", "i\n", "xxwx", "gpne", "wxwx", "gpnd"], "outputs": ["x\n", "x\n", "x\n", "x\n", "xxxx\n", "xxxx\n", "xxxx\n", "xxxx\n"]}
| 120
| 70
|
coding
|
Solve the programming task below in a Python markdown code block.
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.
Now Petya wants to know for each friend i the number of a friend who has given him a gift.
Input
The first line contains one integer n (1 β€ n β€ 100) β the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi β the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.
Output
Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.
Examples
Input
4
2 3 4 1
Output
4 1 2 3
Input
3
1 3 2
Output
1 3 2
Input
2
1 2
Output
1 2
|
{"inputs": ["1\n1\n", "2\n2 1\n", "2\n1 2\n", "3\n1 3 2\n", "4\n2 3 4 1\n", "5\n5 4 3 2 1\n", "6\n4 3 6 5 1 2\n", "7\n2 1 5 7 3 4 6\n"], "outputs": ["1 \n", "2 1 \n", "1 2 \n", "1 3 2 \n", "4 1 2 3 \n", "5 4 3 2 1 \n", "5 6 2 1 4 3 \n", "2 1 5 6 3 7 4 \n"]}
| 386
| 182
|
coding
|
Solve the programming task below in a Python markdown code block.
Arya is new to matrices. With lots of subtopics in the chapter, he finds it difficult in getting good in all of them. As of now, he is practising matrix multiplications. He takes two different matrices and checks in how many different ways could they be multiplied. If they are multiplicable, he multiplies in all the ways possible.
Your job is, for a given order of two matrices, find how many unique matrix multiplications does Arya do with them.
Input Format:
First line contains T, number of test cases.
T lines follows, denoting T test cases.
Each test case has 4 integer numbers x1,y1,x2,y2. Where x1,y1 are number of rows and columns of matrix A and x2,y2 are number of rows and columns of matrix B.
Output Format:
Output single integer in answer for each test case in separate lines.
Constraints:
1 β€ T β€ 100
1 β€ x1,x2,y1,y2 β€ 100
Problem Setter : Vinay Kumar
SAMPLE INPUT
2
2 2 2 2
4 3 2 1
SAMPLE OUTPUT
2
0
|
{"inputs": ["11\n12 4 3 12\n12 4 4 12\n18 20 10 23\n10 13 11 8\n3 20 3 14\n13 23 12 20\n12 17 5 19\n15 22 22 9\n20 20 15 3\n7 19 18 8\n2 16 6 19", "36\n30 2 2 30\n14 1 2 14\n30 6 38 40\n9 24 25 11\n7 48 10 18\n18 22 21 19\n4 24 24 23\n31 38 6 22\n30 49 34 48\n46 1 6 6\n9 31 11 48\n9 17 10 36\n42 15 20 19\n24 10 42 46\n43 27 39 16\n47 24 16 44\n10 32 23 5\n32 6 33 28\n39 40 41 48\n24 4 13 1\n33 17 18 32\n36 8 31 15\n19 29 34 25\n9 17 8 5\n13 19 48 30\n40 44 29 36\n26 29 40 21\n44 1 32 8\n25 28 22 6\n33 16 35 8\n29 7 49 24\n41 37 28 7\n18 5 11 32\n16 13 4 40\n6 46 47 48\n44 1 2 34", "70\n70 40 56 70\n70 40 40 70\n24 80 73 44\n70 40 56 71\n6 41 42 2\n43 5 96 26\n99 56 80 55\n27 34 61 9\n92 77 45 18\n55 19 33 11\n74 76 96 4\n52 44 14 53\n78 57 82 55\n30 21 60 77\n47 29 75 40\n51 73 63 36\n16 41 50 6\n84 70 60 82\n5 58 44 54\n10 55 1 57\n57 88 12 82\n8 87 7 69\n15 54 16 79\n81 66 25 76\n54 97 7 74\n17 38 65 64\n64 21 94 10\n72 74 75 92\n52 30 60 85\n44 57 17 64\n7 56 9 30\n5 87 20 33\n88 59 82 25\n55 3 94 48\n78 17 22 86\n77 51 88 94\n11 30 78 48\n22 54 84 94\n26 28 10 93\n52 31 14 30\n39 38 87 93\n66 93 41 79\n56 42 9 62\n45 32 92 96\n60 53 61 68\n36 82 7 45\n41 62 10 14\n15 92 90 21\n54 53 31 75\n31 20 45 71\n49 84 60 53\n21 91 16 52\n18 80 44 74\n62 53 60 48\n88 1 13 68\n75 1 93 1\n90 30 52 22\n47 21 47 96\n57 93 3 7\n88 75 85 17\n73 4 53 27\n81 33 57 14\n68 67 33 67\n45 41 68 24\n14 35 70 20\n22 60 53 16\n70 76 53 54\n61 56 56 36\n16 34 60 3\n81 94 64 15"], "outputs": ["1\n2\n0\n0\n0\n0\n0\n1\n0\n0\n0", "2\n1\n0\n0\n0\n0\n1\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0", "1\n2\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n1\n0\n0"]}
| 258
| 1,588
|
coding
|
Solve the programming task below in a Python markdown code block.
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`).
If the input is `0` or negative value, then you should return `"00:00"`
**Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example the remainder of 5 / 2 is 1, so 5 modulo 2 is 1.
## Example
If the input is `78`, then you should return `"01:18"`, because 78 minutes converts to 1 hour and 18 minutes.
Good luck! :D
Also feel free to reuse/extend the following starter code:
```python
def time_convert(num):
```
|
{"functional": "_inputs = [[0], [-6], [8], [32], [75], [63], [134], [180], [970], [565757]]\n_outputs = [['00:00'], ['00:00'], ['00:08'], ['00:32'], ['01:15'], ['01:03'], ['02:14'], ['03:00'], ['16:10'], ['9429:17']]\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(time_convert(*i), o[0])"}
| 173
| 264
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
The following is an easy game that the setter of this problem played when he was 8:
A boatman, a wolf, a sheep, and a cabbage are on the bank of a river. They have a small boat that is capable of carrying the boatman and at most one other animal/item with him. However, if left alone by the boatman, the wolf can eat the sheep, and the sheep can eat the cabbage. How can all four be moved safely to the opposite bank of the river?
Here is a nice visualization of the whole process in the original game. Disclaimer: writers, testers and CodeChef are not related to this link.
This leads to a more general problem. If there are other groups of animals/items with the boatman, is it possible to move them all to the opposite bank of the river in such a way that nobody/nothing gets eaten?
We will give you the number of animals/items (not including the boatman). Moreover, we will give you all a list of pairs of the form "X Y" where the X-th animal/item will be eaten by the Y-th one if they are both on the opposite bank to the boatman.
You are to determine whether it is possible to achieve the task or not.
------ 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 contains two space separated integers N and M - the number of animals/items not including the boatman, and the number of relations of the form "X will be eaten by Y", respectively.
The following M lines contain pairs of the form X Y with the meaning that the X-th animal/item will be eaten by the Y-th one if they are both on the opposite bank to the boatman.
------ Output ------
For each test case, output a single line containing either "YES" or "NO" - the answer to the question "Is it possible to move them all to the opposite bank of the river in such a way that nobody/nothing gets eaten?".
------ Constraints ------
$1 β€ T β€ 100000$
$Subtask 1: 1 β€ N β€ 5, 0 β€ M β€ 10 - 73 points.$
$Subtask 2: 1 β€ N β€ 10, 0 β€ M β€ 20 - 27 points.$
----- Sample Input 1 ------
2
3 2
1 2
2 3
3 3
1 2
2 3
1 3
----- Sample Output 1 ------
YES
NO
----- explanation 1 ------
The first example is the original version of the problem.
The second example would have a solution if a boat could seat an additional animal/item.
|
{"inputs": ["2\n3 2\n1 2\n2 3\n3 3\n1 2\n2 3\n1 3", "2\n3 2\n1 2\n2 3\n3 3\n1 2\n2 3\n2 3", "2\n4 2\n1 2\n4 3\n3 3\n1 2\n3 3\n2 2", "2\n3 2\n1 2\n2 5\n3 2\n1 2\n2 3\n1 1", "2\n7 4\n1 2\n2 3\n4 3\n1 2\n2 0\n2 4", "2\n4 2\n1 2\n2 3\n3 3\n1 2\n2 3\n2 3", "2\n3 2\n1 2\n1 3\n3 3\n1 2\n2 3\n2 3", "2\n4 2\n1 2\n2 3\n3 3\n1 2\n2 3\n2 1"], "outputs": ["YES\nNO", "YES\nNO\n", "NO\nNO\n", "YES\nYES\n", "NO\nYES\n", "YES\nNO\n", "YES\nNO\n", "YES\nNO\n"]}
| 608
| 301
|
coding
|
Solve the programming task below in a Python markdown code block.
N of us are going on a trip, by train or taxi.
The train will cost each of us A yen (the currency of Japan).
The taxi will cost us a total of B yen.
How much is our minimum total travel expense?
-----Constraints-----
- All values in input are integers.
- 1 \leq N \leq 20
- 1 \leq A \leq 50
- 1 \leq B \leq 50
-----Input-----
Input is given from Standard Input in the following format:
N A B
-----Output-----
Print an integer representing the minimum total travel expense.
-----Sample Input-----
4 2 9
-----Sample Output-----
8
The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.
|
{"inputs": ["6 2 7", "4 4 9", "3 2 8", "6 1 0", "6 4 1", "7 4 2", "5 2 5", "5 2 8"], "outputs": ["7\n", "9\n", "6\n", "0\n", "1\n", "2\n", "5\n", "8\n"]}
| 199
| 94
|
coding
|
Solve the programming task below in a Python markdown code block.
In this problem the input will consist of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks ' (apostrophe), . (full stop), , (comma), ; (semicolon), :(colon) and white space characters (blank, newline).
Your task is print the words in the text in lexicographic order (that is, dictionary order). Each word should appear exactly once in your list. You can ignore the case (for instance, "The" and "the" are to be treated as the same word). There should be no uppercase letters in the output.
For example, consider the following candidate for the input text:
This is a sample piece of text to illustrate this
problem.
The corresponding output would read as:
a
illustrate
is
of
piece
problem
sample
text
this
to
-----Input format-----
- The first line of input contains a single integer $N$, indicating the number of lines in the input.
- This is followed by $N$ lines of input text.
-----Output format-----
- The first line of output contains a single integer $M$ indicating the number of distinct words in the given text.
- The next $M$ lines list out these words in lexicographic order.
-----Constraints-----
- $1 \leq N \leq 10000$
- There are at most 80 characters in each line.
- There are at the most 1000 distinct words in the given text.
-----Sample Input-----
2
This is a sample piece of text to illustrate this
problem.
-----Sample Output-----
10
a
illustrate
is
of
piece
problem
sample
text
this
to
|
{"inputs": ["2\nThis is a sample piece of text to illustrate this\nproblem."], "outputs": ["10\na\nillustrate\nis\nof\npiece\nproblem\nsample\ntext\nthis\nto"]}
| 374
| 50
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a 2D integer array groups of length n. You are also given an integer array nums.
You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).
Return true if you can do this task, and false otherwise.
Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.
Β
Please complete the following python code precisely:
```python
class Solution:
def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:
```
|
{"functional": "def check(candidate):\n assert candidate(groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]) == True\n assert candidate(groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]) == False\n assert candidate(groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]) == False\n\n\ncheck(Solution().canChoose)"}
| 204
| 137
|
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.
Chef Aditi keeps changing the flavours of her dishes and she wants to analyse feedback from her customers in order to improve her performance. The customers visiting Aditi's restaurant can rate the food online and Aditi knows an aggregated rating for each day. As she is busy cooking, you should perform the data analysis.
You are given a sequence $A_{1}, A_{2}, \ldots, A_{N}$ of distinct integers denoting the customers' feedback during $N$ days. You should process $Q$ queries. In each query, you are given two integers $L$ and $R$. Consider any contiguous subsequence $A_{p}, A_{p+1}, \ldots, A_{q}$, where $L β€ p < q β€ R$; let's call it a *maximal increasing subsequence* if the following conditions hold:
$A_{p} < A_{p+1} \ldots < A_{q}$
if $p > L$, then $A_{p} < A_{p-1}$
if $q < R$, then $A_{q} > A_{q+1}$
Similarly, let's define a *maximal decreasing subsequence*. You should find out if the number of maximal increasing subsequences is equal to the number of maximal decreasing subsequences (with $L β€ p < q β€ R$).
For example, if $A = (10, 20, 30, 5)$, we can see that the only maximal increasing subsequence of this sequence (for $L=1$ and $R=N$) is $(10, 20, 30)$, since $(10, 20)$ does not satisfy the third condition and $(20, 30)$ does not satisfy the second condition, and there is only one maximal decreasing subsequence $(30, 5)$.
------ Input ------
The first line of the input contains two space-separated integers $N$ and $Q$.
The second line contains $N$ space-separated integers $A_{1}, A_{2}, \ldots, A_{N}$.
$Q$ lines follow. Each of these lines contains two space-separated integers $L$ and $R$ describing a query.
------ Output ------
For each query, print a single line containing the string "YES" if the number of maximal increasing contiguous subsequences is equal to the number of maximal decreasing contiguous subsequences or "NO" otherwise (without quotes).
------ Constraints ------
$2 β€ N β€ 10^{5}$
$1 β€ Q β€ 10^{5}$
$1 β€ A_{i} β€ 10^{9}$ for each valid $i$
$1 β€ L < R β€ N$
$A_{1}, A_{2}, \ldots, A_{N}$ are pairwise distinct
------ Subtasks ------
Subtasks #1 (20 points): $Q β€ 50$
Subtasks #2 (80 points): original constraints
----- Sample Input 1 ------
4 3
1 3 2 4
1 4
2 3
2 4
----- Sample Output 1 ------
NO
NO
YES
----- explanation 1 ------
For the first query, there are two maximal increasing subsequences $(1, 3)$ and $(2, 4)$, but only one maximal decreasing subsequence $(3, 2)$.
|
{"inputs": ["4 3\n1 3 2 4\n1 4\n2 3\n2 4"], "outputs": ["NO\nNO\nYES"]}
| 768
| 38
|
coding
|
Solve the programming task below in a Python markdown code block.
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.
A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m β€ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.
Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.
Help the Beaver to write a program that will encrypt messages in the described manner.
Input
The first input line contains three integers n, m and c, separated by single spaces.
The second input line contains n integers ai (0 β€ ai < c), separated by single spaces β the original message.
The third input line contains m integers bi (0 β€ bi < c), separated by single spaces β the encryption key.
The input limitations for getting 30 points are:
* 1 β€ m β€ n β€ 103
* 1 β€ c β€ 103
The input limitations for getting 100 points are:
* 1 β€ m β€ n β€ 105
* 1 β€ c β€ 103
Output
Print n space-separated integers β the result of encrypting the original message.
Examples
Input
4 3 2
1 1 1 1
1 1 1
Output
0 1 1 0
Input
3 1 5
1 2 3
4
Output
0 1 2
Note
In the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
|
{"inputs": ["3 1 5\n1 2 3\n7\n", "3 1 5\n1 0 3\n7\n", "3 1 5\n1 1 3\n7\n", "3 1 1\n1 0 3\n7\n", "3 1 1\n2 0 3\n7\n", "3 1 1\n2 0 0\n7\n", "3 1 5\n1 2 3\n4\n", "3 1 1\n2 0 0\n14\n"], "outputs": ["3 4 0\n", "3 2 0\n", "3 3 0\n", "0 0 0\n", "0 0 0\n", "0 0 0\n", "0 1 2 ", "0 0 0\n"]}
| 580
| 198
|
coding
|
Solve the programming task below in a Python markdown code block.
Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?
Input
The first line contains the only integer n (1 β€ n β€ 100) β the number of cookie bags Anna and Maria have. The second line contains n integers ai (1 β€ ai β€ 100) β the number of cookies in the i-th bag.
Output
Print in the only line the only number β the sought number of ways. If there are no such ways print 0.
Examples
Input
1
1
Output
1
Input
10
1 2 2 3 4 4 4 2 2 2
Output
8
Input
11
2 2 2 2 2 2 2 2 2 2 99
Output
1
Note
In the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.
In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies β 5 + 3 = 8 ways in total.
In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2 * 9 + 99 = 117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies.
|
{"inputs": ["1\n2\n", "1\n4\n", "1\n8\n", "1\n1\n", "2\n1 2\n", "2\n2 2\n", "2\n1 1\n", "2\n0 1\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "2\n", "0\n", "1\n"]}
| 436
| 94
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Some robots are standing on an infinite number line with their initial coordinates given by a 0-indexed integer array nums and will start moving once given the command to move. The robots will move a unit distance each second.
You are given a string s denoting the direction in which robots will move on command. 'L' means the robot will move towards the left side or negative side of the number line, whereas 'R' means the robot will move towards the right side or positive side of the number line.
If two robots collide, they will start moving in opposite directions.
Return the sum of distances between all theΒ pairs of robots d seconds afterΒ the command. Since the sum can be very large, return it modulo 109 + 7.
Note:
For two robots at the index i and j, pair (i,j) and pair (j,i) are considered the same pair.
When robots collide, they instantly change their directions without wasting any time.
Collision happensΒ when two robots share the same place in aΒ moment.
For example, if a robot is positioned in 0 going to the right and another is positioned in 2 going to the left, the next second they'll be both in 1 and they will change direction and the next second the first one will be in 0, heading left, and another will be in 2, heading right.
For example,Β if a robot is positioned in 0 going to the right and another is positioned in 1Β going to the left, the next second the first one will be in 0, heading left, and another will be in 1, heading right.
Β
Please complete the following python code precisely:
```python
class Solution:
def sumDistance(self, nums: List[int], s: str, d: int) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [-2,0,2], s = \"RLL\", d = 3) == 8\n assert candidate(nums = [1,0], s = \"RL\", d = 2) == 5\n\n\ncheck(Solution().sumDistance)"}
| 394
| 70
|
coding
|
Solve the programming task below in a Python markdown code block.
# Task
Smartphones software security has become a growing concern related to mobile telephony. It is particularly important as it relates to the security of available personal information.
For this reason, Ahmed decided to encrypt phone numbers of contacts in such a way that nobody can decrypt them. At first he tried encryption algorithms very complex, but the decryption process is tedious, especially when he needed to dial a speed dial.
He eventually found the algorithm following: instead of writing the number itself, Ahmed multiplied by 10, then adds the result to the original number.
For example, if the phone number is `123`, after the transformation, it becomes `1353`. Ahmed truncates the result (from the left), so it has as many digits as the original phone number. In this example Ahmed wrote `353` instead of `123` in his smart phone.
Ahmed needs a program to recover the original phone number from number stored on his phone. The program return "impossible" if the initial number can not be calculated.
Note: There is no left leading zero in either the input or the output; Input `s` is given by string format, because it may be very huge ;-)
# Example
For `s="353"`, the result should be `"123"`
```
1230
+ 123
.......
= 1353
truncates the result to 3 digit -->"353"
So the initial number is "123"
```
For `s="123456"`, the result should be `"738496"`
```
7384960
+ 738496
.........
= 8123456
truncates the result to 6 digit -->"123456"
So the initial number is "738496"
```
For `s="4334"`, the result should be `"impossible"`
Because no such a number can be encrypted to `"4334"`.
# Input/Output
- `[input]` string `s`
string presentation of n with `1 <= n <= 10^100`
- `[output]` a string
The original phone number before encryption, or `"impossible"` if the initial number can not be calculated.
Also feel free to reuse/extend the following starter code:
```python
def decrypt(s):
```
|
{"functional": "_inputs = [['353'], ['444'], ['123456'], ['147'], ['4334']]\n_outputs = [['123'], ['404'], ['738496'], ['377'], ['impossible']]\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(decrypt(*i), o[0])"}
| 554
| 204
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
Find the leftmost occurrence of the substring part and remove it from s.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
Β
Please complete the following python code precisely:
```python
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
```
|
{"functional": "def check(candidate):\n assert candidate(s = \"daabcbaabcbc\", part = \"abc\") == \"dab\"\n assert candidate(s = \"axxxxyyyyb\", part = \"xy\") == \"ab\"\n\n\ncheck(Solution().removeOccurrences)"}
| 110
| 64
|
coding
|
Solve the programming task below in a Python markdown code block.
Your algorithm is so good at predicting the market that you now know what the share price of Mahindra & Mahindra. (M&M) will be for the next N days.
Each day, you can either buy one share of M&M, sell any number of shares of M&M that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?
Input
The first line contains the number of test cases T. T test cases follow:
The first line of each test case contains a number N. The next line contains N integers, denoting the predicted price of M&M shares for the next N days.
Output
Output T lines, containing the maximum profit which can be obtained for the corresponding test case.
Constraints
1 β€ T β€ 10
1 β€ N β€ 50000
All share prices are between 1 and 100000
SAMPLE INPUT
3
3
5 3 2
3
1 2 100
4
1 3 1 2
SAMPLE OUTPUT
0
197
3
Explanation
For the 1st case, you cannot obtain any profit because the share price never rises.
For the 2nd case, you can buy one share on the first two days, and sell both of them on the third day.
For the 3rd case, you can buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.
|
{"inputs": ["3\n3\n5 3 2\n3\n1 2 100\n4\n1 3 1 2"], "outputs": ["0\n197\n3"]}
| 341
| 46
|
coding
|
Solve the programming task below in a Python markdown code block.
The cat Snuke wants to play a popular Japanese game called Γ
tCoder, so Iroha has decided to teach him Japanese.
When counting pencils in Japanese, the counter word "ζ¬" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "ζ¬" in the phrase "N ζ¬" for a positive integer N not exceeding 999 is as follows:
- hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;
- pon when the digit in the one's place of N is 0, 1, 6 or 8;
- bon when the digit in the one's place of N is 3.
Given N, print the pronunciation of "ζ¬" in the phrase "N ζ¬".
-----Constraints-----
- N is a positive integer not exceeding 999.
-----Input-----
Input is given from Standard Input in the following format:
N
-----Output-----
Print the answer.
-----Sample Input-----
16
-----Sample Output-----
pon
The digit in the one's place of 16 is 6, so the "ζ¬" in "16 ζ¬" is pronounced pon.
|
{"inputs": ["4", "6", "9", "8", "5", "0", "1", "7"], "outputs": ["hon\n", "pon\n", "hon\n", "pon\n", "hon\n", "pon\n", "pon\n", "hon\n"]}
| 270
| 62
|
coding
|
Solve the programming task below in a Python markdown code block.
Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams.
Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry.
However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that the items are split into two groups, and one group contains exactly K items. Then Chef will carry the heavier group, and his son will carry the other group.
Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the maximum possible difference between the weight carried by him and the weight carried by the kid.
-----Input:-----
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. The first line of each test contains two space-separated integers N and K. The next line contains N space-separated integers W1, W2, ..., WN.
-----Output:-----
For each test case, output the maximum possible difference between the weights carried by both in grams.
-----Constraints:-----
- 1 β€ T β€ 100
- 1 β€ K < N β€ 100
- 1 β€ Wi β€ 100000 (105)
-----Example:-----
Input:
2
5 2
8 4 5 2 10
8 3
1 1 1 1 1 1 1 1
Output:
17
2
-----Explanation:-----
Case #1: The optimal way is that Chef gives his son K=2 items with weights 2 and 4. Chef carries the rest of the items himself. Thus the difference is: (8+5+10) β (4+2) = 23 β 6 = 17.
Case #2: Chef gives his son 3 items and he carries 5 items himself.
|
{"inputs": ["2\n5 2\n3 2 5 2 1\n8 3\n1 1 1 1 1 1 0 1", "2\n5 2\n3 2 5 0 6\n8 3\n1 0 1 1 1 1 1 1", "2\n5 1\n3 2 5 2 1\n8 3\n1 1 1 1 1 1 0 1", "2\n5 2\n3 4 5 1 6\n8 3\n0 1 1 0 1 1 0 1", "2\n5 2\n3 2 5 2 8\n8 4\n1 1 1 1 1 1 1 1", "2\n5 2\n3 2 5 0 6\n8 3\n0 0 1 1 1 1 1 1", "2\n5 1\n3 2 5 2 1\n8 3\n1 1 1 1 1 0 0 1", "2\n5 2\n3 2 5 2 8\n8 4\n1 1 1 1 0 1 1 1"], "outputs": ["7\n3\n", "12\n3\n", "11\n3\n", "11\n5\n", "12\n0\n", "12\n4\n", "11\n4\n", "12\n1\n"]}
| 485
| 357
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian as well.
There are N cards placed in a row, where every card has two numbers written on it, one on the top and
one on the bottom. The numbers are between 1 and N (both inclusive). Every number is written on the top of exactly one card, and on the bottom of exactly one card as well.
Chef wants to rearrange the cards, such that the length of the longest common contiguous subsequence between the sequence formed by number written on top of the cards, and that formed by those written on the bottom is maximum. He can't modify the numbers written on any card and can't flip the cards, that is, for any card the number written on top remains at the top and the number written on bottom stays at the bottom. Find out the maximum possible length of the common contiguous subsequence.
------ Input ------
The first line of input contains an integer T denoting the number of test cases.
The first line of each test
case contains an integer N.
The next line contains N space separated integers A_{1}, A_{2}, ... , A_{N}, where A_{i}(1 β€ i β€ N) is the number written on the top of the i-th card.
The next line contains N space separated integers B_{1}, B_{2}, ... , B_{N}, where B_{i}(1 β€ i β€ N) is the number written at the bottom of the i-th card.
------ Output ------
For each test case, output a single line containing the integer L: the maximum length of the longest common contiguous subsequence.
------ Constraints ------
$1 β€ T β€ 100 $
$1 β€ N β€ 2000 $
$1 β€ A_{i}, B_{i} β€ N $
$All the elements in both arrays A and B are distinct.$
----- Sample Input 1 ------
2
3
1 3 2
2 1 3
8
3 8 4 2 6 1 5 7
5 2 4 3 8 7 6 1
----- Sample Output 1 ------
2
4
----- explanation 1 ------
First Example :
One of the possible card arrangements is:
1 2 3
2 3 1
Length of the longest common contiguous subsequence between [1, 2, 3] and [2, 3, 1] is 2, [2, 3]. And that's the maximum possible, so answer is 2.
Second Example:
One of the possible card arrangements is :
7 3 2 8 6 5 4 1
1 5 3 2 8 6 4 7
The longest common contiguous subsequence has length 4 [3, 2, 8, 6] here. There is no way to arrange these cards such that it's more than 4.
Note
Let L be the answer. Let Ci be the value written on the top of the card at ith position and Di be the value written on the bottom of the card at ith position after rearranging. Then, there should be a pair (x, y) (1 ? x,y ? N-L+1) such that the condition Cx+j = Dy+j is satisfied for all j, where 0 ? j .
|
{"inputs": ["2\n3\n1 3 2\n2 1 3\n8\n3 8 4 2 6 1 5 7\n5 2 4 3 8 7 6 1"], "outputs": ["2\n4"]}
| 732
| 62
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
Our chef Remy ate all the delicious food he made. As a result, he has become really fat :). Chef's assistant Linguini has taken up the
herculean task of bringing back chef Remy to shape.
Linguini has built a fence which has N planks in a straight line. The planks are numbered 1 to N from left to right. In front of M of these N planks, he has put a bucket of paint. The paints may be of different colors. Each color is represented by any uppercase letter (A-Z). Chef Remy needs to paint the fence. He uses his painting brush to paint the fence.
Chef Remy starts the task by choosing a plank which has a bucket of paint in front of it and dips his brush in the bucket. He starts walking
randomly along the straight fence passing the planks. He never moves out of the fence. Note that walking randomly along a fence means that Remy keeps walking all the time along his current direction. He can change his direction any time he wishes. Moving along a straight fence has just two directions, forward and backward.
Linguini has devised the following recipe for painting the fence.
Each bucket has an infinite supply of paint.
The brush can carry paint of a single color at any time.
When Remy passes a paint bucket, the brush acquires the color in the
bucket first.
Every plank that Remy passes in his random walk must be colored with
the color in the brush. A plank will be colored completely.
A plank can be colored multiple times. A plank's color is the latest color it
is painted with.
A fence coloring is complete when each plank is painted with some color.
Linguini is watching Remy dance around with colors. He wonders how many different complete fence colorings will he be able to see. Two fence colorings are different if there is atleast one plank numbered x whose color differs in both the colorings. Find out the number of
different complete fence colorings modulo 1000000009.
------ Input ------
First line contains T, the number of test cases. T test cases follow. The first line of each case contains N and M
separated by a space. Next M lines follow each of the form x and y separated by a space. Here x is the color in the bucket which is placed at plank
numbered y.
------ Constraints ------
$ 1 β€ T β€ 10 $
$ 1 β€ N β€ 100000 $
$ 1 β€ M β€ N $
$ x will be an uppercase letter between A to Z $
$ 1 β€ y β€ N $
------ Output ------
The number of different complete fence colorings modulo 1000000009 for each case on a new line.
----- Sample Input 1 ------
3
2 1
R 1
3 1
A 2
6 2
A 2
B 6
----- Sample Output 1 ------
1
1
4
|
{"inputs": ["3\n2 1\nR 1\n3 1\nA 2\n6 2\nA 2\nB 6"], "outputs": ["1\n1\n4"]}
| 668
| 44
|
coding
|
Solve the programming task below in a Python markdown code block.
Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.
He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:
- a < b + c
- b < c + a
- c < a + b
How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.
-----Constraints-----
- All values in input are integers.
- 3 \leq N \leq 2 \times 10^3
- 1 \leq L_i \leq 10^3
-----Input-----
Input is given from Standard Input in the following format:
N
L_1 L_2 ... L_N
-----Constraints-----
Print the number of different triangles that can be formed.
-----Sample Input-----
4
3 4 2 1
-----Sample Output-----
1
Only one triangle can be formed: the triangle formed by the first, second, and third sticks.
|
{"inputs": ["3\n4 2 3\n", "4\n5 4 2 1", "4\n5 2 2 1", "4\n8 2 2 1", "4\n8 2 1 1", "4\n6 4 2 1", "4\n5 4 3 1", "4\n6 2 2 1"], "outputs": ["1\n", "1\n", "1\n", "1\n", "0\n", "0\n", "1\n", "1\n"]}
| 252
| 125
|
coding
|
Solve the programming task below in a Python markdown code block.
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this:
* If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the numberβs integer part.
* If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the numberβs integer part.
* If the numberβs integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position.
Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the Kingβs order?
Input
The first line contains a single number to round up β the integer part (a non-empty set of decimal digits that do not start with 0 β with the exception of a case when the set consists of a single digit β in this case 0 can go first), then follows character Β«.Β» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.
Output
If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).
Examples
Input
0.0
Output
0
Input
1.49
Output
1
Input
1.50
Output
2
Input
2.71828182845904523536
Output
3
Input
3.14159265358979323846
Output
3
Input
12345678901234567890.1
Output
12345678901234567890
Input
123456789123456789.999
Output
GOTO Vasilisa.
|
{"inputs": ["7.6\n", "7.5\n", "8.3\n", "9.8\n", "0.9\n", "4.4\n", "2.6\n", "5.0\n"], "outputs": ["8", "8", "8", "GOTO Vasilisa.", "1", "4", "3", "5"]}
| 652
| 82
|
coding
|
Solve the programming task below in a Python markdown code block.
Master Shifu is training Po to become The Dragon Warrior and as a final assignment he must obtain maximum deliciousness from dumplings. There are $N$ plates of dumplings in front of him with deliciousness $A_1, A_2, \ldots, A_N$, Po can choose any number of continuous plates of dumplings. The total deliciousness is the sum of deliciousness of all the chosen dumplings.
What is the minimum number of plates he must choose so that total deliciousness is maximum possible?
Note: Po must choose atleast one plate.
-----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 line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
-----Output:-----
For each test case, print a single line containing one integer.
-----Constraints-----
- $1 \le T \le 10$
- $1 \le N \le 2 \cdot 10^5$
- $0 \le A_i \le 10^9$
-----Sample Input:-----
2
4
1 2 3 4
5
3 2 0 3 0
-----Sample Output:-----
4
4
|
{"inputs": ["2\n4\n1 2 3 4\n5\n3 2 0 3 0"], "outputs": ["4\n4"]}
| 313
| 36
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin Chinese and Russian.
As we all know, Binomial Coefficient C(n, r) is defined by the
following formula.
Also define S(n) as follows.
Note that n will be provided to you as an input parameter.
Since S(n) can be very large, please print it modulo (10^{9} + 7).
------ Input ------
The first line contains a single integer T representing the number of test cases.
Each of the next T lines contains an integer n.
------ Output ------
For each test case, output a single line containing the value of S(n) modulo (10^{9} + 7).
------ Constraints ------
10 points:
1 β€ T β€ 300
1 β€ n β€ 300
30 points:
1 β€ T β€ 10^{5}
1 β€ n β€ 5000
60 points:
1 β€ T β€ 10^{5}
1 β€ n β€ 10^{18}
------ Example ------
Input:
5
1
2
3
4
5
Output:
2
4
2
4
8
|
{"inputs": ["5\n1\n2\n3\n4\n5"], "outputs": ["2\n4\n2\n4\n8"]}
| 258
| 30
|
coding
|
Solve the programming task below in a Python markdown code block.
Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islands and n-1 bridges. The bridges are built so that all the islands are reachable from all the other islands by crossing one or more bridges. The bridge removal team can choose any island as the starting point, and can repeat either of the following steps.
* Move to another island by crossing a bridge that is connected to the current island.
* Remove one bridge that is connected to the current island, and stay at the same island after the removal.
Of course, a bridge, once removed, cannot be crossed in either direction. Crossing or removing a bridge both takes time proportional to the length of the bridge. Your task is to compute the shortest time necessary for removing all the bridges. Note that the island where the team starts can differ from where the team finishes the work.
Input
The input consists of at most 100 datasets. Each dataset is formatted as follows.
> n
> p2 p3 ... pn
> d2 d3 ... dn
The first integer n (3 β€ n β€ 800) is the number of the islands. The islands are numbered from 1 to n. The second line contains n-1 island numbers pi (1 β€ pi < i), and tells that for each i from 2 to n the island i and the island pi are connected by a bridge. The third line contains n-1 integers di (1 β€ di β€ 100,000) each denoting the length of the corresponding bridge. That is, the length of the bridge connecting the island i and pi is di. It takes di units of time to cross the bridge, and also the same units of time to remove it. Note that, with this input format, it is assured that all the islands are reachable each other by crossing one or more bridges.
The input ends with a line with a single zero.
Output
For each dataset, print the minimum time units required to remove all the bridges in a single line. Each line should not have any character other than this number.
Sample Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output for the Sample Input
80
136
2
Example
Input
4
1 2 3
10 20 30
10
1 2 2 1 5 5 1 8 8
10 1 1 20 1 1 30 1 1
3
1 1
1 1
0
Output
80
136
2
|
{"inputs": ["4\n1 2 2\n10 20 30\n10\n1 2 2 2 5 5 1 8 9\n9 1 1 20 2 2 5 1 1\n3\n1 1\n2 2\n0", "4\n1 2 2\n10 20 30\n10\n1 2 2 2 5 5 1 8 9\n9 1 1 20 2 2 5 1 2\n3\n1 1\n2 2\n0", "4\n1 2 2\n10 20 30\n10\n1 2 3 2 5 5 1 8 9\n9 1 1 20 2 2 5 1 2\n3\n1 1\n2 2\n0", "4\n1 2 2\n10 20 30\n10\n1 2 3 2 5 5 1 8 9\n9 1 1 20 2 4 5 1 2\n3\n1 1\n2 2\n0", "4\n1 2 2\n10 20 30\n10\n1 2 3 2 5 5 1 8 9\n9 1 1 35 2 4 5 1 2\n3\n1 1\n2 2\n0", "4\n1 2 2\n10 20 47\n10\n1 2 3 2 5 2 1 8 9\n9 1 1 35 2 4 5 1 2\n3\n1 1\n2 2\n0", "4\n1 2 3\n10 20 30\n10\n1 2 2 1 5 5 1 8 8\n10 1 1 20 1 1 0 1 1\n3\n1 1\n1 1\n0", "4\n1 2 3\n10 20 30\n10\n1 2 2 1 5 5 1 8 4\n10 1 1 20 1 1 0 1 1\n3\n1 1\n1 1\n0"], "outputs": ["60\n77\n4\n", "60\n78\n4\n", "60\n80\n4\n", "60\n82\n4\n", "60\n112\n4\n", "77\n112\n4\n", "80\n66\n2\n", "80\n67\n2\n"]}
| 659
| 650
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
We are given n different types of stickers. Each sticker has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.
Β
Please complete the following python code precisely:
```python
class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate( stickers = [\"with\",\"example\",\"science\"], target = \"thehat\") == 3\n assert candidate(stickers = [\"notice\",\"possible\"], target = \"basicbasic\") == -1\n\n\ncheck(Solution().minStickers)"}
| 179
| 68
|
coding
|
Solve the programming task below in a Python markdown code block.
Let's call a permutation $p$ of length $n$ anti-Fibonacci if the condition $p_{i-2} + p_{i-1} \ne p_i$ holds for all $i$ ($3 \le i \le n$). Recall that the permutation is the array of length $n$ which contains each integer from $1$ to $n$ exactly once.
Your task is for a given number $n$ print $n$ distinct anti-Fibonacci permutations of length $n$.
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 48$) β the number of test cases.
The single line of each test case contains a single integer $n$ ($3 \le n \le 50$).
-----Output-----
For each test case, print $n$ lines. Each line should contain an anti-Fibonacci permutation of length $n$. In each test case, you cannot print any permutation more than once.
If there are multiple answers, print any of them. It can be shown that it is always possible to find $n$ different anti-Fibonacci permutations of size $n$ under the constraints of the problem.
-----Examples-----
Input
2
4
3
Output
4 1 3 2
1 2 4 3
3 4 1 2
2 4 1 3
3 2 1
1 3 2
3 1 2
-----Note-----
None
|
{"inputs": ["2\n4\n3\n"], "outputs": ["1 4 3 2\n2 4 3 1\n3 4 2 1\n4 3 2 1\n1 3 2\n2 3 1\n3 2 1\n"]}
| 332
| 66
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in [Hindi], [Mandarin Chinese], [Russian], and [Vietnamese] as well.
Dr.D got so famous thanks to his first problem that he decided to commemorate it by making yet another problem with an almost identical statement β he only changed one word.
We want to choose exactly two integers (not necessarily distinct) from the interval $[L, R]$. Find the maximum possible value of the bitwise OR of the chosen integers.
------ 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 two space-separated integers $L$, $R$.
------ Output ------
For each test case, print a single line containing one integer β the maximum bitwise OR.
------ Constraints ------
$1 β€ T β€ 10^{5}$
$0 β€ L β€ R β€ 10^{18}$
----- Sample Input 1 ------
4
1 3
4 5
1031 93714
1000000000123 1000000123456
----- Sample Output 1 ------
3
5
131071
1000000192511
|
{"inputs": ["4\n1 3\n4 5\n1031 93714\n1000000000123 1000000123456"], "outputs": ["3\n5\n131071\n1000000192511"]}
| 306
| 82
|
coding
|
Solve the programming task below in a Python markdown code block.
Suppose Chef is stuck on an island and currently he has $x$ units of food supply and $y$ units of water supply in total that he could collect from the island. He needs $x_{r}$ units of food supply and $y_{r}$ units of water supply per day at the minimal to have sufficient energy to build a boat from the woods and also to live for another day. Assuming it takes exactly $D$ days to build the boat and reach the shore, tell whether Chef has the sufficient amount of supplies to be able to reach the shore by building the boat?
------ Input: ------
First line will contain $T$, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, five integers $x, y, x_{r}, y_{r}, D$.
------ Output: ------
For each testcase, output in a single line answer "YES" if Chef can reach the shore by building the boat and "NO" if not (without quotes).
You may print each character of each string in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and "YES" will all be treated as identical).
------ Constraints ------
$1 β€ T β€ 300$
$1 β€ x, y β€ 100$
$1 β€ x_{r}, y_{r}, D β€ 10$
----- Sample Input 1 ------
3
4 2 1 1 1
4 2 1 3 1
4 2 4 2 2
----- Sample Output 1 ------
YES
NO
NO
----- explanation 1 ------
TestCase 1: Chef's food supply will last for $\frac{4}{1} = 4$ days and water supply will last for $\frac{2}{1} = 2$ days, so in total he will be able to survive for $min(4, 2) = 2$ days and since required time to reach the shore is $1$ day, he will be able to reach there.
TestCase 2: Chef's food supply will last for $\frac{4}{1} = 4$ days and water supply will last for $\frac{2}{3} = 0.67$ days, so in total he will be able to survive for $min(4, 0.67) = 0.67$ days and since required time to reach the shore is $1$ day, he won't be able to reach there.
TestCase 3: Chef's food supply will last for $\frac{4}{4} = 1$ day and water supply will also last for $\frac{2}{2} = 1$ day, so in total he will be able to survive for $min(1, 1) = 1$ day and since required time to reach the shore is $2$ days, he won't be able to reach there.
|
{"inputs": ["3\n4 2 1 1 1\n4 2 1 3 1\n4 2 4 2 2"], "outputs": ["YES\nNO\nNO"]}
| 637
| 46
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an integer n. There are n rooms numbered from 0 to n - 1.
You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.
Meetings are allocated to rooms in the following manner:
Each meeting will take place in the unused room with the lowest number.
If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.
When a room becomes unused, meetings that have an earlier original start time should be given the room.
Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.
A half-closed interval [a, b) is the interval between a and b including a and not including b.
Β
Please complete the following python code precisely:
```python
class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]) == 0\n assert candidate(n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]) == 1\n\n\ncheck(Solution().mostBooked)"}
| 253
| 89
|
coding
|
Solve the programming task below in a Python markdown code block.
> [Run-length encoding](https://en.wikipedia.org/w/index.php?title=Run-length_encoding) (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. Wikipedia
## Task
Your task is to write such a run-length encoding. For a given string, return a list (or array) of pairs (or arrays)
[
(i1, s1),
(i2, s2),
β¦,
(in, sn)
], such that one can reconstruct the original string by replicating the character sx ix times and concatening all those strings. Your run-length encoding should be minimal, ie. for all i the values si and si+1 should differ.
## Examples
As the article states, RLE is a _very_ simple form of data compression. It's only suitable for runs of data, as one can see in the following example:
```python
run_length_encoding("hello world!")
//=> [[1,'h'], [1,'e'], [2,'l'], [1,'o'], [1,' '], [1,'w'], [1,'o'], [1,'r'], [1,'l'], [1,'d'], [1,'!']]
```
It's very effective if the same data value occurs in many consecutive data elements:
```python
run_length_encoding("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb")
# => [[34,'a'], [3,'b']]
```
Also feel free to reuse/extend the following starter code:
```python
def run_length_encoding(s):
```
|
{"functional": "_inputs = [[''], ['abc'], ['aab'], ['hello world!'], ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb']]\n_outputs = [[[]], [[[1, 'a'], [1, 'b'], [1, 'c']]], [[[2, 'a'], [1, 'b']]], [[[1, 'h'], [1, 'e'], [2, 'l'], [1, 'o'], [1, ' '], [1, 'w'], [1, 'o'], [1, 'r'], [1, 'l'], [1, 'd'], [1, '!']]], [[[34, 'a'], [3, 'b']]]]\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(run_length_encoding(*i), o[0])"}
| 366
| 285
|
coding
|
Solve the programming task below in a Python markdown code block.
Let $length(A)$ denote the count of digits of a number $\mbox{A}$ in its decimal representation.
John is looking for new methods of determining which numbers are strange all day long.
All non-negative numbers of length 1 are strange. Further, a number $\mbox{X}$ with $length(X)\geq1$ can also be considered strange if and only if
$\mbox{X}$ is evenly divisible by $length(X)$
the number $X/length(X)$ is recursively strange
Your task is to calculate how many strange numbers belong to an interval $[L,R]$.
Input Format
The first line contains single integer $\mathbf{T}$ - the number of test cases. Next $\mathbf{T}$ lines contain two integers separated by single space $\boldsymbol{\mbox{L}}$ and $\mbox{R}$.
Output Format
In $\mathbf{T}$ lines, print $\mathbf{T}$ integers - count of strange numbers belonging to the interval $[L,R]$.
Constraints
$1\leq T\leq200$
$0\leq L<R\leq10^{18}$
Sample Input
5
7 25
45 50
1 100
99 103
0 1000000
Sample Output
10
1
26
0
96
Explanation
First testcase: There are $10$ strange numbers that belong to the interval $[7,25]$. They are $7,8,9,10,12,14,16,18,20,24$.
Second testcase: Only $48$ satisfies the given constraints.
|
{"inputs": ["5\n7 25\n45 50\n1 100\n99 103\n0 1000000\n"], "outputs": ["10\n1\n26\n0\n96\n"]}
| 387
| 59
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given the root of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Choose any node in the binary tree and a direction (right or left).
If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
Change the direction from right to left or from left to right.
Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return the longest ZigZag path contained in that tree.
Β
Please complete the following python code precisely:
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(root = tree_node([1,None,1,1,1,None,None,1,1,None,1,None,None,None,1,None,1])) == 3\n assert candidate(root = tree_node([1,1,1,None,1,None,None,1,1,None,1])) == 4\n assert candidate(root = tree_node([1])) == 0\n\n\ncheck(Solution().longestZigZag)"}
| 234
| 105
|
coding
|
Solve the programming task below in a Python markdown code block.
The only difference between the two versions is that in this version $n \leq 1000$ and the sum of $n$ over all test cases does not exceed $1000$.
A terminal is a row of $n$ equal segments numbered $1$ to $n$ in order. There are two terminals, one above the other.
You are given an array $a$ of length $n$. For all $i = 1, 2, \dots, n$, there should be a straight wire from some point on segment $i$ of the top terminal to some point on segment $a_i$ of the bottom terminal. You can't select the endpoints of a segment. For example, the following pictures show two possible wirings if $n=7$ and $a=[4,1,4,6,7,7,5]$.
A crossing occurs when two wires share a point in common. In the picture above, crossings are circled in red.
What is the maximum number of crossings there can be if you place the wires optimally?
-----Input-----
The first line contains an integer $t$ ($1 \leq t \leq 1000$) β the number of test cases.
The first line of each test case contains an integer $n$ ($1 \leq n \leq 1000$) β the length of the array.
The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq n$) β the elements of the array.
The sum of $n$ across all test cases does not exceed $1000$.
-----Output-----
For each test case, output a single integer β the maximum number of crossings there can be if you place the wires optimally.
-----Examples-----
Input
4
7
4 1 4 6 7 7 5
2
2 1
1
1
3
2 2 2
Output
6
1
0
3
-----Note-----
The first test case is shown in the second picture in the statement.
In the second test case, the only wiring possible has the two wires cross, so the answer is $1$.
In the third test case, the only wiring possible has one wire, so the answer is $0$.
|
{"inputs": ["4\n7\n4 1 4 6 7 7 5\n2\n2 1\n1\n1\n3\n2 2 2\n"], "outputs": ["6\n1\n0\n3\n"]}
| 518
| 54
|
coding
|
Solve the programming task below in a Python markdown code block.
In this Kata, you will be given a string and your task is to return the most valuable character. The value of a character is the difference between the index of its last occurrence and the index of its first occurrence. Return the character that has the highest value. If there is a tie, return the alphabetically lowest character. `[For Golang return rune]`
All inputs will be lower case.
```
For example:
solve('a') = 'a'
solve('ab') = 'a'. Last occurrence is equal to first occurrence of each character. Return lexicographically lowest.
solve("axyzxyz") = 'x'
```
More examples in test cases. Good luck!
Also feel free to reuse/extend the following starter code:
```python
def solve(st):
```
|
{"functional": "_inputs = [['a'], ['aa'], ['bcd'], ['axyzxyz'], ['dcbadcba'], ['aabccc'], ['efgefg'], ['efghijefghi'], ['acefacef'], ['acefacefacef']]\n_outputs = [['a'], ['a'], ['b'], ['x'], ['a'], ['c'], ['e'], ['e'], ['a'], ['a']]\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(solve(*i), o[0])"}
| 174
| 225
|
coding
|
Solve the programming task below in a Python markdown code block.
For a [permutation] P of the integers 1 to N, we define a new array A_{P} of length N-2 as follows:
For 1 β€ i β€ N-2, (A_{P})_i denotes the number of [inversions] in the subarray P[i : i+2], i.e, the number of inversions in the array [P_{i}, P_{i+1}, P_{i+2}].
You are given an array A of length N, all of whose elements lie between 0 and 3. Does there exist a permutation P of length N+2 such that A_{P} = A?
------ Input Format ------
- The first line of input will contain one integer T, the number of test cases. The description of T test cases follows.
- Each test case consists of two lines of input.
- The first line of each test case contains a single integer N, the size of A.
- The second line of each test case contains N space-separated integers β the values of A_{1}, A_{2}, \ldots, A_{N}.
------ Output Format ------
For each test case, output in a single line the answer β \texttt{YES} if a permutation that satisfies the given conditions exists, and \texttt{NO} otherwise.
The output is not case sensitive, so for example the strings \texttt{YES, Yes, yES}, etc. will all be treated as correct.
------ Constraints ------
$1 β€ T β€ 10^{5}$
$1 β€ N β€ 10^{5}$
$0 β€ A_{i} β€ 3$
- The sum of $N$ over all test cases doesn't exceed $10^{5}$
----- Sample Input 1 ------
4
4
0 1 3 2
4
0 1 2 3
4
0 0 0 0
5
0 1 2 1 0
----- Sample Output 1 ------
YES
NO
YES
NO
----- explanation 1 ------
Test case $1$: Consider $P = [1, 2, 6, 5, 3, 4]$. It can be verified that $A_{P} = [0, 1, 3, 2]$. There are other permutations which give the same array β for example $[2, 3, 6, 5, 1, 4]$ and $[3, 4, 6, 5, 1, 2]$.
Test case $2$: It can be verified that no permutation $P$ of length $6$ has $A_{P} = [0, 1, 2, 3]$.
Test case $3$: The only permutation that satisfies the condition is $P = [1, 2, 3, 4, 5, 6]$.
Test case $4$: It can be verified that no permutation $P$ of length $7$ has $A_{P} = [0, 1, 2, 1, 0]$
|
{"inputs": ["4\n4\n0 1 3 2\n4\n0 1 2 3\n4\n0 0 0 0\n5\n0 1 2 1 0"], "outputs": ["YES\nNO\nYES\nNO"]}
| 676
| 60
|
coding
|
Solve the programming task below in a Python markdown code block.
Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.
Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 105) β the number of markers and the number of caps, correspondingly.
Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 β€ xi, yi β€ 1000) β the i-th marker's color and diameter, correspondingly.
Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 β€ aj, bj β€ 1000) β the color and diameter of the j-th cap, correspondingly.
Output
Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.
Examples
Input
3 4
1 2
3 4
2 4
5 4
2 4
1 1
1 2
Output
3 2
Input
2 2
1 2
2 1
3 4
5 1
Output
1 0
Note
In the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed β the first and the third markers.
|
{"inputs": ["1 1\n1 1\n1 1\n", "1 1\n1 1\n2 2\n", "1 1\n1 1\n1 2\n", "1 1\n1 2\n2 2\n", "1 1\n2 1\n1 2\n", "1 1\n1 2\n1 2\n", "1 1\n0 1\n1 2\n", "1 1\n0 1\n2 2\n"], "outputs": ["1 1\n", "0 0\n", "0 0\n", "1 0\n", "0 0\n", "1 1\n", "0 0\n", "0 0\n"]}
| 491
| 166
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
Β
Please complete the following python code precisely:
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
```
|
{"functional": "def check(candidate):\n assert candidate(root = tree_node([3,9,20,None,None,15,7])) == [[3],[20,9],[15,7]]\n assert candidate(root = tree_node([1])) == [[1]]\n assert candidate(root = tree_node([])) == []\n\n\ncheck(Solution().zigzagLevelOrder)"}
| 146
| 88
|
coding
|
Solve the programming task below in a Python markdown code block.
The sum of digits of a non-negative integer $a$ is the result of summing up its digits together when written in the decimal system. For example, the sum of digits of $123$ is $6$ and the sum of digits of $10$ is $1$. In a formal way, the sum of digits of $\displaystyle a=\sum_{i=0}^{\infty} a_i \cdot 10^i$, where $0 \leq a_i \leq 9$, is defined as $\displaystyle\sum_{i=0}^{\infty}{a_i}$.
Given an integer $n$, find two non-negative integers $x$ and $y$ which satisfy the following conditions.
$x+y=n$, and
the sum of digits of $x$ and the sum of digits of $y$ differ by at most $1$.
It can be shown that such $x$ and $y$ always exist.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10000$).
Each test case consists of a single integer $n$ ($1 \leq n \leq 10^9$)
-----Output-----
For each test case, print two integers $x$ and $y$.
If there are multiple answers, print any.
-----Examples-----
Input
5
1
161
67
1206
19
Output
1 0
67 94
60 7
1138 68
14 5
-----Note-----
In the second test case, the sum of digits of $67$ and the sum of digits of $94$ are both $13$.
In the third test case, the sum of digits of $60$ is $6$, and the sum of digits of $7$ is $7$.
|
{"inputs": ["5\n1\n161\n67\n1206\n19\n"], "outputs": ["0 1\n130 31\n33 34\n103 1103\n14 5\n"]}
| 429
| 60
|
coding
|
Solve the programming task below in a Python markdown code block.
Chef is playing a game with his brother Chefu. He asked Chefu to choose a positive integer $N$, multiply it by a given integer $A$, then choose a divisor of $N$ (possibly $N$ itself) and add it to the product. Let's denote the resulting integer by $M$; more formally, $M = A \cdot N + d$, where $d$ is some divisor of $N$.
Chefu told Chef the value of $M$ and now, Chef should guess $N$. Help him find all values of $N$ which Chefu could have chosen.
-----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 two space-separated integers $A$ and $M$.
-----Output-----
For each test case, print two lines. The first line should contain a single integer $C$ denoting the number of possible values of $N$. The second line should contain $C$ space-separated integers denoting all possible values of $N$ in increasing order.
It is guaranteed that the sum of $C$ over all test cases does not exceed $10^7$.
-----Constraints-----
- $1 \le T \le 100$
- $2 \le M \le 10^{10}$
- $1 \le A < M$
-----Subtasks-----
Subtask #1 (50 points):
- $M \le 10^6$
Subtask #2 (50 points): original constraints
-----Example Input-----
3
3 35
5 50
4 65
-----Example Output-----
1
10
0
3
13 15 16
|
{"inputs": ["3\n3 35\n5 50\n4 65"], "outputs": ["1\n10\n0\n3\n13 15 16"]}
| 397
| 43
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an array of points in the X-Y plane points where points[i] = [xi, yi].
Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.
Β
Please complete the following python code precisely:
```python
class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate([[1,1],[1,3],[3,1],[3,3],[2,2]]) == 4\n assert candidate([[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]) == 2\n\n\ncheck(Solution().minAreaRect)"}
| 107
| 80
|
coding
|
Solve the programming task below in a Python markdown code block.
Chef Shifu wanted to celebrate the success of his new restaurant with all his employees. He was willing to host a party and he had decided the location of the party as well. However, Chef Shifu was a shy person and wanted to communicate with the least possible employees to inform them about the party, and that these employees could inform their friends.
Note that an employee could only inform his/her immediate friends about the party, not his/her friendsβ friends.
Chef Shifu has a list of all the friendships among his employees. Help him find the minimum number of employees he should inform, so that every employee knows about the celebration party.
-----Input-----
First line contains a single integer T - the total number of testcases.
T testcases follow. For each testcase:
The first line contains 2 space-separated integers N and M - the total number of employees working under Chef Shifu and the number of friendship relations.
M lines follow - each line contains 2 space-separated integers u and v, indicating that employee u is a friend of employee v and vice-versa.
The employees are numbered from 1 to N, and each employee is assigned a distinct integer.
-----Output-----
For each testcase, print the minimum number of employees to be informed on a new line.
-----Constraints-----
Subtask 1: 5 points
1 β€ T β€ 5
1 β€ N β€ 4
0 β€ M β€ N*(N-1)/2
Subtask 2: 35 points
1 β€ T β€ 5
1 β€ N β€ 15
0 β€ M β€ N*(N-1)/2
Subtask 3: 60 points
1 β€ T β€ 5
1 β€ N β€ 20
0 β€ M β€ N*(N-1)/2
-----Example-----
Input
2
3 3
1 2
2 3
1 3
4 3
1 2
2 3
3 4
Output
1
2
Explanation
In testcase 1, since every employee is a friend of every other employee, we just need to select 1 employee.
In testcase 2, selecting employees 2 and 4 would ensure that all 4 employees are represented.
Similarly, selecting employees 1 and 3 would also ensure that all 4 employees are selected.
In both cases, we must select 2 employees in the best case.
|
{"inputs": ["2\n3 3\n1 2\n2 3\n1 3\n4 3\n1 2\n2 3\n3 4"], "outputs": ["1\n2"]}
| 510
| 46
|
coding
|
Solve the programming task below in a Python markdown code block.
Given an array of numbers, calculate the largest sum of all possible blocks of consecutive elements within the array. The numbers will be a mix of positive and negative values. If all numbers of the sequence are nonnegative, the answer will be the sum of the entire array. If all numbers in the array are negative, your algorithm should return zero. Similarly, an empty array should result in a zero return from your algorithm.
```
largestSum([-1,-2,-3]) == 0
largestSum([]) == 0
largestSum([1,2,3]) == 6
```
Easy, right? This becomes a lot more interesting with a mix of positive and negative numbers:
```
largestSum([31,-41,59,26,-53,58,97,-93,-23,84]) == 187
```
The largest sum comes from elements in positions 3 through 7:
```59+26+(-53)+58+97 == 187```
Once your algorithm works with these, the test-cases will try your submission with increasingly larger random problem sizes.
Also feel free to reuse/extend the following starter code:
```python
def largest_sum(arr):
```
|
{"functional": "_inputs = [[[-1, -2, -3]], [[]], [[1, 2, 3, 4]], [[31, -41, 59, 26, -53, 58, 97, -93, -23, 84]]]\n_outputs = [[0], [0], [10], [187]]\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(largest_sum(*i), o[0])"}
| 281
| 228
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.
A substring is a contiguous sequence of characters within a string.
Β
Please complete the following python code precisely:
```python
class Solution:
def largestOddNumber(self, num: str) -> str:
```
|
{"functional": "def check(candidate):\n assert candidate(num = \"52\") == \"5\"\n assert candidate(num = \"4206\") == \"\"\n assert candidate(num = \"35427\") == \"35427\"\n\n\ncheck(Solution().largestOddNumber)"}
| 104
| 71
|
coding
|
Solve the programming task below in a Python markdown code block.
Late last night in the Tanner household, ALF was repairing his spaceship so he might get back to Melmac. Unfortunately for him, he forgot to put on the parking brake, and the spaceship took off during repair. Now it's hovering in space.
ALF has the technology to bring the spaceship home if he can lock on to its location.
Given a map:
````
..........
..........
..........
.......X..
..........
..........
````
The map will be given in the form of a string with \n separating new lines. The bottom left of the map is [0, 0]. X is ALF's spaceship.
In this example:
If you cannot find the spaceship, the result should be
```
"Spaceship lost forever."
```
Can you help ALF?
Check out my other 80's Kids Katas:
80's Kids #1: How Many Licks Does It Take
80's Kids #2: Help Alf Find His Spaceship
80's Kids #3: Punky Brewster's Socks
80's Kids #4: Legends of the Hidden Temple
80's Kids #5: You Can't Do That on Television
80's Kids #6: Rock 'Em, Sock 'Em Robots
80's Kids #7: She's a Small Wonder
80's Kids #8: The Secret World of Alex Mack
80's Kids #9: Down in Fraggle Rock
80's Kids #10: Captain Planet
Also feel free to reuse/extend the following starter code:
```python
def find_spaceship(astromap):
```
|
{"functional": "_inputs = [['X'], ['X\\n.'], ['.X\\n..'], ['..\\n.X'], ['..\\nX.'], ['.......\\nX.......'], ['..........\\n..........\\n.......X..\\n..........\\n..........'], ['..........\\n..........\\n..........\\n........X.\\n..........'], ['........................'], ['\\n\\n\\n\\n']]\n_outputs = [[[0, 0]], [[0, 1]], [[1, 1]], [[1, 0]], [[0, 0]], [[0, 0]], [[7, 2]], [[8, 1]], ['Spaceship lost forever.'], ['Spaceship lost forever.']]\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_spaceship(*i), o[0])"}
| 351
| 292
|
coding
|
Solve the programming task below in a Python markdown code block.
zscoder wants to generate an input file for some programming competition problem.
His input is a string consisting of n letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.
Initially, the text editor is empty. It takes him x seconds to insert or delete a letter 'a' from the text file and y seconds to copy the contents of the entire text file, and duplicate it.
zscoder wants to find the minimum amount of time needed for him to create the input file of exactly n letters 'a'. Help him to determine the amount of time needed to generate the input.
-----Input-----
The only line contains three integers n, x and y (1 β€ n β€ 10^7, 1 β€ x, y β€ 10^9) β the number of letters 'a' in the input file and the parameters from the problem statement.
-----Output-----
Print the only integer t β the minimum amount of time needed to generate the input file.
-----Examples-----
Input
8 1 1
Output
4
Input
8 1 10
Output
8
|
{"inputs": ["8 1 1\n", "1 1 1\n", "1 1 1\n", "1 1 0\n", "8 1 2\n", "2 1 0\n", "8 1 0\n", "4 1 0\n"], "outputs": ["4\n", "1\n", "1", "1", "6", "1", "1", "1"]}
| 249
| 96
|
coding
|
Solve the programming task below in a Python markdown code block.
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least a_{i} candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:
Give m candies to the first child of the line. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. Repeat the first two steps while the line is not empty.
Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?
-----Input-----
The first line contains two integers n, m (1 β€ n β€ 100;Β 1 β€ m β€ 100). The second line contains n integers a_1, a_2, ..., a_{n} (1 β€ a_{i} β€ 100).
-----Output-----
Output a single integer, representing the number of the last child.
-----Examples-----
Input
5 2
1 3 1 4 2
Output
4
Input
6 4
1 1 2 2 3 3
Output
6
-----Note-----
Let's consider the first sample.
Firstly child 1 gets 2 candies and go home. Then child 2 gets 2 candies and go to the end of the line. Currently the line looks like [3, 4, 5, 2] (indices of the children in order of the line). Then child 3 gets 2 candies and go home, and then child 4 gets 2 candies and goes to the end of the line. Currently the line looks like [5, 2, 4]. Then child 5 gets 2 candies and goes home. Then child 2 gets two candies and goes home, and finally child 4 gets 2 candies and goes home.
Child 4 is the last one who goes home.
|
{"inputs": ["1 3\n5\n", "1 4\n3\n", "1 4\n3\n", "1 3\n5\n", "1 8\n3\n", "1 3\n6\n", "1 2\n3\n", "1 6\n6\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
| 470
| 102
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.
Β
Please complete the following python code precisely:
```python
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(n = 1, k = 1) == 0\n assert candidate(n = 2, k = 1) == 0\n assert candidate(n = 2, k = 2) == 1\n\n\ncheck(Solution().kthGrammar)"}
| 181
| 71
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin, Russian and Vietnamese as well.
There are N sets of integers from 1 to K both inclusive. Find out number of pairs of sets whose union contains all the K elements.
------ Input ------
The first line contains an integer T denotes number of test cases.
The first line of each test case contains two space separated integers N, K.
The each of the next line first contains an integer len_{i} denoting number of elements in the i-th set, followed by len_{i} space separated integers in the range [1, K] denoting the elements in the set.
------ Output ------
For each test case, output a single integer corresponding to the answer.
------ Constraints ------
$1 β€ T β€ 10$
$1 β€ N, K β€ 2500$
$1 β€ len_{i} β€ K$
$Note that a set can't contain repeated elements.$
$1 β€ len_{1} + len_{2} + .. + len_{N} β€ 10000$
------ Subtasks ------
Subtask #1 (40 points)
$1 β€ T β€ 10$
$1 β€ N, K β€ 250$
$1 β€ len_{1} + len_{2} + .. + len_{N} β€ 1000$
Subtask #2 (60 points)
$original constraints.$
----- Sample Input 1 ------
3
2 2
1 1
1 1
3 2
2 1 2
2 1 2
2 1 2
3 4
3 1 2 3
4 1 2 3 4
3 2 3 4
----- Sample Output 1 ------
0
3
3
----- explanation 1 ------
Example 1. No pair of sets is there with its union = 2.
For example 2 and 3, all the pairs are valid.
|
{"inputs": ["3\n2 2\n1 1\n1 1\n3 2\n2 1 2\n2 1 2\n2 1 2\n3 4\n3 1 2 3\n4 1 2 3 4\n3 2 3 4"], "outputs": ["0\n3\n3"]}
| 429
| 80
|
coding
|
Solve the programming task below in a Python markdown code block.
There is a field with plants β a grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$); out of its $NM$ cells, $K$ cells contain plants, while the rest contain weeds. Two cells are adjacent if they have a common side.
You want to build fences in the field in such a way that the following conditions hold for each cell that contains a plant:
- it is possible to move from this cell to each adjacent cell containing a plant without crossing any fences
- it is impossible to move from this cell to any cell containing weeds or to leave the grid without crossing any fences
The fences can only be built between cells or on the boundary of the grid, i.e. on the sides of cells. The total length of the built fences is the number of pairs of side-adjacent cells such that there is a fence built on their common side plus the number of sides of cells on the boundary of the grid which have fences built on them. Find the minimum required total length of fences that need to be built.
-----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 line of each test case contains three space-separated integers $N$, $M$ and $K$.
- $K$ lines follow. Each of these lines contains two space-separated integers $r$ and $c$ denoting that the cell in row $r$ and column $c$ contains a plant.
-----Output-----
For each test case, print a single line containing one integer β the minimum required length of fences.
-----Constraints-----
- $1 \le T \le 10$
- $1 \le N, M \le 10^9$
- $1 \le K \le 10^5$
- $1 \le r \le N$
- $1 \le c \le M$
- the cells containing plants are pairwise distinct
-----Subtasks-----
Subtask #1 (30 points): $1 \le N, M \le 1,000$
Subtask #2 (70 points): original constraints
-----Example Input-----
2
4 4 9
1 4
2 1
2 2
2 3
3 1
3 3
4 1
4 2
4 3
4 4 1
1 1
-----Example Output-----
20
4
-----Explanation-----
Example case 1: The field looks like this ('x' denotes a cell containing a plant, '.' denotes a cell containing weeds):
...x
xxx.
x.x.
xxx.
An optimal solution is to build fences around the topmost plant (with length $4$), around the remaining eight plants (with length $12$) and around the hole between them (with length $4$). The total length is $4+12+4 = 20$.
|
{"inputs": ["2\n4 4 9\n1 4\n2 1\n2 2\n2 3\n3 1\n3 3\n4 1\n4 2\n4 3\n4 4 1\n1 1"], "outputs": ["20\n4"]}
| 651
| 67
|
coding
|
Solve the programming task below in a Python markdown code block.
There are N towns in JOI, which are connected by M bidirectional roads. There are shopping malls in K towns, and the people go to one of those towns through the road to shop.
Depending on the location of your home, you may have to travel long distances to go shopping, which is very inconvenient. To understand this situation, the King decided to investigate how the shortest distance to the town where the shopping mall is located can be longer depending on the location of the house. This survey is very difficult because the house may be built in the middle of the road (see the explanation in Input Example 1). So the King asked you, a good programmer, to create a program to do the research.
input
Read the following input from standard input.
* The integers N, M, and K are written on the first line, separated by blanks. N represents the number of towns in JOI country, M represents the number of roads in JOI country, and i> K represents the number of towns with shopping malls. The towns are numbered 1, 2, ..., N.
* The following M line represents road information. The integers ai, bi, li (1 β€ ai β€ N, 1 β€ bi β€ N, 1 β€ li β€ 1000) are written on the first line (1 β€ i β€ M), separated by blanks. This means that the i-th road connects the town ai and the town bi and is li in length. Both ends of the road are never the same town. Also, for any two towns p and q, there are no more than two roads connecting p and q. You can follow several roads from any town to any town.
* The following K line represents shopping mall information. One integer si (1 β€ si β€ N) is written on the i + M + 1 line (1 β€ i β€ K). This means that there is a shopping mall in the town si. The same value does not appear more than once in s1, ..., sK.
output
To the standard output, output one integer rounded to the nearest whole number of the shortest distance to the town where the shopping mall is located.
Example
Input
3 3 1
1 2 1
2 3 1
3 1 1
1
Output
2
|
{"inputs": ["4 3 1\n1 2 1\n2 3 1\n3 1 1\n1", "4 3 1\n1 2 1\n2 3 2\n1 1 1\n1", "4 3 1\n1 2 1\n2 3 1\n1 2 1\n2", "4 3 1\n1 2 1\n2 3 4\n1 1 1\n1", "8 3 1\n1 1 2\n2 3 4\n3 1 0\n1", "4 3 1\n1 2 2\n2 4 4\n1 1 1\n1", "4 3 1\n1 1 0\n1 3 0\n3 2 0\n1", "4 3 1\n1 2 1\n2 3 1\n1 1 1\n1"], "outputs": ["2\n", "3\n", "1\n", "5\n", "4\n", "6\n", "0\n", "2\n"]}
| 490
| 254
|
coding
|
Solve the programming task below in a Python markdown code block.
Chef _c8kbf_ has an unrooted, weighted tree with N nodes, where vertices u and v are connected by an edge with weight w.
The value of the simple path from x to y is defined as the [bitwise XOR] of the weights of the edges it consists of.
Recall that a simple path is a path that does not have repeating vertices.
Help Chef _c8kbf_ find any four vertices a, b, c, d, such that:
a < b and c < d;
The value of the simple path from a to b is equal to that of the path from c to d;
The pairs (a, b) and (c, d) are different. In other words, a \neq c or b \neq d.
Note that the four vertices do not have to be all distinct. For example, it is allowed for a and c to be the same if b and d are different.
If no four vertices satisfy such a property, report so. If there are multiple answers, output any one of them.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- Each test case consists of multiple lines of input. For each test case,
- The first line contains an integer N,Β the number of vertices.
- The next N-1 lines contain three space-separated integers u_{i}, v_{i}, and w_{i}, denoting an edge between u_{i} and v_{i} with weight w_{i}. It is guaranteed that these edges will form a tree.
------ Output Format ------
For each test case, output four space-separated integers a, b, c, and d on a new line, representing the four vertices. If there are multiple answers, output any one of them.
If no four vertices satisfy the property, output -1 on a new line instead.
------ Constraints ------
$1 β€ T β€ 10$
$3 β€ N β€ 10^{5}$
$1 β€ u_{i}, v_{i} β€ N$
$u_{i} \neq v_{i}$ for each $1 β€ i β€ N-1$.
$0 β€ w_{i} β€ 2^{20}$
- It is guaranteed that the given edges will form a tree.
- The sum of $N$ over all test cases won't exceed $3\cdot10^{5}$.
----- Sample Input 1 ------
3
4
1 2 1
2 3 2
2 4 3
4
1 2 2
2 3 4
2 4 8
3
1 2 5
2 3 0
----- Sample Output 1 ------
1 4 2 3
-1
1 2 1 3
----- explanation 1 ------
Test case $1$: The _value_ of the path between vertices $1$ and $4$ is $1\oplus 3 = 2$. The path between vertices $3$ and $2$ only has one edge, so the _value_ is also $2$. Note that $2$ $3$ $1$ $4$ or $2$ $4$ $1$ $3$ would be other acceptable answers.
Test case $2$: No four vertices satisfy the property.
Test case $3$: Note that $a = c$ for the output of this case, which is allowed.
|
{"inputs": ["3\n4\n1 2 1\n2 3 2\n2 4 3\n4\n1 2 2\n2 3 4\n2 4 8\n3\n1 2 5\n2 3 0"], "outputs": ["1 4 2 3\n-1\n1 2 1 3"]}
| 748
| 83
|
coding
|
Solve the programming task below in a Python markdown code block.
If the strings are consecutive, you can replace the characters with a rule to shorten the string. For example, for the string AAAA, the expression @ 4A will compress one character. Create a program that restores the character string compressed by this rule to the original character string. However, it is assumed that the @ character does not appear in the restored character string.
In addition, the original character string is uppercase letters, lowercase letters, numbers, and symbols, and can be up to 100 characters, and consecutive characters can be up to 9 characters.
input
Multiple strings are given. One string is given per line. The number of strings does not exceed 50.
output
For each character string, output the restored character string for each character on one line.
Example
Input
ab@5C1@8050
@99+1=1@90
Output
abCCCCC10000000050
999999999+1=1000000000
|
{"inputs": ["ab@5C1@8050\n@99,1=1@90", "ab@5C2@8050\n@99,1=1@90", "ab@5C2?8050\n@99,1=1@90", "ab@5C1@8050\nA99+1=1@90", "ab@5C2@8050\n@89,1=1@90", "ab@5C2?8050\n@91,1=9@90", "`b@5C1@8050\nA99+1=1@90", "ab@5C3@8050\n@89,1=1@90"], "outputs": ["abCCCCC10000000050\n999999999,1=1000000000", "abCCCCC20000000050\n999999999,1=1000000000", "abCCCCC2?8050\n999999999,1=1000000000", "abCCCCC10000000050\nA99+1=1000000000", "abCCCCC20000000050\n99999999,1=1000000000", "abCCCCC2?8050\n111111111,1=9000000000", "`bCCCCC10000000050\nA99+1=1000000000", "abCCCCC30000000050\n99999999,1=1000000000"]}
| 238
| 478
|
coding
|
Solve the programming task below in a Python markdown code block.
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is w_{i}, and weight is an important matter in kayaking β if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.
Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.
Help the party to determine minimum possible total instability!
-----Input-----
The first line contains one number n (2 β€ n β€ 50).
The second line contains 2Β·n integer numbers w_1, w_2, ..., w_2n, where w_{i} is weight of person i (1 β€ w_{i} β€ 1000).
-----Output-----
Print minimum possible total instability.
-----Examples-----
Input
2
1 2 3 4
Output
1
Input
4
1 3 4 6 3 4 100 200
Output
5
|
{"inputs": ["2\n1 2 3 4\n", "2\n1 2 3 2\n", "2\n1 2 3 1\n", "2\n1 2 5 1\n", "2\n1 2 5 2\n", "2\n2 2 5 2\n", "2\n1 2 3 4\n", "2\n55 5 3 51\n"], "outputs": ["1\n", "0\n", "0\n", "0\n", "0\n", "0\n", "1\n", "2\n"]}
| 367
| 136
|
coding
|
Solve the programming task below in a Python markdown code block.
There are N piles where the i^{th} pile consists of A_{i} stones.
Chef and Chefina are playing a game taking alternate turns with Chef starting first.
In his/her turn, a player can choose any non-empty pile and remove exactly 1 stone from it.
The game ends when exactly 1 pile becomes empty. The player who made the last move wins.
Determine the winner if both players play optimally.
------ Input Format ------
- The first line of input will contain a single integer T, denoting the number of test cases.
- Each test case consists of multiple lines of input.
- The first line of each test case contains a single integer N denoting the number of piles.
- Next line contains N space-separated integers A_{1}, A_{2}, \dots, A_{N} - denoting the number of stones in each pile.
------ Output Format ------
For each test case, output CHEF if Chef wins the game, otherwise output CHEFINA.
Note that the output is case-insensitive i.e. CHEF, Chef, cHeF, and chef are all considered the same.
------ Constraints ------
$1 β€ T β€ 1000$
$1 β€ N β€ 10^{5}$
$1 β€ A_{i} β€ 10^{9}$
- Sum of $N$ over all test cases does not exceed $2 \cdot 10^{5}$.
----- Sample Input 1 ------
3
2
2 2
1
10
3
1 5 6
----- Sample Output 1 ------
CHEFINA
CHEFINA
CHEF
----- explanation 1 ------
Test Case $1$: No matter which stone Chef removes, Chefina will remove the remaining stone from the same pile and make it empty.
Test Case $2$: Since there is only $1$ pile containing $10$ stones, the game will last exactly $10$ moves with last move made by Chefina.
Test Case $3$: Chef can remove $1$ stone from the first pile and thus make it empty.
|
{"inputs": ["3\n2\n2 2\n1\n10\n3\n1 5 6\n"], "outputs": ["CHEFINA\nCHEFINA\nCHEF\n"]}
| 454
| 42
|
coding
|
Solve the programming task below in a Python markdown code block.
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.
Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c_1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c_2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c_3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c_4 burles.
Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
-----Input-----
The first line contains four integers c_1, c_2, c_3, c_4 (1 β€ c_1, c_2, c_3, c_4 β€ 1000) β the costs of the tickets.
The second line contains two integers n and m (1 β€ n, m β€ 1000) β the number of buses and trolleys Vasya is going to use.
The third line contains n integers a_{i} (0 β€ a_{i} β€ 1000) β the number of times Vasya is going to use the bus number i.
The fourth line contains m integers b_{i} (0 β€ b_{i} β€ 1000) β the number of times Vasya is going to use the trolley number i.
-----Output-----
Print a single number β the minimum sum of burles Vasya will have to spend on the tickets.
-----Examples-----
Input
1 3 7 19
2 3
2 5
4 4 4
Output
12
Input
4 3 2 1
1 3
798
1 2 3
Output
1
Input
100 100 8 100
3 5
7 94 12
100 1 47 0 42
Output
16
-----Note-----
In the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2Β·1) + 3 + 7 = 12 burles.
In the second sample the profitable strategy is to buy one ticket of the fourth type.
In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
|
{"inputs": ["4 4 4 1\n1 1\n0\n0\n", "4 4 4 1\n1 1\n0\n0\n", "4 3 2 1\n1 3\n798\n1 2 3\n", "1 1 3 4\n2 3\n1 1\n1 1 1\n", "1 1 3 4\n2 3\n1 1\n1 1 1\n", "4 3 1 1\n1 3\n798\n1 2 3\n", "1 2 3 4\n2 3\n1 1\n1 1 1\n", "4 3 1 1\n1 3\n798\n2 2 3\n"], "outputs": ["0\n", "0", "1\n", "4\n", "4", "1\n", "4\n", "1\n"]}
| 660
| 216
|
coding
|
Solve the programming task below in a Python markdown code block.
The final match of the Berland Football Cup has been held recently. The referee has shown $n$ yellow cards throughout the match. At the beginning of the match there were $a_1$ players in the first team and $a_2$ players in the second team.
The rules of sending players off the game are a bit different in Berland football. If a player from the first team receives $k_1$ yellow cards throughout the match, he can no longer participate in the match β he's sent off. And if a player from the second team receives $k_2$ yellow cards, he's sent off. After a player leaves the match, he can no longer receive any yellow cards. Each of $n$ yellow cards was shown to exactly one player. Even if all players from one team (or even from both teams) leave the match, the game still continues.
The referee has lost his records on who has received each yellow card. Help him to determine the minimum and the maximum number of players that could have been thrown out of the game.
-----Input-----
The first line contains one integer $a_1$ $(1 \le a_1 \le 1\,000)$ β the number of players in the first team.
The second line contains one integer $a_2$ $(1 \le a_2 \le 1\,000)$ β the number of players in the second team.
The third line contains one integer $k_1$ $(1 \le k_1 \le 1\,000)$ β the maximum number of yellow cards a player from the first team can receive (after receiving that many yellow cards, he leaves the game).
The fourth line contains one integer $k_2$ $(1 \le k_2 \le 1\,000)$ β the maximum number of yellow cards a player from the second team can receive (after receiving that many yellow cards, he leaves the game).
The fifth line contains one integer $n$ $(1 \le n \le a_1 \cdot k_1 + a_2 \cdot k_2)$ β the number of yellow cards that have been shown during the match.
-----Output-----
Print two integers β the minimum and the maximum number of players that could have been thrown out of the game.
-----Examples-----
Input
2
3
5
1
8
Output
0 4
Input
3
1
6
7
25
Output
4 4
Input
6
4
9
10
89
Output
5 9
-----Note-----
In the first example it could be possible that no player left the game, so the first number in the output is $0$. The maximum possible number of players that could have been forced to leave the game is $4$ β one player from the first team, and three players from the second.
In the second example the maximum possible number of yellow cards has been shown $(3 \cdot 6 + 1 \cdot 7 = 25)$, so in any case all players were sent off.
|
{"inputs": ["2\n3\n5\n1\n8\n", "8\n4\n1\n2\n9\n", "1\n7\n2\n3\n5\n", "1\n1\n1\n1\n1\n", "1\n1\n1\n1\n2\n", "1\n1\n7\n1\n2\n", "1\n1\n1\n3\n4\n", "8\n4\n1\n2\n9\n"], "outputs": ["0 4\n", "5 8\n", "0 2\n", "1 1\n", "2 2\n", "0 1\n", "2 2\n", "5 8\n"]}
| 661
| 150
|
coding
|
Solve the programming task below in a Python markdown code block.
Welcome to Codeforces Stock Exchange! We're pretty limited now as we currently allow trading on one stock, Codeforces Ltd. We hope you'll still be able to make profit from the market!
In the morning, there are $n$ opportunities to buy shares. The $i$-th of them allows to buy as many shares as you want, each at the price of $s_i$ bourles.
In the evening, there are $m$ opportunities to sell shares. The $i$-th of them allows to sell as many shares as you want, each at the price of $b_i$ bourles. You can't sell more shares than you have.
It's morning now and you possess $r$ bourles and no shares.
What is the maximum number of bourles you can hold after the evening?
-----Input-----
The first line of the input contains three integers $n, m, r$ ($1 \leq n \leq 30$, $1 \leq m \leq 30$, $1 \leq r \leq 1000$) β the number of ways to buy the shares on the market, the number of ways to sell the shares on the market, and the number of bourles you hold now.
The next line contains $n$ integers $s_1, s_2, \dots, s_n$ ($1 \leq s_i \leq 1000$); $s_i$ indicates the opportunity to buy shares at the price of $s_i$ bourles.
The following line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \leq b_i \leq 1000$); $b_i$ indicates the opportunity to sell shares at the price of $b_i$ bourles.
-----Output-----
Output a single integer β the maximum number of bourles you can hold after the evening.
-----Examples-----
Input
3 4 11
4 2 5
4 4 5 4
Output
26
Input
2 2 50
5 7
4 2
Output
50
-----Note-----
In the first example test, you have $11$ bourles in the morning. It's optimal to buy $5$ shares of a stock at the price of $2$ bourles in the morning, and then to sell all of them at the price of $5$ bourles in the evening. It's easy to verify that you'll have $26$ bourles after the evening.
In the second example test, it's optimal not to take any action.
|
{"inputs": ["1 1 1\n1\n1\n", "1 1 4\n3\n4\n", "1 1 7\n5\n6\n", "1 1 7\n5\n7\n", "1 1 5\n5\n6\n", "1 1 4\n4\n5\n", "1 1 5\n1\n4\n", "1 1 4\n8\n7\n"], "outputs": ["1\n", "5\n", "8\n", "9\n", "6\n", "5\n", "20\n", "4\n"]}
| 573
| 135
|
coding
|
Solve the programming task below in a Python markdown code block.
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.
Let's call a positive integer a undoubtedly lucky, if there are such digits x and y (0 β€ x, y β€ 9), that the decimal representation of number a (without leading zeroes) contains only digits x and y.
Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number.
-----Input-----
The first line contains a single integer n (1 β€ n β€ 10^9) β Polycarpus's number.
-----Output-----
Print a single integer that says, how many positive integers that do not exceed n are undoubtedly lucky.
-----Examples-----
Input
10
Output
10
Input
123
Output
113
-----Note-----
In the first test sample all numbers that do not exceed 10 are undoubtedly lucky.
In the second sample numbers 102, 103, 104, 105, 106, 107, 108, 109, 120, 123 are not undoubtedly lucky.
|
{"inputs": ["1\n", "2\n", "1\n", "3\n", "4\n", "5\n", "6\n", "7\n"], "outputs": ["1\n", "2\n", "1\n", "3\n", "4\n", "5\n", "6\n", "7\n"]}
| 316
| 70
|
coding
|
Solve the programming task below in a Python markdown code block.
You are provided with array of positive non-zero ints and int n representing n-th power (n >= 2).
For the given array, calculate the sum of each value to the n-th power. Then subtract the sum of the original array.
Example 1: Input: {1, 2, 3}, 3 --> (1 ^ 3 + 2 ^ 3 + 3 ^ 3 ) - (1 + 2 + 3) --> 36 - 6 --> Output: 30
Example 2: Input: {1, 2}, 5 --> (1 ^ 5 + 2 ^ 5) - (1 + 2) --> 33 - 3 --> Output: 30
Also feel free to reuse/extend the following starter code:
```python
def modified_sum(a, n):
```
|
{"functional": "_inputs = [[[1, 2, 3], 3], [[1, 2], 5], [[3, 5, 7], 2], [[1, 2, 3, 4, 5], 3], [[2, 7, 13, 17], 2], [[2, 5, 8], 3], [[2, 4, 6, 8], 6], [[5, 10, 15], 4], [[3, 6, 9, 12], 3]]\n_outputs = [[30], [30], [68], [210], [472], [630], [312940], [61220], [2670]]\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(modified_sum(*i), o[0])"}
| 194
| 322
|
coding
|
Solve the programming task below in a Python markdown code block.
Implement `String#whitespace?(str)` (Ruby), `String.prototype.whitespace(str)` (JavaScript), `String::whitespace(str)` (CoffeeScript), or `whitespace(str)` (Python), which should return `true/True` if given object consists exclusively of zero or more whitespace characters, `false/False` otherwise.
Also feel free to reuse/extend the following starter code:
```python
def whitespace(string):
```
|
{"functional": "_inputs = [[''], [' '], ['\\n\\r\\n\\r'], ['a'], ['w\\n'], ['\\t'], [' a\\n'], ['\\t \\n\\r\\n '], ['\\n\\r\\n\\r '], ['\\n\\r\\n\\r 3']]\n_outputs = [[True], [True], [True], [False], [False], [True], [False], [True], [True], [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(whitespace(*i), o[0])"}
| 102
| 246
|
coding
|
Solve the programming task below in a Python markdown code block.
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price β their owners are ready to pay Bob if he buys their useless apparatus. Bob can Β«buyΒ» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
Input
The first line contains two space-separated integers n and m (1 β€ m β€ n β€ 100) β amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 β€ ai β€ 1000) β prices of the TV sets.
Output
Output the only number β the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.
Examples
Input
5 3
-6 0 35 -2 4
Output
8
Input
4 2
7 0 0 -7
Output
7
|
{"inputs": ["1 1\n0\n", "1 1\n1\n", "1 1\n-1\n", "1 1\n555\n", "1 1\n-24\n", "4 2\n7 1 0 -7\n", "4 2\n7 0 0 -7\n", "2 2\n-742 -187\n"], "outputs": ["0\n", "0\n", "1\n", "0\n", "24\n", "7\n", "7\n", "929\n"]}
| 268
| 129
|
coding
|
Solve the programming task below in a Python markdown code block.
We have three boxes A, B, and C, each of which contains an integer.
Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.
We will now do the operations below in order. Find the content of each box afterward.
- Swap the contents of the boxes A and B
- Swap the contents of the boxes A and C
-----Constraints-----
- 1 \leq X,Y,Z \leq 100
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
X Y Z
-----Output-----
Print the integers contained in the boxes A, B, and C, in this order, with space in between.
-----Sample Input-----
1 2 3
-----Sample Output-----
3 1 2
After the contents of the boxes A and B are swapped, A, B, and C contain 2, 1, and 3, respectively.
Then, after the contents of A and C are swapped, A, B, and C contain 3, 1, and 2, respectively.
|
{"inputs": ["2 2 3", "2 2 5", "2 2 7", "3 2 7", "4 1 9", "3 1 9", "3 2 9", "1 2 3"], "outputs": ["3 2 2\n", "5 2 2\n", "7 2 2\n", "7 3 2\n", "9 4 1\n", "9 3 1\n", "9 3 2\n", "3 1 2"]}
| 248
| 125
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
Β
Please complete the following python code precisely:
```python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(root = tree_node([1,7,0,7,-8,None,None])) == 2\n assert candidate(root = tree_node([989,None,10250,98693,-89388,None,None,None,-32127])) == 2\n\n\ncheck(Solution().maxLevelSum)"}
| 152
| 88
|
coding
|
Solve the programming task below in a Python markdown code block.
AmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are $n$ cities in Italy indexed from $1$ to $n$ and $m$ directed roads indexed from $1$ to $m$. Initially, Keshi is located in the city $1$ and wants to go to AmShZ's house in the city $n$. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.
In the beginning of each day, AmShZ can send one of the following two messages to Keshi:
AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day.
AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city $B$ is reachable from city $A$ if there's an out-going road from city $A$ to city $B$ which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.
Note that AmShZ always knows Keshi's current location.
AmShZ and Keshi want to find the smallest possible integer $d$ for which they can make sure that they will see each other after at most $d$ days. Help them find $d$.
-----Input-----
The first line of the input contains two integers $n$ and $m$ $(2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)$ β the number of cities and roads correspondingly.
The $i$-th line of the following $m$ lines contains two integers $v_i$ and $u_i$ $(1 \le v_i , u_i \le n,v_i \neq u_i)$, denoting a directed road going from city $v_i$ to city $u_i$.
It is guaranteed that there is at least one route from city $1$ to city $n$. Note that there may be more than one road between a pair of cities in each direction.
-----Output-----
Output the smallest possible integer $d$ to make sure that AmShZ and Keshi will see each other after at most $d$ days.
-----Examples-----
Input
2 1
1 2
Output
1
Input
4 4
1 2
1 4
2 4
1 4
Output
2
Input
5 7
1 2
2 3
3 5
1 4
4 3
4 5
3 1
Output
4
-----Note-----
In the first sample, it's enough for AmShZ to send the second type of message.
In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city $1$ will be city $4$. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.
It's also possible for AmShZ to tell Keshi to move for two days.
|
{"inputs": ["2 1\n1 2\n", "4 4\n1 2\n1 4\n2 4\n1 4\n", "5 7\n1 2\n2 3\n3 5\n1 4\n4 3\n4 5\n3 1\n"], "outputs": ["1\n", "2\n", "4\n"]}
| 713
| 84
|
coding
|
Solve the programming task below in a Python markdown code block.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem.
Input
The single line contains two integers l and r (1 β€ l β€ r β€ 109) β the left and right interval limits.
Output
In the single line print the only number β the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r).
Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
2 7
Output
33
Input
7 7
Output
7
Note
In the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33
In the second sample: next(7) = 7
|
{"inputs": ["3 4\n", "1 2\n", "5 6\n", "1 1\n", "4 7\n", "1 9\n", "6 6\n", "6 9\n"], "outputs": ["8\n", "8\n", "14\n", "4\n", "25\n", "125\n", "7\n", "102\n"]}
| 334
| 92
|
coding
|
Solve the programming task below in a Python markdown code block.
We have a 3Γ3 square grid, where each square contains a lowercase English letters.
The letter in the square at the i-th row from the top and j-th column from the left is c_{ij}.
Print the string of length 3 that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.
-----Constraints-----
- Input consists of lowercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
c_{11}c_{12}c_{13}
c_{21}c_{22}c_{23}
c_{31}c_{32}c_{33}
-----Output-----
Print the string of length 3 that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.
-----Sample Input-----
ant
obe
rec
-----Sample Output-----
abc
The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.
|
{"inputs": ["ant\nobe\nrfc", "ddu\ncat\nion", "ant\nobe\nrcf", "ddu\ncat\nioo", "ddu\ncat\nooi", "una\nobe\nrcf", "edu\nbau\nooi", "una\npbe\nfdr"], "outputs": ["abc\n", "dan\n", "abf\n", "dao\n", "dai\n", "ubf\n", "eai\n", "ubr\n"]}
| 267
| 113
|
coding
|
Solve the programming task below in a Python markdown code block.
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.
The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 β€ i β€ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 β€ pi β€ i.
In order not to get lost, Vasya decided to act as follows.
* Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.
* Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal.
Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.
Input
The first line contains integer n (1 β€ n β€ 103) β the number of rooms. The second line contains n integers pi (1 β€ pi β€ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.
Output
Print a single number β the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
2
1 2
Output
4
Input
4
1 1 2 3
Output
20
Input
5
1 1 1 1 1
Output
62
|
{"inputs": ["1\n1\n", "2\n1 1\n", "2\n1 2\n", "3\n1 1 3\n", "4\n1 2 2 3\n", "4\n1 2 2 4\n", "4\n1 2 2 1\n", "4\n1 1 2 3\n"], "outputs": ["2\n", "6\n", "4\n", "8\n", "14\n", "10\n", "18\n", "20\n"]}
| 460
| 122
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a 0-indexed integer array nums. Initially on minute 0, the array is unchanged. Every minute, the leftmost element in nums is removed until no elements remain. Then, every minute, one element is appended to the end of nums, in the order they were removed in, until the original array is restored. This process repeats indefinitely.
For example, the array [0,1,2] would change as follows: [0,1,2] β [1,2] β [2] β [] β [0] β [0,1] β [0,1,2] β [1,2] β [2] β [] β [0] β [0,1] β [0,1,2] β ...
You are also given a 2D integer array queries of size n where queries[j] = [timej, indexj]. The answer to the jth query is:
nums[indexj] if indexj < nums.length at minute timej
-1 if indexj >= nums.length at minute timej
Return an integer array ans of size n where ans[j] is the answer to the jth query.
Β
Please complete the following python code precisely:
```python
class Solution:
def elementInNums(self, nums: List[int], queries: List[List[int]]) -> List[int]:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [0,1,2], queries = [[0,2],[2,0],[3,2],[5,0]]) == [2,2,-1,0]\n assert candidate(nums = [2], queries = [[0,0],[1,0],[2,0],[3,0]]) == [2,-1,2,-1]\n\n\ncheck(Solution().elementInNums)"}
| 301
| 101
|
coding
|
Solve the programming task below in a Python markdown code block.
#### Task:
Your job here is to implement a function `factors`, which takes a number `n`, and outputs an array of arrays comprised of two
parts, `sq` and `cb`. The part `sq` will contain all the numbers that, when squared, yield a number which is a factor of `n`,
while the `cb` part will contain all the numbers that, when cubed, yield a number which is a factor of `n`. Discard all `1`s
from both arrays.
Both `sq` and `cb` should be sorted in ascending order.
#### What it looks like:
```python
factors(int) #=> [
sq (all the numbers that can be squared to give a factor of n) : list,
cb (all the numbers that can be cubed to give a factor of n) : list
]
```
#### Some examples:
Also check out my other creations β [Keep the Order](https://www.codewars.com/kata/keep-the-order), [Naming Files](https://www.codewars.com/kata/naming-files), [Elections: Weighted Average](https://www.codewars.com/kata/elections-weighted-average), [Identify Case](https://www.codewars.com/kata/identify-case), [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions),
[Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2).
If you notice any issues or have any suggestions/comments whatsoever, please don't hesitate to mark an issue or just comment. Thanks!
Also feel free to reuse/extend the following starter code:
```python
def factors(n):
```
|
{"functional": "_inputs = [[1], [4], [16], [81], [80], [100], [5], [120], [18], [8]]\n_outputs = [[[[], []]], [[[2], []]], [[[2, 4], [2]]], [[[3, 9], [3]]], [[[2, 4], [2]]], [[[2, 5, 10], []]], [[[], []]], [[[2], [2]]], [[[3], []]], [[[2], [2]]]]\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(factors(*i), o[0])"}
| 485
| 260
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.