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. Read problems statements in Mandarin chinese, Russian and Vietnamese as well. Masha has $N$ minions. Each minion has two characteristics: power $a$ and endurance $b$. Masha thinks that a non-empty set of minions $\{m_{1}, m_{2}, \dots, m_{k}\}$ with characteristics $(a_{m_{1}},b_{m_{1}}), (a_{m_{2}},b_{m_{2}}), \dots, (a_{m_{k}},b_{m_{k}})$ is *good* if the mean endurance of this set doesn't exceed the minimum power in it, i.e. if $min(a_{m_{1}}, a_{m_{2}}, \dots, a_{m_{k}}) ≥ (b_{m_{1}}+b_{m_{2}}+\dots+b_{m_{k}}) / k$. Masha would like to choose a good subset of her minions and give these minions to Mark. Your task is to calculate the maximum number of minions Masha can give to Mark. ------ 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 following $N$ lines describe minions. Each of these lines contains two space-separated integers $a$ and $b$ denoting the power and endurance of one minion. ------ Output ------ For each test case, print a single line containing one number — the size of the largest good set of minions, or $0$ if no such set exists. ------ Constraints ------ $1 ≤ T ≤ 1,000$ $1 ≤ N ≤ 4\cdot10^{5}$ $1 ≤ a, b ≤ 10^{9}$ the sum of $N$ for all test cases does not exceed $4\cdot10^{5}$ ----- Sample Input 1 ------ 2 3 1 4 3 3 2 1 2 3 5 1 4 ----- Sample Output 1 ------ 2 0 ----- explanation 1 ------ Example case 1: The set of minions $\{2, 3\}$ is good, since $\mathrm{min}(3,2) ≥ (3+1)/2$. Example case 2: There is no non-empty good subset of minions.
{"inputs": ["2\n3\n1 4\n3 3\n2 1\n2\n3 5\n1 4"], "outputs": ["2\n0"]}
535
38
coding
Solve the programming task below in a Python markdown code block. How many bees are in the beehive? * bees can be facing UP, DOWN, LEFT, or RIGHT * bees can share parts of other bees Examples Ex1 ``` bee.bee .e..e.. .b..eeb ``` *Answer: 5* Ex2 ``` bee.bee e.e.e.e eeb.eeb ``` *Answer: 8* # Notes * The hive may be empty or null/None/nil/... * Python: the hive is passed as a list of lists (not a list of strings) Also feel free to reuse/extend the following starter code: ```python def how_many_bees(hive): ```
{"functional": "_inputs = [[None]]\n_outputs = [[0]]\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(how_many_bees(*i), o[0])"}
162
157
coding
Solve the programming task below in a Python markdown code block. In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east. A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i). Takahashi the king is interested in the following Q matters: - The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i. Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him. -----Constraints----- - N is an integer between 1 and 500 (inclusive). - M is an integer between 1 and 200 \ 000 (inclusive). - Q is an integer between 1 and 100 \ 000 (inclusive). - 1 \leq L_i \leq R_i \leq N (1 \leq i \leq M) - 1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q) -----Input----- Input is given from Standard Input in the following format: N M Q L_1 R_1 L_2 R_2 : L_M R_M p_1 q_1 p_2 q_2 : p_Q q_Q -----Output----- Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i. -----Sample Input----- 2 3 1 1 1 1 2 2 2 1 2 -----Sample Output----- 3 As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.
{"inputs": ["2 3 1\n1 1\n1 2\n2 2\n1 2", "2 3 1\n1 1\n1 2\n2 2\n1 2\n", "10 3 2\n0 8\n2 8\n0 9\n1 2\n3 3", "10 3 2\n0 8\n2 8\n0 9\n1 2\n2 3", "10 3 2\n0 8\n2 8\n0 9\n1 2\n2 6", "10 0 2\n0 8\n2 8\n0 9\n1 2\n2 6", "10 0 2\n0 8\n2 8\n0 9\n1 2\n2 9", "10 0 2\n0 8\n0 8\n0 9\n1 2\n2 9"], "outputs": ["3", "3\n", "0\n0\n", "0\n0\n", "0\n0\n", "0\n0\n", "0\n0\n", "0\n0\n"]}
437
264
coding
Solve the programming task below in a Python markdown code block. Chef's last task in his internship requires him to construct 2 permutations, each having length N, such that the [bitwise AND] of each pair of elements at every index is the same. Formally, if the permutations are A and B, then, the value A_{i} \& B_{i} must be constant over all 1≤ i ≤ N. Help Chef by providing him 2 such permutations. If it is not possible to construct such permutations, print -1 instead. A permutation is a sequence of integers from 1 to N of length N containing each number exactly once. ------ 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, a single integer N denoting the size of the required permutations. ------ Output Format ------ - If there are valid permutations that satisfy the required condition, then: - In the first line, output N space-separated integers denoting the permutation A. - In the second line, output N space-separated integers denoting the permutation B. - If there is no valid pair of permutations, print -1 in a single line. ------ Constraints ------ $1 ≤ T ≤ 1000$ $1 ≤ N ≤ 10^{5}$ - Sum of $N$ over all test cases does not exceed $2\cdot 10^{5}$. ----- Sample Input 1 ------ 3 1 2 3 ----- Sample Output 1 ------ 1 1 1 2 2 1 -1 ----- explanation 1 ------ Test case $1$: There is only one element in each array and the resultant bitwise AND is $1$. Thus, $A = [1]$ and $B = [1]$. Test case $2$: Let $A = [1,2]$ and $B = [2,1]$. The resultant bitwise AND of each pair at any index is equal to $0$. So, this is a valid pair of permutations. Test case $3$: There are $6$ permutations of length $3$. It can be seen that any pair of the $6$ permutations does not satisfy the stated condition.
{"inputs": ["3\n1\n2\n3\n"], "outputs": ["1\n1\n1 2\n2 1\n-1\n"]}
474
33
coding
Solve the programming task below in a Python markdown code block. Instead of writing,$a \times (b+c) = a \times b + a \times c$, Joe by mistakenly swapped the $\times$ and + signs on the left hand side. The equation became, $a+(b \times c)= a \times b + a \times c$ ? Joe somehow knew the value of a, but forgot the values of b and c such that the equation is satisfied. Can you help him find how many ordered pairs $(b,c)$ satisfy the above equation? If there exists infinite ordered pair, output -1. Note: $a,b,c$ are integers ------ Input ------ Single line containing a single integer $a$ ------ Output ------ Single line containing one integer, denoting the number of ordered set (b,c) ------ Constraints ------ $$|a| ≤ 10^{18}$$ ------ Sample Input ------ 2 ------ Sample Output ------ 4 ------ Explanation ------ Possible ordered pairs are $(0,1), (1,0), (3,4), (4,3)$
{"inputs": ["2"], "outputs": ["4\n"]}
232
13
coding
Solve the programming task below in a Python markdown code block. This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved. You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times. An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line contains a single integer n (1 ≤ n ≤ 200 000) — the length of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ min(n, 100)) — elements of the array. Output You should output exactly one integer — the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0. Examples Input 7 1 1 2 2 3 3 3 Output 6 Input 10 1 1 1 5 4 1 3 1 2 2 Output 7 Input 1 1 Output 0 Note In the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times.
{"inputs": ["1\n1\n", "7\n1 2 3 3 3 2 1\n", "7\n2 2 3 3 3 2 1\n", "7\n2 4 3 3 3 2 1\n", "7\n1 1 4 4 3 4 3\n", "7\n1 1 2 2 3 4 3\n", "7\n1 1 4 2 3 4 3\n", "7\n2 4 6 3 3 2 1\n"], "outputs": ["0\n", "3\n", "7\n", "3\n", "5\n", "7\n", "7\n", "7\n"]}
431
170
coding
Solve the programming task below in a Python markdown code block. For encoding an even-length binary string into a sequence of A, T, C, and G, we iterate from left to right and replace the characters as follows: 00 is replaced with A 01 is replaced with T 10 is replaced with C 11 is replaced with G Given a binary string S of length N (N is even), find the encoded sequence. ------ Input Format ------ - First line will contain T, number of test cases. Then the test cases follow. - Each test case contains two lines of input. - First line contains a single integer N, the length of the sequence. - Second line contains binary string S of length N. ------ Output Format ------ For each test case, output in a single line the encoded sequence. Note: Output is case-sensitive. ------ Constraints ------ $1 ≤ T ≤ 100$ $2 ≤ N ≤ 10^{3}$ $N$ is even. - Sum of $N$ over all test cases is at most $10^{3}$. $S$ contains only characters 0 and 1. ----- Sample Input 1 ------ 4 2 00 4 0011 6 101010 4 1001 ----- Sample Output 1 ------ A AG CCC CT ----- explanation 1 ------ Test case $1$: Based on the rules 00 is replaced with A. Test case $2$: Based on the rules 00 is replaced with A. Similarly, 11 is replaced with G. Thus, the encoded sequence is AG. Test case $3$: The first two characters are 10 which is encoded as C. Similarly, the next two characters 10 are encoded as C and the last two characters 10 are encoded as C. Thus, the encoded string is CCC. Test case $4$: The first two characters are 10 which is encoded as C. Similarly, the next two characters 01 are encoded as T. Thus, the encoded string is CT.
{"inputs": ["4\n2\n00\n4\n0011\n6\n101010\n4\n1001\n"], "outputs": ["A\nAG\nCCC\nCT"]}
445
47
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 sum of values of its deepest leaves.   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 deepestLeavesSum(self, root: Optional[TreeNode]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(root = tree_node([1,2,3,4,5,None,6,7,None,None,None,None,8])) == 15\n assert candidate(root = tree_node([6,7,8,2,7,1,3,9,None,1,4,None,None,None,5])) == 19\n\n\ncheck(Solution().deepestLeavesSum)"}
120
95
coding
Solve the programming task below in a Python markdown code block. R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher. There are n letters in R3D3’s alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letter’s sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabet’s code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help. Given the costs c_0 and c_1 for each '0' and '1' in R3D3’s alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost. -----Input----- The first line of input contains three integers n (2 ≤ n ≤ 10^8), c_0 and c_1 (0 ≤ c_0, c_1 ≤ 10^8) — the number of letters in the alphabet, and costs of '0' and '1', respectively. -----Output----- Output a single integer — minimum possible total a cost of the whole alphabet. -----Example----- Input 4 1 2 Output 12 -----Note----- There are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4·1 + 4·2 = 12.
{"inputs": ["4 1 2\n", "2 1 5\n", "3 1 1\n", "5 5 5\n", "4 0 0\n", "6 0 6\n", "6 6 0\n", "2 1 2\n"], "outputs": ["12\n", "6\n", "5\n", "60\n", "0\n", "30\n", "30\n", "3\n"]}
517
106
coding
Solve the programming task below in a Python markdown code block. In ACM-ICPC contests, there are usually three people in a team. For each person in the team, you know their scores in three skills - hard work, intelligence and persistence. You want to check whether it is possible to order these people (assign them numbers from 1 to 3) in such a way that for each 1 ≤ i ≤ 2, i+1-th person is stricly better than the i-th person. A person x is said to be better than another person y if x doesn't score less than y in any of the skills and scores more than y in at least one skill. Determine whether such an ordering exists. -----Input----- The first line fo the input contains an integer T denoting the number of test cases. Each test consists of three lines. Each of these lines contains three space separated integers s1, s2 and s3 denoting the scores of one member of the team in each of the three skills, in the given order. -----Output----- For each test case, output a single line containing "yes" if such an ordering exists or "no" if doesn't exist (without quotes). -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ s1, s2, s3 ≤ 100 -----Example----- Input 3 1 2 3 2 3 4 2 3 5 1 2 3 2 3 4 2 3 4 5 6 5 1 2 3 2 3 4 Output yes no yes -----Explanation----- Test Case 1: We can order them as (3, 2, 1). Person 3 is better than Person 2 because his scores in the first two skills are not lesser than Person 2's. And in skill 3, Person 3 scores higher. Similarly, Person 2 is better than Person 1. He scores more than Person 1 in every skill, in fact.
{"inputs": ["3\n1 2 3\n2 3 4\n2 3 5\n1 2 3\n2 3 4\n2 3 4\n5 6 5\n1 2 3\n2 3 4"], "outputs": ["yes\nno\nyes"]}
437
70
coding
Solve the programming task below in a Python markdown code block. In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. Input The first line has 4 natural numbers: k (1 ≤ k ≤ 100) — the number of Kostya's allies, n (1 ≤ n ≤ 50) — the number of basic artifacts, m (0 ≤ m ≤ 50) — the number of composite artifacts, q (1 ≤ q ≤ 500) — the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. №1> <Art. №1 Number>, <Art. №2> <Art. №2 Number>, ... <Art. №X> <Art. №Х Number> All the numbers are natural numbers not exceeding 100 (1 ≤ X ≤ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≤ ai ≤ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it. Output The output file should consist of k blocks. The first line should contain number bi — the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive. Examples Input 2 3 2 5 desolator refresher perseverance vanguard: desolator 1, refresher 1 maelstorm: perseverance 2 1 desolator 2 perseverance 1 refresher 2 desolator 2 perseverance Output 1 vanguard 1 2 desolator 1 maelstorm 1
{"inputs": ["1 2 0 2\nb\na\n1 a\n1 b\n", "1 1 1 1\na\nb: a 1\n1 a\n", "1 1 1 1\na\nc: a 1\n1 a\n", "1 1 1 1\na\nc: a 2\n1 a\n", "10 1 1 3\na\nb: a 2\n1 a\n1 a\n1 a\n", "20 1 1 3\na\nb: a 2\n1 a\n1 a\n1 a\n", "10 1 1 3\na\nc: a 2\n1 a\n1 a\n1 a\n", "20 1 1 3\na\nc: a 2\n1 a\n1 a\n1 a\n"], "outputs": ["2\na 1\nb 1\n", "1\nb 1\n", "1\nc 1\n", "1\na 1\n", "2\na 1\nb 1\n0\n0\n0\n0\n0\n0\n0\n0\n0\n", "2\na 1\nb 1\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n", "2\na 1\nc 1\n0\n0\n0\n0\n0\n0\n0\n0\n0\n", "2\na 1\nc 1\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n"]}
767
397
coding
Solve the programming task below in a Python markdown code block. You have a given picture with size $w \times h$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below: A "+" shape has one center nonempty cell. There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction. All other cells are empty. Find out if the given picture has single "+" shape. -----Input----- The first line contains two integers $h$ and $w$ ($1 \le h$, $w \le 500$) — the height and width of the picture. The $i$-th of the next $h$ lines contains string $s_{i}$ of length $w$ consisting "." and "*" where "." denotes the empty space and "*" denotes the non-empty space. -----Output----- If the given picture satisfies all conditions, print "YES". Otherwise, print "NO". You can output each letter in any case (upper or lower). -----Examples----- Input 5 6 ...... ..*... .****. ..*... ..*... Output YES Input 3 5 ..*.. ****. .*... Output NO Input 7 7 ....... ...*... ..****. ...*... ...*... ....... .*..... Output NO Input 5 6 ..**.. ..**.. ****** ..**.. ..**.. Output NO Input 3 7 .*...*. ***.*** .*...*. Output NO Input 5 10 .......... ..*....... .*.******. ..*....... .......... Output NO -----Note----- In the first example, the given picture contains one "+". In the second example, two vertical branches are located in a different column. In the third example, there is a dot outside of the shape. In the fourth example, the width of the two vertical branches is $2$. In the fifth example, there are two shapes. In the sixth example, there is an empty space inside of the shape.
{"inputs": ["1 1\n*\n", "1 1\n*\n", "2 2\n..\n..\n", "2 2\n..\n..\n", "3 3\n*.*\n***\n*.*\n", "3 3\n...\n...\n...\n", "3 3\n...\n..*\n.**\n", "3 3\n.*.\n***\n.*.\n"], "outputs": ["NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "YES\n"]}
467
133
coding
Solve the programming task below in a Python markdown code block. In Japan, temperature is usually expressed using the Celsius (℃) scale. In America, they used the Fahrenheit (℉) scale instead. $20$ degrees Celsius is roughly equal to $68$ degrees Fahrenheit. A phrase such as "Today’s temperature is $68$ degrees" is commonly encountered while you are in America. A value in Fahrenheit can be converted to Celsius by first subtracting $32$ and then multiplying by $\frac{5}{9}$. A simplified method may be used to produce a rough estimate: first subtract $30$ and then divide by $2$. Using the latter method, $68$ Fahrenheit is converted to $19$ Centigrade, i.e., $\frac{(68-30)}{2}$. Make a program to convert Fahrenheit to Celsius using the simplified method: $C = \frac{F - 30}{2}$. Input The input is given in the following format. $F$ The input line provides a temperature in Fahrenheit $F$ ($30 \leq F \leq 100$), which is an integer divisible by $2$. Output Output the converted Celsius temperature in a line. Examples Input 68 Output 19 Input 50 Output 10
{"inputs": ["6", "82", "60", "85", "51", "96", "65", "57"], "outputs": ["-12\n", "26\n", "15\n", "27\n", "10\n", "33\n", "17\n", "13\n"]}
285
78
coding
Solve the programming task below in a Python markdown code block. Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant. A set of directions consists of several instructions. The first instruction is of the form "Begin on XXX", indicating the street that the route begins on. Each subsequent instruction is of the form "Left on XXX" or "Right on XXX", indicating a turn onto the specified road. When reversing directions, all left turns become right turns and vice versa, and the order of roads and turns is reversed. See the sample input for examples. -----Input----- Input will begin with an integer T, the number of test cases that follow. Each test case begins with an integer N, the number of instructions in the route. N lines follow, each with exactly one instruction in the format described above. -----Output----- For each test case, print the directions of the reversed route, one instruction per line. Print a blank line after each test case. -----Constraints----- - 1 ≤ T ≤ 15 - 2 ≤ N ≤ 40 - Each line in the input will contain at most 50 characters, will contain only alphanumeric characters and spaces and will not contain consecutive spaces nor trailing spaces. By alphanumeric characters we mean digits and letters of the English alphabet (lowercase and uppercase). -----Sample Input----- 2 4 Begin on Road A Right on Road B Right on Road C Left on Road D 6 Begin on Old Madras Road Left on Domlur Flyover Left on 100 Feet Road Right on Sarjapur Road Right on Hosur Road Right on Ganapathi Temple Road -----Sample Output----- Begin on Road D Right on Road C Left on Road B Left on Road A Begin on Ganapathi Temple Road Left on Hosur Road Left on Sarjapur Road Left on 100 Feet Road Right on Domlur Flyover Right on Old Madras Road -----Explanation----- In the first test case, the destination lies on Road D, hence the reversed route begins on Road D. The final turn in the original route is turning left from Road C onto Road D. The reverse of this, turning right from Road D onto Road C, is the first turn in the reversed route.
{"inputs": ["2\n4\nBegin on Road A\nRight on Road B\nRight on Road C\nLeft on Road D\n6\nBegin on Old Madras Road\nLeft on Domlur Flyover\nLeft on 100 Feet Road\nRight on Sarjapur Road\nRight on Hosur Road\nRight on Ganapathi Temple Road\n"], "outputs": ["Begin on Road D\nRight on Road C\nLeft on Road B\nLeft on Road A\n\nBegin on Ganapathi Temple Road\nLeft on Hosur Road\nLeft on Sarjapur Road\nLeft on 100 Feet Road\nRight on Domlur Flyover\nRight on Old Madras Road"]}
503
146
coding
Solve the programming task below in a Python markdown code block. Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration. Suppose that the distance between neighboring crossings are all the same equal to one kilometer. -----Input----- The first line contains two integers N и M — size of the city (1 ≤ N, M ≤ 10^9). In the next line there is a single integer C (1 ≤ C ≤ 10^5) — the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 ≤ x ≤ N, 1 ≤ y ≤ M). The next line contains an integer H — the number of restaurants (1 ≤ H ≤ 10^5). Following H lines contain descriptions of restaurants in the same format. Several restaurants and hotels may be located near the same crossing. -----Output----- In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them. -----Examples----- Input 10 10 2 1 1 3 3 2 1 10 4 4 Output 6 2
{"inputs": ["1 1\n1\n1 1\n1\n1 1\n", "1 1\n1\n1 1\n1\n1 1\n", "1 1\n1\n1 1\n1\n2 1\n", "100 100\n1\n1 100\n1\n1 100\n", "100 100\n1\n1 100\n1\n1 100\n", "101 100\n1\n1 100\n1\n1 100\n", "111 100\n1\n1 100\n1\n1 100\n", "100 101\n1\n1 100\n1\n1 100\n"], "outputs": ["0\n1\n", "0\n1\n", "1\n1\n", "0\n1\n", "0\n1\n", "0\n1\n", "0\n1\n", "0\n1\n"]}
354
238
coding
Solve the programming task below in a Python markdown code block. The palindrome is a string that can be read the same way from left to right and from right to left. For example, strings "aaaaa", "1221", "bbaabb" are palindromes, however the string "chef" is not a palindrome because if we read it from right to left, we will obtain "fehc" that is not the same as "chef". We call a string a "double string" if it has an even length and the first half of this string is equal to the second half of this string, for example "abab" is a double string because the first half "ab" is equal to the second half "ab", however the string "abba" is not a double string because the first half "ab" is not equal to the second half "ba". The empty string "" is a double string, and its length is 0. Chef doesn't like palindromes, however he likes "double strings". He often likes to change the order of letters in some palindrome and sometimes to remove some symbols from it. Now he wonders: if a palindrome of length N is given, what is the maximal possible number of characters in a "double string" that can be obtained by removing and changing the order of symbols in it? ------ Input ------ Several test cases are given. The first line of the sample input contains an integer T - the number of test cases. Then, T lines follow. Each line consists of a single integer N - the length of a palindrome. ------ Output ------ For each test case output a single integer - answer to the problem. ------ Constraints ------ $1≤T≤10000$ $1≤N≤1000000000$ ----- Sample Input 1 ------ 2 2 4 ----- Sample Output 1 ------ 2 4
{"inputs": ["2\n2\n4", "2\n2\n0", "2\n4\n0", "2\n8\n0", "2\n0\n0", "2\n6\n1", "2\n0\n2", "2\n6\n2"], "outputs": ["2\n4", "2\n0\n", "4\n0\n", "8\n0\n", "0\n0\n", "6\n0\n", "0\n2\n", "6\n2\n"]}
400
109
coding
Solve the programming task below in a Python markdown code block. There is a house with 4 levels. In that house there is an elevator. You can program this elevator to go up or down, depending on what button the user touches inside the elevator. Valid levels must be only these numbers: `0,1,2,3` Valid buttons must be only these strings: `'0','1','2','3'` Possible return values are these numbers: `-3,-2,-1,0,1,2,3` If the elevator is on the ground floor(0th level) and the user touches button '2' the elevator must go 2 levels up, so our function must return 2. If the elevator is on the 3rd level and the user touches button '0' the elevator must go 3 levels down, so our function must return -3. If the elevator is on the 2nd level, and the user touches button '2' the elevator must remain on the same level, so we return 0. We cannot endanger the lives of our passengers, so if we get erronous inputs, our elevator must remain on the same level. So for example: - `goto(2,'4')` must return 0, because there is no button '4' in the elevator. - `goto(4,'0')` must return 0, because there is no level 4. - `goto(3,undefined)` must return 0. - `goto(undefined,'2')` must return 0. - `goto([],'2')` must return 0 because the type of the input level is array instead of a number. - `goto(3,{})` must return 0 because the type of the input button is object instead of a string. Also feel free to reuse/extend the following starter code: ```python def goto(level,button): ```
{"functional": "_inputs = [[0, '0'], [0, '1'], [0, '2'], [0, '3'], [1, '0'], [1, '1'], [1, '2'], [1, '3'], [2, '0'], [2, '1'], [2, '2'], [2, '3'], [3, '0'], [3, '1'], [3, '2'], [3, '3'], [0, '4'], [0, None], [1, '4'], [1, None], [2, '4'], [2, None], [3, '4'], [3, None], [4, '2'], [None, '2'], [[], '2'], [3, {}], ['2', '3'], [2, 3], [1.5, '3'], ['length', 'length']]\n_outputs = [[0], [1], [2], [3], [-1], [0], [1], [2], [-2], [-1], [0], [1], [-3], [-2], [-1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]\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(goto(*i), o[0])"}
400
432
coding
Solve the programming task below in a Python markdown code block. According to the new tax scheme, a new tax called the binary string tax was introduced! JJ has a binary string S of length N. According to the tax scheme, for every occurrence of 01 in S, a tax of X rupees will be charged, while for every occurrence of 10 in S, a tax of Y rupees will be charged. For example, if X = 5, Y = 7 and S = 11010, then S has 1 occurrence of 01 and 2 occurrences of 10, so the tax charged = 5 \cdot 1 + 7 \cdot 2 = 19 JJ can rearrange the string S in any way he wants. He wants to minimize the amount of tax he has to pay. Can you help him do so? ------ 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 three integers N, X and Y - the length of the binary string S, the tax charged on an occurrence of 01 and the tax charged on an occurrence of 10. - The second line of each test case contains a binary string S of length N containing 0s and 1s only. ------ Output Format ------ For each test case, output the minimum amount of tax that JJ has to pay. ------ Constraints ------ $1 ≤ T ≤ 100$ $2 ≤ N ≤ 1000$ $1 ≤X, Y ≤100$ ----- Sample Input 1 ------ 2 4 7 3 1101 5 3 4 00000 ----- Sample Output 1 ------ 3 0 ----- explanation 1 ------ Test Case 1: JJ can rearrange $S$ to $1110$ for which the tax charged will be $3$ which is the minimum value of tax. Test Case 2: The tax charged for the string $S = 00000$ is $0$ which can not be reduced further.
{"inputs": ["2\n4 7 3\n1101\n5 3 4\n00000\n"], "outputs": ["3\n0\n"]}
462
39
coding
Solve the programming task below in a Python markdown code block. For a positive integer n, let us define f(n) as the number of digits in base 10. You are given an integer S. Count the number of the pairs of positive integers (l, r) (l \leq r) such that f(l) + f(l + 1) + ... + f(r) = S, and find the count modulo 10^9 + 7. -----Constraints----- - 1 \leq S \leq 10^8 -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print the answer. -----Sample Input----- 1 -----Sample Output----- 9 There are nine pairs (l, r) that satisfies the condition: (1, 1), (2, 2), ..., (9, 9).
{"inputs": ["4", "3", "6", "8", "1", "2", "1\n", "2\n"], "outputs": ["9096\n", "908\n", "900993\n", "90009092\n", "9", "98", "9\n", "98\n"]}
186
81
coding
Solve the programming task below in a Python markdown code block. So the Chef has become health conscious and is now lifting weights at the gym. But its his first time so the trainer gives him a simple job to do. He has been given a weight lifting rod and N heavy weights, each weighing 20, 21, .... , 2n-1. He has to stick each of the "N" weights on the rod, one after another, in such a way that the right side is never heavier than the left side. At each step he chooses one of the weights that has not yet been fixed on the rod, and fix it on either the left side of the rod or the right, until all of the weights have been placed. Now help the chef and find out, in how many ways the chef can accomplish this? -----Input----- First line of input contains an integer T, the number of test cases. Then T test cases follow. Each line of test case contains one integer, N denoting the number of weights -----Output----- The output contains T lines, each containing an integer denoting all possible combinations -----Example----- Input: 3 2 5 18 Output: 3 945 221643095476699771875
{"inputs": ["3\n2\n5\n18"], "outputs": ["3\n945\n221643095476699771875"]}
276
45
coding
Solve the programming task below in a Python markdown code block. You are given a string S of length 2N, containing N occurrences of `a` and N occurrences of `b`. You will choose some of the characters in S. Here, for each i = 1,2,...,N, it is not allowed to choose exactly one of the following two: the i-th occurrence of `a` and the i-th occurrence of `b`. (That is, you can only choose both or neither.) Then, you will concatenate the chosen characters (without changing the order). Find the lexicographically largest string that can be obtained in this way. Constraints * 1 \leq N \leq 3000 * S is a string of length 2N containing N occurrences of `a` and N occurrences of `b`. Input Input is given from Standard Input in the following format: N S Output Print the lexicographically largest string that satisfies the condition. Examples Input 3 aababb Output abab Input 3 bbabaa Output bbabaa Input 6 bbbaabbabaaa Output bbbabaaa Input 9 abbbaababaababbaba Output bbaababababa
{"inputs": ["3\nbabbaa", "3\naabbba", "3\nbababa", "3\naaabbb", "3\nbbaaba", "3\naabbab", "3\nababab", "3\nabbbaa"], "outputs": ["bbaa\n", "ba\n", "bababa\n", "ab\n", "bbaaba\n", "abab\n", "ababab\n", "bbaa\n"]}
271
103
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s consisting of lowercase English letters, return the first letter to appear twice. Note: A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b. s will contain at least one letter that appears twice.   Please complete the following python code precisely: ```python class Solution: def repeatedCharacter(self, s: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(s = \"abccbaacz\") == \"c\"\n assert candidate(s = \"abcdd\") == \"d\"\n\n\ncheck(Solution().repeatedCharacter)"}
101
50
coding
Solve the programming task below in a Python markdown code block. # Task Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it. Both of them did not like the sequence and started deleting some numbers in the following way. ``` First they deleted every 2nd number. So remaining numbers on the paper: 1,3,5,7,9,11..........till infinity. Then they deleted every 3rd number. So remaining numbers on the paper: 1,3,7,9,13,15..........till infinity.. Then they deleted every 4th number. So remaining numbers on the paper: 1,3,7,13,15..........till infinity.``` Then kept on doing this (deleting every 5th, then every 6th ...) untill they got old and died. It is obvious that some of the numbers will never get deleted(E.g. 1,3,7,13..) and hence are know to us as survivor numbers. Given a number `n`, check whether its a survivor number or not. # Input/Output - `[input]` integer `n` `0 < n <= 10^8` - `[output]` a boolean value `true` if the number is a survivor else `false`. Also feel free to reuse/extend the following starter code: ```python def survivor(n): ```
{"functional": "_inputs = [[1], [5], [8], [9], [13], [15], [134], [289]]\n_outputs = [[True], [False], [False], [False], [True], [False], [False], [True]]\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(survivor(*i), o[0])"}
329
203
coding
Solve the programming task below in a Python markdown code block. One day, Tanya was studying graph theory. She is very inquisitive, so the following problem soon came to her mind. Find the number of undirected unweighted connected simple graphs with $N$ vertices (numbered $1$ through $N$) and $M$ edges, such that for each $i$ ($2 \le i \le N$), the shortest path from vertex $1$ to vertex $i$ is unique and its length is equal to $A_i$. In other words, for each $i$ ($2 \le i \le N$), there should be exactly one path with length $A_i$ between vertices $1$ and $i$, and there should be no paths with smaller length between these vertices. Two graphs with $N$ vertices are distinct if we can find two vertices $u$ and $v$ such that there is an edge between these vertices in one graph, but not in the other graph. Since the answer could be very large, compute it modulo $1,000,000,007$ ($10^9 + 7$). -----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 two space-separated integers $N$ and $M$. - The second line contains $N - 1$ space-separated integers $A_2, A_3, \ldots, A_N$. -----Output----- For each test case, print a single line containing one integer ― the number of graphs modulo $10^9 + 7$. -----Constraints----- - $1 \le T \le 1,000$ - $2 \le N \le 10^5$ - $N-1 \le M \le \mathrm{min}\left(2\cdot 10^5, \frac{N(N-1)}{2}\right)$ - $1 \le A_i \le N-1$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $2 \cdot 10^5$ - the sum of $M$ over all test cases does not exceed $2 \cdot 10^5$ -----Subtasks----- Subtask #1 (50 points): $M = N-1$ Subtask #2 (50 points): original constraints -----Example Input----- 3 4 3 1 2 1 4 6 1 2 1 3 2 2 2 -----Example Output----- 2 0 0 -----Explanation----- Example case 1: The two graphs which satisfy all conditions are:
{"inputs": ["3\n4 3\n1 2 1\n4 6\n1 2 1\n3 2\n2 2"], "outputs": ["2\n0\n0"]}
596
44
coding
Solve the programming task below in a Python markdown code block. There is a grid, consisting of $2$ rows and $m$ columns. The rows are numbered from $1$ to $2$ from top to bottom. The columns are numbered from $1$ to $m$ from left to right. The robot starts in a cell $(1, 1)$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid. Initially, all cells, except for the cell $(1, 1)$, are locked. Each cell $(i, j)$ contains a value $a_{i,j}$ — the moment that this cell gets unlocked. The robot can only move into a cell $(i, j)$ if at least $a_{i,j}$ seconds have passed before the move. The robot should visit all cells without entering any cell twice or more (cell $(1, 1)$ is considered entered at the start). It can finish in any cell. What is the fastest the robot can achieve that? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases. The first line of each testcase contains a single integer $m$ ($2 \le m \le 2 \cdot 10^5$) — the number of columns of the grid. The $i$-th of the next $2$ lines contains $m$ integers $a_{i,1}, a_{i,2}, \dots, a_{i,m}$ ($0 \le a_{i,j} \le 10^9$) — the moment of time each cell gets unlocked. $a_{1,1} = 0$. If $a_{i,j} = 0$, then cell $(i, j)$ is unlocked from the start. The sum of $m$ over all testcases doesn't exceed $2 \cdot 10^5$. -----Output----- For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more. -----Examples----- Input 4 3 0 0 1 4 3 2 5 0 4 8 12 16 2 6 10 14 18 4 0 10 10 10 10 10 10 10 2 0 0 0 0 Output 5 19 17 3 -----Note----- None
{"inputs": ["4\n3\n0 0 1\n4 3 2\n5\n0 4 8 12 16\n2 6 10 14 18\n4\n0 10 10 10\n10 10 10 10\n2\n0 0\n0 0\n"], "outputs": ["5\n19\n17\n3\n"]}
574
98
coding
Solve the programming task below in a Python markdown code block. Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total. Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod. Input The first line contains four integers n, m, b, mod (1 ≤ n, m ≤ 500, 0 ≤ b ≤ 500; 1 ≤ mod ≤ 109 + 7) — the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer. The next line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of bugs per line for each programmer. Output Print a single integer — the answer to the problem modulo mod. Examples Input 3 3 3 100 1 1 1 Output 10 Input 3 6 5 1000000007 1 2 3 Output 0 Input 3 5 6 11 1 2 1 Output 0
{"inputs": ["1 1 1 1\n0\n", "1 1 1 1\n2\n", "1 2 1 1\n2\n", "2 2 1 1\n2\n", "1 5 1 10\n1\n", "1 5 1 13\n1\n", "1 5 5 1000\n1\n", "1 1 0 1000\n0\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "1\n", "1\n"]}
419
142
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s, return true if the s can be palindrome after deleting at most one character from it.   Please complete the following python code precisely: ```python class Solution: def validPalindrome(self, s: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(s = \"aba\") == True\n assert candidate(s = \"abca\") == True\n assert candidate(s = \"abc\") == False\n\n\ncheck(Solution().validPalindrome)"}
69
53
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.   Please complete the following python code precisely: ```python class Solution: def removeKdigits(self, num: str, k: int) -> str: ```
{"functional": "def check(candidate):\n assert candidate(num = \"1432219\", k = 3) == \"1219\"\n assert candidate(num = \"10200\", k = 1) == \"200\"\n assert candidate(num = \"10\", k = 2) == \"0\"\n\n\ncheck(Solution().removeKdigits)"}
79
90
coding
Solve the programming task below in a Python markdown code block. Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b. Input The only line contains two integers a and b (1 ≤ a, b ≤ 105). It is guaranteed that number b is lucky. Output In the only line print a single number — the number c that is sought by Petya. Examples Input 1 7 Output 7 Input 100 47 Output 147
{"inputs": ["1 4\n", "4 4\n", "7 7\n", "7 4\n", "4 7\n", "0 7\n", "1 7\n", "44 4\n"], "outputs": ["4\n", "14\n", "17\n", "14\n", "7\n", "7\n", "7\n", "45\n"]}
289
91
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s and an integer k, return true if s is a k-palindrome. A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.   Please complete the following python code precisely: ```python class Solution: def isValidPalindrome(self, s: str, k: int) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(s = \"abcdeca\", k = 2) == True\n assert candidate(s = \"abbababa\", k = 1) == True\n\n\ncheck(Solution().isValidPalindrome)"}
95
55
coding
Solve the programming task below in a Python markdown code block. A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist. Input The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0. Output If the required point exists, output its coordinates, otherwise output -1. Examples Input 2 5 3 Output 6 -3
{"inputs": ["0 2 3\n", "2 5 4\n", "4 5 4\n", "0 2 2\n", "0 2 4\n", "2 5 3\n", "0 -1 -2\n", "-1 1 -2\n"], "outputs": ["-1\n\n", "8 -4", "4 -4", "0 -1", "0 -2", "6 -3\n", "0 -2\n", "0 2\n"]}
166
114
coding
Solve the programming task below in a Python markdown code block. It is the easy version of the problem. The only difference is that in this version $k = 3$. You are given a positive integer $n$. Find $k$ positive integers $a_1, a_2, \ldots, a_k$, such that: $a_1 + a_2 + \ldots + a_k = n$ $LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$ Here $LCM$ is the least common multiple of numbers $a_1, a_2, \ldots, a_k$. We can show that for given constraints the answer always exists. -----Input----- The first line contains a single integer $t$ $(1 \le t \le 10^4)$ — the number of test cases. The only line of each test case contains two integers $n$, $k$ ($3 \le n \le 10^9$, $k = 3$). -----Output----- For each test case print $k$ positive integers $a_1, a_2, \ldots, a_k$, for which all conditions are satisfied. -----Examples----- Input 3 3 3 8 3 14 3 Output 1 1 1 4 2 2 2 6 6 -----Note----- None
{"inputs": ["3\n3 3\n8 3\n14 3\n"], "outputs": ["1 1 1\n4 2 2\n2 6 6\n"]}
306
43
coding
Solve the programming task below in a Python markdown code block. ## Task Given a positive integer `n`, calculate the following sum: ``` n + n/2 + n/4 + n/8 + ... ``` All elements of the sum are the results of integer division. ## Example ``` 25 => 25 + 12 + 6 + 3 + 1 = 47 ``` Also feel free to reuse/extend the following starter code: ```python def halving_sum(n): ```
{"functional": "_inputs = [[25], [127], [38], [1], [320], [13], [15], [47], [101], [257]]\n_outputs = [[47], [247], [73], [1], [638], [23], [26], [89], [198], [512]]\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(halving_sum(*i), o[0])"}
115
236
coding
Solve the programming task below in a Python markdown code block. A [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) is a prime number that can be represented as: Mn = 2^(n) - 1. Therefore, every Mersenne prime is one less than a power of two. Write a function that will return whether the given integer `n` will produce a Mersenne prime or not. The tests will check random integers up to 2000. Also feel free to reuse/extend the following starter code: ```python def valid_mersenne(n): ```
{"functional": "_inputs = [[2], [3], [5], [7], [11], [13], [17], [19], [21], [23], [31], [49], [61], [89], [107], [127], [221], [521], [607], [1279]]\n_outputs = [[True], [True], [True], [True], [False], [True], [True], [True], [False], [False], [True], [False], [True], [True], [True], [True], [False], [True], [True], [True]]\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(valid_mersenne(*i), o[0])"}
130
293
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an m x n picture consisting of black 'B' and white 'W' pixels and an integer target, return the number of black lonely pixels. A black lonely pixel is a character 'B' that located at a specific position (r, c) where: Row r and column c both contain exactly target black pixels. For all rows that have a black pixel at column c, they should be exactly the same as row r.   Please complete the following python code precisely: ```python class Solution: def findBlackPixel(self, picture: List[List[str]], target: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(picture = [[\"W\",\"B\",\"W\",\"B\",\"B\",\"W\"],[\"W\",\"B\",\"W\",\"B\",\"B\",\"W\"],[\"W\",\"B\",\"W\",\"B\",\"B\",\"W\"],[\"W\",\"W\",\"B\",\"W\",\"B\",\"W\"]], target = 3) == 6\n assert candidate(picture = [[\"W\",\"W\",\"B\"],[\"W\",\"W\",\"B\"],[\"W\",\"W\",\"B\"]], target = 1) == 0\n\n\ncheck(Solution().findBlackPixel)"}
142
132
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an m x n binary matrix grid. In one operation, you can choose any row or column and flip each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). Return true if it is possible to remove all 1's from grid using any number of operations or false otherwise.   Please complete the following python code precisely: ```python class Solution: def removeOnes(self, grid: List[List[int]]) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(grid = [[0,1,0],[1,0,1],[0,1,0]]) == True\n assert candidate(grid = [[1,1,0],[0,0,0],[0,0,0]]) == False\n assert candidate(grid = [[0]]) == True\n\n\ncheck(Solution().removeOnes)"}
128
85
coding
Solve the programming task below in a Python markdown code block. # SpeedCode #2 - Array Madness ## Objective Given two **integer arrays** ```a, b```, both of ```length >= 1```, create a program that returns ```true``` if the **sum of the squares** of each element in ```a``` is **strictly greater than** the **sum of the cubes** of each element in ```b```. E.g. ```python array_madness([4, 5, 6], [1, 2, 3]) => True #because 4 ** 2 + 5 ** 2 + 6 ** 2 > 1 ** 3 + 2 ** 3 + 3 ** 3 ``` Get your timer out. Are you ready? Ready, get set, GO!!! Also feel free to reuse/extend the following starter code: ```python def array_madness(a,b): ```
{"functional": "_inputs = [[[4, 5, 6], [1, 2, 3]]]\n_outputs = [[True]]\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(array_madness(*i), o[0])"}
203
171
coding
Solve the programming task below in a Python markdown code block. The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo! There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad. Help Bessie to minimize the number of sad guests by lining the guests in an optimal way. -----Input----- The first line contains integers $n$ and $k$ ($2 \le n \le 10^5$, $1 \le k \le 10^5$), the number of snacks and the number of guests. The $i$-th of the following $k$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), favorite snack flavors of the $i$-th guest. -----Output----- Output one integer, the smallest possible number of sad guests. -----Examples----- Input 5 4 1 2 4 3 1 4 3 4 Output 1 Input 6 5 2 3 2 1 3 4 6 5 4 5 Output 0 -----Note----- In the first example, Bessie can order the guests like this: $3, 1, 2, 4$. Guest $3$ goes first and eats snacks $1$ and $4$. Then the guest $1$ goes and eats the snack $2$ only, because the snack $1$ has already been eaten. Similarly, the guest $2$ goes up and eats the snack $3$ only. All the snacks are gone, so the guest $4$ will be sad. In the second example, one optimal ordering is $2, 1, 3, 5, 4$. All the guests will be satisfied.
{"inputs": ["2 1\n1 2\n", "2 1\n1 2\n", "4 2\n1 2\n2 3\n", "4 2\n1 3\n2 4\n", "4 2\n1 3\n2 4\n", "4 2\n1 2\n2 3\n", "4 2\n2 3\n2 4\n", "4 2\n1 2\n2 4\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
525
142
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.   Please complete the following python code precisely: ```python class Solution: def maxNonOverlapping(self, nums: List[int], target: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,1,1,1,1], target = 2) == 2\n assert candidate(nums = [-1,3,5,1,4,2,-9], target = 6) == 2\n assert candidate(nums = [-2,6,6,3,5,4,1,2,8], target = 10) == 3\n assert candidate(nums = [0,0,0], target = 0) == 3\n\n\ncheck(Solution().maxNonOverlapping)"}
90
130
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).   Please complete the following python code precisely: ```python class Solution: def canBeIncreasing(self, nums: List[int]) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,2,10,5,7]) == True\n assert candidate(nums = [2,3,1,2]) == False\n assert candidate(nums = [1,1,1]) == False\n assert candidate(nums = [1,2,3]) == True\n\n\ncheck(Solution().canBeIncreasing)"}
117
87
coding
Solve the programming task below in a Python markdown code block. Your task is to write an update for a lottery machine. Its current version produces a sequence of random letters and integers (passed as a string to the function). Your code must filter out all letters and return **unique** integers as a string, in their order of first appearance. If there are no integers in the string return `"One more run!"` ## Examples ``` "hPrBKWDH8yc6Lt5NQZWQ" --> "865" "ynMAisVpHEqpqHBqTrwH" --> "One more run!" "555" --> "5" ``` Also feel free to reuse/extend the following starter code: ```python def lottery(s): ```
{"functional": "_inputs = [['wQ8Hy0y5m5oshQPeRCkG'], ['ffaQtaRFKeGIIBIcSJtg'], ['555'], ['HappyNewYear2020'], ['20191224isXmas'], ['']]\n_outputs = [['805'], ['One more run!'], ['5'], ['20'], ['20194'], ['One more run!']]\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(lottery(*i), o[0])"}
168
239
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. An experiment is being conducted in a lab. To ensure accuracy, there are two sensors collecting data simultaneously. You are given two arrays sensor1 and sensor2, where sensor1[i] and sensor2[i] are the ith data points collected by the two sensors. However, this type of sensor has a chance of being defective, which causes exactly one data point to be dropped. After the data is dropped, all the data points to the right of the dropped data are shifted one place to the left, and the last data point is replaced with some random value. It is guaranteed that this random value will not be equal to the dropped value. For example, if the correct data is [1,2,3,4,5] and 3 is dropped, the sensor could return [1,2,4,5,7] (the last position can be any value, not just 7). We know that there is a defect in at most one of the sensors. Return the sensor number (1 or 2) with the defect. If there is no defect in either sensor or if it is impossible to determine the defective sensor, return -1.   Please complete the following python code precisely: ```python class Solution: def badSensor(self, sensor1: List[int], sensor2: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(sensor1 = [2,3,4,5], sensor2 = [2,1,3,4]) == 1\n assert candidate(sensor1 = [2,2,2,2,2], sensor2 = [2,2,2,2,5]) == -1\n assert candidate(sensor1 = [2,3,2,2,3,2], sensor2 = [2,3,2,3,2,7]) == 2\n\n\ncheck(Solution().badSensor)"}
290
124
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 search tree (BST) and an integer val. Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.   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 searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: ```
{"functional": "def check(candidate):\n assert is_same_tree(candidate(root = tree_node([4,2,7,1,3]), val = 2), tree_node([2,1,3]))\n assert is_same_tree(candidate(root = tree_node([4,2,7,1,3]), val = 5), tree_node([]))\n\n\ncheck(Solution().searchBST)"}
157
88
coding
Solve the programming task below in a Python markdown code block. You are now in a bookshop with your friend Alice to buy a book, "The Winning Strategy for the Programming Koshien Contest,” just released today. As you definitely want to buy it, you are planning to borrow some money from Alice in case the amount you have falls short of the price. If the amount you receive from Alice still fails to meet the price, you have to abandon buying the book this time. Write a program to calculate the minimum amount of money you need to borrow from Alice given the following three items of data: the money you and Alice have now and the price of the book. Input The input is given in the following format. m f b A line containing the three amounts of money is given: the amount you have with you now m (0 ≤ m ≤ 10000), the money Alice has now f (0 ≤ f ≤ 10000) and the price of the book b (100 ≤ b ≤ 20000). Output Output a line suggesting the minimum amount of money you need to borrow from Alice. Output "NA" if all the money Alice has with him now is not a sufficient amount for you to buy the book. Examples Input 1000 3000 3000 Output 2000 Input 5000 3000 4500 Output 0 Input 500 1000 2000 Output NA
{"inputs": ["1 1110 3", "0 1100 3", "1 1100 2", "350 7 354", "0 1110 13", "0 1110 20", "0 1110 10", "1 1110 10"], "outputs": ["2\n", "3\n", "1\n", "4\n", "13\n", "20\n", "10\n", "9\n"]}
330
126
coding
Solve the programming task below in a Python markdown code block. Two coordinates (a1, a2) and (b1, b2) on a two-dimensional grid of r × c are given. The cost of moving from a cell (e, f) to one of the cells (e + 1, f), (e-1, f), (e, f + 1), (e, f-1) is 1. And. You can also move between (e, c-1) and (e, 0), and between (r-1, f) and (0, f) at a cost of 1. At this time, find the number of routes that can be moved from the first coordinate to the second coordinate at the shortest cost. Input The input is given in the following format. r c a1 a2 b1 b2 Input meets the following constraints 1 ≤ r, c ≤ 1,000 0 ≤ a1, b1 <r 0 ≤ a2, b2 <c Output Output the remainder of the answer value divided by 100,000,007. Examples Input 4 4 0 0 3 3 Output 2 Input 4 4 0 0 1 1 Output 2 Input 2 3 0 0 1 2 Output 4 Input 500 500 0 0 200 200 Output 34807775
{"inputs": ["4 1 0 0 1 1", "4 4 1 0 3 3", "2 3 0 0 1 1", "2 1 0 0 1 1", "4 7 0 0 1 2", "4 4 0 0 1 1", "4 4 0 0 3 3", "2 3 0 0 1 2"], "outputs": ["1\n", "6\n", "4\n", "2\n", "3\n", "2", "2", "4"]}
335
139
coding
Solve the programming task below in a Python markdown code block. We have N+M balls, each of which has an integer written on it. It is known that: - The numbers written on N of the balls are even. - The numbers written on M of the balls are odd. Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even. It can be shown that this count does not depend on the actual values written on the balls. -----Constraints----- - 0 \leq N,M \leq 100 - 2 \leq N+M - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M -----Output----- Print the answer. -----Sample Input----- 2 1 -----Sample Output----- 1 For example, let us assume that the numbers written on the three balls are 1,2,4. - If we choose the two balls with 1 and 2, the sum is odd; - If we choose the two balls with 1 and 4, the sum is odd; - If we choose the two balls with 2 and 4, the sum is even. Thus, the answer is 1.
{"inputs": ["1 2", "4 0", "0 5", "1 3", "0 0", "2 2", "4 6", "2 3"], "outputs": ["1\n", "6\n", "10\n", "3\n", "0\n", "2\n", "21\n", "4\n"]}
274
80
coding
Solve the programming task below in a Python markdown code block. A permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array. An inversion in a permutation $p$ is a pair of indices $(i, j)$ such that $i > j$ and $a_i < a_j$. For example, a permutation $[4, 1, 3, 2]$ contains $4$ inversions: $(2, 1)$, $(3, 1)$, $(4, 1)$, $(4, 3)$. You are given a permutation $p$ of size $n$. However, the numbers on some positions are replaced by $-1$. Let the valid permutation be such a replacement of $-1$ in this sequence back to numbers from $1$ to $n$ in such a way that the resulting sequence is a permutation of size $n$. The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation. Calculate the expected total number of inversions in the resulting valid permutation. It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the sequence. The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($-1 \le p_i \le n$, $p_i \ne 0$) — the initial sequence. It is guaranteed that all elements not equal to $-1$ are pairwise distinct. -----Output----- Print a single integer — the expected total number of inversions in the resulting valid permutation. It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$. -----Examples----- Input 3 3 -1 -1 Output 499122179 Input 2 1 2 Output 0 Input 2 -1 -1 Output 499122177 -----Note----- In the first example two resulting valid permutations are possible: $[3, 1, 2]$ — $2$ inversions; $[3, 2, 1]$ — $3$ inversions. The expected value is $\frac{2 \cdot 1 + 3 \cdot 1}{2} = 2.5$. In the second example no $-1$ are present, thus the only valid permutation is possible — the given one. It has $0$ inversions. In the third example there are two resulting valid permutations — one with $0$ inversions and one with $1$ inversion.
{"inputs": ["1\n1\n", "1\n1\n", "1\n-1\n", "1\n-1\n", "2\n1 2\n", "2\n2 1\n", "2\n1 2\n", "2\n-1 2\n"], "outputs": ["0\n", " 0", "0\n", " 0", "0\n", "1\n", " 0", "0\n"]}
688
100
coding
Solve the programming task below in a Python markdown code block. We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j). Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares. Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game. When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares. The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.
{"inputs": ["3 3\n..#\n..\n...", "3 3\n..#\n.#.\n...", "1 3\n..#\n#..\n...", "3 3\n..#\n#..\n...", "3 3\n..#\n#..\n...\n", "6 37\n.....................................\n...#...####...####..###...###...###..\n..#.#..#...#.##....#...#.#...#.#...#.\n..#.#..#...#.#.....#...#.#...#.#...#.\n.###.#.###.#.#...#.....#.##..#.#...#.\n.#####.####..#.....#...#..##....##...\n.#...#.#...#.#...#.....#.#...#.#...#.\n.#...#.#...#.##....#...#.#...#.#...#.\n.#...#.####...####..###...###...###..\n..../................................", "6 37\n.....................................\n...#...####...####..###...###...###..\n..#.#..#...#.##....#...#.#...#.#...#.\n..#.#..#...#.#.....#...#.#...#.#...#.\n.###.#.###.#.#...#./...#.##..#.#...#.\n.#####.####..#.....#...#..##....##...\n.#...#.#...#.#...#.....#.#...#.#...#.\n.#...#.#...#.##....#...#.#...#.#...#.\n.#...#.####...####..###...###...###..\n..../................................", "6 37\n.....................................\n...#...####...####..###...###...###..\n..#.#..#...#.##....#...#.#...#.#...#.\n..#.#..#...#.#../..#...#.#...#.#...#.\n.###.#.###.#.#...#./...#.##..#.#...#.\n.#####.####..#.....#...#..##....##...\n.#...#.#...#.#...#-....#.#...#.#...#.\n.#...#.#...#.##....#...#.#...#.#...#.\n.#...#.#\"##...####..###...###...###..\n..../................................"], "outputs": ["2", "2\n", "-1\n", "2", "2\n", "107\n", "106\n", "105\n"]}
331
574
coding
Solve the programming task below in a Python markdown code block. Karan's company makes software that provides different features based on the version of operating system of the user. For finding which version is more recent, Karan uses the following method: While this function worked for OS versions 10.6, 10.7, 10.8 and 10.9, the Operating system company just released OS version 10.10. Karan's function fails for the new version: ```python compare_versions ("10.9", "10.10"); # returns True, while it should return False ``` Karan now wants to spend some time to right a more robust version comparison function that works for any future version/sub-version updates. Help Karan write this function. Here are a few sample cases: ```python compare_versions("11", "10"); # returns True compare_versions("11", "11"); # returns True compare_versions("10.4.6", "10.4"); # returns True compare_versions("10.4", "11"); # returns False compare_versions("10.4", "10.10"); # returns False compare_versions("10.4.9", "10.5"); # returns False ``` ```haskell compareVersions "11" "10" `shouldBe` GT compareVersions "10.4.6" "10.4" `shouldBe` GT compareVersions "10.10" "10.9" `shouldBe` GT compareVersions xs xs `shouldBe` EQ -- xs is an arbitrary version compareVersions "10" "11" `shouldBe` LT compareVersions "10.4" "10.4.6" `shouldBe` LT compareVersions "10.99" "10.100" `shouldBe` LT ``` It can be assumed that version strings are non empty and only contain numeric literals and the character `'.'`. Also feel free to reuse/extend the following starter code: ```python def compare_versions(version1, version2): ```
{"functional": "_inputs = [['11', '10'], ['11', '11'], ['10.4.6', '10.4'], ['10.4', '10.4.8'], ['10.4', '11'], ['10.4.9', '10.5'], ['4.3.3', '4.3.3.1'], ['10.4.9', '104.9'], ['10.15', '10.12']]\n_outputs = [[True], [True], [True], [False], [False], [False], [False], [False], [True]]\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(compare_versions(*i), o[0])"}
477
288
coding
Solve the programming task below in a Python markdown code block. *This kata is based on [Project Euler Problem #349](https://projecteuler.net/problem=349). You may want to start with solving [this kata](https://www.codewars.com/kata/langtons-ant) first.* --- [Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) moves on a regular grid of squares that are coloured either black or white. The ant is always oriented in one of the cardinal directions (left, right, up or down) and moves according to the following rules: - if it is on a black square, it flips the colour of the square to white, rotates 90 degrees counterclockwise and moves forward one square. - if it is on a white square, it flips the colour of the square to black, rotates 90 degrees clockwise and moves forward one square. Starting with a grid that is **entirely white**, how many squares are black after `n` moves of the ant? **Note:** `n` will go as high as 10^(20) --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) #### *Translations are welcome!* Also feel free to reuse/extend the following starter code: ```python def langtons_ant(n): ```
{"functional": "_inputs = [[0], [1], [2], [10], [100], [1000], [10000], [100000], [1000000], [10000000]]\n_outputs = [[0], [1], [2], [6], [20], [118], [720], [11108], [114952], [1153412]]\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(langtons_ant(*i), o[0])"}
312
257
coding
Solve the programming task below in a Python markdown code block. Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi. Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change. Input The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital. Output Output a single integer representing the maximum number of the train routes which can be closed. Examples Input 5 5 3 1 2 1 2 3 2 1 3 3 3 4 4 1 5 5 3 5 4 5 5 5 Output 2 Input 2 2 3 1 2 2 2 1 3 2 1 2 2 2 3 Output 2
{"inputs": ["2 1 1\n1 2 1\n2 1000000000\n", "2 1 1\n1 2 1\n2 1100000000\n", "2 1 1\n1 2 1\n2 1100000100\n", "3 2 2\n1 2 4\n2 3 4\n2 2\n3 6\n", "3 2 2\n1 3 4\n2 3 4\n2 2\n3 2\n", "3 2 2\n1 3 4\n2 3 4\n2 2\n3 6\n", "3 2 2\n1 2 100\n2 3 1\n2 1\n3 3\n", "2 2 3\n1 2 2\n2 1 3\n2 2\n2 2\n2 3\n"], "outputs": ["1", "1\n", "1\n", "1", "0\n", "1\n", "1", "3\n"]}
456
262
coding
Solve the programming task below in a Python markdown code block. Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string. Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer a_{i} and reversed a piece of string (a segment) from position a_{i} to position |s| - a_{i} + 1. It is guaranteed that 2·a_{i} ≤ |s|. You face the following task: determine what Pasha's string will look like after m days. -----Input----- The first line of the input contains Pasha's string s of length from 2 to 2·10^5 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≤ m ≤ 10^5) —  the number of days when Pasha changed his string. The third line contains m space-separated elements a_{i} (1 ≤ a_{i}; 2·a_{i} ≤ |s|) — the position from which Pasha started transforming the string on the i-th day. -----Output----- In the first line of the output print what Pasha's string s will look like after m days. -----Examples----- Input abcdef 1 2 Output aedcbf Input vwxyz 2 2 2 Output vwxyz Input abcdef 3 1 2 3 Output fbdcea
{"inputs": ["abcdef\n1\n2\n", "abcdef\n1\n1\n", "abdcef\n1\n2\n", "abcdef\n1\n2\n", "vwxyz\n2\n2 2\n", "vwwyz\n2\n2 2\n", "vwwyz\n2\n2 1\n", "vwxyz\n2\n2 2\n"], "outputs": ["aedcbf\n", "fedcba\n", "aecdbf\n", "aedcbf\n", "vwxyz\n", "vwwyz\n", "zwwyv\n", "vwxyz\n"]}
365
131
coding
Solve the programming task below in a Python markdown code block. Chef has invited Alice for his birthday party. Now, Alice is thinking about what to give Chef as a present. She should obviously choose a sequence ― what could possibly be a better birthday gift than a sequence! After some thinking, Alice chose a sequence of integers $A_1, A_2, \ldots, A_N$. However, she does not want to simply give this sequence to Chef. Instead, she decided to give Chef a sequence $B_1, B_2, \ldots, B_N$, where $B_i = \bigvee_{j=1}^i A_j$ for each valid $i$ and $\bigvee$ denotes the bitwise OR operation. Chef can try to generate a sequence $A$ from $B$, but there could be more than one such possible sequence. Now, Alice is wondering how many sequences $A$ correspond to the given sequence $B$. Since this number could be very large, compute it modulo $10^9 + 7$. Note that it is not guaranteed that the given sequence $B$ was generated from some sequence $A$. -----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 $B_1, B_2, \ldots, B_N$. -----Output----- For each test case, print a single line containing one integer ― the number of possible sequences $A$ modulo $10^9 + 7$. -----Constraints----- - $1 \le T \le 25$ - $1 \le N \le 5 \cdot 10^4$ - $0 \le B_i < 2^{30}$ for each valid $i$ -----Example Input----- 2 2 2 3 4 2 6 7 7 -----Example Output----- 2 64 -----Explanation----- Example case 1: There are two possible options for $A$: $(2, 1)$ and $(2, 3)$.
{"inputs": ["2\n2\n2 3\n4\n2 6 7 7"], "outputs": ["2\n64"]}
472
31
coding
Solve the programming task below in a Python markdown code block. Alice has a standard deck of 52 cards. She wants to play a card game with K-1 of her friends. This particular game requires each person to have an equal number of cards, so Alice needs to discard a certain number of cards from her deck so that she can equally distribute the remaining cards amongst her and her friends. Find the minimum number of cards Alice has to discard such that she can play the game. Note: It doesn't matter which person gets which card. The only thing that matters is that each person should have an equal number of cards. ------ Input Format ------ - The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follows. - Each test case consists of a single line of input, containing a single integer K — the number of people playing the game (including Alice). ------ Output Format ------ - For each test case, output in a single line the minimum number of cards Alice has to discard from her deck such that she can play the game with her friends. ------ Constraints ------ $1 ≤ T ≤ 51$ $2 ≤ K ≤ 52$ ----- Sample Input 1 ------ 4 3 50 2 14 ----- Sample Output 1 ------ 1 2 0 10 ----- explanation 1 ------ Test Case $1$: Alice can discard any single card which will leave her with $51$ cards. She can then give her friends and herself $17$ cards each. Test Case $2$: Alice can discard any $2$ cards and then give $1$ card each to her friends and herself. Test Case $3$: Alice need not discard any card and can give $26$ cards each to her friend and herself. Test Case $4$: Alice can discard any $10$ cards and then give $3$ cards each to her friends and herself.
{"inputs": ["4\n3\n50\n2\n14\n"], "outputs": ["1\n2\n0\n10\n"]}
413
31
coding
Solve the programming task below in a Python markdown code block. ### Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. * Note:`Returning` the pattern is not the same as `Printing` the pattern. #### Parameters: pattern( n ); ^ | Term upto which Basic Pattern(this) should be created #### Rules/Note: * If `n < 1` then it should return "" i.e. empty string. * `The length of each line is same`, and is equal to the length of longest line in the pattern i.e (2n-1). * Range of Parameters (for the sake of CW Compiler) : + `n ∈ (-∞,100]` ### Examples: * pattern(5): 1 1 2 2 3 3 4 4 5 4 4 3 3 2 2 1 1 * pattern(10): 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 * pattern(15): 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 0 1 1 2 2 3 3 4 4 5 4 4 3 3 2 2 1 1 0 0 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 [List of all my katas]("http://www.codewars.com/users/curious_db97/authored") Also feel free to reuse/extend the following starter code: ```python def pattern(n): ```
{"functional": "_inputs = [[3], [15], [-3], [-25], [0]]\n_outputs = [['1 1\\n 2 2 \\n 3 \\n 2 2 \\n1 1'], ['1 1\\n 2 2 \\n 3 3 \\n 4 4 \\n 5 5 \\n 6 6 \\n 7 7 \\n 8 8 \\n 9 9 \\n 0 0 \\n 1 1 \\n 2 2 \\n 3 3 \\n 4 4 \\n 5 \\n 4 4 \\n 3 3 \\n 2 2 \\n 1 1 \\n 0 0 \\n 9 9 \\n 8 8 \\n 7 7 \\n 6 6 \\n 5 5 \\n 4 4 \\n 3 3 \\n 2 2 \\n1 1'], [''], [''], ['']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(pattern(*i), o[0])"}
634
446
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin chinese, Russian and Vietnamese as well. Chef is so good at programming that he won almost all competitions. With all the prizes, Chef bought a new house. The house looks like a grid of size N (1-indexed) which consists of N × N rooms containing diamonds. For each room, the room number is equal to the sum of the row number and the column number. The number of diamonds present in each room is equal to the absolute difference between the sum of even digits and sum of odd digits in its room number. For example, if the room number is 3216, then the number of diamonds present in that room will be |(2+6)-(3+1)| = 4. You are given the number N. You have to print the total number of diamonds present in Chef's house. ------ 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 only line of each test case contains a single integer N. ------ Output ------ For each test case, print the answer on a separate line. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ N ≤ 10^{6}$ ------ Subtasks ------ Subtask #1 (15 points): $1 ≤ T ≤ 10$ $1 ≤ N ≤ 1000$ Subtask #2 (15 points): $1 ≤ T ≤ 10$ $1 ≤ N ≤ 10^{6}$ Subtask #3 (70 points): original constraints ----- Sample Input 1 ------ 3 1 2 3 ----- Sample Output 1 ------ 2 12 36 ----- explanation 1 ------ Example case 3: There are 9 rooms. Room (1,1) has number 2, room (1,2) has number 3, etc. For each room, the number of diamonds in it is equal to the room number, so the total number of diamonds present is (2+3+4+3+4+5+4+5+6) = 36.
{"inputs": ["3\n1\n2\n3"], "outputs": ["2\n12\n36"]}
472
24
coding
Solve the programming task below in a Python markdown code block. User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. 1. At first, the score is 0. 2. For each block of contiguous "o"s with length x the score increases by x2. 3. For each block of contiguous "x"s with length y the score decreases by y2. For example, if a = 6, b = 3 and ainta have arranged the cards in the order, that is described by string "ooxoooxxo", the score of the deck equals 22 - 12 + 32 - 22 + 12 = 9. That is because the deck has 5 blocks in total: "oo", "x", "ooo", "xx", "o". User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards. Input The first line contains two space-separated integers a and b (0 ≤ a, b ≤ 105; a + b ≥ 1) — the number of "o" cards and the number of "x" cards. Output In the first line print a single integer v — the maximum score that ainta can obtain. In the second line print a + b characters describing the deck. If the k-th card of the deck contains "o", the k-th character must be "o". If the k-th card of the deck contains "x", the k-th character must be "x". The number of "o" characters must be equal to a, and the number of "x " characters must be equal to b. If there are many ways to maximize v, print any. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 2 3 Output -1 xoxox Input 4 0 Output 16 oooo Input 0 4 Output -16 xxxx
{"inputs": ["1 2\n", "1 0\n", "4 9\n", "4 7\n", "2 1\n", "4 3\n", "8 6\n", "2 2\n"], "outputs": ["-1\nxox\n", "1\no\n", "-13\nxxoxxoxxoxxox\n", "-7\nxxxoooxxoxx\n", "3\nxoo\n", "11\nxxoooox\n", "46\nxxxooooooooxxx\n", "2\nxoox\n"]}
500
125
coding
Solve the programming task below in a Python markdown code block. We will call a string that can be obtained by concatenating two equal strings an even string. For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not. You are given an even string S consisting of lowercase English letters. Find the length of the longest even string that can be obtained by deleting one or more characters from the end of S. It is guaranteed that such a non-empty string exists for a given input. -----Constraints----- - 2 \leq |S| \leq 200 - S is an even string consisting of lowercase English letters. - There exists a non-empty even string that can be obtained by deleting one or more characters from the end of S. -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print the length of the longest even string that can be obtained. -----Sample Input----- abaababaab -----Sample Output----- 6 - abaababaab itself is even, but we need to delete at least one character. - abaababaa is not even. - abaababa is not even. - abaabab is not even. - abaaba is even. Thus, we should print its length, 6.
{"inputs": ["xxxy", "xxwx", "yyxx", "xxvx", "xxyy", "yyxw", "yyyx", "yywx"], "outputs": ["2\n", "2\n", "2\n", "2\n", "2\n", "2\n", "2\n", "2\n"]}
270
72
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so "a" is considered a different type of stone from "A".   Please complete the following python code precisely: ```python class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: ```
{"functional": "def check(candidate):\n assert candidate(jewels = \"aA\", stones = \"aAAbbbb\") == 3\n assert candidate(jewels = \"z\", stones = \"ZZ\") == 0\n\n\ncheck(Solution().numJewelsInStones)"}
125
66
coding
Solve the programming task below in a Python markdown code block. Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break. The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers f_{i} and t_{i}. Value t_{i} shows the time the Rabbits need to lunch in the i-th restaurant. If time t_{i} exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal f_{i} - (t_{i} - k). Otherwise, the Rabbits get exactly f_{i} units of joy. Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value. -----Input----- The first line contains two space-separated integers — n (1 ≤ n ≤ 10^4) and k (1 ≤ k ≤ 10^9) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — f_{i} (1 ≤ f_{i} ≤ 10^9) and t_{i} (1 ≤ t_{i} ≤ 10^9) — the characteristics of the i-th restaurant. -----Output----- In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch. -----Examples----- Input 2 5 3 3 4 5 Output 4 Input 4 6 5 8 3 6 2 3 2 2 Output 3 Input 1 5 1 7 Output -1
{"inputs": ["1 5\n1 7\n", "1 2\n0 8\n", "1 7\n1 7\n", "1 5\n1 7\n", "1 5\n1 13\n", "1 4\n1 13\n", "1 4\n0 13\n", "1 2\n0 13\n"], "outputs": ["-1\n", "-6\n", "1\n", "-1\n", "-7\n", "-8\n", "-9\n", "-11\n"]}
413
124
coding
Solve the programming task below in a Python markdown code block. Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game. -----Output----- If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes). -----Examples----- Input 6 ADAAAA Output Anton Input 7 DDDAADA Output Danik Input 6 DADADA Output Friendship -----Note----- In the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton". In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik". In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".
{"inputs": ["1\nA\n", "1\nD\n", "1\nA\n", "1\nD\n", "2\nDA\n", "2\nDA\n", "2\nDA\n", "2\nAD\n"], "outputs": ["Anton\n", "Danik\n", "Anton\n", "Danik\n", "Friendship\n", "Friendship\n", "Friendship\n", "Friendship\n"]}
381
94
coding
Solve the programming task below in a Python markdown code block. For given two segments s1 and s2, print "1" if they are intersect, "0" otherwise. s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st query 2nd query ... qth query Each query consists of integer coordinates of end points of s1 and s2 in the following format: xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3 Output For each query, print "1" or "0". Example Input 3 0 0 3 0 1 1 2 -1 0 0 3 0 3 1 3 -1 0 0 3 0 3 -2 5 0 Output 1 1 0
{"inputs": ["3\n0 0 3 0 1 1 2 0\n0 0 0 0 3 1 3 -1\n0 0 6 1 1 -2 5 0", "3\n0 0 3 0 1 1 2 -1\n0 0 3 0 3 1 3 -1\n0 0 6 0 3 -2 5 0", "3\n0 0 3 0 1 1 2 -1\n0 0 0 0 3 1 3 -1\n0 0 6 0 1 -2 5 0", "3\n1 0 3 0 1 1 0 -1\n0 0 3 0 3 1 3 -1\n0 0 6 0 2 -4 5 0", "3\n-1 -1 4 0 2 1 4 1\n2 1 0 0 0 0 3 0\n0 2 6 2 1 -2 5 0", "3\n0 0 3 0 1 1 2 -1\n0 0 3 0 3 1 3 -1\n0 0 6 0 1 -2 5 0", "3\n0 0 3 0 1 1 2 -1\n0 0 2 0 3 1 3 -1\n0 0 3 0 3 -2 5 0", "3\n0 0 3 0 1 1 2 -1\n0 0 3 0 3 1 3 -1\n1 0 6 0 3 -2 5 0"], "outputs": ["1\n0\n0\n", "1\n1\n1\n", "1\n0\n1\n", "0\n1\n1\n", "0\n1\n0\n", "1\n1\n1\n", "1\n0\n0\n", "1\n1\n1\n"]}
252
479
coding
Solve the programming task below in a Python markdown code block. Chef has N empty bottles where each bottle has a capacity of X litres. There is a water tank in Chefland having K litres of water. Chef wants to fill the empty bottles using the water in the tank. Assuming that Chef does not spill any water while filling the bottles, find out the maximum number of bottles Chef can fill completely. ------ 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 N, X, and K. ------ Output Format ------ For each test case, output in a single line answer, the maximum number of bottles Chef can fill completely. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N, X ≤ 10^{5}$ $0 ≤ K ≤ 10^{5}$ ----- Sample Input 1 ------ 3 5 2 8 10 5 4 3 1 4 ----- Sample Output 1 ------ 4 0 3 ----- explanation 1 ------ Test Case $1$: The amount of water in the tank is $8$ litres. The capacity of each bottle is $2$ litres. Hence, $4$ water bottles can be filled completely. Test Case $2$: The amount of water in the tank is $4$ litres. The capacity of each bottle is $5$ litres. Hence, no water bottle can be filled completely. Test Case $3$: The amount of water in the tank is $4$ litres. The capacity of each bottle is $1$ litre. Chef has $3$ bottles available. He can fill all these bottles completely using $3$ litres of water.
{"inputs": ["3\n5 2 8\n10 5 4\n3 1 4"], "outputs": ["4\n0\n3"]}
375
35
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row. You start on square 1 of the board. In each move, starting from square curr, do the following: Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)]. This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board. If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next. The game ends when you reach the square n2. A board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 are not the starting points of any snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4. Return the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1.   Please complete the following python code precisely: ```python class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]) == 4\n assert candidate(board = [[-1,-1],[-1,3]]) == 1\n\n\ncheck(Solution().snakesAndLadders)"}
406
127
coding
Solve the programming task below in a Python markdown code block. You are given a sequence of integers $a_1, a_2, \dots, a_n$. You need to paint elements in colors, so that: If we consider any color, all elements of this color must be divisible by the minimal element of this color. The number of used colors must be minimized. For example, it's fine to paint elements $[40, 10, 60]$ in a single color, because they are all divisible by $10$. You can use any color an arbitrary amount of times (in particular, it is allowed to use a color only once). The elements painted in one color do not need to be consecutive. For example, if $a=[6, 2, 3, 4, 12]$ then two colors are required: let's paint $6$, $3$ and $12$ in the first color ($6$, $3$ and $12$ are divisible by $3$) and paint $2$ and $4$ in the second color ($2$ and $4$ are divisible by $2$). For example, if $a=[10, 7, 15]$ then $3$ colors are required (we can simply paint each element in an unique color). -----Input----- The first line contains an integer $n$ ($1 \le n \le 100$), where $n$ is the length of the given sequence. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$). These numbers can contain duplicates. -----Output----- Print the minimal number of colors to paint all the given numbers in a valid way. -----Examples----- Input 6 10 2 3 5 4 2 Output 3 Input 4 100 100 100 100 Output 1 Input 8 7 6 5 4 3 2 2 3 Output 4 -----Note----- In the first example, one possible way to paint the elements in $3$ colors is: paint in the first color the elements: $a_1=10$ and $a_4=5$, paint in the second color the element $a_3=3$, paint in the third color the elements: $a_2=2$, $a_5=4$ and $a_6=2$. In the second example, you can use one color to paint all the elements. In the third example, one possible way to paint the elements in $4$ colors is: paint in the first color the elements: $a_4=4$, $a_6=2$ and $a_7=2$, paint in the second color the elements: $a_2=6$, $a_5=3$ and $a_8=3$, paint in the third color the element $a_3=5$, paint in the fourth color the element $a_1=7$.
{"inputs": ["1\n1\n", "1\n1\n", "1\n2\n", "1\n100\n", "2\n1 1\n", "2\n1 2\n", "1\n100\n", "2\n1 1\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
674
96
coding
Solve the programming task below in a Python markdown code block. A Hackerrank number is a magic number that can be used to get sudo permissions on the site. We are going to generate a hackerrank number from two integers A & B. Each number has two parts to it - the left (L) & the right side (R). For eg: for the number 100101, L could be 100 & R could be 101 (or) L could be 1 and R could be 00101 and so on.. How to generate a hackerrank number? Let x & y be integers such that, (1 <= x <= A & 1 <= y <= B) Generate the left part of any hackerrank number (L) by multiplying x and y (i.e) x*y and the right part of any hackerrank number (R) by bitwise xor-ing x and y (i.e) x^y Add leading zeros to R to make length(R) = length(B) + 1. Concatenate both L & R to form the hackerrank number. Can you find the sum of all possible hackerrank numbers generated by this rule? Input format Each input contains 2 integers A and B separated by a space. Constraints 1 <= A <= 30 1 <= B <= 10^{8} Output format Print the sum of all possible numbers that satisfy the above mentioned property. Sample Input 2 4 Sample Output 14502 The left value can be one of {1 * 1, 1 * 2, 1 * 3, 1 * 4, 2 * 1, 2 * 2, 2 * 3, 2 * 4} which is {1,2,3,4,2,4,6,8} and the distinct values are {1, 2, 3, 4, 6, 8} The right value can be one of {1^1,1^2,1^3,1^4,2^1,2^2,2^3,2^4} which is {0, 3, 2, 5, 3, 0, 1, 6} and the distinct values are {0, 1, 2, 3, 5, 6} All the possible value are { 100, 101, 102, 103, 105, 106, 200, 201, 202, 203, 205, 206, 300, 301, 302, 303, 305, 306, 400, 401, 402, 403, 405, 406, 600, 601, 602, 603, 605, 606, 800, 801, 802, 803, 805, 806 } S = all the sum of the above = 14502. Note: Any number can only be added once.
{"inputs": ["2 4\n"], "outputs": ["14502\n"]}
745
20
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a string s of lowercase English letters and an integer array shifts of the same length. Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times. Return the final string after all such shifts to s are applied.   Please complete the following python code precisely: ```python class Solution: def shiftingLetters(self, s: str, shifts: List[int]) -> str: ```
{"functional": "def check(candidate):\n assert candidate(s = \"abc\", shifts = [3,5,9]) == \"rpl\"\n\n\ncheck(Solution().shiftingLetters)"}
168
43
coding
Solve the programming task below in a Python markdown code block. Chef 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. Chef has a positive integer N. He can apply any of the following operations as many times as he want in any order: - Add 1 to the number N. - Take some digit of N and replace it by any non-zero digit. - Add any non-zero leading digit to N. Find the minimum number of operations that is needed for changing N to the lucky number. -----Input----- The first line contains a single positive integer T, the number of test cases. T test cases follow. The only line of each test case contains a positive integer N without leading zeros. -----Output----- For each T test cases print one integer, the minimum number of operations that is needed for changing N to the lucky number. -----Constraints----- 1 ≤ T ≤ 10 1 ≤ N < 10100000 -----Example----- Input: 3 25 46 99 Output: 2 1 2
{"inputs": ["3\n4\n5\n0", "3\n0\n7\n61", "3\n0\n8\n24", "3\n0\n12\n5", "3\n3\n4\n70", "3\n32\n5\n7", "3\n1\n7\n44", "3\n1\n5\n44"], "outputs": ["0\n1\n1\n", "1\n0\n2\n", "1\n1\n1\n", "1\n2\n1\n", "1\n0\n1\n", "2\n1\n0\n", "1\n0\n0\n", "1\n1\n0\n"]}
268
149
coding
Solve the programming task below in a Python markdown code block. You are given a tree with N nodes and each has a value associated with it. You are given Q queries, each of which is either an update or a retrieval operation. Initially all node values are zero. The update query is of the format a1 d1 a2 d2 A B This means you'd have to add $(a1+z*d1)*(a2+z*d2)*R^z$ in all nodes in the path from A to B where $z$ is the distance between the node and A. The retrieval query is of the format i j You need to return the sum of the node values lying in the path from node i to node j modulo 1000000007. Note: First all update queries are given and then all retrieval queries. Distance between 2 nodes is the shortest path length between them taking each edge weight as 1. Input Format The first line contains two integers (N and R respectively) separated by a space. In the next N-1 lines, the i^{th} line describes the i^{th} edge: a line with two integers x y separated by a single space denotes an edge between nodes x and y. The next line contains 2 space separated integers (U and Q respectively) representing the number of Update and Query operations to follow. U lines follow. Each of the next U lines contains 6 space separated integers (a1,d1,a2,d2,A and B respectively). Each of the next Q lines contains 2 space separated integers, i and j respectively. Output Format It contains exactly Q lines and each line containing the answer of the i^{th} query. Constraints 2 <= N <= $10^{5} $ 2 <= R <= $10^{9} $ 1 <= U <= $10^{5} $ 1 <= Q <= $10^{5} $ 1 <= a1,a2,d1,d2 <= $10^{8} $ 1 <= x, y, i, j, A, B <= N Note For the update operation, x can be equal to y and for the query operation, i can be equal to j. Sample Input 7 2 1 2 1 3 2 4 2 6 4 5 6 7 1 4 1 1 1 1 4 6 4 5 2 7 4 7 5 3 Sample Output 1 44 45 9 Explanation The node values after updation becomes : 0 8 0 1 0 36 0 Answer to Query #1: 1+0 = 1 Answer to Query #2: 8+36+0 = 44 Answer to Query #3: 1+8+36+0 = 45 Answer to Query #4: 0+1+8+0+0 = 9
{"inputs": ["7 2\n1 2\n1 3\n2 4\n2 6\n4 5\n6 7\n1 4\n1 1 1 1 4 6\n4 5\n2 7\n4 7\n5 3\n"], "outputs": ["1\n44\n45\n9\n"]}
649
80
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Design an algorithm to figure out if someone has won a game of tic-tac-toe. Input is a string array of size N x N, including characters " ", "X" and "O", where " " represents a empty grid. The rules of tic-tac-toe are as follows: Players place characters into an empty grid(" ") in turn. The first player always place character "O", and the second one place "X". Players are only allowed to place characters in empty grid. Replacing a character is not allowed. If there is any row, column or diagonal filled with N same characters, the game ends. The player who place the last charater wins. When there is no empty grid, the game ends. If the game ends, players cannot place any character further. If there is any winner, return the character that the winner used. If there's a draw, return "Draw". If the game doesn't end and there is no winner, return "Pending". Please complete the following python code precisely: ```python class Solution: def tictactoe(self, board: List[str]) -> str: ```
{"functional": "def check(candidate):\n assert candidate(board = [\"O X\",\" XO\",\"X O\"]) == \"X\"\n assert candidate(board = [\"OOX\",\"XXO\",\"OXO\"]) == \"Draw\"\n assert candidate(board = [\"OOX\",\"XXO\",\"OX \"]) == \"Pending\"\n\n\ncheck(Solution().tictactoe)"}
253
85
coding
Solve the programming task below in a Python markdown code block. Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a_1, a_2, ..., a_{n}. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise a_{i} times. Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the n-th exercise. Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training. -----Input----- The first line contains integer n (1 ≤ n ≤ 20). The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 25) — the number of times Greg repeats the exercises. -----Output----- Print word "chest" (without the quotes), if the chest gets the most exercise, "biceps" (without the quotes), if the biceps gets the most exercise and print "back" (without the quotes) if the back gets the most exercise. It is guaranteed that the input is such that the answer to the problem is unambiguous. -----Examples----- Input 2 2 8 Output biceps Input 3 5 1 10 Output back Input 7 3 3 2 7 9 6 8 Output chest -----Note----- In the first sample Greg does 2 chest, 8 biceps and zero back exercises, so the biceps gets the most exercises. In the second sample Greg does 5 chest, 1 biceps and 10 back exercises, so the back gets the most exercises. In the third sample Greg does 18 chest, 12 biceps and 8 back exercises, so the chest gets the most exercise.
{"inputs": ["1\n10\n", "1\n19\n", "1\n19\n", "1\n10\n", "1\n19\n", "1\n35\n", "1\n14\n", "1\n70\n"], "outputs": ["chest\n", "chest\n", "chest\n", "chest\n", "chest\n", "chest\n", "chest\n", "chest\n"]}
488
94
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.   Please complete the following python code precisely: ```python class Solution: def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4) == 6\n\n\ncheck(Solution().minHeightShelves)"}
279
66
coding
Solve the programming task below in a Python markdown code block. Find the 2nd largest integer in array If the array has no 2nd largest integer then return nil. Reject all non integers elements and then find the 2nd largest integer in array find_2nd_largest([1,2,3]) => 2 find_2nd_largest([1,1,1,1,1]) => nil because all elements are same. Largest no. is 1. and there is no 2nd largest no. find_2nd_largest([1,'a','2',3,3,4,5,'b']) => 4 as after rejecting non integers array will be [1,3,3,4,5] Largest no. is 5. and 2nd largest is 4. Return nil if there is no 2nd largest integer. Take care of big numbers as well Also feel free to reuse/extend the following starter code: ```python def find_2nd_largest(arr): ```
{"functional": "_inputs = [[[1, 2, 3]], [[1, 1, 1, 1, 1, 1, 1]], [[1, 'a', '2', 3, 3, 4, 5, 'b']], [[1, 'a', '2', 3, 3, 3333333333333333333334, 544444444444444444444444444444, 'b']]]\n_outputs = [[2], [None], [4], [3333333333333333333334]]\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_2nd_largest(*i), o[0])"}
222
314
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively. You are also given two 0-indexed integer arrays energy and experience, both of length n. You will face n opponents in order. The energy and experience of the ith opponent is denoted by energy[i] and experience[i] respectively. When you face an opponent, you need to have both strictly greater experience and energy to defeat them and move to the next opponent if available. Defeating the ith opponent increases your experience by experience[i], but decreases your energy by energy[i]. Before starting the competition, you can train for some number of hours. After each hour of training, you can either choose to increase your initial experience by one, or increase your initial energy by one. Return the minimum number of training hours required to defeat all n opponents.   Please complete the following python code precisely: ```python class Solution: def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(initialEnergy = 5, initialExperience = 3, energy = [1,4,3,2], experience = [2,6,3,1]) == 8\n assert candidate(initialEnergy = 2, initialExperience = 4, energy = [1], experience = [3]) == 0\n\n\ncheck(Solution().minNumberOfHours)"}
242
90
coding
Solve the programming task below in a Python markdown code block. Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be? See notes for definition of a tandem repeat. -----Input----- The first line contains s (1 ≤ |s| ≤ 200). This string contains only small English letters. The second line contains number k (1 ≤ k ≤ 200) — the number of the added characters. -----Output----- Print a single number — the maximum length of the tandem repeat that could have occurred in the new string. -----Examples----- Input aaba 2 Output 6 Input aaabbbb 2 Output 6 Input abracadabra 10 Output 20 -----Note----- A tandem repeat of length 2n is string s, where for any position i (1 ≤ i ≤ n) the following condition fulfills: s_{i} = s_{i} + n. In the first sample Kolya could obtain a string aabaab, in the second — aaabbbbbb, in the third — abracadabrabracadabra.
{"inputs": ["aaba\n2\n", "ayi\n10\n", "ayi\n10\n", "ayi\n11\n", "yai\n20\n", "abaa\n2\n", "yai\n11\n", "aaab\n2\n"], "outputs": ["6\n", "12\n", "12\n", "14\n", "22\n", "6\n", "14\n", "4\n"]}
280
104
coding
Solve the programming task below in a Python markdown code block. Luba needs your help again! Luba has n TV sets. She knows that i-th TV set will be working from moment of time li till moment ri, inclusive. Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of integer moments of time when at least one of TV sets is working won't decrease. Luba will be very upset if she has to switch off a non-redundant TV set. Help Luba by telling her the index of some redundant TV set. If there is no any, print -1. Input The first line contains one integer number n (1 ≤ n ≤ 2·105) — the number of TV sets. Then n lines follow, each of them containing two integer numbers li, ri (0 ≤ li ≤ ri ≤ 109) denoting the working time of i-th TV set. Output If there is no any redundant TV set, print -1. Otherwise print the index of any redundant TV set (TV sets are indexed from 1 to n). If there are multiple answers, print any of them. Examples Input 3 1 3 4 6 1 7 Output 1 Input 2 0 10 0 10 Output 1 Input 3 1 2 3 4 6 8 Output -1 Input 3 1 2 2 3 3 4 Output 2 Note Consider the first sample. Initially all integer moments of time such that at least one TV set is working are from the segment [1;7]. It's easy to see that this segment won't change if we switch off the first TV set (or the second one). Note that in the fourth sample you can switch off the second TV set, since even without it all integer moments such that any of the TV sets is working denote the segment [1;4].
{"inputs": ["1\n0 0\n", "1\n8 9\n", "1\n8 17\n", "1\n16 17\n", "2\n1 2\n1 3\n", "2\n1 3\n1 6\n", "2\n1 3\n2 4\n", "2\n2 2\n1 3\n"], "outputs": ["-1\n", "-1\n", "-1\n", "-1\n", "1\n", "1\n", "-1\n", "1\n"]}
431
122
coding
Solve the programming task below in a Python markdown code block. You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest. Example $candles=[4,4,1,3]$ The maximum height candles are $4$ units high. There are $2$ of them, so return $2$. Function Description Complete the function birthdayCakeCandles in the editor below. birthdayCakeCandles has the following parameter(s): int candles[n]: the candle heights Returns int: the number of candles that are tallest Input Format The first line contains a single integer, $n$, the size of $\textit{candles[]}$. The second line contains $n$ space-separated integers, where each integer $\boldsymbol{i}$ describes the height of $\textit{candles}[i]$. Constraints $1\leq n\leq10^5$ $1\leq\textit{candles}[i]\leq10^7$ Sample Input 0 4 3 2 1 3 Sample Output 0 2 Explanation 0 Candle heights are $[3,2,1,3]$. The tallest candles are $3$ units, and there are $2$ of them.
{"inputs": ["4\n3 2 1 3\n"], "outputs": ["2\n"]}
310
22
coding
Solve the programming task below in a Python markdown code block. You are given a string S consisting of 0 and 1. Find the maximum integer K not greater than |S| such that we can turn all the characters of S into 0 by repeating the following operation some number of times. - Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfied). For each integer i such that l\leq i\leq r, do the following: if S_i is 0, replace it with 1; if S_i is 1, replace it with 0. -----Constraints----- - 1\leq |S|\leq 10^5 - S_i(1\leq i\leq N) is either 0 or 1. -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print the maximum integer K such that we can turn all the characters of S into 0 by repeating the operation some number of times. -----Sample Input----- 010 -----Sample Output----- 2 We can turn all the characters of S into 0 by the following operations: - Perform the operation on the segment S[1,3] with length 3. S is now 101. - Perform the operation on the segment S[1,2] with length 2. S is now 011. - Perform the operation on the segment S[2,3] with length 2. S is now 000.
{"inputs": ["011", "111", "101", "001", "000", "110", "100", "010"], "outputs": ["2\n", "3\n", "2\n", "2\n", "3\n", "2\n", "2\n", "2"]}
336
77
coding
Solve the programming task below in a Python markdown code block. Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with three hands — hour, minute, and second. Time froze, and clocks now show the time h hours, m minutes, s seconds. Last time Misha talked with the coordinator at t_1 o'clock, so now he stands on the number t_1 on the clock face. The contest should be ready by t_2 o'clock. In the terms of paradox it means that Misha has to go to number t_2 somehow. Note that he doesn't have to move forward only: in these circumstances time has no direction. Clock hands are very long, and Misha cannot get round them. He also cannot step over as it leads to the collapse of space-time. That is, if hour clock points 12 and Misha stands at 11 then he cannot move to 1 along the top arc. He has to follow all the way round the clock center (of course, if there are no other hands on his way). Given the hands' positions, t_1, and t_2, find if Misha can prepare the contest on time (or should we say on space?). That is, find if he can move from t_1 to t_2 by the clock face. -----Input----- Five integers h, m, s, t_1, t_2 (1 ≤ h ≤ 12, 0 ≤ m, s ≤ 59, 1 ≤ t_1, t_2 ≤ 12, t_1 ≠ t_2). Misha's position and the target time do not coincide with the position of any hand. -----Output----- Print "YES" (quotes for clarity), if Misha can prepare the contest on time, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES"). -----Examples----- Input 12 30 45 3 11 Output NO Input 12 0 1 12 1 Output YES Input 3 47 0 4 9 Output YES -----Note----- The three examples are shown on the pictures below from left to right. The starting position of Misha is shown with green, the ending position is shown with pink. Note that the positions of the hands on the pictures are not exact, but are close to the exact and the answer is the same. $\oplus 0 \theta$
{"inputs": ["1 5 4 3 2\n", "6 0 0 2 8\n", "5 8 2 1 3\n", "2 0 0 1 3\n", "1 5 6 2 1\n", "5 0 0 6 7\n", "6 0 1 6 7\n", "3 5 1 1 2\n"], "outputs": ["YES\n", "NO\n", "NO\n", "NO\n", "YES\n", "YES\n", "NO\n", "NO\n"]}
591
134
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation. If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.   Please complete the following python code precisely: ```python class Solution: def solveEquation(self, equation: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(equation = \"x+5-3+x=6+x-2\") == \"x=2\"\n assert candidate(equation = \"x=x\") == \"Infinite solutions\"\n assert candidate(equation = \"2x=x\") == \"x=0\"\n\n\ncheck(Solution().solveEquation)"}
144
84
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd". Return the resulting string.   Please complete the following python code precisely: ```python class Solution: def reversePrefix(self, word: str, ch: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(word = \"abcdefd\", ch = \"d\") == \"dcbaefd\"\n assert candidate(word = \"xyxzxe\", ch = \"z\") == \"zxyxxe\"\n assert candidate(word = \"abcd\", ch = \"z\") == \"abcd\"\n\n\ncheck(Solution().reversePrefix)"}
152
81
coding
Solve the programming task below in a Python markdown code block. Xenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue. The distance between two tree nodes v and u is the number of edges in the shortest path between v and u. Xenia needs to learn how to quickly execute queries of two types: 1. paint a specified blue node in red; 2. calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — an edge of the tree. Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≤ ti ≤ 2, 1 ≤ vi ≤ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi. It is guaranteed that the given graph is a tree and that all queries are correct. Output For each second type query print the reply in a single line. Examples Input 5 4 1 2 2 3 2 4 4 5 2 1 2 5 1 2 2 5 Output 0 3 2
{"inputs": ["5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n2 5\n1 2\n2 1\n", "5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n2 1\n1 2\n2 1\n", "5 4\n1 2\n2 3\n2 4\n1 5\n2 1\n2 5\n1 2\n2 5\n", "5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n1 5\n1 2\n2 1\n", "5 4\n1 2\n2 3\n2 4\n1 5\n2 2\n2 5\n1 2\n2 5\n", "5 4\n1 2\n2 3\n1 4\n4 5\n2 1\n2 5\n1 2\n2 1\n", "5 4\n1 2\n2 3\n2 4\n1 5\n1 2\n2 5\n1 2\n2 5\n", "5 4\n1 2\n2 3\n2 4\n4 5\n2 1\n2 3\n1 2\n2 5\n"], "outputs": ["0\n3\n0\n", "0\n0\n0\n", "0\n1\n1\n", "0\n0\n", "1\n1\n1\n", "0\n2\n0\n", "1\n1\n", "0\n2\n2\n"]}
402
370
coding
Solve the programming task below in a Python markdown code block. Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rectangles. -----Input----- The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. Each test case is given in two lines. The first line contains two integers $a_1$ and $b_1$ ($1 \le a_1, b_1 \le 100$) — the dimensions of the first one obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). The second line contains two integers $a_2$ and $b_2$ ($1 \le a_2, b_2 \le 100$) — the dimensions of the second obtained after cutting rectangle. The sizes are given in random order (that is, it is not known which of the numbers is the width, and which of the numbers is the length). -----Output----- Print $t$ answers, each of which is a string "YES" (in the case of a positive answer) or "NO" (in the case of a negative answer). The letters in words can be printed in any case (upper or lower). -----Example----- Input 3 2 3 3 1 3 2 1 3 3 3 1 3 Output Yes Yes No
{"inputs": ["1\n5 2\n3 14\n", "1\n5 1\n3 14\n", "1\n5 12\n5 0\n", "1\n5 1\n5 14\n", "1\n5 12\n5 1\n", "1\n5 9\n41 14\n", "1\n8 9\n41 14\n", "1\n5 3\n41 14\n"], "outputs": ["No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]}
388
145
coding
Solve the programming task below in a Python markdown code block. You are given a positive integer $n$. You have to find $4$ positive integers $a, b, c, d$ such that $a + b + c + d = n$, and $\gcd(a, b) = \operatorname{lcm}(c, d)$. If there are several possible answers you can output any of them. It is possible to show that the answer always exists. In this problem $\gcd(a, b)$ denotes the greatest common divisor of $a$ and $b$, and $\operatorname{lcm}(c, d)$ denotes the least common multiple of $c$ and $d$. -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with integer $n$ ($4 \le n \le 10^9$) — the sum of $a$, $b$, $c$, and $d$. -----Output----- For each test case output $4$ positive integers $a$, $b$, $c$, $d$ such that $a + b + c + d = n$ and $\gcd(a, b) = \operatorname{lcm}(c, d)$. -----Examples----- Input 5 4 7 8 9 10 Output 1 1 1 1 2 2 2 1 2 2 2 2 2 4 2 1 3 5 1 1 -----Note----- In the first test case $\gcd(1, 1) = \operatorname{lcm}(1, 1) = 1$, $1 + 1 + 1 + 1 = 4$. In the second test case $\gcd(2, 2) = \operatorname{lcm}(2, 1) = 2$, $2 + 2 + 2 + 1 = 7$. In the third test case $\gcd(2, 2) = \operatorname{lcm}(2, 2) = 2$, $2 + 2 + 2 + 2 = 8$. In the fourth test case $\gcd(2, 4) = \operatorname{lcm}(2, 1) = 2$, $2 + 4 + 2 + 1 = 9$. In the fifth test case $\gcd(3, 5) = \operatorname{lcm}(1, 1) = 1$, $3 + 5 + 1 + 1 = 10$.
{"inputs": ["5\n4\n7\n8\n9\n10\n"], "outputs": ["1 1 1 1\n4 1 1 1\n5 1 1 1\n6 1 1 1\n7 1 1 1\n"]}
582
63
coding
Solve the programming task below in a Python markdown code block. You are given a permutation $p_1, p_2, \dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once. Find three indices $i$, $j$ and $k$ such that: $1 \le i < j < k \le n$; $p_i < p_j$ and $p_j > p_k$. Or say that there are no such indices. -----Input----- The first line contains a single integer $T$ ($1 \le T \le 200$) — the number of test cases. Next $2T$ lines contain test cases — two lines per test case. The first line of each test case contains the single integer $n$ ($3 \le n \le 1000$) — the length of the permutation $p$. The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$; $p_i \neq p_j$ if $i \neq j$) — the permutation $p$. -----Output----- For each test case: if there are such indices $i$, $j$ and $k$, print YES (case insensitive) and the indices themselves; if there are no such indices, print NO (case insensitive). If there are multiple valid triples of indices, print any of them. -----Example----- Input 3 4 2 1 4 3 6 4 6 1 2 5 3 5 5 3 1 2 4 Output YES 2 3 4 YES 3 5 6 NO
{"inputs": ["3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n5 3 1 2 4\n", "3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n5 3 1 2 4\n", "3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n5 2 1 2 4\n", "3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n8 3 1 2 4\n", "3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n6 3 1 2 4\n", "3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n5 3 1 2 5\n", "3\n4\n2 1 4 3\n6\n4 8 1 2 5 3\n5\n5 3 1 2 4\n", "3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n4 2 1 2 4\n"], "outputs": ["YES\n2 3 4\nYES\n1 2 3\nNO\n", "YES\n2 3 4\nYES\n1 2 3\nNO\n", "YES\n2 3 4\nYES\n1 2 3\nNO\n", "YES\n2 3 4\nYES\n1 2 3\nNO\n", "YES\n2 3 4\nYES\n1 2 3\nNO\n", "YES\n2 3 4\nYES\n1 2 3\nNO\n", "YES\n2 3 4\nYES\n1 2 3\nNO\n", "YES\n2 3 4\nYES\n1 2 3\nNO\n"]}
394
486
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type.   Please complete the following python code precisely: ```python class Solution: def isValid(self, s: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(s = \"()\") == True\n assert candidate(s = \"()[]{}\") == True\n assert candidate(s = \"(]\") == False\n\n\ncheck(Solution().isValid)"}
116
54
coding
Solve the programming task below in a Python markdown code block. Consider an array A consisting of N positive elements. The *frequency array* of A is the array B of size N such that B_{i} = *frequency* of element A_{i} in A. For example, if A = [4, 7, 4, 11, 2, 7, 7], the *frequency array* B = [2, 3, 2, 1, 1, 3, 3]. You have lost the array A, but fortunately you have the array B. Your task is to construct the lexicographically smallest array A such that: 1≤ A_{i} ≤ 10^{5}; The frequency array of A is equal to B. If no such array A exists, print -1. Note: Array X is lexicographically smaller than array 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 two lines of input. - The first line of each test case contains a single integer N — the size of the array. - The next line contains N space-separated integers - B_{1}, B_{2}, \ldots, B_{N}, the frequency array. ------ Output Format ------ For each test case, output on a new line, N space separated integers - A_{1}, A_{2}, \ldots, A_{N}, the lexicographically smallest array A. If no such array A exists, print -1. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ N ≤ 10^{5}$ $1 ≤ B_{i} ≤ 10^{5}$ - The sum of $N$ over all test cases won't exceed $10^{6}$. ----- Sample Input 1 ------ 5 5 2 3 3 3 2 5 1 1 1 1 1 5 5 5 5 5 5 3 1 2 4 8 1 3 2 3 2 2 2 3 ----- Sample Output 1 ------ 1 2 2 2 1 1 2 3 4 5 1 1 1 1 1 -1 1 2 3 2 3 4 4 2 ----- explanation 1 ------ Test case $1$: The lexicographically smallest array $A$ having the given frequency array $B$ is $A = [1, 2, 2, 2, 1]$. The element $A_{1}$ and $A_{5}$ have frequency $2$ while $A_{2}, A_{3},$ and $A_{4}$ have frequency $3$. Test case $2$: The lexicographically smallest array $A$ having the given frequency array $B$ is $A = [1, 2, 3, 4, 5]$. Each element in $A$ has frequency $1$. Test case $3$: The lexicographically smallest array $A$ having the given frequency array $B$ is $A = [1, 1, 1, 1, 1]$. Each element in $A$ has frequency $5$. Test case $4$: No possible array $A$ exists having the given frequency array.
{"inputs": ["5\n5\n2 3 3 3 2\n5\n1 1 1 1 1\n5\n5 5 5 5 5\n3\n1 2 4\n8\n1 3 2 3 2 2 2 3"], "outputs": ["1 2 2 2 1\n1 2 3 4 5\n1 1 1 1 1\n-1\n1 2 3 2 3 4 4 2\n"]}
761
122
coding
Solve the programming task below in a Python markdown code block. DZY loves chessboard, and he enjoys playing with it. He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge. You task is to find any suitable placement of chessmen on the given chessboard. -----Input----- The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad. -----Output----- Output must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell. If multiple answers exist, print any of them. It is guaranteed that at least one answer exists. -----Examples----- Input 1 1 . Output B Input 2 2 .. .. Output BW WB Input 3 3 .-. --- --. Output B-B --- --B -----Note----- In the first sample, DZY puts a single black chessman. Of course putting a white one is also OK. In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output. In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are.
{"inputs": ["1 1\n.\n", "1 1\n-\n", "1 1\n-\n", "1 1\n.\n", "2 2\n..\n..\n", "3 1\n-\n.\n.\n", "3 1\n-\n.\n.\n", "2 2\n..\n-.\n"], "outputs": ["B\n", "-\n", "-\n", "B\n", "BW\nWB\n", "-\nW\nB\n", "-\nW\nB\n", "BW\n-B\n"]}
434
127
coding
Solve the programming task below in a Python markdown code block. A Sumo wrestling championship is scheduled to be held this winter in the HackerCity where N wrestlers from different parts of the world are going to participate. The rules state that two wrestlers can fight against each other if and only if the difference in their height is less than or equal to K, (i.e) wrestler A and wrestler B can fight if and only if |height(A)-height(B)|<=K. Given an array H[], where H[i] represents the height of the i^{th} fighter, for a given l, r where 0 <= l <= r < N, can you count the number of pairs of fighters between l and r (both inclusive) who qualify to play a game? Input Format The first line contains an integer N and K separated by a single space representing the number of Sumo wrestlers who are going to participate and the height difference K. The second line contains N integers separated by a single space, representing their heights H[0] H[1] ... H[N - 1]. The third line contains Q, the number of queries. This is followed by Q lines each having two integers l and r separated by a space. Output Format For each query Q, output the corresponding value of the number of pairs of fighters for whom the absolute difference of height is not greater that K. Constraints 1 <= N <= 100000 0 <= K <= $10^{9} $ 0 <= H[i] <= $10^{9} $ 1 <= Q <= 100000 0 <= l <= r < N Sample Input 5 2 1 3 4 3 0 3 0 1 1 3 0 4 Sample Output 1 3 6 Explanation Query #0: Between 0 and 1 we have i,j as (0,1) and |H[0]-H[1]|=2 therefore output is 1. Query #1: The pairs (H[1],H[2]) (H[1],H[3]) and (H[2],H[3]) are the pairs such that |H[i]-H[j]| <=2. Hence output is 3. Query #2: Apart from those in Query #1, we have (H[0],H[1]), (H[0], H[3]), (H[0], H[4]), hence 6. Timelimits Timelimits are given here
{"inputs": ["5 2\n1 3 4 3 0\n3\n0 1\n1 3\n0 4\n"], "outputs": ["1\n3\n6\n"]}
539
44
coding
Solve the programming task below in a Python markdown code block. The goal of this Kata is to reduce the passed integer to a single digit (if not already) by converting the number to binary, taking the sum of the binary digits, and if that sum is not a single digit then repeat the process. - n will be an integer such that 0 < n < 10^20 - If the passed integer is already a single digit there is no need to reduce For example given 5665 the function should return 5: ``` 5665 --> (binary) 1011000100001 1011000100001 --> (sum of binary digits) 5 ``` Given 123456789 the function should return 1: ``` 123456789 --> (binary) 111010110111100110100010101 111010110111100110100010101 --> (sum of binary digits) 16 16 --> (binary) 10000 10000 --> (sum of binary digits) 1 ``` Also feel free to reuse/extend the following starter code: ```python def single_digit(n): ```
{"functional": "_inputs = [[5], [999], [1234444123], [443566], [565656565], [9889345778311094737448], [4868872], [234234235], [567448], [10000000000]]\n_outputs = [[5], [8], [1], [2], [3], [2], [8], [2], [7], [3]]\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(single_digit(*i), o[0])"}
315
282
coding
Solve the programming task below in a Python markdown code block. One of the games that uses the Hyakunin Isshu tag is "Buddhist turning". It is a simple game that uses only picture cards, so it is widely enjoyed. There are various derivative types of rules, but the shaved turn considered here is performed by N participants according to the following rules. * Use a total of 100 cards, including 64 "men", 15 "boys", and 21 "princesses". * Turn the bill over so that you can't see the picture and mix well to make a "bill pile". * Draw one card from the first participant in order. After the Nth person, repeat from the first person. * If the drawn card is a man, the person who draws will get the card. * If the drawn card is a shaven, the person who draws puts all the cards he has, including that card, into the "field". * If the drawn card is a princess, the person who draws gets all the cards in play, including that card. * When there are no more cards in the bill pile, the game ends, and the person with the most cards wins. Given the number of participants and the order of the cards piled up in the bill pile, the number of cards each participant has at the end of the game is arranged in ascending order, and the number of cards remaining in the field is shown. Create a program to output. input The input consists of multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: N c1c2 ... c100 Each dataset has two rows, and the first row is given the integer N (2 ≤ N ≤ 10) representing the number of participants. The next line is given a character string that represents the arrangement of the bills piled up in the bill pile. The letter ci represents the i-th drawn tag, where M is a man, S is a shaven, and L is a princess. There is no space between each character. The number of datasets does not exceed 100. output For each data set, the sequence of the number of cards at the end of the game is output on one line. As the number of cards, the number of cards that each participant has is arranged in ascending order, and then the number of cards remaining in the field is output. Separate each number of bills with one blank. Do not print blanks at the end of the line. Example Input 2 SSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM 2 SSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMSL 5 MMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSMLMSMMMMMMMSMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM 0 Output 42 58 0 0 100 0 0 0 3 10 59 28
{"inputs": ["2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n2\nSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMSL\n5\nMMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSSLMSMMMMMMMMMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM\n0", "2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n2\nSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLMMMMMMSL\n5\nMMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSMLMSMMMMMMMSMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM\n0", "2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n2\nSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMSL\n1\nMMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSSLMSMMMMMMMMMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM\n0", "2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n2\nLSMMMMMMLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLSSSSSSSSSSSSSS\n5\nMMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSMLMSMMMMMMMSMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM\n0", "2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n2\nLSMMMMMMLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLLLLLLLLLLLLLLLLLLLLSSSSSSSSSSSSSS\n0\nMMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSMLMSMMMMMMMSMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM\n0", "2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n2\nSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLMMMMMMSL\n0\nMMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSMLMSMMMMMMMSMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM\n0", "2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n4\nSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMSL\n5\nMMMMMMSLSLLMMMSMMSLMMMLMMMMLSLLLLMLSMMLMMLLMSSSLMMMMLMLSSLMSMMMMMMMMMMMMMMLMMMMMSMMMLMMLMMMMMMMMMSSM\n0", "2\nSSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n2\nSSSSSSSSSSSSSSLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMLMMMMMMSL\n5\nMSSMMMMMMMMMLMMLMMMSMMMMMLMMMMMMSMMMMMMMSMLMSLMLMMMMLSSSMLLMMLMMSLMLLLLSLMMMMLMMMLSMMSMMMLLSLSMMMMMM\n0"], "outputs": ["42 58 0\n0 100 0\n0 0 3 8 16 73\n", "42 58 0\n0 100 0\n0 0 3 10 59 28\n", "42 58 0\n0 100 0\n1 99\n", "42 58 0\n0 0 100\n0 0 3 10 59 28\n", "42 58 0\n0 0 100\n", "42 58 0\n0 100 0\n", "42 58 0\n0 21 21 58 0\n0 0 3 8 16 73\n", "42 58 0\n0 100 0\n1 1 2 7 81 8\n"]}
682
1,171
coding
Solve the programming task below in a Python markdown code block. Write a simple parser that will parse and run Deadfish. Deadfish has 4 commands, each 1 character long: * `i` increments the value (initially `0`) * `d` decrements the value * `s` squares the value * `o` outputs the value into the return array Invalid characters should be ignored. ```python parse("iiisdoso") ==> [8, 64] ``` Also feel free to reuse/extend the following starter code: ```python def parse(data): ```
{"functional": "_inputs = [['ooo'], ['ioioio'], ['idoiido'], ['isoisoiso'], ['codewars']]\n_outputs = [[[0, 0, 0]], [[1, 2, 3]], [[0, 1]], [[1, 4, 25]], [[0]]]\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(parse(*i), o[0])"}
128
207
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. The Game of Master Mind is played as follows: The computer has four slots, and each slot will contain a ball that is red (R). yellow (Y). green (G) or blue (B). For example, the computer might have RGGB (Slot #1 is red, Slots #2 and #3 are green, Slot #4 is blue). You, the user, are trying to guess the solution. You might, for example, guess YRGB. When you guess the correct color for the correct slot, you get a "hit:' If you guess a color that exists but is in the wrong slot, you get a "pseudo-hit:' Note that a slot that is a hit can never count as a pseudo-hit. For example, if the actual solution is RGBY and you guess GGRR, you have one hit and one pseudo-hit. Write a method that, given a guess and a solution, returns the number of hits and pseudo-hits. Given a sequence of colors solution, and a guess, write a method that return the number of hits and pseudo-hit answer, where answer[0] is the number of hits and answer[1] is the number of pseudo-hit. Please complete the following python code precisely: ```python class Solution: def masterMind(self, solution: str, guess: str) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(solution=\"RGBY\",guess=\"GGRR\") == [1,1]\n\n\ncheck(Solution().masterMind)"}
294
39
coding
Solve the programming task below in a Python markdown code block. Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them. Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block. For example: the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos. Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem. -----Input----- The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters. -----Output----- Print the given word without any changes if there are no typos. If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them. -----Examples----- Input hellno Output hell no Input abacaba Output abacaba Input asdfasdf Output asd fasd f
{"inputs": ["a\n", "b\n", "x\n", "b\n", "x\n", "a\n", "c\n", "y\n"], "outputs": ["a \n", "b \n", "x \n", "b\n", "x\n", "a\n", "c\n", "y\n"]}
453
73
coding
Solve the programming task below in a Python markdown code block. You are given a sequence $s$ consisting of $n$ digits from $1$ to $9$. You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one. More formally: if the resulting division of the sequence is $t_1, t_2, \dots, t_k$, where $k$ is the number of element in a division, then for each $i$ from $1$ to $k-1$ the condition $t_{i} < t_{i + 1}$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied. For example, if $s=654$ then you can divide it into parts $[6, 54]$ and it will be suitable division. But if you will divide it into parts $[65, 4]$ then it will be bad division because $65 > 4$. If $s=123$ then you can divide it into parts $[1, 23]$, $[1, 2, 3]$ but not into parts $[12, 3]$. Your task is to find any suitable division for each of the $q$ independent queries. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 300$) — the number of queries. The first line of the $i$-th query contains one integer number $n_i$ ($2 \le n_i \le 300$) — the number of digits in the $i$-th query. The second line of the $i$-th query contains one string $s_i$ of length $n_i$ consisting only of digits from $1$ to $9$. -----Output----- If the sequence of digits in the $i$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query. Otherwise in the first line of the answer to this query print "YES", on the second line print $k_i$ — the number of parts in your division of the $i$-th query sequence and in the third line print $k_i$ strings $t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$ — your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $s_i$. See examples for better understanding. -----Example----- Input 4 6 654321 4 1337 2 33 4 2122 Output YES 3 6 54 321 YES 3 1 3 37 NO YES 2 21 22
{"inputs": ["1\n3\n333\n", "1\n3\n333\n", "1\n3\n343\n", "1\n3\n218\n", "1\n3\n242\n", "1\n4\n3333\n", "1\n4\n5234\n", "1\n4\n9999\n"], "outputs": ["YES\n2\n3 33\n", "YES\n2\n3 33\n", "YES\n2\n3 43\n", "YES\n2\n2 18\n", "YES\n2\n2 42\n", "YES\n2\n3 333\n", "YES\n2\n5 234\n", "YES\n2\n9 999\n"]}
691
180
coding
Solve the programming task below in a Python markdown code block. People in Chefland have three different eye colors, namely brown, blue, and green. green is the rarest of the eye colors whereas brown is most common. The eye color of the child of two people is most likely to be the most common eye color between them. You are given two characters denoting the eye colors of two people in Chefland. The character R denotes bRown color, B denotes Blue color, and G denotes Green color. Determine the most likely eye color of their child. (Print R, B or G denoting bRown, Blue or Green respectively). Please see the sample test cases below for explained examples. ------ Input Format ------ - The first (and only) line of input contains two space-separated characters, the eye colors of the parents. ------ Output Format ------ Print a single character denoting the most likely eye color of the child. (Print R, B or G denoting brown, blue or green respectively). ------ Constraints ------ - The input contains two space-separated characters - Each character in the input is one among {R, B, G}. ------ subtasks ------ ----- Sample Input 1 ------ R B ----- Sample Output 1 ------ R ----- explanation 1 ------ The two people have brown and blue eyes and brown is the most common. Therefore, their child will most likely have brown eyes. ----- Sample Input 2 ------ B B ----- Sample Output 2 ------ B ----- explanation 2 ------ Both parents have blue eyes, therefore their child will most likely have blue eyes ----- Sample Input 3 ------ G B ----- Sample Output 3 ------ B ----- explanation 3 ------ The parents have green and blue eyes, out of which blue is more common than green, therefore the child will most likely have blue eyes.
{"inputs": ["R B\n", "B B\n", "G B\n"], "outputs": ["R", "B", "B"]}
393
30
coding
Solve the programming task below in a Python markdown code block. Debug the functions Should be easy, begin by looking at the code. Debug the code and the functions should work. There are three functions: ```Multiplication (x)``` ```Addition (+)``` and ```Reverse (!esreveR)``` i { font-size:16px; } #heading { padding: 2em; text-align: center; background-color: #0033FF; width: 100%; height: 5em; } Also feel free to reuse/extend the following starter code: ```python def multi(l_st): ```
{"functional": "_inputs = [[[8, 2, 5]]]\n_outputs = [[80]]\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(multi(*i), o[0])"}
140
161
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true: It is (). It can be written as AB (A concatenated with B), where A and B are valid parentheses strings. It can be written as (A), where A is a valid parentheses string. You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked, If locked[i] is '1', you cannot change s[i]. But if locked[i] is '0', you can change s[i] to either '(' or ')'. Return true if you can make s a valid parentheses string. Otherwise, return false.   Please complete the following python code precisely: ```python class Solution: def canBeValid(self, s: str, locked: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(s = \"))()))\", locked = \"010100\") == True\n assert candidate(s = \"()()\", locked = \"0000\") == True\n assert candidate(s = \")\", locked = \"0\") == False\n\n\ncheck(Solution().canBeValid)"}
212
78
coding
Solve the programming task below in a Python markdown code block. Last summer, Feluda gifted Lalmohan-Babu a balanced bracket sequence $s$ of length $2 n$. Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of $2 n$ vertices using the balanced bracket sequence $s$. For any two distinct vertices $i$ and $j$ ($1 \le i < j \le 2 n$), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the subsegment $s[i \ldots j]$ forms a balanced bracket sequence. Determine the number of connected components in Topshe's graph. See the Notes section for definitions of the underlined terms. -----Input----- Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^5$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 10^5$) — the number of opening brackets in string $s$. The second line of each test case contains a string $s$ of length $2 n$ — a balanced bracket sequence consisting of $n$ opening brackets "(", and $n$ closing brackets ")". It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case, output a single integer — the number of connected components in Topshe's graph. -----Examples----- Input 4 1 () 3 ()(()) 3 ((())) 4 (())(()) Output 1 2 3 3 -----Note----- Sample explanation: In the first test case, the graph constructed from the bracket sequence (), is just a graph containing nodes $1$ and $2$ connected by a single edge. In the second test case, the graph constructed from the bracket sequence ()(()) would be the following (containing two connected components): Definition of Underlined Terms: A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters $+$ and $1$. For example, sequences (())(), (), and (()(())) are balanced, while )(, ((), and (()))( are not. The subsegment $s[l \ldots r]$ denotes the sequence $[s_l, s_{l + 1}, \ldots, s_r]$. A connected component is a set of vertices $X$ such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to $X$ violates this rule.
{"inputs": ["4\n1\n()\n3\n()(())\n3\n((()))\n4\n(())(())\n"], "outputs": ["1\n2\n3\n3\n"]}
576
44
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well. You are given a binary string $S$. Chef defines $\mathrm{MEX}(S)$ as the smallest non-negative integer such that its binary representation (without leading '0'-s; in particular, the binary representation of $0$ is "0") is not a [subsequence] of $S$. Chef is asking you to find $\mathrm{MEX}(S)$. Since this integer could be very large, find its binary representation (without leading '0'-s). ------ Input ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. The first and only line of each test case contains a single string $S$. ------ Output ------ For each test case, print a single line containing one string: $\mathrm{MEX}(S)$ in binary representation. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ |S| ≤ 10^{6}$ $S$ contains only characters '0' and '1' the sum of $|S|$ over all test cases does not exceed $2 \cdot 10^{6}$ ------ Subtasks ------ Subtask #1 (20 points): - $1 ≤ T ≤ 2 \cdot 10^{3}$ $|S| ≤ 10$ Subtask #2 (20 points): - $1 ≤ T ≤ 10^{5}$ $|S| ≤ 60$ Subtask #2 (60 points): - original constraints ----- Sample Input 1 ------ 2 1001011 1111 ----- Sample Output 1 ------ 1100 0 ----- explanation 1 ------ Example case 1: All integers between $0$ and $11$ inclusive, in binary representation, appear in $S$ as subsequences. However, the binary representation of $12$ (which is "1100") is not a subsequence of $S$. Example case 2: Since $S$ contains only '1'-s, the string "0" is not a subsequence of $S$ and therefore $\mathrm{MEX}(S) = 0$.
{"inputs": ["2\n1001011\n1111"], "outputs": ["1100\n0"]}
525
30