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. You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$. Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on. The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal. Count the number of different legal paths you can take from the start to the goal modulo $10^9 + 7$. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other. -----Input----- The first line contains two integers $n, m$ — dimensions of the labyrinth ($1 \leq n, m \leq 2000$). Next $n$ lines describe the labyrinth. Each of these lines contains $m$ characters. The $j$-th character of the $i$-th of these lines is equal to "R" if the cell $(i, j)$ contains a rock, or "." if the cell $(i, j)$ is empty. It is guaranteed that the starting cell $(1, 1)$ is empty. -----Output----- Print a single integer — the number of different legal paths from $(1, 1)$ to $(n, m)$ modulo $10^9 + 7$. -----Examples----- Input 1 1 . Output 1 Input 2 3 ... ..R Output 0 Input 4 4 ...R .RR. .RR. R... Output 4 -----Note----- In the first sample case we can't (and don't have to) move, hence the only path consists of a single cell $(1, 1)$. In the second sample case the goal is blocked and is unreachable. Illustrations for the third sample case can be found here: https://assets.codeforces.com/rounds/1225/index.html
{"inputs": ["1 1\n.\n", "1 1\n.\n", "1 3\n.R.\n", "1 3\n.R.\n", "2 2\n.R\nR.\n", "2 2\n.R\nR.\n", "2 2\n.R\n.R\n", "2 2\nR.\n.R\n"], "outputs": ["1\n", "1\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
521
115
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A split of an integer array is good if: The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right. The sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right. Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.   Please complete the following python code precisely: ```python class Solution: def waysToSplit(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,1,1]) == 1\n assert candidate(nums = [1,2,2,2,5,0]) == 3\n assert candidate(nums = [3,2,1]) == 0\n\n\ncheck(Solution().waysToSplit)"}
165
74
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times. Return the length of the longest substring containing the same letter you can get after performing the above operations.   Please complete the following python code precisely: ```python class Solution: def characterReplacement(self, s: str, k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(s = \"ABAB\", k = 2) == 4\n assert candidate(s = \"AABABBA\", k = 1) == 4\n\n\ncheck(Solution().characterReplacement)"}
110
57
coding
Solve the programming task below in a Python markdown code block. You are given an integer N where N ≤ 10. Consider any array A with length N where each element can either be 0, 1, or 2, we define f(A) as the number of extrema in A. You need to find the sum of f(A) over all possible arrays A. Note: In an array A, we consider A_{i} as an extremum if it is strictly greater than both of its neighbors (i.e. A_{i} > A_{i - 1} and A_{i} > A_{i + 1}), or if it is strictly smaller than both of its neighbors (i.e. A_{i} < A_{i - 1} and A_{i} < A_{i + 1}). Note that first and last elements are not counted as extremum. Extrema is the plural of extremum. ------ Input Format ------ - The first line of the input contains an integer T - the number of test cases. The test cases then follow. - The only line of each test case contains one integer N. ------ Output Format ------ For each test case, output on a single the sum of f(A) over all possible arrays A. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N ≤ 10$ ----- Sample Input 1 ------ 3 1 3 5 ----- Sample Output 1 ------ 0 10 270 ----- explanation 1 ------ - Test case $1$: - $A = [0]$. Then $f(A) = 0$. - $A = [1]$. Then $f(A) = 0$. - $A = [2]$. Then $f(A) = 0$. Therefore the answer is $0$. - Test case $2$: There are $10$ arrays $A$ with $f(A) = 1$: - $A = [0, 1, 0]$. - $A = [0, 2, 0]$. - $A = [0, 2, 1]$. - $A = [1, 2, 0]$. - $A = [1, 2, 1]$. - $A = [2, 1, 2]$. - $A = [2, 0, 2]$. - $A = [2, 0, 1]$. - $A = [1, 0, 2]$. - $A = [1, 0, 1]$. The remaining $A$'s has $f(A) = 0$. Therefore the answer is $1 \cdot 10 = 10$.
{"inputs": ["3\n1\n3\n5"], "outputs": ["0\n10\n270\n"]}
592
26
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string expression representing arbitrarily nested ternary expressions, evaluate the expression, and return the result of it. You can always assume that the given expression is valid and only contains digits, '?', ':', 'T', and 'F' where 'T' is true and 'F' is false. All the numbers in the expression are one-digit numbers (i.e., in the range [0, 9]). The conditional expressions group right-to-left (as usual in most languages), and the result of the expression will always evaluate to either a digit, 'T' or 'F'.   Please complete the following python code precisely: ```python class Solution: def parseTernary(self, expression: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(expression = \"T?2:3\") == \"2\"\n assert candidate(expression = \"F?1:T?4:5\") == \"4\"\n assert candidate(expression = \"T?T?F:5:3\") == \"F\"\n\n\ncheck(Solution().parseTernary)"}
168
79
coding
Solve the programming task below in a Python markdown code block. The country of Berland initially has N isolated cities, the i-th city has a significance of A_{i}. The President of Berland wants to connect all the cities. He can construct a bidirectional road of length L (L > 0) from city X to city Y if (A_{X} \& A_{Y} \& L) = L, where \& represents the [bitwise AND] operator. What is the minimum total length of roads he has to construct, in order to connect all the cities in Berland? Print -1 if it is impossible. Note: City X and City Y are said to be connected if there exists a sequence of cities C_{1}, C_{2}, \ldots, C_{K} (K ≥ 1) such that C_{1} = X, C_{K} = Y, and there exists a road from C_{i} to C_{i+1}, (1 ≤ i < K). All the cities in Berland are said to be connected when every pair of cities in Berland are connected. ------ 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 N — the number of cities. - The second line contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N} — the significance of each of the N cities. ------ Output Format ------ For each test case, output on a new line the minimum total length of roads to connect all the cities in Berland, or -1 if it is impossible. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ N ≤ 10^{5}$ $0 ≤ A_{i} ≤ 10^{9}$ - The sum of $N$ over all test cases won't exceed $3 \cdot 10^{5}$. ----- Sample Input 1 ------ 2 4 4 4 4 4 3 2 4 6 ----- Sample Output 1 ------ 12 6 ----- explanation 1 ------ Test case 1: The following roads with minimum total length can be constructed to connect Berland: - A road with $L=4$ between city $1$ and city $2$, since ($A_{1} \& A_{2} \& 4) = 4$. - A road with $L=4$ between city $2$ and city $3$, since ($A_{2} \& A_{3} \& 4) = 4$. - A road with $L=4$ between city $3$ and city $4$, since ($A_{3} \& A_{4} \& 4) = 4$. Test case 2: The following roads with minimum total length can be constructed to connect Berland: - A road with $L=2$ between city $1$ and city $3$, since ($A_{1} \& A_{3} \& 2) = 2$. - A road with $L=4$ between city $2$ and city $3$, since ($A_{2} \& A_{3} \& 4) = 4$.
{"inputs": ["2\n4\n4 4 4 4\n3\n2 4 6"], "outputs": ["12\n6\n"]}
721
34
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Single letters represent a singleton set containing that word. R("a") = {"a"} R("w") = {"w"} When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R("{a,b,c}") = {"a","b","c"} R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once) When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R("{a,b}{c,d}") = {"ac","ad","bc","bd"} R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"} Formally, the three rules for our grammar: For every lowercase letter x, we have R(x) = {x}. For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product. Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.   Please complete the following python code precisely: ```python class Solution: def braceExpansionII(self, expression: str) -> List[str]: ```
{"functional": "def check(candidate):\n assert candidate(expression = \"{a,b}{c,{d,e}}\") == [\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]\n assert candidate(expression = \"{{a,z},a{b,c},{ab,z}}\") == [\"a\",\"ab\",\"ac\",\"z\"]\n\n\ncheck(Solution().braceExpansionII)"}
438
84
coding
Solve the programming task below in a Python markdown code block. `late_clock` function receive an array with 4 digits and should return the latest time that can be built with those digits. The time should be in `HH:MM` format. Examples: ``` [1, 9, 8, 3] => 19:38 [9, 1, 2, 5] => 21:59 ``` You can suppose the input is correct and you can build from it a correct 24-hour time. Also feel free to reuse/extend the following starter code: ```python def late_clock(digits): ```
{"functional": "_inputs = [[[9, 1, 2, 5]], [[1, 9, 8, 3]], [[0, 2, 2, 2]], [[3, 5, 0, 2]], [[9, 0, 1, 1]], [[2, 3, 2, 4]], [[1, 2, 8, 9]]]\n_outputs = [['21:59'], ['19:38'], ['22:20'], ['23:50'], ['19:10'], ['23:42'], ['19:28']]\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(late_clock(*i), o[0])"}
139
282
coding
Solve the programming task below in a Python markdown code block. The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang. The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map. Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed. Input The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 100) — the number of rows and columns in the table, correspondingly. Each of the next n lines contains m characters — the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".". It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements. Output Print two integers — the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right. Examples Input 3 2 .* .. ** Output 1 1 Input 3 3 *.* *.. ... Output 2 3
{"inputs": ["2 2\n*.\n**\n", "2 2\n**\n.*\n", "2 2\n**\n/*\n", "2 3\n*.*\n..*\n", "3 2\n.*\n..\n**\n", "2 5\n*....\n*...*\n", "3 3\n*.*\n*..\n-..\n", "3 3\n*.*\n*..\n...\n"], "outputs": ["1 2", "2 1", "2 1\n", "2 1", "1 1", "1 5", "2 3\n", "2 3"]}
374
156
coding
Solve the programming task below in a Python markdown code block. Shaun was given $N$ pairs of parenthesis ( ) by his teacher who gave him a difficult task.The task consists of two steps. First,Shaun should colour all $N$ pairs of parenthesis each with different color but opening and closing bracket of a particular pair should be of same colour. Then,Shaun should report to his teacher the number of ways he can arrange all $2*N$ brackets such that sequence form is valid. Teacher defined valid sequence by these rules: - Any left parenthesis '(' must have a corresponding right parenthesis ')'. - Any right parenthesis ')' must have a corresponding left parenthesis '('. - Left parenthesis '(' must go before the corresponding right parenthesis ')'. Note: Shaun could match opening and closing brackets of different colours. Since number of ways can be large, Shaun would report the answer as modulo 1000000007 ($10^9 + 7$). -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, one integer $N$. -----Output:----- For each testcase, output in a single line answer given by Shaun to his teacher modulo 1000000007. -----Constraints----- - $1 \leq T \leq 100000$ - $1 \leq N \leq 100000$ -----Sample Input:----- 3 1 2 3 -----Sample Output:----- 1 6 90 -----EXPLANATION:----- Here numbers from $1$ to $N$ have been used to denote parenthesis.A unique number corresponds to a unique pair of parenthesis. -In the first test case , you can use only one color to color the parenthesis you could arrange it only in one way i.e, 1 1 -In the second test case you can use two colors and the possible ways of arranging it are 1 1 2 2 1 2 2 1 1 2 1 2 2 2 1 1 2 1 1 2 2 1 2 1
{"inputs": ["3\n1\n2\n3"], "outputs": ["1\n6\n90"]}
472
23
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city. It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.   Please complete the following python code precisely: ```python class Solution: def destCity(self, paths: List[List[str]]) -> str: ```
{"functional": "def check(candidate):\n assert candidate(paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]) == \"Sao Paulo\" \n assert candidate(paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]) == \"A\"\n assert candidate(paths = [[\"A\",\"Z\"]]) == \"Z\"\n\n\ncheck(Solution().destCity)"}
125
103
coding
Solve the programming task below in a Python markdown code block. Leha is a usual student at 'The Usual University for Usual Students'. Sometimes he studies hard; at other times he plays truant and gets busy with other things besides academics. He has already studied at the university for N months. For the ith month (1 ≤ i ≤ N), he has received some non-negative integer grade A[i]. Now he wants to analyse his progress for some periods of his university education. An arbitrary period, defined by two positive integers L and R, begins at Leha's Lth month at the university and ends at the Rth. The analysis is performed via the following steps. 1. Write down all the grades for each month from L to R and sort them. Let's call the sorted list S. 2. Calculate the sum of squared differences of consecutive elements in S, that is, (S[2] - S[1])2 + (S[3] - S[2])2 + ... + (S[R-L+1] - S[R-L])2. -----Input----- The first line contains one integer N — the number of months Leha has already studied at the university. The second line contains N integers — list A of Leha's grades. The third line contains one integer M — the number of periods Leha is interested in analyzing. Each of the following M lines contain two integers L and R describing each period. -----Output----- For each query, output one integer — the result of the progress analysis for the corresponding period. -----Constraints----- - 1 ≤ N, M ≤ 5*104 - 0 ≤ A[i] ≤ 106 -----Subtasks----- - Subtask 1 (19 points) 1 ≤ N, M ≤ 200, time limit = 2 sec - Subtask 2 (31 points) 1 ≤ N, M ≤ 10 000, time limit = 2 sec - Subtask 3 (26 points) 0 ≤ A[i] ≤ 100, time limit = 5 sec - Subtask 4 (24 points) no additional constraints, , time limit = 5 sec -----Example----- Input:5 1 3 2 4 5 5 1 5 1 4 2 4 3 3 3 5 Output:4 3 2 0 5 Explanation The first query: sorted array looks like (1, 2, 3, 4, 5) and the answer is calculated as (2-1)2 + (3-2)2 + (4-3)2 + (5-4)2 = 4 The second query: sorted array looks like (1, 2, 3, 4) and the answer is calculated as (2-1)2 + (3-2)2 + (4-3)2 = 3 The last query: sorted array looks like (2, 4, 5) and the answer is calculated as (4-2)2 + (5-4)2 = 5
{"inputs": ["5\n1 3 2 4 5\n5\n1 5\n1 4\n2 4\n3 3\n3 5"], "outputs": ["4\n3\n2\n0\n5"]}
667
52
coding
Solve the programming task below in a Python markdown code block. # Task You're given a two-dimensional array of integers `matrix`. Your task is to determine the smallest non-negative integer that is not present in this array. # Input/Output - `[input]` 2D integer array `matrix` A non-empty rectangular matrix. `1 ≤ matrix.length ≤ 10` `1 ≤ matrix[0].length ≤ 10` - `[output]` an integer The smallest non-negative integer that is not present in matrix. # Example For ``` matrix = [ [0, 2], [5, 1]]``` the result should be `3` 0,1,2,`(3)`...5 Also feel free to reuse/extend the following starter code: ```python def smallest_integer(matrix): ```
{"functional": "_inputs = [[[[0, 2], [5, 1]]], [[[4, 5, 3, 21, 3, 8], [2, 2, 6, 5, 10, 9], [7, 5, 6, 8, 2, 6], [1, 4, 7, 8, 9, 0], [1, 3, 6, 5, 5, 1], [2, 7, 3, 4, 4, 3]]], [[[4, 5, 3, -4, 3, 8], [2, 0, 6, 5, 4, 9], [7, 5, 6, 8, 2, 6], [1, 4, 7, 8, 9, 11], [1, 3, 10, 5, 5, 1], [12, 7, 3, 4, 4, 3]]], [[[1, 2], [3, 4]]], [[[0, 1], [2, 3]]], [[[4, 5, 13, 0, 3], [2, 6, 5, 10, 9], [7, 5, -6, 8, 6], [1, 4, 7, 8, 9], [2, 3, 4, 44, 3]]], [[[-1, 100, -1, 100], [100, -1, 100, -1], [-1, 100, -1, 100], [100, -1, 100, -1]]], [[[-1, -1], [-1, -1]]]]\n_outputs = [[3], [11], [13], [0], [4], [11], [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(smallest_integer(*i), o[0])"}
182
598
coding
Solve the programming task below in a Python markdown code block. 'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is a_{i} points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price. The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again. All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve. -----Input----- The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7) — the prices of the questions. The third line contains m distinct integers b_{i} (1 ≤ b_{i} ≤ n) — the numbers of auction questions. Assume that the questions are numbered from 1 to n. -----Output----- In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type. -----Examples----- Input 4 1 1 3 7 5 3 Output 18 Input 3 2 10 3 8 2 3 Output 40 Input 2 2 100 200 1 2 Output 400
{"inputs": ["1 1\n1\n1\n", "1 1\n1\n1\n", "1 1\n2\n1\n", "2 1\n1 2\n1\n", "2 1\n1 2\n2\n", "2 1\n1 2\n2\n", "2 1\n1 2\n1\n", "2 1\n1 0\n1\n"], "outputs": ["1\n", " 1", "2\n", "4\n", "3\n", " 3", " 4", "1\n"]}
593
131
coding
Solve the programming task below in a Python markdown code block. Snuke built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the string `AC` as the verdict to a program. Constraints * 2 \leq |S| \leq 5 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: S Output If the judge can return the string `AC` as a verdict to a program, print `Yes`; if it cannot, print `No`. Examples Input BACD Output Yes Input ABCD Output No Input CABD Output No Input ACACA Output Yes Input XX Output No
{"inputs": ["XW", "XV", "VX", "YW", "WY", "VY", "YV", "YU"], "outputs": ["No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]}
207
69
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given the head of a linked list. Remove every node which has a node with a greater value anywhere to the right side of it. Return the head of the modified linked list.   Please complete the following python code precisely: ```python # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: ```
{"functional": "def check(candidate):\n assert is_same_list(candidate(head = list_node([5,2,13,3,8])), list_node([13,8]))\n assert is_same_list(candidate(head = list_node([1,1,1,1])), list_node([1,1,1,1]))\n\n\ncheck(Solution().removeNodes)"}
129
83
coding
Solve the programming task below in a Python markdown code block. Recall that a tree is an undirected, connected acyclic graph. We have a weighted tree, $\mathbf{T}$, with $n$ vertices; let $dist_{u,v}$ be the total sum of edge weights on the path between nodes $\mbox{u}$ and $\boldsymbol{\nu}$. Let's consider all the matrices, $A_{u,v}$, such that: $A_{u,v}=-A_{v,u}$ $0\leq|A_{u,v}|\leq dist_{u,v}$ $\sum_{i=1}^{n}A_{u,i}=0$ for each $u\neq1$ and $u\neq n$ We consider the total value of matrix $\mbox{A}$ to be: $\sum_{i=1}^{n}A_{1,i}$ Calculate and print the maximum total value of $\mbox{A}$ for a given tree, $\mathbf{T}$. Input Format The first line contains a single positive integer, $n$, denoting the number of vertices in tree $\mathbf{T}$. Each line $\boldsymbol{i}$ of the $n-1$ subsequent lines contains three space-separated positive integers denoting the respective $a_i$, $b_i$, and $c_i$ values defining an edge connecting nodes $a_i$ and $b_i$ (where $1\leq a_i,b_i\leq n$) with edge weight $c_i$. Constraints $2\leq n\leq5000000$ $1\leq c_i\leq10^4$ Test cases with $n\leq10$ have $30\%$ of total score Test cases with $n\leq500$ have $60\%$ of total score Output Format Print a single integer denoting the maximum total value of matrix $\mbox{A}$ satisfying the properties specified in the Problem Statement above. Sample Input 3 1 2 2 1 3 1 Sample Output 3 Explanation In the sample case, matrix $\mbox{A}$ is: $A=\begin{pmatrix}0&2&1\\ -2&0&2\\ -1&-2&0\end{pmatrix}$ The sum of the elements of the first row is equal to $3$.
{"inputs": ["3\n1 2 2\n1 3 1\n"], "outputs": ["3\n"]}
527
26
coding
Solve the programming task below in a Python markdown code block. Hi there! You have to implement the `String get_column_title(int num) // syntax depends on programming language` function that takes an integer number (index of the Excel column) and returns the string represents the title of this column. #Intro In the MS Excel lines are numbered by decimals, columns - by sets of letters. For example, the first column has the title "A", second column - "B", 26th - "Z", 27th - "AA". "BA"(53) comes after "AZ"(52), "AAA" comes after "ZZ". Excel? Columns? More details [here](https://en.wikipedia.org/wiki/Microsoft_Excel) #Input It takes only one argument - column decimal index number. Argument `num` is a natural number. #Output Output is the upper-case string represents the title of column. It contains the English letters: A..Z #Errors For cases `num < 1` your function should throw/raise `IndexError`. In case of non-integer argument you should throw/raise `TypeError`. In Java, you should throw `Exceptions`. Nothing should be returned in Haskell. #Examples Python, Ruby: ``` >>> get_column_title(52) "AZ" >>> get_column_title(1337) "AYK" >>> get_column_title(432778) "XPEH" >>> get_column_title() TypeError: >>> get_column_title("123") TypeError: >>> get_column_title(0) IndexError: ``` JS, Java: ``` >>> getColumnTitle(52) "AZ" >>> getColumnTitle(1337) "AYK" >>> getColumnTitle(432778) "XPEH" >>> getColumnTitle() TypeError: >>> getColumnTitle("123") TypeError: >>> getColumnTitle(0) IndexError: ``` #Hint The difference between the 26-digits notation and Excel columns numeration that in the first system, after "Z" there are "BA", "BB", ..., while in the Excel columns scale there is a range of 26 elements: AA, AB, ... , AZ between Z and BA. It is as if in the decimal notation was the following order: 0, 1, 2, .., 9, 00, 01, 02, .., 09, 10, 11, .., 19, 20..29..99, 000, 001 and so on. #Also The task is really sapid and hard. If you're stuck - write to the discussion board, there are many smart people willing to help. Also feel free to reuse/extend the following starter code: ```python def get_column_title(num): ```
{"functional": "_inputs = [[1], [26], [52], [53], [702]]\n_outputs = [['A'], ['Z'], ['AZ'], ['BA'], ['ZZ']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(get_column_title(*i), o[0])"}
615
184
coding
Solve the programming task below in a Python markdown code block. Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times. One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed. Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times. Input The first line contains three integers: a, b, n (1 ≤ a, b, n ≤ 105). Output In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them. Examples Input 5 4 5 Output 524848 Input 12 11 1 Output 121 Input 260 150 10 Output -1
{"inputs": ["3 4 1\n", "3 7 2\n", "5 4 7\n", "3 1 1\n", "5 4 9\n", "3 1 2\n", "7 4 9\n", "1 1 2\n"], "outputs": ["32\n", "350\n", "52000000\n", "30\n", "5200000000\n", "300\n", "7200000000\n", "100\n"]}
276
135
coding
Solve the programming task below in a Python markdown code block. The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x_0, y_0) of a rectangular squared field of size x × y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly x·y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same. After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code. Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it. The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up. -----Input----- The first line of the input contains four integers x, y, x_0, y_0 (1 ≤ x, y ≤ 500, 1 ≤ x_0 ≤ x, 1 ≤ y_0 ≤ y) — the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right. The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100 000 characters and only consists of characters 'L', 'R', 'U', 'D'. -----Output----- Print the sequence consisting of (length(s) + 1) numbers. On the k-th position, starting with zero, print the number of tests where the robot will run exactly k commands before it blows up. -----Examples----- Input 3 4 2 2 UURDRDRL Output 1 1 0 1 1 1 1 0 6 Input 2 2 2 2 ULD Output 1 1 1 1 -----Note----- In the first sample, if we exclude the probable impact of the mines, the robot's route will look like that: $(2,2) \rightarrow(1,2) \rightarrow(1,2) \rightarrow(1,3) \rightarrow(2,3) \rightarrow(2,4) \rightarrow(3,4) \rightarrow(3,4) \rightarrow(3,3)$.
{"inputs": ["1 2 1 1\nR\n", "2 1 1 1\nD\n", "2 1 1 1\nD\n", "1 2 1 1\nR\n", "1 2 1 2\nLR\n", "2 1 2 1\nUD\n", "1 2 1 2\nLR\n", "2 1 2 1\nUD\n"], "outputs": ["1 1\n", "1 1\n", "1 1 ", "1 1 ", "1 1 0\n", "1 1 0\n", "1 1 0 ", "1 1 0 "]}
678
155
coding
Solve the programming task below in a Python markdown code block. Given a string of length n s = s1, s2,…, sn and m queries. Each query qk (1 ≤ k ≤ m) is one of four types, "L ++", "L-", "R ++", "R-", and l [for the kth query qk. k] and r [k] are defined below. * L ++: l [k] = l [k-1] + 1, r [k] = r [k-1] * L-: l [k] = l [k-1] -1, r [k] = r [k-1] * R ++: l [k] = l [k-1], r [k] = r [k-1] +1 * R-: l [k] = l [k-1], r [k] = r [k-1] -1 However, l [0] = r [0] = 1. At this time, how many kinds of character strings are created for m substrings sl [k], sl [k] + 1,…, sr [k] -1, sr [k] (1 ≤ k ≤ m). Answer if you can. Constraints * The string s consists of a lowercase alphabet * 1 ≤ n ≤ 3 x 105 * 1 ≤ m ≤ 3 × 105 * qk (1 ≤ k ≤ m) is one of "L ++", "L-", "R ++", "R-" * 1 ≤ l [k] ≤ r [k] ≤ n (1 ≤ k ≤ m) Input Input is given in the following format > n m > s > q1 > q2 >… > qm > Output Output the solution of the problem on one line Examples Input 5 4 abcde R++ R++ L++ L-- Output 3 Input 4 6 abab R++ L++ R++ L++ R++ L++ Output 4 Input 10 13 aacacbabac R++ R++ L++ R++ R++ L++ L++ R++ R++ L-- L-- R-- R-- Output 11
{"inputs": ["6 4\nabcde\nR++\nR++\nL++\nL--", "6 2\nabdde\nR++\nR++\nL++\nL--", "5 0\nabcde\nR++\nR++\nL++\nL--", "6 1\nabcde\nR++\nR++\nL++\nL--", "6 4\nabdde\nR++\nR++\nL++\nL--", "2 4\nabcde\nR++\nR++\nL++\nL--", "6 2\neddba\nR++\nR++\nL++\nL--", "6 3\neddba\nR++\nR++\nL++\nL--"], "outputs": ["3\n", "2\n", "0\n", "1\n", "3\n", "3\n", "2\n", "3\n"]}
498
222
coding
Solve the programming task below in a Python markdown code block. Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. Example: ```python create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890" ``` ```f# createPhoneNumber [1; 2; 3; 4; 5; 6; 7; 8; 9; 0] // => returns "(123) 456-7890" ``` The returned format must be correct in order to complete this challenge. Don't forget the space after the closing parentheses! Also feel free to reuse/extend the following starter code: ```python def create_phone_number(n): ```
{"functional": "_inputs = [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[0, 2, 3, 0, 5, 6, 0, 8, 9, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]\n_outputs = [['(123) 456-7890'], ['(111) 111-1111'], ['(023) 056-0890'], ['(000) 000-0000']]\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(create_phone_number(*i), o[0])"}
207
333
coding
Solve the programming task below in a Python markdown code block. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
{"inputs": ["2 2 1\n2\n", "2 1 2\n1\n", "3 1 3\n1 2\n", "3 2 3\n2 2\n", "4 2 3\n3 2 2\n", "4 2 3\n2 1 3\n", "4 2 3\n3 2 1\n", "5 2 3\n2 4 2 3\n"], "outputs": ["1\n", "2\n", "2 3\n", "2 3\n", "3 3 2\n", "3 1 3\n", "3 3 1\n", "2 4 3 3\n"]}
385
162
coding
Solve the programming task below in a Python markdown code block. I love Fibonacci numbers in general, but I must admit I love some more than others. I would like for you to write me a function that when given a number (n) returns the n-th number in the Fibonacci Sequence. For example: ```python nth_fib(4) == 2 ``` Because 2 is the 4th number in the Fibonacci Sequence. For reference, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. Also feel free to reuse/extend the following starter code: ```python def nth_fib(n): ```
{"functional": "_inputs = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25]]\n_outputs = [[0], [1], [1], [2], [3], [5], [8], [13], [21], [34], [55], [89], [144], [233], [377], [610], [987], [1597], [2584], [4181], [6765], [10946], [17711], [28657], [46368]]\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(nth_fib(*i), o[0])"}
146
359
coding
Solve the programming task below in a Python markdown code block. Is every value in the array an array? This should only test the second array dimension of the array. The values of the nested arrays don't have to be arrays. Examples: ```python [[1],[2]] => true ['1','2'] => false [{1:1},{2:2}] => false ``` Also feel free to reuse/extend the following starter code: ```python def arr_check(arr): ```
{"functional": "_inputs = [[[]], [[['string']]], [[[], {}]], [[[1], [2], [3]]], [['A', 'R', 'R', 'A', 'Y']]]\n_outputs = [[True], [True], [False], [True], [False]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(arr_check(*i), o[0])"}
104
201
coding
Solve the programming task below in a Python markdown code block. You are given an array $a_1, a_2, \dots, a_n$ where all $a_i$ are integers and greater than $0$. In one operation, you can choose two different indices $i$ and $j$ ($1 \le i, j \le n$). If $gcd(a_i, a_j)$ is equal to the minimum element of the whole array $a$, you can swap $a_i$ and $a_j$. $gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. Now you'd like to make $a$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $a$ is non-decreasing if and only if $a_1 \le a_2 \le \ldots \le a_n$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 10^5$) — the length of array $a$. The second line of each test case contains $n$ positive integers $a_1, a_2, \ldots a_n$ ($1 \le a_i \le 10^9$) — the array itself. It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$. -----Output----- For each test case, output "YES" if it is possible to make the array $a$ non-decreasing using the described operation, or "NO" if it is impossible to do so. -----Example----- Input 4 1 8 6 4 3 6 6 2 9 4 4 5 6 7 5 7 5 2 2 4 Output YES YES YES NO -----Note----- In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $a_1$ and $a_3$ first, and swap $a_1$ and $a_5$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation.
{"inputs": ["1\n5\n2 6 2 4 5\n", "1\n5\n2 6 2 4 5\n", "1\n5\n2 6 2 4 1\n", "1\n5\n2 6 2 4 8\n", "1\n5\n2 6 4 4 1\n", "1\n5\n2 6 2 4 6\n", "1\n5\n3 6 4 4 1\n", "1\n5\n2 4 2 4 1\n"], "outputs": ["NO\n", "NO\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n"]}
520
166
coding
Solve the programming task below in a Python markdown code block. Iahub got bored, so he invented a game to be played on paper. He writes n integers a_1, a_2, ..., a_{n}. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values a_{k} for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x. The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. -----Input----- The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a_1, a_2, ..., a_{n}. It is guaranteed that each of those n values is either 0 or 1. -----Output----- Print an integer — the maximal number of 1s that can be obtained after exactly one move. -----Examples----- Input 5 1 0 0 1 0 Output 4 Input 4 1 0 0 1 Output 4 -----Note----- In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1]. In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
{"inputs": ["1\n1\n", "1\n0\n", "1\n0\n", "1\n1\n", "2\n1 1\n", "2\n1 1\n", "2\n0 0\n", "4\n1 0 0 1\n"], "outputs": ["0\n", "1\n", "1", "0\n", "1\n", "1\n", "2\n", "4\n"]}
398
97
coding
Solve the programming task below in a Python markdown code block. In the final of CODE FESTIVAL in some year, there are N participants. The height and power of Participant i is H_i and P_i, respectively. Ringo is hosting a game of stacking zabuton (cushions). The participants will line up in a row in some order, and they will in turn try to add zabuton to the stack of zabuton. Initially, the stack is empty. When it is Participant i's turn, if there are H_i or less zabuton already stacked, he/she will add exactly P_i zabuton to the stack. Otherwise, he/she will give up and do nothing. Ringo wants to maximize the number of participants who can add zabuton to the stack. How many participants can add zabuton to the stack in the optimal order of participants? Constraints * 1 \leq N \leq 5000 * 0 \leq H_i \leq 10^9 * 1 \leq P_i \leq 10^9 Input Input is given from Standard Input in the following format: N H_1 P_1 H_2 P_2 : H_N P_N Output Print the maximum number of participants who can add zabuton to the stack. Examples Input 3 0 2 1 3 3 4 Output 2 Input 3 2 4 3 1 4 1 Output 3 Input 10 1 3 8 4 8 3 9 1 6 4 2 3 4 2 9 2 8 3 0 1 Output 5
{"inputs": ["3\n2 4\n3 1\n4 2", "3\n0 2\n1 0\n3 4", "3\n2 7\n3 1\n4 1", "3\n0 0\n1 0\n3 4", "3\n3 7\n3 1\n4 1", "3\n0 0\n1 0\n6 4", "3\n3 7\n3 2\n4 1", "3\n0 0\n1 0\n6 3"], "outputs": ["2\n", "3\n", "3\n", "3\n", "3\n", "3\n", "3\n", "3\n"]}
378
158
coding
Solve the programming task below in a Python markdown code block. Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters. Input The first input data line contains a string whose length is equal to n (1 ≤ n ≤ 105). The string consists of lowercase Latin letters. The second line contains the number k (0 ≤ k ≤ 105). Output Print on the first line the only number m — the least possible number of different characters that could remain in the given string after it loses no more than k characters. Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them. Examples Input aaaaa 4 Output 1 aaaaa Input abacaba 4 Output 1 aaaa Input abcdefgh 10 Output 0 Note In the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length. In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string. In the third sample you are given a line whose length is equal to 8, and k = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string.
{"inputs": ["a\n1\n", "a\n0\n", "a\n2\n", "aa\n2\n", "aa\n3\n", "cky\n79\n", "aaaa\n4\n", "aaaa\n1\n"], "outputs": ["0\n", "1\na", "0\n", "0\n", "0\n", "0\n", "0\n", "1\naaaa"]}
524
90
coding
Solve the programming task below in a Python markdown code block. Karl is developing a key storage service. Each user has a positive integer key. Karl knows that storing keys in plain text is bad practice. So, instead of storing a key, he decided to store a fingerprint of a key. However, using some existing fingerprint algorithm looked too boring to him, so he invented his own one. Karl's fingerprint is calculated by the following process: divide the given integer by 2, then divide the result by 3, then divide the result by 4, and so on, until we get a result that equals zero (we are speaking about integer division each time). The fingerprint is defined as the multiset of the remainders of these divisions. For example, this is how Karl's fingerprint algorithm is applied to the key 11: 11 divided by 2 has remainder 1 and result 5, then 5 divided by 3 has remainder 2 and result 1, and 1 divided by 4 has remainder 1 and result 0. Thus, the key 11 produces the sequence of remainders [1, 2, 1] and has the fingerprint multiset \{1, 1, 2\}. Ksenia wants to prove that Karl's fingerprint algorithm is not very good. For example, she found that both keys 178800 and 123456 produce the fingerprint of \{0, 0, 0, 0, 2, 3, 3, 4\}. Thus, users are at risk of fingerprint collision with some commonly used and easy to guess keys like 123456. Ksenia wants to make her words more persuasive. She wants to calculate the number of other keys that have the same fingerprint as the keys in the given list of some commonly used keys. Your task is to help her. Input The first line contains an integer t (1 ≤ t ≤ 50 000) — the number of commonly used keys to examine. Each of the next t lines contains one integer k_i (1 ≤ k_i ≤ 10^{18}) — the key itself. Output For each of the keys print one integer — the number of other keys that have the same fingerprint. Example Input 3 1 11 123456 Output 0 1 127 Note The other key with the same fingerprint as 11 is 15. 15 produces a sequence of remainders [1, 1, 2]. So both numbers have the fingerprint multiset \{1, 1, 2\}.
{"inputs": ["3\n3\n1\n222880\n", "3\n3\n1\n339159\n", "3\n4\n1\n337517\n", "3\n3\n19\n45773\n", "3\n4\n1\n528334\n", "3\n2\n3\n223713\n", "3\n3\n3\n125981\n", "3\n1\n38\n45773\n"], "outputs": ["0\n0\n1070\n", "0\n0\n199\n", "0\n0\n107\n", "0\n1\n699\n", "0\n0\n2411\n", "0\n0\n95\n", "0\n0\n664\n", "0\n6\n699\n"]}
571
207
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows. originalText is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText. encodedText is then formed by appending all characters of the matrix in a row-wise fashion. The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed. For example, if originalText = "cipher" and rows = 3, then we encode it in the following manner: The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = "ch ie pr". Given the encoded string encodedText and number of rows rows, return the original string originalText. Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.   Please complete the following python code precisely: ```python class Solution: def decodeCiphertext(self, encodedText: str, rows: int) -> str: ```
{"functional": "def check(candidate):\n assert candidate(encodedText = \"ch ie pr\", rows = 3) == \"cipher\"\n assert candidate(encodedText = \"iveo eed l te olc\", rows = 4) == \"i love leetcode\"\n assert candidate(encodedText = \"coding\", rows = 1) == \"coding\"\n assert candidate(encodedText = \" b ac\", rows = 2) == \" abc\"\n\n\ncheck(Solution().decodeCiphertext)"}
341
115
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol). The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n. If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r]. If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c]. Return the minimum total cost for this robot to return home.   Please complete the following python code precisely: ```python class Solution: def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]) == 18\n assert candidate(startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]) == 0\n\n\ncheck(Solution().minCost)"}
306
114
coding
Solve the programming task below in a Python markdown code block. Chef had an array A with length N, but some of its elements got lost. Now, each element of this array is either unknown (denoted by -1) or a positive integer not exceeding K. Chef decided to restore the array A by replacing each unknown element by a positive integer not exceeding K. However, Chef has M restrictions that must hold for the restored array. There are two types of restrictions: - I L R, meaning that for each i such that L < i ≤ R, the condition Ai - Ai-1 = 1 should be satisfied. - D L R, meaning that for each i such that L < i ≤ R, the condition Ai - Ai-1 = -1 should be satisfied. Chef would like to know the number of ways to restore the array while satisfying all restrictions, modulo 109+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 three space-separated integers N, M and K. - The second line contains N integers A1, A2, ..., AN. - Each of the following M lines contains one restriction in the form I L R or D L R. -----Output----- For each test case, print a single line containing one integer - the number of ways to restore the array modulo 109+7. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N, M ≤ 100,000 - 1 ≤ K ≤ 1,000,000,000 - 1 ≤ L < R ≤ N - 1 ≤ Ai ≤ K or Ai = -1 for each valid i - 1 ≤ sum of N over all test cases ≤ 500,000 - 1 ≤ sum of M over all test cases ≤ 500,000 -----Example----- Input: 3 4 2 10 2 3 5 4 I 1 2 D 3 4 5 2 10 -1 -1 -1 -1 -1 I 1 3 D 3 5 6 2 2 -1 -1 -1 -1 -1 -1 I 1 4 D 4 6 Output: 1 8 0
{"inputs": ["3\n4 2 10\n2 3 5 4\nI 1 2\nD 3 4\n5 2 10\n-1 -1 -1 -1 -1\nI 1 3\nD 3 5\n6 2 2\n-1 -1 -1 -1 -1 -1\nI 1 4\nD 4 6"], "outputs": ["1\n8\n0"]}
528
104
coding
Solve the programming task below in a Python markdown code block. Chef likes strings a lot but he likes palindromic strings even more. Today he found an old string s in his garage. The string is so old that some of its characters have faded and are unidentifiable now. Faded characters in the string are represented by '.' whereas other characters are lower case Latin alphabets i.e ['a'-'z']. Chef being the palindrome lover decided to construct the lexicographically smallest palindrome by filling each of the faded character ('.') with a lower case Latin alphabet. Can you please help him completing the task? -----Input----- First line of input contains a single integer T denoting the number of test cases. T test cases follow. First and the only line of each case contains string s denoting the old string that chef has found in his garage. -----Output----- For each test case, print lexicographically smallest palindrome after filling each faded character - if it possible to construct one. Print -1 otherwise. -----Constraints----- - 1 ≤ T ≤ 50 - 1 ≤ |s| ≤ 12345 - String s consists of ['a'-'z'] and '.' only. -----Subtasks-----Subtask #1 (47 points) - 1 ≤ T ≤ 50, 1 ≤ |S| ≤ 123 Subtask #2 (53 points) - 1 ≤ T ≤ 50, 1 ≤ |S| ≤ 12345 -----Example-----Input 3 a.ba cb.bc a.b Output abba cbabc -1 -----Explanation----- In example 1, you can create a palindrome by filling the faded character by 'b'. In example 2, you can replace the faded character by any character from 'a' to 'z'. We fill it by 'a', as it will generate the lexicographically smallest palindrome. In example 3, it is not possible to make the string s a palindrome.
{"inputs": ["3\na.ba\ncb.bc\na.b"], "outputs": ["abba\ncbabc\n-1"]}
425
30
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i]. Return true if it is possible to form the array arr from pieces. Otherwise, return false.   Please complete the following python code precisely: ```python class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(arr = [15,88], pieces = [[88],[15]]) == True\n assert candidate(arr = [49,18,16], pieces = [[16,18,49]]) == False\n assert candidate(arr = [91,4,64,78], pieces = [[78],[4,64],[91]]) == True\n\n\ncheck(Solution().canFormArray)"}
132
108
coding
Solve the programming task below in a Python markdown code block. The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k × n × m, that is, it has k layers (the first layer is the upper one), each of which is a rectangle n × m with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (x, y) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment. Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1 × 1 × 1 cubes. Input The first line contains three numbers k, n, m (1 ≤ k, n, m ≤ 10) which are the sizes of the plate. Then follow k rectangles consisting of n lines each containing m characters '.' or '#', which represents the "layers" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) which are the tap's coordinates. x is the number of the line and y is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to n, columns of each layer are numbered from top to bottom by the integers from 1 to m. Output The answer should contain a single number, showing in how many minutes the plate will be filled. Examples Input 1 1 1 . 1 1 Output 1 Input 2 1 1 . # 1 1 Output 1 Input 2 2 2 .# ## .. .. 1 1 Output 5 Input 3 2 2 #. ## #. .# .. .. 1 2 Output 7 Input 3 3 3 .#. ### ##. .## ### ##. ... ... ... 1 1 Output 13
{"inputs": ["1 1 1\n\n.\n\n1 1\n", "2 1 1\n\n.\n\n#\n\n1 1\n", "1 1 10\n\n..........\n\n1 6\n", "2 2 2\n\n#.\n..\n\n.#\n#.\n\n2 1\n", "2 2 2\n\n#.\n..\n\n.#\n.#\n\n2 1\n", "2 2 2\n\n.#\n##\n\n..\n..\n\n1 1\n", "1 6 2\n\n##\n..\n##\n.#\n##\n#.\n\n6 2\n", "4 1 3\n\n...\n\n...\n\n...\n\n...\n\n1 1\n"], "outputs": ["1", "1", "10", "4", "5\n", "5", "1", "12"]}
557
219
coding
Solve the programming task below in a Python markdown code block. While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper. Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct. Input The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got. Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit. Output If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO". If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option. Examples Input 5 aca aba aba cab bac Output YES abacaba Input 4 abc bCb cb1 b13 Output NO Input 7 aaa aaa aaa aaa aaa aaa aaa Output YES aaaaaaaaa
{"inputs": ["1\nabc\n", "1\nacc\n", "1\nbac\n", "1\naac\n", "1\ncaa\n", "2\nbba\nabb\n", "2\nabc\nbga\n", "2\naba\naba\n"], "outputs": ["YES\nabc\n", "YES\nacc\n", "YES\nbac\n", "YES\naac\n", "YES\ncaa\n", "YES\nabba\n", "NO\n", "NO\n"]}
384
107
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.   Please complete the following python code precisely: ```python class Solution: def removeVowels(self, s: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(s = \"leetcodeisacommunityforcoders\") == \"ltcdscmmntyfrcdrs\"\n assert candidate(s = \"aeiou\") == \"\"\n\n\ncheck(Solution().removeVowels)"}
82
60
coding
Solve the programming task below in a Python markdown code block. You are given two integers $A$ and $B$, calculate the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true; $conc(a, b)$ is the concatenation of $a$ and $b$ (for example, $conc(12, 23) = 1223$, $conc(100, 11) = 10011$). $a$ and $b$ should not contain leading zeroes. -----Input----- The first line contains $t$ ($1 \le t \le 100$) — the number of test cases. Each test case contains two integers $A$ and $B$ $(1 \le A, B \le 10^9)$. -----Output----- Print one integer — the number of pairs $(a, b)$ such that $1 \le a \le A$, $1 \le b \le B$, and the equation $a \cdot b + a + b = conc(a, b)$ is true. -----Example----- Input 3 1 11 4 2 191 31415926 Output 1 0 1337 -----Note----- There is only one suitable pair in the first test case: $a = 1$, $b = 9$ ($1 + 9 + 1 \cdot 9 = 19$).
{"inputs": ["1\n1 59\n", "1\n1 51\n", "1\n1 374\n", "1\n2 366\n", "1\n2 692\n", "1\n2 374\n", "1\n1 182\n", "1\n1 257\n"], "outputs": ["1\n", "1\n", "2\n", "4\n", "4\n", "4\n", "2\n", "2\n"]}
349
116
coding
Solve the programming task below in a Python markdown code block. Write a function that takes an arbitrary number of strings and interlaces them (combines them by alternating characters from each string). For example `combineStrings('abc', '123')` should return `'a1b2c3'`. If the strings are different lengths the function should interlace them until each string runs out, continuing to add characters from the remaining strings. For example `combineStrings('abcd', '123')` should return `'a1b2c3d'`. The function should take any number of arguments and combine them. For example `combineStrings('abc', '123', '£$%')` should return `'a1£b2$c3%'`. **Note: if only one argument is passed return only that string. If no arguments are passed return an empty string.** Also feel free to reuse/extend the following starter code: ```python def combine_strings(*args): ```
{"functional": "_inputs = [['abc'], ['abc', '123'], ['abcd', '123'], ['abc', '1234'], ['abc', '123', '$%'], ['abcd', '123', '$%'], ['abcd', '123', '$%^&'], ['abcd', '123', '$%^&', 'qwertyuiop'], ['abcd', '123', '$%^&', 'qwertyuiop', 'X']]\n_outputs = [['abc'], ['a1b2c3'], ['a1b2c3d'], ['a1b2c34'], ['a1$b2%c3'], ['a1$b2%c3d'], ['a1$b2%c3^d&'], ['a1$qb2%wc3^ed&rtyuiop'], ['a1$qXb2%wc3^ed&rtyuiop']]\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(combine_strings(*i), o[0])"}
206
340
coding
Solve the programming task below in a Python markdown code block. Chef was recently studying the [Bitwise OR] operation, and stumbled upon the following problem: Let F(i) = 1 \ | \ 2 \ | \ 3 \ | \ \ldots \ | \ i, where | denotes bitwise OR. You are given an integer N. Find the number of distinct i such that 2 ≤ i ≤ N and F(i) = F(i-1). ------ Input Format ------ - The first line of input will contain an integer T — the number of test cases. The description of T test cases follows. - The first and only line of each test case contains an integer N. ------ Output Format ------ For each test case, output the number of distinct i such that 2 ≤ i ≤ N and F(i) = F(i-1). ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $2 ≤ N ≤ 10^{9}$ ----- Sample Input 1 ------ 3 2 3 4 ----- Sample Output 1 ------ 0 1 1 ----- explanation 1 ------ We have: $F(1) = 1$ $F(2) = 3$ $F(3) = 3$ $F(4) = 7$ Test case $1$: $F(2) \neq F(1)$. Hence the answer is $0$. Test case $2$: For $i = 3$, $F(i) = F(i-1)$. Hence the answer is $1$. Test case $3$: For $i = 3$, $F(i) = F(i-1)$. For $i = 2, 4$, $F(i) \neq F(i-1)$. Hence the answer is $1$.
{"inputs": ["3\n2\n3\n4"], "outputs": ["0\n1\n1"]}
388
22
coding
Solve the programming task below in a Python markdown code block. Tanish is the president of the chemistry club at his school. He considers everyone who doesn't like chemistry as his enemy. After years of research, he has invented a lethal poison, which he named success. Now Tanish plans to kill all his enemies with his success. Success is extremely deadly and is untraceable in small concentrations. Tanish has $\text{N}$ flasks lying on the shelf of his lab. All of these flasks contain the same volume of poison solution. The concentration of poison in the $\text{ith}$ flask is $\mathbf{a_i}$. In one move - Tanish picks up any two flasks, pours half of the contents of each of these flasks into a third initially empty flask, discards the two flasks and places the third flask (which now has the same volume of solution as all other flasks) on the shelf. He performs N-1 such moves to end up with only one flask of poison on the shelf. He wishes to perform these moves such that the concentration of poison in this flask is the minimum possible. What is the minimum concentration of poison that he can achieve? -----Input----- First line of the input contains a single integer $\text{T}$ - the number of test cases. For each test case, The first line contains a single integer $\text{N}$, the number of bottles. The second line contains N space-separated integers, the concentrations. -----Output----- For each test case, print one line containing the lowest final concentration. The output will be accepted if the absolute error is $\leq 10^{-6}$. -----Constraints----- $1 \leq \text{T} \leq 10$ $2 \leq \text{N} \leq 10^4$ $0 \leq \mathbf{a_i} \leq 10^9$ -----Sample Input----- 2 2 9 3 3 3 2 9 -----Sample Output----- 6.00000000 4.00000000 -----Explanation----- In test 1, Tanish mixes flasks 1 and 2. In test 2, he first mixes flasks 1 and 3 to get a flask of concentration 6 and then mixes this flask with flask 2 to get a flask of poison concentration 4. -----Note----- The concentration is given in the unit ppb i.e. parts per billion. 1 gram poison in $10^9$ ml solution is 1 ppb. Concentration in ppb = (Number of grams of poison / Volume of solution in ml) x $10^9$
{"inputs": ["2\n2\n9 3\n3\n3 2 9"], "outputs": ["6.00000000\n4.00000000"]}
574
46
coding
Solve the programming task below in a Python markdown code block. In this kata the function returns an array/list of numbers without its last element. The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it. Good luck! Hint: watch out for side effects. ~~~if:javascript Some good reading: [MDN Docs about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) ~~~ ~~~if:python Some good reading: [Python Lists](http://www.compciv.org/guides/python/fundamentals/lists-mutability/) ~~~ Also feel free to reuse/extend the following starter code: ```python def without_last(lst): ```
{"functional": "_inputs = [[[1, 2, 3, 4, 5]], [[9, 7, 6, 9]]]\n_outputs = [[[1, 2, 3, 4]], [[9, 7, 6]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(without_last(*i), o[0])"}
164
197
coding
Solve the programming task below in a Python markdown code block. Our bear's forest has a checkered field. The checkered field is an n × n table, the rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. Let's denote a cell of the field on the intersection of row x and column y by record (x, y). Each cell of the field contains growing raspberry, at that, the cell (x, y) of the field contains x + y raspberry bushes. The bear came out to walk across the field. At the beginning of the walk his speed is (dx, dy). Then the bear spends exactly t seconds on the field. Each second the following takes place: Let's suppose that at the current moment the bear is in cell (x, y). First the bear eats the raspberry from all the bushes he has in the current cell. After the bear eats the raspberry from k bushes, he increases each component of his speed by k. In other words, if before eating the k bushes of raspberry his speed was (dx, dy), then after eating the berry his speed equals (dx + k, dy + k). Let's denote the current speed of the bear (dx, dy) (it was increased after the previous step). Then the bear moves from cell (x, y) to cell (((x + dx - 1) mod n) + 1, ((y + dy - 1) mod n) + 1). Then one additional raspberry bush grows in each cell of the field. You task is to predict the bear's actions. Find the cell he ends up in if he starts from cell (sx, sy). Assume that each bush has infinitely much raspberry and the bear will never eat all of it. -----Input----- The first line of the input contains six space-separated integers: n, sx, sy, dx, dy, t (1 ≤ n ≤ 10^9; 1 ≤ sx, sy ≤ n;  - 100 ≤ dx, dy ≤ 100; 0 ≤ t ≤ 10^18). -----Output----- Print two integers — the coordinates of the cell the bear will end up in after t seconds. -----Examples----- Input 5 1 2 0 1 2 Output 3 1 Input 1 1 1 -1 -1 2 Output 1 1 -----Note----- Operation a mod b means taking the remainder after dividing a by b. Note that the result of the operation is always non-negative. For example, ( - 1) mod 3 = 2. In the first sample before the first move the speed vector will equal (3,4) and the bear will get to cell (4,1). Before the second move the speed vector will equal (9,10) and he bear will get to cell (3,1). Don't forget that at the second move, the number of berry bushes increased by 1. In the second sample before the first move the speed vector will equal (1,1) and the bear will get to cell (1,1). Before the second move, the speed vector will equal (4,4) and the bear will get to cell (1,1). Don't forget that at the second move, the number of berry bushes increased by 1.
{"inputs": ["5 1 2 0 1 2\n", "1 1 1 1 1 0\n", "1 1 1 1 1 0\n", "5 1 1 0 1 2\n", "5 1 2 0 1 2\n", "1 1 1 -1 -1 2\n", "2 2 1 -2 -2 5\n", "2 2 1 -2 -2 5\n"], "outputs": ["3 1", "1 1", "1 1\n", "3 5\n", "3 1\n", "1 1", "1 2", "1 2\n"]}
720
162
coding
Solve the programming task below in a Python markdown code block. You are given a sequence of integers $a_1, a_2, ..., a_N$. An element ak is said to be an average element if there are indices $i, j$ (with $i \neq j$) such that $a_k = \frac{a_i + a_j}{2}$. In the sequence 371022171537102217153 \quad 7 \quad 10 \quad 22 \quad 17 \quad 15 for $i=1, j=5$ and $k=3$, we get $a_k = \frac{a_i + a_j}{2}$. Thus $a_3 = 10$ is an average element in this sequence. You can check that $a_3$ is the only average element in this sequence. Consider the sequence 371031837103183 \quad 7 \quad 10 \quad 3 \quad 18 With $i=1, j=4$ and $k=1$ we get $a_k = \frac{a_i + a_j}{2}$. Thus $a_1=3$ is an average element. We could also choose $i=1, j=4$ and $k=4$ and get $a_k = \frac{a_i + a_j}{2}$. You can check that $a_1$ and $a_4$ are the only average elements of this sequence. On the other hand, the sequence 38111730381117303 \quad 8 \quad 11 \quad 17 \quad 30 has no average elements. Your task is to count the number of average elements in the given sequence. -----Input:----- The first line contains a single integer $N$ indicating the number of elements in the sequence. This is followed by $N$ lines containing one integer each (Line $i+1$ contains $a_i$). (You may assume that $a_i + a_j$ would not exceed MAXINT for any $i$ and $j$). -----Output:----- The output must consist of a single line containing a single integer $k$ indicating the number of average elements in the given sequence. -----Constraints:----- - You may assume that $1 \leq N \leq 10000$. - In $30 \%$ of the inputs $1 \leq N \leq 200$. - In $60 \%$ of the inputs $1 \leq N \leq 5000$. -----Sample Input 1:----- 6 3 7 10 17 22 15 -----Sample Output 1:----- 1 -----Sample Input 2:----- 5 3 7 10 3 18 -----Sample Output 2:----- 2 -----Sample Input 3;----- 5 3 8 11 17 30 -----Sample Output 3:----- 0
{"inputs": ["5\n3\n7\n10\n3\n18", "5\n3\n8\n11\n17\n30", "6\n3\n7\n10\n17\n22\n15"], "outputs": ["2", "0", "1"]}
688
65
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions: The length of the subarray is k, and All the elements of the subarray are distinct. Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0. A subarray is a contiguous non-empty sequence of elements within an array.   Please complete the following python code precisely: ```python class Solution: def maximumSubarraySum(self, nums: List[int], k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,5,4,2,9,9,9], k = 3) == 15\n assert candidate(nums = [4,4,4], k = 3) == 0\n\n\ncheck(Solution().maximumSubarraySum)"}
149
72
coding
Solve the programming task below in a Python markdown code block. Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has three representations 2 + 3 + 5 + 7 + 11 + 13, 11 + 13 + 17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20. Your mission is to write a program that reports the number of representations for the given positive integer. Input The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero. Output The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted in the output. Example Input 2 3 17 41 20 666 12 53 0 Output 1 1 2 3 0 0 1 2
{"inputs": ["2\n3\n25\n2\n4\n429\n1\n56\n0", "2\n3\n25\n2\n4\n429\n1\n94\n0", "2\n3\n25\n2\n4\n429\n0\n94\n0", "2\n3\n17\n70\n4\n429\n1\n56\n0", "2\n3\n25\n70\n4\n429\n1\n56\n0", "2\n3\n17\n70\n4\n429\n1\n85\n0", "2\n4\n17\n70\n4\n429\n1\n85\n0", "2\n3\n2\n41\n20\n666\n46\n53\n0"], "outputs": ["1\n1\n0\n1\n0\n0\n0\n1\n", "1\n1\n0\n1\n0\n0\n0\n0\n", "1\n1\n0\n1\n0\n0\n", "1\n1\n2\n0\n0\n0\n0\n1\n", "1\n1\n0\n0\n0\n0\n0\n1\n", "1\n1\n2\n0\n0\n0\n0\n0\n", "1\n0\n2\n0\n0\n0\n0\n0\n", "1\n1\n1\n3\n0\n0\n0\n2\n"]}
347
336
coding
Solve the programming task below in a Python markdown code block. Each army fighting the world war Z is denoted with a word consisting any combination of 26 alphabets. An army is a match for his/her opponent if and only if his name is an anagram of his/her opponent. Your job as a programmer is to help find whether two randomly selected members are match for each other or not. (An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. Your task is to find whether a given pair of words is anagrams to each other. Eg: Silent is anagram to listen.) Input: Number of test cases (t ≤ 10). Each test case consists of a pair of strings (length of string ≤ 1000) separated by a single space. Output: For each test case, print ‘Yes’ if they are a match to each other and ‘No’ otherwise. SAMPLE INPUT 2 listen silent mancap pacmaan SAMPLE OUTPUT Yes No
{"inputs": ["3\nman app\na b\nabcde edcba"], "outputs": ["No\nNo\nYes"]}
236
27
coding
Solve the programming task below in a Python markdown code block. Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he understood, and he's ready to face the evils of the Empire! The rebels have $s$ spaceships, each with a certain attacking power $a$. They want to send their spaceships to destroy the empire bases and steal enough gold and supplies in order to keep the rebellion alive. The empire has $b$ bases, each with a certain defensive power $d$, and a certain amount of gold $g$. A spaceship can attack all the bases which have a defensive power less than or equal to its attacking power. If a spaceship attacks a base, it steals all the gold in that base. The rebels are still undecided which spaceship to send out first, so they asked for the Doctor's help. They would like to know, for each spaceship, the maximum amount of gold it can steal. -----Input----- The first line contains integers $s$ and $b$ ($1 \leq s, b \leq 10^5$), the number of spaceships and the number of bases, respectively. The second line contains $s$ integers $a$ ($0 \leq a \leq 10^9$), the attacking power of each spaceship. The next $b$ lines contain integers $d, g$ ($0 \leq d \leq 10^9$, $0 \leq g \leq 10^4$), the defensive power and the gold of each base, respectively. -----Output----- Print $s$ integers, the maximum amount of gold each spaceship can steal, in the same order as the spaceships are given in the input. -----Example----- Input 5 4 1 3 5 2 4 0 1 4 2 2 8 9 4 Output 1 9 11 9 11 -----Note----- The first spaceship can only attack the first base. The second spaceship can attack the first and third bases. The third spaceship can attack the first, second and third bases.
{"inputs": ["1 1\n88372488\n74842436 22\n", "1 1\n88372488\n529378808 22\n", "1 1\n93269973\n529378808 22\n", "1 1\n93269973\n529378808 14\n", "1 1\n93269973\n858288489 14\n", "1 1\n93269973\n360212747 22\n", "1 1\n88372488\n319157478 348\n", "1 1\n88372488\n319157478 348\n"], "outputs": ["22\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0 "]}
506
264
coding
Solve the programming task below in a Python markdown code block. Tomya is a girl. She loves Chef Ciel very much. Tomya like a positive integer p, and now she wants to get a receipt of Ciel's restaurant whose total price is exactly p. The current menus of Ciel's restaurant are shown the following table. Name of Menupriceeel flavored water1deep-fried eel bones2clear soup made with eel livers4grilled eel livers served with grated radish8savory egg custard with eel16eel fried rice (S)32eel fried rice (L)64grilled eel wrapped in cooked egg128eel curry rice256grilled eel over rice512deluxe grilled eel over rice1024eel full-course2048 Note that the i-th menu has the price 2i-1 (1 ≤ i ≤ 12). Since Tomya is a pretty girl, she cannot eat a lot. So please find the minimum number of menus whose total price is exactly p. Note that if she orders the same menu twice, then it is considered as two menus are ordered. (See Explanations for details) -----Input----- The first line contains an integer T, the number of test cases. Then T test cases follow. Each test case contains an integer p. -----Output----- For each test case, print the minimum number of menus whose total price is exactly p. -----Constraints----- 1 ≤ T ≤ 5 1 ≤ p ≤ 100000 (105) There exists combinations of menus whose total price is exactly p. -----Sample Input----- 4 10 256 255 4096 -----Sample Output----- 2 1 8 2 -----Explanations----- In the first sample, examples of the menus whose total price is 10 are the following: 1+1+1+1+1+1+1+1+1+1 = 10 (10 menus) 1+1+1+1+1+1+1+1+2 = 10 (9 menus) 2+2+2+2+2 = 10 (5 menus) 2+4+4 = 10 (3 menus) 2+8 = 10 (2 menus) Here the minimum number of menus is 2. In the last sample, the optimal way is 2048+2048=4096 (2 menus). Note that there is no menu whose price is 4096.
{"inputs": ["4\n5\n23\n1\n1090", "4\n7\n23\n1\n1090", "4\n8\n73\n94\n2919", "4\n8\n73\n12\n2919", "4\n6\n73\n12\n2919", "4\n3\n73\n94\n2919", "4\n15\n18\n12\n689", "4\n5\n23\n12\n1090"], "outputs": ["2\n4\n1\n3\n", "3\n4\n1\n3\n", "1\n3\n5\n8\n", "1\n3\n2\n8\n", "2\n3\n2\n8\n", "2\n3\n5\n8\n", "4\n2\n2\n5\n", "2\n4\n2\n3\n"]}
556
212
coding
Solve the programming task below in a Python markdown code block. Chef has an old machine if the chef enters any natural number, the machine will display 1, 2, …n, n-1, n-2, n-3,…1 series and in next line prints sum of cubes of each number in the series. Chef wants to create a computer program which can replicate the functionality of the machine. Help the chef to code. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, $N$. -----Output:----- For each test case, output in a single line answer. -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq N \leq 50$ -----Sample Input:----- 2 1 3 -----Sample Output:----- 1 45 -----EXPLANATION:----- For 2) series will be 1, 2, 3, 2, 1 and the sum will be = 1 + 8 + 27 + 8+ 1
{"inputs": ["2\n1\n3"], "outputs": ["1\n45"]}
246
19
coding
Solve the programming task below in a Python markdown code block. Gildong's town has a train system that has $100$ trains that travel from the bottom end to the top end and $100$ trains that travel from the left end to the right end. The trains starting from each side are numbered from $1$ to $100$, respectively, and all trains have the same speed. Let's take a look at the picture below. The train system can be represented as coordinates on a 2D plane. The $i$-th train starting at the bottom end is initially at $(i,0)$ and will be at $(i,T)$ after $T$ minutes, and the $i$-th train starting at the left end is initially at $(0,i)$ and will be at $(T,i)$ after $T$ minutes. All trains arrive at their destinations after $101$ minutes. However, Gildong found that some trains scheduled to depart at a specific time, simultaneously, are very dangerous. At this time, $n$ trains are scheduled to depart from the bottom end and $m$ trains are scheduled to depart from the left end. If two trains are both at $(x,y)$ at the same time for some $x$ and $y$, they will crash into each other. Therefore, he is asking you to find the minimum number of trains that should be cancelled to prevent all such crashes. -----Input----- Each test contains one or more test cases. The first line contains the number of test cases $t$ ($1 \le t \le 100$). Each test case contains three lines. The first line of each test case consists of two integers $n$ and $m$ ($1 \le n, m \le 100$) — the number of trains scheduled to depart from the bottom end, and the number of trains scheduled to depart from the left end, respectively. The second line of each test case contains $n$ integers. Each integer is a train number that is scheduled to start from the bottom end. The numbers are given in strictly increasing order, and are between $1$ and $100$, inclusive. The third line of each test case contains $m$ integers. Each integer is a train number that is scheduled to start from the left end. The numbers are given in strictly increasing order, and are between $1$ and $100$, inclusive. -----Output----- For each test case, print a single integer: the minimum number of trains that should be canceled in order to prevent all crashes. -----Examples----- Input 3 1 2 1 3 4 3 2 1 3 4 2 4 9 14 2 7 16 28 33 57 59 86 99 3 9 14 19 25 26 28 35 41 59 85 87 99 100 Output 0 1 3 -----Note----- In the first case, we can show that there will be no crashes if the current schedule is followed. Therefore, the answer is zero. In the second case, at $T=4$, there will be a crash, as can be seen in the picture below. We can prove that after canceling one of these trains, the remaining trains will not crash. Therefore, the answer is one.
{"inputs": ["3\n1 2\n1\n1 4\n3 2\n2 3 4\n3 4\n9 14\n2 7 9 28 33 12 59 92 99\n6 9 14 19 8 26 5 35 41 68 85 87 99 100\n", "3\n1 2\n1\n1 4\n3 2\n2 3 4\n3 4\n9 14\n2 7 9 28 33 12 59 92 99\n6 9 14 19 8 45 5 35 41 68 85 87 99 100\n", "3\n1 2\n1\n1 4\n3 2\n2 3 4\n3 4\n9 14\n2 7 9 28 33 12 59 92 99\n6 9 14 19 8 45 5 35 41 61 85 87 99 100\n", "3\n1 2\n2\n1 4\n3 2\n1 2 4\n3 4\n9 14\n2 7 16 28 33 12 59 92 99\n6 9 14 3 8 26 5 35 55 42 85 87 99 100\n", "3\n1 2\n2\n1 6\n3 2\n1 3 4\n3 4\n9 14\n2 7 16 28 4 12 59 92 99\n6 9 23 19 8 26 5 69 35 58 85 87 99 100\n", "3\n1 2\n2\n1 4\n3 2\n1 3 4\n3 4\n9 14\n2 7 16 28 33 12 59 92 99\n6 9 14 19 8 26 5 69 41 68 85 87 99 100\n", "3\n1 2\n2\n1 4\n3 2\n1 3 4\n3 4\n9 14\n2 7 16 28 33 12 59 92 99\n6 9 14 19 8 26 5 35 55 42 85 87 10 100\n", "3\n1 2\n2\n1 4\n3 2\n1 2 4\n3 4\n9 14\n2 7 16 28 33 12 59 92 99\n6 9 14 19 8 26 5 69 35 58 85 87 99 100\n"], "outputs": ["1\n2\n2\n", "1\n2\n2\n", "1\n2\n2\n", "0\n1\n1\n", "0\n2\n1\n", "0\n2\n1\n", "0\n2\n0\n", "0\n1\n1\n"]}
730
841
coding
Solve the programming task below in a Python markdown code block. Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti. You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only. Input The first line contains single integer n (1 ≤ n ≤ 105) — the number of strings Ivan remembers. The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi, 1, xi, 2, ..., xi, ki in increasing order — positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1 ≤ xi, j ≤ 106, 1 ≤ ki ≤ 106, and the sum of all ki doesn't exceed 106. The strings ti can coincide. It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists. Output Print lexicographically minimal string that fits all the information Ivan remembers. Examples Input 3 a 4 1 3 5 7 ab 2 1 5 ca 1 4 Output abacaba Input 1 a 1 3 Output aaa Input 3 ab 1 1 aba 1 3 ab 2 3 5 Output ababab
{"inputs": ["1\na 1 1\n", "1\na 1 3\n", "2\naba 1 1\nb 1 2\n", "3\nab 1 1\naba 1 3\nab 2 3 5\n", "3\na 4 1 3 5 7\nab 2 1 5\nca 1 4\n", "4\na 2 1 10\na 3 1 2 9\na 2 3 8\na 2 4 7\n", "4\na 2 1 10\na 3 1 2 9\na 2 3 8\na 2 4 3\n", "4\na 2 1 3\na 3 1 1 9\na 2 3 15\na 2 4 3\n"], "outputs": ["a\n", "aaa\n", "aba\n", "ababab\n", "abacaba\n", "aaaaaaaaaa\n", "aaaaaaaaaa\n", "aaaaaaaaaaaaaaa\n"]}
447
253
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time. The ith day is a good day to rob the bank if: There are at least time days before and after the ith day, The number of guards at the bank for the time days before i are non-increasing, and The number of guards at the bank for the time days after i are non-decreasing. More formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]. Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.   Please complete the following python code precisely: ```python class Solution: def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(security = [5,3,3,3,5,6,2], time = 2) == [2,3]\n assert candidate(security = [1,1,1,1,1], time = 0) == [0,1,2,3,4]\n assert candidate(security = [1,2,3,4,5,6], time = 2) == []\n\n\ncheck(Solution().goodDaysToRobBank)"}
267
118
coding
Solve the programming task below in a Python markdown code block. You are given a book with n chapters. Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list. Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter. Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 2⋅10^4). The first line of each test case contains a single integer n (1 ≤ n ≤ 2⋅10^5) — number of chapters. Then n lines follow. The i-th line begins with an integer k_i (0 ≤ k_i ≤ n-1) — number of chapters required to understand the i-th chapter. Then k_i integers a_{i,1}, a_{i,2}, ..., a_{i, k_i} (1 ≤ a_{i, j} ≤ n, a_{i, j} ≠ i, a_{i, j} ≠ a_{i, l} for j ≠ l) follow — the chapters required to understand the i-th chapter. It is guaranteed that the sum of n and sum of k_i over all testcases do not exceed 2⋅10^5. Output For each test case, if the entire book can be understood, print how many times you will read it, otherwise print -1. Example Input 5 4 1 2 0 2 1 4 1 2 5 1 5 1 1 1 2 1 3 1 4 5 0 0 2 1 2 1 2 2 2 1 4 2 2 3 0 0 2 3 2 5 1 2 1 3 1 4 1 5 0 Output 2 -1 1 2 5 Note In the first example, we will understand chapters \{2, 4\} in the first reading and chapters \{1, 3\} in the second reading of the book. In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book. In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go. In the fourth example, we will understand chapters \{2, 3, 4\} in the first reading and chapter 1 in the second reading of the book. In the fifth example, we will understand one chapter in every reading from 5 to 1.
{"inputs": ["5\n4\n1 2\n0\n2 1 4\n1 2\n5\n1 5\n1 1\n1 1\n1 3\n1 4\n5\n0\n0\n2 1 2\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 2\n1 3\n1 4\n1 5\n0\n", "5\n4\n1 2\n0\n2 1 4\n1 2\n5\n1 5\n1 1\n1 1\n1 3\n1 4\n5\n0\n0\n2 1 2\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 2\n1 3\n1 4\n1 3\n0\n", "5\n4\n1 2\n0\n2 1 4\n1 2\n5\n1 5\n1 1\n1 2\n1 3\n1 4\n5\n0\n0\n2 1 4\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 2\n1 3\n1 4\n1 5\n0\n", "5\n4\n1 2\n0\n2 1 4\n1 3\n5\n1 5\n1 1\n1 2\n1 3\n1 4\n5\n0\n0\n2 1 4\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 2\n1 3\n1 4\n1 5\n0\n", "5\n4\n1 2\n0\n2 1 4\n1 3\n5\n1 5\n1 1\n1 2\n1 3\n1 4\n5\n0\n0\n2 1 4\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 4\n1 3\n1 4\n1 5\n0\n", "5\n4\n1 2\n0\n2 1 4\n1 3\n5\n1 5\n1 1\n1 1\n1 1\n1 4\n5\n0\n0\n2 1 2\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 2\n1 3\n1 4\n1 3\n0\n", "5\n4\n1 2\n0\n2 1 4\n1 2\n5\n1 5\n1 1\n1 1\n1 1\n1 4\n5\n0\n0\n2 1 2\n1 2\n2 2 1\n4\n2 2 4\n0\n0\n2 3 1\n5\n1 2\n1 3\n1 4\n1 3\n0\n", "5\n4\n1 2\n0\n2 1 4\n1 2\n5\n1 5\n1 2\n1 1\n1 1\n1 4\n5\n0\n0\n2 1 4\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 1\n1 3\n1 4\n1 3\n0\n"], "outputs": ["2\n-1\n1\n2\n5\n", "2\n-1\n1\n2\n-1\n", "2\n-1\n2\n2\n5\n", "-1\n-1\n2\n2\n5\n", "-1\n-1\n2\n2\n4\n", "-1\n-1\n1\n2\n-1\n", "2\n-1\n1\n-1\n-1\n", "2\n-1\n2\n2\n-1\n"]}
652
947
coding
Solve the programming task below in a Python markdown code block. Assume we take a number `x` and perform any one of the following operations: ```Pearl a) Divide x by 3 (if it is divisible by 3), or b) Multiply x by 2 ``` After each operation, we write down the result. If we start with `9`, we can get a sequence such as: ``` [9,3,6,12,4,8] -- 9/3=3 -> 3*2=6 -> 6*2=12 -> 12/3=4 -> 4*2=8 ``` You will be given a shuffled sequence of integers and your task is to reorder them so that they conform to the above sequence. There will always be an answer. ``` For the above example: solve([12,3,9,4,6,8]) = [9,3,6,12,4,8]. ``` More examples in the test cases. Good luck! Also feel free to reuse/extend the following starter code: ```python def solve(arr): ```
{"functional": "_inputs = [[[1, 3]], [[4, 2]], [[12, 3, 9, 4, 6, 8]], [[4, 8, 6, 3, 12, 9]], [[558, 744, 1488, 279, 2232, 1116]], [[9, 1, 3]], [[3000, 9000]], [[4, 1, 2]], [[10, 5]]]\n_outputs = [[[3, 1]], [[2, 4]], [[9, 3, 6, 12, 4, 8]], [[9, 3, 6, 12, 4, 8]], [[279, 558, 1116, 2232, 744, 1488]], [[9, 3, 1]], [[9000, 3000]], [[1, 2, 4]], [[5, 10]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(solve(*i), o[0])"}
246
388
coding
Solve the programming task below in a Python markdown code block. Alice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a gift — a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden. Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is Ti, each pile will reduce its volume by Ti. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other. Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day. You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day. Input The first line contains a single integer N (1 ≤ N ≤ 105) — the number of days. The second line contains N integers V1, V2, ..., VN (0 ≤ Vi ≤ 109), where Vi is the initial size of a snow pile made on the day i. The third line contains N integers T1, T2, ..., TN (0 ≤ Ti ≤ 109), where Ti is the temperature on the day i. Output Output a single line with N integers, where the i-th integer represents the total volume of snow melted on day i. Examples Input 3 10 10 5 5 7 2 Output 5 12 4 Input 5 30 25 20 15 10 9 10 12 4 13 Output 9 20 35 11 25 Note In the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day.
{"inputs": ["1\n4\n5\n", "1\n5\n4\n", "1\n5\n5\n", "1\n6\n5\n", "1\n5\n0\n", "1\n6\n6\n", "1\n2\n6\n", "1\n2\n1\n"], "outputs": ["4 ", "4 ", "5 ", "5\n", "0\n", "6\n", "2\n", "1\n"]}
540
99
coding
Solve the programming task below in a Python markdown code block. For the New Year, Polycarp decided to send postcards to all his $n$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $w \times h$, which can be cut into pieces. Polycarp can cut any sheet of paper $w \times h$ that he has in only two cases: If $w$ is even, then he can cut the sheet in half and get two sheets of size $\frac{w}{2} \times h$; If $h$ is even, then he can cut the sheet in half and get two sheets of size $w \times \frac{h}{2}$; If $w$ and $h$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above. After cutting a sheet of paper, the total number of sheets of paper is increased by $1$. Help Polycarp to find out if he can cut his sheet of size $w \times h$ at into $n$ or more pieces, using only the rules described above. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. Each test case consists of one line containing three integers $w$, $h$, $n$ ($1 \le w, h \le 10^4, 1 \le n \le 10^9$) — the width and height of the sheet Polycarp has and the number of friends he needs to send a postcard to. -----Output----- For each test case, output on a separate line: "YES", if it is possible to cut a sheet of size $w \times h$ into at least $n$ pieces; "NO" otherwise. You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive). -----Examples----- Input 5 2 2 3 3 3 2 5 10 2 11 13 1 1 4 4 Output YES NO YES YES YES -----Note----- In the first test case, you can first cut the $2 \times 2$ sheet into two $2 \times 1$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $1 \times 1$. We can choose any three of them and send them to our friends. In the second test case, a $3 \times 3$ sheet cannot be cut, so it is impossible to get two sheets. In the third test case, you can cut a $5 \times 10$ sheet into two $5 \times 5$ sheets. In the fourth test case, there is no need to cut the sheet, since we only need one sheet. In the fifth test case, you can first cut the $1 \times 4$ sheet into two $1 \times 2$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $1 \times 1$.
{"inputs": ["1\n1 001 1334\n", "1\n2 001 1334\n", "1\n2 011 1334\n", "1\n2 111 1334\n", "1\n98 101 9313\n", "1\n671 011 4442\n", "1\n671 011 7638\n", "1\n136 011 7638\n"], "outputs": ["NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
703
165
coding
Solve the programming task below in a Python markdown code block. You are given an array $a_1, a_2, \dots , a_n$. Array is good if for each pair of indexes $i < j$ the condition $j - a_j \ne i - a_i$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option). For example, if $a = [1, 1, 3, 5]$, then shuffled arrays $[1, 3, 5, 1]$, $[3, 5, 1, 1]$ and $[5, 3, 1, 1]$ are good, but shuffled arrays $[3, 1, 5, 1]$, $[1, 1, 3, 5]$ and $[1, 1, 5, 3]$ aren't. It's guaranteed that it's always possible to shuffle an array to meet this condition. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. The first line of each test case contains one integer $n$ ($1 \le n \le 100$) — the length of array $a$. The second line of each test case contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le 100$). -----Output----- For each test case print the shuffled version of the array $a$ which is good. -----Example----- Input 3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 Output 7 1 5 1 3 2 4 6 1 3 5
{"inputs": ["1\n3\n4 2 1\n", "1\n3\n4 2 1\n", "1\n3\n6 2 1\n", "1\n8\n1 2 3 4 5 6 7 8\n", "1\n8\n1 2 3 4 5 6 7 8\n", "1\n8\n1 2 2 4 5 6 7 8\n", "1\n8\n1 2 4 4 5 6 7 8\n", "1\n8\n1 2 2 4 5 6 7 6\n"], "outputs": ["4 2 1\n", "4 2 1\n", "6 2 1\n", "8 7 6 5 4 3 2 1\n", "8 7 6 5 4 3 2 1\n", "8 7 6 5 4 2 2 1\n", "8 7 6 5 4 4 2 1\n", "7 6 6 5 4 2 2 1\n"]}
413
266
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian as well. Mike and his friend Tom are playing a very interesting game right now. Here is the description of the game: Initially, there is a positive integer N written on the desk, which is strictly greater than 1; Mike makes the first move, then players make moves alternatively; On each move the current player can either decrease the number on the desk by 1, or divide it by one of it's divisors except itself and 1; It's forbidden to decrease the number if it's equal to 1; If the current player can't make a move, then he loses. In other words, if there is "1" written on the desk right before his move, then he loses. You are given a number N. You need to determine the winner of the game, if N is the number written of the desk initially. You may assume, that both players play optimally. ------ Input ------ There are multiple test cases in the input. The first line of the input contains one integer T, denoting the number of test cases in the input. The next T lines contain one integer each, denoting the initial number of the game. All the test cases are independent and must be considered separately!   ------ Output ------ Your output should contain exactly T lines, each contains the name of the winner(Mike or Tom) of the corresponding game. You should output the verdicts of the games in the order they appear in the input.   ------ Constraints ------ 1 ≤ T ≤ 10 000; 2 ≤ N ≤ 10^{8}, for each test case appeared in the input. ------ Example ------ Input: 4 5 3 2 4 Output: Tom Tom Mike Mike
{"inputs": ["4 \n5 \n3 \n2 \n4"], "outputs": ["Tom\nTom\nMike\nMike"]}
386
30
coding
Solve the programming task below in a Python markdown code block. Who's interested in football? Rayne Wooney has been one of the top players for his football club for the last few years. But unfortunately, he got injured during a game a few months back and has been out of play ever since. He's got proper treatment and is eager to go out and play for his team again. Before doing that, he has to prove to his fitness to the coach and manager of the team. Rayne has been playing practice matches for the past few days. He's played N practice matches in all. He wants to convince the coach and the manager that he's improved over time and that his injury no longer affects his game. To increase his chances of getting back into the team, he's decided to show them stats of any 2 of his practice games. The coach and manager will look into the goals scored in both the games and see how much he's improved. If the number of goals scored in the 2nd game(the game which took place later) is greater than that in 1st, then he has a chance of getting in. Tell Rayne what is the maximum improvement in terms of goal difference that he can show to maximize his chances of getting into the team. If he hasn't improved over time, he's not fit to play. Scoring equal number of goals in 2 matches will not be considered an improvement. Also, he will be declared unfit if he doesn't have enough matches to show an improvement. -----Input:----- The first line of the input contains a single integer T, the number of test cases. Each test case begins with a single integer N, the number of practice matches Rayne has played. The next line contains N integers. The ith integer, gi, on this line represents the number of goals Rayne scored in his ith practice match. The matches are given in chronological order i.e. j > i means match number j took place after match number i. -----Output:----- For each test case output a single line containing the maximum goal difference that Rayne can show to his coach and manager. If he's not fit yet, print "UNFIT". -----Constraints:----- 1<=T<=10 1<=N<=100000 0<=gi<=1000000 (Well, Rayne's a legend! You can expect him to score so many goals!) -----Example:-----Input: 3 6 3 7 1 4 2 4 5 5 4 3 2 1 5 4 3 2 2 3 Output: 4 UNFIT 1 Explanation: In the first test case, Rayne can choose the first and second game. Thus he gets a difference of 7-3=4 goals. Any other pair would give him a lower improvement. In the second test case, Rayne has not been improving in any match. Thus he's declared UNFIT. Note: Large input data. Use faster I/O methods. Prefer scanf,printf over cin/cout.
{"inputs": ["3\n6\n3 7 1 4 2 4\n5\n5 4 3 2 1\n5\n4 3 2 2 3"], "outputs": ["4\nUNFIT\n1"]}
640
55
coding
Solve the programming task below in a Python markdown code block. Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right. Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one. At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls. He asks you to help to find the initial arrangement of the balls in the boxes. -----Input----- The first line of the input contains two integers n and x (2 ≤ n ≤ 10^5, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a_1, a_2, ..., a_{n}, where integer a_{i} (0 ≤ a_{i} ≤ 10^9, a_{x} ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. -----Output----- Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them. -----Examples----- Input 4 4 4 3 1 6 Output 3 2 5 4 Input 5 2 3 2 0 2 7 Output 2 1 4 1 6 Input 3 3 2 3 1 Output 1 2 3
{"inputs": ["3 3\n2 3 1\n", "3 3\n4 3 1\n", "3 3\n2 3 1\n", "4 4\n4 3 1 6\n", "4 4\n4 3 1 6\n", "5 2\n3 2 0 2 7\n", "5 4\n3 1 3 1 3\n", "5 4\n3 1 3 1 3\n"], "outputs": ["1 2 3 ", "3 2 3\n", "1 2 3\n", "3 2 5 4 ", "3 2 5 4\n", "2 1 4 1 6 ", "2 0 2 5 2 ", "2 0 2 5 2\n"]}
737
194
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where: difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]). Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0. Return the maximum profit we can achieve after assigning the workers to the jobs.   Please complete the following python code precisely: ```python class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]) == 100\n assert candidate(difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]) == 0\n\n\ncheck(Solution().maxProfitAssignment)"}
204
117
coding
Solve the programming task below in a Python markdown code block. Did you ever hear about 'Dragon Food' ? Its used to refer to the chocolates bought for your loved ones :). Po offers dragon food to master Shifu, who is a famous cook in the valley of food. In return, Shifu hands over the dragon scroll to Po, which is said to hold the ingredients of the secret recipe. To open the dragon scroll, one has to solve the following puzzle. 1. Consider a N-bit integer A. We call an integer A' as shuffle-A, if A' can be obtained by shuffling the bits of A in its binary representation. For eg. if N = 5 and A = 6 = (00110)_{2}, A' can be any 5-bit integer having exactly two 1s in it i.e., any of (00011)_{2}, (00101)_{2}, (00110)_{2}, (01010)_{2}, ...., (11000)_{2}. 2. Given two N-bit integers A and B, find the maximum possible value of (A' xor B') where A' is a shuffle-A, B' is a shuffle-B and xor is the bit-wise xor operator. Given N, A and B, please help Po in opening the dragon scroll. Notes 1. xor operator takes two bit strings of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 OR only the second bit is 1, but will be 0 if both are 1 or both are 0. For eg: 5 (0101) xor 3(0011) = 6(0110). In most languages it is represented using ^ symbol. 5 ^ 3 = 6. 2. If the integer actually needs less than N bits to represent in binary, append sufficient number of leading 0 bits. For eg. as shown in the problem statement for N = 5, A = 6 = (00110)_{2} ------ Input ------ First line contains an integer T ( number of test cases, around 100 ). T cases follow, each having N A B in a single line, separated by a space. ( 1 ≤ N ≤ 30, 0 ≤ A,B < 2^{N} ) ------ Output ------ For each case, output the maximum possible value of (shuffle-A xor shuffle-B) in a separate line. ----- Sample Input 1 ------ 3 3 5 4 5 0 1 4 3 7 ----- Sample Output 1 ------ 7 16 14 ----- explanation 1 ------ Case 1: 5 and 4 as 3-bit binary strings are (101)2 and (100)2 respectively. After shuffling, xor can be maximum for (110)2 ^ (001)2 = (111)2 = 7 Case 2: Maximum Possible result can be for (00000)2 ^ (10000)2 = (10000)2 = 16 Case 3: Maximum Possible result can be for (0011)2 ^ (1101)2 = (1110)2 = 14
{"inputs": ["3\n3 5 4\n5 0 1\n4 3 7", "3\n3 5 4\n2 0 1\n4 3 7", "3\n3 5 4\n2 0 1\n4 3 0", "3\n3 5 4\n1 0 1\n4 3 6", "3\n3 5 0\n2 0 1\n4 3 7", "3\n3 5 0\n3 0 1\n4 3 7", "3\n5 5 0\n3 0 1\n4 3 7", "3\n5 5 0\n3 1 1\n4 3 7"], "outputs": ["7\n16\n14", "7\n2\n14\n", "7\n2\n12\n", "7\n1\n15\n", "6\n2\n14\n", "6\n4\n14\n", "24\n4\n14\n", "24\n6\n14\n"]}
745
248
coding
Solve the programming task below in a Python markdown code block. You have $N$ items that you want to put them into a knapsack. Item $i$ has value $v_i$, weight $w_i$ and limitation $m_i$. You want to find a subset of items to put such that: * The total value of the items is as large as possible. * The items have combined weight at most $W$, that is capacity of the knapsack. * You can select at most $m_i$ items for $i$-th item. Find the maximum total value of items in the knapsack. Constraints * $1 \le N \le 50$ * $1 \le v_i \le 50$ * $1 \le w_i \le 10^9$ * $1 \le m_i \le 10^9$ * $1 \le W \le 10^9$ Input $N$ $W$ $v_1$ $w_1$ $m_1$ $v_2$ $w_2$ $m_2$ : $v_N$ $w_N$ $m_N$ The first line consists of the integers $N$ and $W$. In the following $N$ lines, the value, weight and limitation of the $i$-th item are given. Output Print the maximum total values of the items in a line. Examples Input 4 8 4 3 2 2 1 1 1 2 4 3 2 2 Output 12 Input 2 100 1 1 100 2 1 50 Output 150 Input 5 1000000000 3 5 1000000000 7 6 1000000000 4 4 1000000000 6 8 1000000000 2 5 1000000000 Output 1166666666
{"inputs": ["2 100\n1 1 100\n2 1 50", "4 8\n4 3 2\n2 1 1\n1 2 4\n2 2 2", "4 8\n4 3 2\n2 1 1\n1 2 1\n3 2 2", "4 8\n4 3 2\n0 1 1\n1 2 4\n2 3 2", "4 8\n4 3 2\n2 2 1\n1 2 4\n3 2 3", "4 8\n6 3 2\n2 3 1\n1 2 4\n3 2 3", "4 8\n8 3 2\n2 1 1\n1 2 4\n3 2 2", "4 8\n0 3 2\n0 1 1\n1 2 4\n2 3 1"], "outputs": ["150", "10\n", "12\n", "9\n", "11\n", "15\n", "19\n", "4\n"]}
472
269
coding
Solve the programming task below in a Python markdown code block. The factorial of the integer $n$, written $n!$, is defined as: $n!=n\times(n-1)\times(n-2)\times\text{}\cdots\times3\times2\times1$ Calculate and print the factorial of a given integer. For example, if $n=30$, we calculate $30\times29\times28\times\text{...}\times2\times1$ and get $265252859812191058636308480000000$. Function Description Complete the extraLongFactorials function in the editor below. It should print the result and return. extraLongFactorials has the following parameter(s): n: an integer Note: Factorials of $n>20$ can't be stored even in a $64-bit$ long long variable. Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle big integers, but we need to write additional code in C/C++ to handle huge values. We recommend solving this challenge using BigIntegers. Input Format Input consists of a single integer $n$ Constraints $1\leq n\leq100$ Output Format Print the factorial of $n$. Sample Input $25$ Sample Output $1551121004330985984000000$ Explanation $25!=25\times24\times23\times\text{...}\times3\times2\times1$
{"inputs": ["25\n"], "outputs": ["15511210043330985984000000\n"]}
371
40
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. There are k workers who want to move n boxes from the right (old) warehouse to the left (new) warehouse. You are given the two integers n and k, and a 2D integer array time of size k x 4 where time[i] = [righti, picki, lefti, puti]. The warehouses are separated by a river and connected by a bridge. Initially, all k workers are waiting on the left side of the bridge. To move the boxes, the ith worker can do the following: Cross the bridge to the right side in righti minutes. Pick a box from the right warehouse in picki minutes. Cross the bridge to the left side in lefti minutes. Put the box into the left warehouse in puti minutes. The ith worker is less efficient than the jth worker if either condition is met: lefti + righti > leftj + rightj lefti + righti == leftj + rightj and i > j The following rules regulate the movement of the workers through the bridge: Only one worker can use the bridge at a time. When the bridge is unused prioritize the least efficient worker on the right side to cross. If there are no workers on the right side, prioritize the least efficient worker on the left side to cross. If enough workers have already been dispatched from the left side to pick up all the remaining boxes, no more workers will be sent from the left side. Return the elapsed minutes at which the last box reaches the left side of the bridge.   Please complete the following python code precisely: ```python class Solution: def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]) == 6\n assert candidate(n = 3, k = 2, time = [[1,9,1,8],[10,10,10,10]]) == 50\n\n\ncheck(Solution().findCrossingTime)"}
370
106
coding
Solve the programming task below in a Python markdown code block. Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money. Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance. Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift. -----Input----- The single line contains integer n (10 ≤ |n| ≤ 10^9) — the state of Ilya's bank account. -----Output----- In a single line print an integer — the maximum state of the bank account that Ilya can get. -----Examples----- Input 2230 Output 2230 Input -10 Output 0 Input -100003 Output -10000 -----Note----- In the first test sample Ilya doesn't profit from using the present. In the second test sample you can delete digit 1 and get the state of the account equal to 0.
{"inputs": ["10\n", "46\n", "46\n", "10\n", "20\n", "17\n", "16\n", "18\n"], "outputs": ["10\n", "46\n", "46\n", "10\n", "20\n", "17\n", "16\n", "18\n"]}
408
86
coding
Solve the programming task below in a Python markdown code block. Read problems statements in mandarin chinese, russian and vietnamese as well. Fehc is Chef's best friend. They grew up with each other, and often help each other with competitive programming. Chef is participating in a programming contest prepared by Fehc and finds the following problem in Fehc's problem set: given a string s[1..N], count the number of pairs of indices 1 ≤ i ≤ j ≤ N such that s[i..j] is palindrome and j-i is even. The characters that may appear in s are 0, 1, 2, ..., 10^{9}. Chef doesn't know the solution, but he knows Fehc's habits of creating test data. When preparing data for a string problem, Fehc always generates a string of N 0's, and replaces some of the 0's by other characters. Thus, Chef assumes that there are only K nonzero characters in s, and K is usually much smaller than N. Given this useful information, can you help Chef solve this problem? ------ Input ------ The first line of input contains one integer T denoting the number of test cases. For each test case, the first line contains two space-separated integers N and K. K lines follow; the i-th of these lines contains two space-separated integers p_{i} and q_{i}, meaning that the i-th nonzero character is s[p_{i}] = q_{i}. ------ Output ------ For each test case, output one integer denoting the answer to the problem. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N ≤ 10^{9}$ $0 ≤ K ≤ 10^{5}$ $1 ≤ p_{1} < p_{2} < ... < p_{K} ≤ N$ $1 ≤ q_{i} ≤ 10^{9}$ Subtask #1 (9 points): $N ≤ 1000$ Subtask #2 (14 points): $N ≤ 10^{5}$ Subtask #3 (21 points): $K ≤ 1000$ Subtask #4 (56 points): $original constraints$ ----- Sample Input 1 ------ 3 7 2 5 1 6 1 7 3 2 1 4 2 6 1 10 0 ----- Sample Output 1 ------ 9 12 30 ----- explanation 1 ------ Example case 1: s={0,0,0,0,1,1,0}. The 9 pairs (i,j) are: (1,1), (2,2), ..., (7,7), (1,3) and (2,4). Example case 2: s={0,1,0,2,0,1,0}. Example case 3: s={0,0,0,0,0,0,0,0,0,0}.
{"inputs": ["3\n7 2\n5 1\n6 1\n7 3\n2 1\n4 2\n6 1\n10 0"], "outputs": ["9\n12\n30"]}
671
51
coding
Solve the programming task below in a Python markdown code block. The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symbol is '1' if students will write the contest in the i-th day and '0' if they will have a day off. At the last moment Gleb said that the camp will be the most productive if it runs with the schedule t (which can be described in the same format as schedule s). Since the number of days in the current may be different from number of days in schedule t, Gleb required that the camp's schedule must be altered so that the number of occurrences of t in it as a substring is maximum possible. At the same time, the number of contest days and days off shouldn't change, only their order may change. Could you rearrange the schedule in the best possible way? Input The first line contains string s (1 ⩽ |s| ⩽ 500 000), denoting the current project of the camp's schedule. The second line contains string t (1 ⩽ |t| ⩽ 500 000), denoting the optimal schedule according to Gleb. Strings s and t contain characters '0' and '1' only. Output In the only line print the schedule having the largest number of substrings equal to t. Printed schedule should consist of characters '0' and '1' only and the number of zeros should be equal to the number of zeros in s and the number of ones should be equal to the number of ones in s. In case there multiple optimal schedules, print any of them. Examples Input 101101 110 Output 110110 Input 10010110 100011 Output 01100011 Input 10 11100 Output 01 Note In the first example there are two occurrences, one starting from first position and one starting from fourth position. In the second example there is only one occurrence, which starts from third position. Note, that the answer is not unique. For example, if we move the first day (which is a day off) to the last position, the number of occurrences of t wouldn't change. In the third example it's impossible to make even a single occurrence.
{"inputs": ["10\n10100\n", "10\n11100\n", "11111111\n1\n", "11000000\n0\n", "10100110\n1\n", "11000000\n1\n", "101101\n010\n", "101101\n000\n"], "outputs": ["10\n", "10\n", "11111111\n", "00000011\n", "11110000\n", "11000000\n", "010111\n", "001111\n"]}
546
178
coding
Solve the programming task below in a Python markdown code block. I decided to play rock-paper-scissors with a group of five good friends. Rock-paper-scissors has three hands: goo, choki, and par. If the game between goo and choki is a match between goo and choki, goo is "winning" and choki is "losing". , Par and Goo have the rule that Par is "winning" and Goo is "losing". If everyone has the same hand, or if all of Goo, Choki, and Par come out, it will be "Aiko". Create a program that inputs the hands of five rock-paper-scissors players and outputs the wins and losses of each person. Rock-paper-scissors hands are represented by the numbers 1 for goo, 2 for choki, and 3 for par. Win / loss is represented by a number of 1, "win" is 1, "los" is 2, and "Aiko" is 3, and they are output according to the input order. Input A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format: h1 h2 h3 h4 h5 The i-th line is given the i-th hand hi (1, 2 or 3). The number of datasets does not exceed 200. Output Outputs the wins and losses of 5 players for each input dataset. Output the win / loss (1, 2 or 3) of the i-th person on the i-line. Example Input 1 2 3 2 1 1 2 2 2 1 0 Output 3 3 3 3 3 1 2 2 2 1
{"inputs": ["1\n3\n3\n2\n1\n1\n2\n2\n2\n1\n0", "1\n1\n1\n2\n1\n1\n2\n2\n2\n1\n0", "1\n2\n3\n2\n1\n1\n1\n2\n2\n1\n0", "1\n2\n2\n2\n1\n1\n1\n2\n2\n1\n0", "1\n2\n3\n2\n1\n1\n2\n2\n2\n2\n0", "1\n3\n1\n2\n1\n1\n2\n1\n2\n1\n0", "1\n2\n3\n2\n1\n1\n2\n3\n2\n2\n0", "1\n2\n2\n2\n1\n1\n2\n3\n2\n2\n0"], "outputs": ["3\n3\n3\n3\n3\n1\n2\n2\n2\n1\n", "1\n1\n1\n2\n1\n1\n2\n2\n2\n1\n", "3\n3\n3\n3\n3\n1\n1\n2\n2\n1\n", "1\n2\n2\n2\n1\n1\n1\n2\n2\n1\n", "3\n3\n3\n3\n3\n1\n2\n2\n2\n2\n", "3\n3\n3\n3\n3\n1\n2\n1\n2\n1\n", "3\n3\n3\n3\n3\n3\n3\n3\n3\n3\n", "1\n2\n2\n2\n1\n3\n3\n3\n3\n3\n"]}
391
366
coding
Solve the programming task below in a Python markdown code block. Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically. Constraints * $1 \leq n, m \leq 1,000$ * $0 \leq a_i, b_i \leq 1,000$ Input The input is given in the following format. $n$ $a_0 \; a_1, ..., \; a_{n-1}$ $m$ $b_0 \; b_1, ..., \; b_{m-1}$ The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers. Output Print 1 $B$ is greater than $A$, otherwise 0. Examples Input 3 1 2 3 2 2 4 Output 1 Input 4 5 4 7 0 5 1 2 3 4 5 Output 0 Input 3 1 1 2 4 1 1 2 2 Output 1
{"inputs": ["3\n1 4 3\n2\n2 4", "3\n1 4 3\n2\n2 2", "3\n1 4 3\n3\n2 2", "3\n1 4 3\n3\n2 1", "3\n1 4 3\n6\n2 1", "3\n1 4 5\n6\n2 1", "3\n1 4 8\n6\n2 1", "3\n1 4 8\n6\n4 1"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
306
158
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Bengali], [Russian], [Mandarin] and [Vietnamese] as well. Chef has X coins worth 1 rupee each and Y coins worth 2 rupees each. He wants to distribute all of these X+Y coins to his two sons so that the total value of coins received by each of them is the same. Find out whether Chef will be able to do so. ------ Input Format ------ - The first line of input contains a single integer T, denoting the number of testcases. The description of T test cases follows. - Each test case consists of a single line of input containing two space-separated integers X and Y. ------ Output Format ------ For each test case, print "YES" (without quotes) if Chef can distribute all the coins equally and "NO" otherwise. You may print each character of the string in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and "YES" will all be treated as identical). ------ Constraints ------ $1 ≤ T ≤ 10^{3}$ $0 ≤ X, Y ≤ 10^{8}$ $ X + Y > 0$ ------ subtasks ------ Subtask 1 (100 points): Original constraints ----- Sample Input 1 ------ 4 2 2 1 3 4 0 1 10 ----- Sample Output 1 ------ YES NO YES NO ----- explanation 1 ------ Test case $1$: Chef gives each of his sons $1$ coin worth one rupee and $1$ coin worth two rupees. Test case $3$: Chef gives each of his sons $2$ coins worth one rupee.
{"inputs": ["4\n2 2\n1 3\n4 0\n1 10\n"], "outputs": ["YES\nNO\nYES\nNO\n"]}
376
37
coding
Solve the programming task below in a Python markdown code block. Sam is an avid collector of numbers. Every time he finds a new number he throws it on the top of his number-pile. Help Sam organise his collection so he can take it to the International Number Collectors Conference in Cologne. Given an array of numbers, your function should return an array of arrays, where each subarray contains all the duplicates of a particular number. Subarrays should be in the same order as the first occurence of the number they contain: Assume the input is always going to be an array of numbers. If the input is an empty array, an empty array should be returned. Also feel free to reuse/extend the following starter code: ```python def group(arr): ```
{"functional": "_inputs = [[[3, 2, 6, 2, 1, 3]], [[3, 2, 6, 2]], [[]], [[1, 100, 4, 2, 4]], [[-1, 1, -1]]]\n_outputs = [[[[3, 3], [2, 2], [6], [1]]], [[[3], [2, 2], [6]]], [[]], [[[1], [100], [4, 4], [2]]], [[[-1, -1], [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(group(*i), o[0])"}
157
270
coding
Solve the programming task below in a Python markdown code block. You are playing a Billiards-like game on an $N \times N$ table, which has its four corners at the points $\{(0, 0), (0, N), (N, 0),$ and $(N, N)\}$. You start from a coordinate $(x,y)$, $(0 < x < N, 0 < y < N)$ and shoot the ball at an angle $45^{\circ}$ with the horizontal. On hitting the sides, the ball continues to move with the same velocity and ensuring that the angle of incidence is equal to the angle of reflection with the normal, i.e, it is reflected with zero frictional loss. On hitting either of the four corners, the ball stops there and doesn’t move any further. Find the coordinates of the point of collision, when the ball hits the sides for the $K^{th}$ time. If the ball stops before hitting the sides $K$ times, find the coordinates of the corner point where the ball stopped instead. -----Input:----- - The first line of the input contains an integer $T$, the number of testcases. - Each testcase contains a single line of input, which has four space separated integers - $N$, $K$, $x$, $y$, denoting the size of the board, the number of collisions to report the answer for, and the starting coordinates. -----Output:----- For each testcase, print the coordinates of the ball when it hits the sides for the $K^{th}$ time, or the coordinates of the corner point if it stopped earlier. -----Constraints----- - $1 \leq T \leq 10^5$ - $2 \leq N \leq 10^9$ - $1 \leq K \leq 10^9$ -----Subtasks----- - $30$ points : Sum of $K$ over all test cases $\le 10^7$ - $70$ points : Original constraints. -----Sample Input:----- 2 5 5 4 4 5 2 3 1 -----Sample Output:----- 5 5 3 5 -----Explanation:----- - Sample Case $1$ : We are given a $5$ by $5$ board. We shoot the ball from coordinates $(4,4)$, and we need to find its coordinates after it has collided with sides $5$ times. However, after shooting, the ball goes directly to the corner $(5,5)$, and stops there. So we report the coordinates $(5,5)$. - Sample Case $2$ : We are given a $5$ by $5$ board. We shoot the ball from the coordinates $(3,1)$, and we need to find its coordinates after it has collided with the sides twice. After shooting, it first hits the right side at $(5,3)$, and then the top side at $(3,5)$. So, we report $(3,5)$.
{"inputs": ["2\n5 5 4 4\n5 2 3 1"], "outputs": ["5 5\n3 5"]}
640
34
coding
Solve the programming task below in a Python markdown code block. There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise. Input The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right. Output Print the number of steps, so that the line remains the same afterward. Examples Input 10 10 9 7 8 6 5 3 4 2 1 Output 2 Input 6 1 2 3 4 5 6 Output 0 Note In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] → [10 8 4] → [10]. So, there are two steps.
{"inputs": ["1\n1\n", "2\n1 2\n", "2\n2 1\n", "6\n6 5 4 3 2 1\n", "6\n1 2 3 4 5 6\n", "10\n10 7 4 2 5 8 9 6 3 1\n", "10\n10 2 7 8 6 5 3 4 2 1\n", "10\n10 9 7 8 6 5 3 0 2 1\n"], "outputs": ["0\n", "0\n", "1\n", "1\n", "0\n", "4\n", "3\n", "2\n"]}
320
170
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin chinese, Russian and Vietnamese as well. Chef likes to mix colors a lot. Recently, she was gifted N colors A_{1}, A_{2}, ..., A_{N} by her friend. Chef wants to make the values of all her colors pairwise distinct, as they will then look stunningly beautiful. In order to achieve that, she can perform the following mixing operation zero or more times: Choose any two colors. Let's denote their values by x and y. Mix the color with value x into the color with value y. After the mixing, the value of the first color remains x, but the value of the second color changes to x + y. Find the minimum number of mixing operations Chef needs to perform to make her colors beautiful. ------ 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 denoting the number of colors. The second line contains N space-separated integers A_{1}, A_{2}, ..., A_{N} denoting Chef's initial colors. ------ Output ------ For each test case, print a single line containing one integer — the minimum number of required mixing operations. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N ≤ 10^{5}$ $1 ≤ A_{i} ≤ 10^{9} for each valid i$ ------ Subtasks ------ Subtask #1 (30 points): 1 ≤ N ≤ 100 Subtask #2 (70 points): original constraints ----- Sample Input 1 ------ 2 3 1 2 3 3 2 1 2 ----- Sample Output 1 ------ 0 1 ----- explanation 1 ------ Example case 1: No two colors have the same value. Hence, they are already beautiful. No mixing is required. Example case 2: Take the second color (with value x = 1) and mix it into the first color (with value x = 2). After the mixing, the colors will be 3 1 2. Now the colors are beautiful. This is the minimum number of mixing operations that are required. Hence, the answer is 1.
{"inputs": ["2\n3\n1 2 3\n3\n2 1 2"], "outputs": ["0\n1"]}
493
30
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not). Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.   Please complete the following python code precisely: ```python class Solution: def shortestWay(self, source: str, target: str) -> int: ```
{"functional": "def check(candidate):\n assert candidate(source = \"abc\", target = \"abcbc\") == 2\n assert candidate(source = \"abc\", target = \"acdbc\") == -1\n assert candidate(source = \"xyz\", target = \"xzyxz\") == 3\n\n\ncheck(Solution().shortestWay)"}
146
75
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Russian], [Mandarin Chinese], [Bengali], and [Vietnamese] as well. An integer x is said to be a Perfect Power if there exists positive integers a and b (i.e a, and b should be ≥ 1) such that x = a^{b+1}. Given an integer n, find the closest Perfect Power to n. If there are multiple *Perfect Powers* equidistant from n and as close as possible to n, find the smallest one. More formally, find the smallest integer x such that x is a Perfect Power and |n - x| ≤ |n - y| over all Perfect Powers y. ------ Input Format ------ - The first line of input contains a single integer T denoting the number of test cases. The description of T test cases follows. - The first and only line of each test case contains a single integer n. ------ Output Format ------ For each test case, print in a separate line, the smallest x such that x is a perfect power and |n - x| is minimum. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ n ≤ 10^{18}$ ----- Sample Input 1 ------ 7 7 10 26 242 129 394857629456789876 353872815358409997 ----- Sample Output 1 ------ 8 9 25 243 128 394857628993920400 353872815358410000 ----- explanation 1 ------ Test case $1$: $n = 7$, $8 = 2^{3}$ is a perfect power, but $6$ is not, so the minimum difference obtainable is $1$ when $x = 8$. Test case $2$: $n = 10$, $9 = 3^{2}$ is a perfect power, but $11$ is not, so the minimum difference obtainable is $1$ when $x = 9$. Test case $3$: $n = 26$, $25 = 5^{2}$ is a perfect power, $27 = 3^{3}$ is also a perfect power. Both $x = 25$ and $x = 27$ give the minimum difference obtainable which is $1$. The smallest of them is $25$. Test case $4$: $n = 242$, $243 = 3^{5}$ is a perfect power but $241$ is not, so the answer is $243$. Test case $5$: $128 = 2^{7}$ is closest to $129$. Test case $6$: $394857628993920400 = 628376980^{2}$ is the closest to $394857629456789876$. Test case $7$: $353872815358410000 = 24390^{4}$ is the closest to $353872815358409997$.
{"inputs": ["7\n7\n10\n26\n242\n129\n394857629456789876\n353872815358409997"], "outputs": ["8\n9\n25\n243\n128\n394857628993920400\n353872815358410000"]}
763
117
coding
Solve the programming task below in a Python markdown code block. We have an array of unique elements. A special kind of permutation is the one that has all of its elements in a different position than the original. Let's see how many of these permutations may be generated from an array of four elements. We put the original array with square brackets and the wanted permutations with parentheses. ``` arr = [1, 2, 3, 4] (2, 1, 4, 3) (2, 3, 4, 1) (2, 4, 1, 3) (3, 1, 4, 2) (3, 4, 1, 2) (3, 4, 2, 1) (4, 1, 2, 3) (4, 3, 1, 2) (4, 3, 2, 1) _____________ A total of 9 permutations with all their elements in different positions than arr ``` The task for this kata would be to create a code to count all these permutations for an array of certain length. Features of the random tests: ``` l = length of the array 10 ≤ l ≤ 5000 ``` See the example tests. Enjoy it! Also feel free to reuse/extend the following starter code: ```python def all_permuted(n): ```
{"functional": "_inputs = [[1], [4], [30]]\n_outputs = [[0], [9], [97581073836835777732377428235481]]\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(all_permuted(*i), o[0])"}
314
199
coding
Solve the programming task below in a Python markdown code block. Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number a_{i}, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1. After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location. -----Input----- The first line contains single integer n (1 ≤ n ≤ 2·10^5) — the number of cubes. The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9), where a_{i} is the number written on the i-th cube after Dima has changed their order. -----Output----- Print n integers, separated by spaces — the numbers written on the cubes in their initial order. It can be shown that the answer is unique. -----Examples----- Input 7 4 3 7 6 9 1 2 Output 2 3 9 6 7 1 4 Input 8 6 1 4 2 5 6 9 2 Output 2 1 6 2 5 4 9 6 -----Note----- Consider the first sample. At the begining row was [2, 3, 9, 6, 7, 1, 4]. After first operation row was [4, 1, 7, 6, 9, 3, 2]. After second operation row was [4, 3, 9, 6, 7, 1, 2]. After third operation row was [4, 3, 7, 6, 9, 1, 2]. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].
{"inputs": ["2\n1 2\n", "2\n4 5\n", "2\n1 5\n", "2\n2 5\n", "2\n3 4\n", "2\n1 2\n", "2\n2 5\n", "2\n3 4\n"], "outputs": ["2 1", "5 4", "5 1", "5 2", "4 3", "2 1\n", "5 2\n", "4 3\n"]}
591
113
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff. Return the number of pairs that satisfy the conditions.   Please complete the following python code precisely: ```python class Solution: def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums1 = [3,2,5], nums2 = [2,2,1], diff = 1) == 3\n assert candidate(nums1 = [3,-1], nums2 = [-2,2], diff = -1) == 0\n\n\ncheck(Solution().numberOfPairs)"}
142
79
coding
Solve the programming task below in a Python markdown code block. Luba has to do n chores today. i-th chore takes a_{i} units of time to complete. It is guaranteed that for every $i \in [ 2 . . n ]$ the condition a_{i} ≥ a_{i} - 1 is met, so the sequence is sorted. Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a_{i} ($x < \operatorname{min}_{i = 1}^{n} a_{i}$). Luba is very responsible, so she has to do all n chores, and now she wants to know the minimum time she needs to do everything. Luba cannot do two chores simultaneously. -----Input----- The first line contains three integers n, k, x (1 ≤ k ≤ n ≤ 100, 1 ≤ x ≤ 99) — the number of chores Luba has to do, the number of chores she can do in x units of time, and the number x itself. The second line contains n integer numbers a_{i} (2 ≤ a_{i} ≤ 100) — the time Luba has to spend to do i-th chore. It is guaranteed that $x < \operatorname{min}_{i = 1}^{n} a_{i}$, and for each $i \in [ 2 . . n ]$ a_{i} ≥ a_{i} - 1. -----Output----- Print one number — minimum time Luba needs to do all n chores. -----Examples----- Input 4 2 2 3 6 7 10 Output 13 Input 5 2 1 100 100 100 100 100 Output 302 -----Note----- In the first example the best option would be to do the third and the fourth chore, spending x = 2 time on each instead of a_3 and a_4, respectively. Then the answer is 3 + 6 + 2 + 2 = 13. In the second example Luba can choose any two chores to spend x time on them instead of a_{i}. So the answer is 100·3 + 2·1 = 302.
{"inputs": ["1 1 1\n100\n", "1 1 1\n100\n", "1 1 1\n110\n", "1 1 2\n100\n", "1 1 2\n110\n", "1 1 2\n101\n", "4 2 2\n3 6 7 10\n", "4 4 2\n3 6 7 10\n"], "outputs": ["1\n", "1\n", "1\n", "2\n", "2\n", "2\n", "13\n", "8\n"]}
514
145
coding
Solve the programming task below in a Python markdown code block. Chef and his girlfriend are going to have a promenade. They are walking along the straight road which consists of segments placed one by one. Before walking Chef and his girlfriend stay at the beginning of the first segment, they want to achieve the end of the last segment. There are few problems: - At the beginning Chef should choose constant integer - the velocity of mooving. It can't be changed inside one segment. - The velocity should be decreased by at least 1 after achieving the end of some segment. - There is exactly one shop on each segment. Each shop has an attractiveness. If it's attractiveness is W and Chef and his girlfriend move with velocity V then if V < W girlfriend will run away into the shop and the promenade will become ruined. Chef doesn't want to lose her girl in such a way, but he is an old one, so you should find the minimal possible velocity at the first segment to satisfy all conditions. -----Input----- - The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains a single integer N denoting the number of segments. The second line contains N space-separated integers W1, W2, ..., WN denoting the attractiveness of shops. -----Output----- - For each test case, output a single line containing the minimal possible velocity at the beginning. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 10^5 - 1 ≤ Wi ≤ 10^6 -----Example----- Input: 2 5 6 5 4 3 2 5 3 4 3 1 1 Output: 6 5 -----Explanation----- Example case 1. If we choose velocity 6, on the first step we have 6 >= 6 everything is OK, then we should decrease the velocity to 5 and on the 2nd segment we'll receive 5 >= 5, again OK, and so on. Example case 2. If we choose velocity 4, the promanade will be ruined on the 2nd step (we sould decrease our velocity, so the maximal possible will be 3 which is less than 4).
{"inputs": ["2\n5\n6 5 4 3 2\n5\n3 4 3 1 1", "2\n5\n6 5 4 3 2\n5\n3 4 6 1 1", "2\n5\n6 5 4 3 2\n5\n3 7 9 1 1", "2\n5\n6 5 4 3 3\n5\n3 7 9 1 1", "2\n5\n6 5 4 3 2\n5\n3 8 3 1 1", "2\n5\n6 5 4 5 2\n5\n3 7 6 1 1", "2\n5\n6 5 4 4 2\n5\n3 8 3 1 1", "2\n5\n6 5 0 3 2\n5\n3 4 3 1 1"], "outputs": ["6\n5", "6\n8\n", "6\n11\n", "7\n11\n", "6\n9\n", "8\n8\n", "7\n9\n", "6\n5\n"]}
495
271
coding
Solve the programming task below in a Python markdown code block. You are given a bracket sequence $s$ consisting of $n$ opening '(' and closing ')' brackets. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not. You can change the type of some bracket $s_i$. It means that if $s_i = $ ')' then you can change it to '(' and vice versa. Your task is to calculate the number of positions $i$ such that if you change the type of the $i$-th bracket, then the resulting bracket sequence becomes regular. -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 10^6$) — the length of the bracket sequence. The second line of the input contains the string $s$ consisting of $n$ opening '(' and closing ')' brackets. -----Output----- Print one integer — the number of positions $i$ such that if you change the type of the $i$-th bracket, then the resulting bracket sequence becomes regular. -----Examples----- Input 6 (((()) Output 3 Input 6 ()()() Output 0 Input 1 ) Output 0 Input 8 )))((((( Output 0
{"inputs": ["1\n)\n", "1\n(\n", "1\n)\n", "2\n((\n", "2\n))\n", "2\n)(\n", "2\n)(\n", "2\n((\n"], "outputs": ["0\n", "0\n", "0", "1\n", "1\n", "0\n", "0", "1"]}
320
88
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi. This year, there will be a big event in the capital (city 0), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed. It's guaranteed that each city can reach city 0 after reorder.   Please complete the following python code precisely: ```python class Solution: def minReorder(self, n: int, connections: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]) == 3\n assert candidate(n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]) == 2\n assert candidate(n = 3, connections = [[1,0],[2,0]]) == 0\n\n\ncheck(Solution().minReorder)"}
209
109
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 most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).   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 findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(root = tree_node([5,2,-3])) == [2,-3,4]\n assert candidate(root = tree_node([5,2,-5])) == [2]\n\n\ncheck(Solution().findFrequentTreeSum)"}
167
64
coding
Solve the programming task below in a Python markdown code block. Прошло много лет, и на вечеринке снова встретились n друзей. С момента последней встречи техника шагнула далеко вперёд, появились фотоаппараты с автоспуском, и теперь не требуется, чтобы один из друзей стоял с фотоаппаратом, и, тем самым, оказывался не запечатлённым на снимке. Упрощенно процесс фотографирования можно описать следующим образом. На фотографии каждый из друзей занимает прямоугольник из пикселей: в стоячем положении i-й из них занимает прямоугольник ширины w_{i} пикселей и высоты h_{i} пикселей. Но также, при фотографировании каждый человек может лечь, и тогда он будет занимать прямоугольник ширины h_{i} пикселей и высоты w_{i} пикселей. Общая фотография будет иметь размеры W × H, где W — суммарная ширина всех прямоугольников-людей, а H — максимальная из высот. Друзья хотят определить, какую минимальную площадь может иметь общая фотография. Помогите им в этом. -----Входные данные----- В первой строке следует целое число n (1 ≤ n ≤ 1000) — количество друзей. В последующих n строках следуют по два целых числа w_{i}, h_{i} (1 ≤ w_{i}, h_{i} ≤ 1000), обозначающие размеры прямоугольника, соответствующего i-му из друзей. -----Выходные данные----- Выведите единственное целое число, равное минимальной возможной площади фотографии, вмещающей всех друзей. -----Примеры----- Входные данные 3 10 1 20 2 30 3 Выходные данные 180 Входные данные 3 3 1 2 2 4 3 Выходные данные 21 Входные данные 1 5 10 Выходные данные 50
{"inputs": ["1\n1 1\n", "1\n5 10\n", "1\n1 1000\n", "1\n1000 1\n", "2\n1 1\n1 1\n", "2\n2 1\n3 1\n", "2\n4 3\n2 1\n", "1\n1000 1000\n"], "outputs": ["1\n", "50\n", "1000\n", "1000\n", "2\n", "5\n", "15\n", "1000000\n"]}
513
141
coding
Solve the programming task below in a Python markdown code block. This is probably the simplest problem ever. You just need to count the number of ordered triples of different numbers (X1, X2, X3), where Xi could be any positive integer from 1 to Ni, inclusive (i = 1, 2, 3). No, wait. I forgot to mention that numbers N1, N2, N3 could be up to 1018. Well, in any case it is still quite simple :) By the way, because of this the answer could be quite large. Hence you should output it modulo 109 + 7. That is you need to find the remainder of the division of the number of required triples by 109 + 7. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains three space-separated integers N1, N2, N3. -----Output----- For each test case, output a single line containing the number of required triples modulo 109 + 7. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ Ni ≤ 1018 -----Example----- Input: 5 3 3 3 2 4 2 1 2 3 25 12 2012 1 1 2013 Output: 6 4 1 578880 0 -----Explanation----- Example case 1. We have the following triples composed of different numbers up to 3: (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) Example case 2. Here the triples are: (1, 3, 2) (1, 4, 2) (2, 3, 1) (2, 4, 1) Example case 3. Here the only triple is (1, 2, 3). Example case 4. Merry Christmas! Example case 5. ... and Happy New Year! By the way here the answer is zero since the only choice for X1 and for is X2 is 1, so any such triple will have equal numbers.
{"inputs": ["5\n3 3 3\n2 4 2\n1 2 3\n25 12 2012\n1 1 2013"], "outputs": ["6\n4\n1\n578880\n0"]}
523
63
coding
Solve the programming task below in a Python markdown code block. Find the length of the longest contiguous segment in an array, in which if a given element $K$ is inserted, $K$ becomes the second largest element of that subarray. -----Input:----- - The first line will contain $T$, number of test cases. Then the test cases follow. - The first line of each test case contains two integers $N$ and $K$. - The next line contains N space-separated integers Ai denoting the elements of the array. -----Output:----- Print a single line corresponding to each test case — the length of the largest segment. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 10^6$ - $1 \leq Ai, K \leq 10^9$ - Sum of N across all test cases doesn't exceed $10^6$ -----Sample Input:----- 2 5 3 2 4 2 4 2 8 5 9 3 5 7 8 11 17 2 -----Sample Output:----- 5 3 -----EXPLANATION:----- If 3 is inserted at anywhere in the array, it is the second largest element. Hence the maximum length is 5. If 5 is inserted anywhere between 1st and 4th element, it is the second largest element. The length of such subarray is 3.
{"inputs": ["2\n5 3\n2 4 2 4 2\n8 5\n9 3 5 7 8 11 17 2"], "outputs": ["5\n3"]}
318
50
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki]. The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki. Return the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.   Please complete the following python code precisely: ```python class Solution: def minimumMoney(self, transactions: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(transactions = [[2,1],[5,0],[4,2]]) == 10\n assert candidate(transactions = [[3,0],[0,3]]) == 3\n\n\ncheck(Solution().minimumMoney)"}
165
62
coding
Solve the programming task below in a Python markdown code block. Alice and Bob are playing a game with a rooted tree. The tree has $N$ vertices and the first node, $1$, is always the root. Here are the basic rules: They move in alternating turns, and both players always move optimally. During each move, a player removes an edge from the tree, disconnecting one of its leaves or branches. The leaf or branch that was disconnected from the rooted tree is removed from the game. The first player to be unable to make a move loses the game. Alice always makes the first move. For example, the diagram below shows a tree of size $n=7$, where the root is node $1$: Now, if a player removes the edge between $1$ and $4$, then nodes $4$ and $7$ become disconnected from the root and are removed from the game: Given the structure of the tree, determine and print the winner of the game. If Alice wins, print $\textbf{Alice}$; otherwise print $\textbf{Bob}$. Input Format The first line contains a single integer, $\mathbf{T}$, denoting the number of test cases. For each test case, the first line contains an integer, $N$, denoting the number of nodes in the tree. Each of the $N-1$ subsequent lines contains $2$ space-separated integers, $\mbox{u}$ and $v$, defining an edge connecting nodes $\mbox{u}$ and $v$. Constraints $1\leq T\leq100$ $1\leq N\leq500$ $1\leq u,v\leq N$ Output Format For each test case, print the name of the winner (i.e., $\textbf{Alice}$ or $\textbf{Bob}$) on a new line. Sample Input 1 5 1 2 3 1 3 4 4 5 Sample Output Alice Explanation Test Case 0: Alice removes the edge connecting node $3$ to node $4$, effectively trimming nodes $4$ and $5$ from the tree. Now the only remaining edges are $1\leftrightarrow2$ and $1\leftrightarrow3$. Because Bob can't remove both of them, Alice will make the last possible move. Because the last player to move wins, we print $\textbf{Alice}$ on a new line.
{"inputs": ["1\n5\n1 2\n3 1\n3 4\n4 5\n"], "outputs": ["Alice\n"]}
519
32
coding
Solve the programming task below in a Python markdown code block. Rng has a connected undirected graph with N vertices. Currently, there are M edges in the graph, and the i-th edge connects Vertices A_i and B_i. Rng will add new edges to the graph by repeating the following operation: * Operation: Choose u and v (u \neq v) such that Vertex v can be reached by traversing exactly three edges from Vertex u, and add an edge connecting Vertices u and v. It is not allowed to add an edge if there is already an edge connecting Vertices u and v. Find the maximum possible number of edges that can be added. Constraints * 2 \leq N \leq 10^5 * 1 \leq M \leq 10^5 * 1 \leq A_i,B_i \leq N * The graph has no self-loops or multiple edges. * The graph is connected. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output Find the maximum possible number of edges that can be added. Examples Input 6 5 1 2 2 3 3 4 4 5 5 6 Output 4 Input 5 5 1 2 2 3 3 1 5 4 5 1 Output 5
{"inputs": ["6 5\n1 2\n2 3\n3 4\n4 5\n4 6", "5 5\n1 2\n2 3\n3 1\n5 3\n5 1", "6 5\n1 2\n2 2\n3 4\n4 5\n5 6", "5 5\n1 2\n2 3\n3 2\n5 4\n5 1", "6 5\n1 2\n2 3\n3 4\n4 5\n3 6", "9 5\n1 2\n2 3\n3 3\n0 5\n4 6", "8 5\n1 1\n2 3\n3 1\n5 3\n5 1", "7 5\n1 1\n2 3\n3 1\n5 3\n5 1"], "outputs": ["3\n", "5\n", "10\n", "1\n", "4\n", "31\n", "23\n", "16\n"]}
317
242
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where people[i] is the time that the ith person will arrive to see the flowers. Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.   Please complete the following python code precisely: ```python class Solution: def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11]) == [1,2,2,2]\n assert candidate(flowers = [[1,10],[3,3]], people = [3,3,2]) == [2,2,1]\n\n\ncheck(Solution().fullBloomFlowers)"}
166
104
coding
Solve the programming task below in a Python markdown code block. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
{"inputs": ["5\n1 2\n1 3\n2 4\n4 5", "5\n1 2\n2 3\n1 5\n4 5", "5\n1 2\n1 3\n2 4\n4 0", "5\n1 2\n3 3\n2 4\n4 5", "5\n1 4\n2 3\n2 4\n4 5", "5\n1 2\n2 3\n0 5\n4 5", "5\n1 2\n2 2\n0 5\n4 5", "5\n1 2\n2 3\n2 4\n4 5"], "outputs": ["Alice\n", "Bob\n", "Alice\n", "Alice\n", "Alice\n", "Alice\n", "Alice\n", "Alice"]}
348
189
coding
Solve the programming task below in a Python markdown code block. find the sum of the even fibonacci numbers till the given number(it is the value not index). INPUT: T test cases next T lines consists of a number n. OUTPUT: Output the sum value. 0<t<10 2<n<10^20 Example: if n=10 the numbers which are less than 10 are 2 and 8 in fibonacci. sum = 2+8=10 SAMPLE INPUT 2 10 100 SAMPLE OUTPUT 10 44
{"inputs": ["5\n14576\n145786\n1254478\n147852\n125478", "10\n457866622145522214789856\n321245663325\n12254\n14221\n14256\n145\n256\n125\n1254785632145632145\n14789666620000000"], "outputs": ["14328\n60696\n1089154\n60696\n60696", "390887039715493615101718\n112925716858\n14328\n14328\n14328\n188\n188\n44\n889989708002357094\n11708364174233842"]}
125
292
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1. Notice that the modulo is performed after getting the maximum product.   Please complete the following python code precisely: ```python class Solution: def maxProductPath(self, grid: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]) == -1\n assert candidate(grid = [[1,-2,1],[1,-2,1],[3,-4,1]]) == 8\n assert candidate(grid = [[1,3],[0,-4]]) == 0\n\n\ncheck(Solution().maxProductPath)"}
194
95
coding
Solve the programming task below in a Python markdown code block. Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes: * Red boxes, each containing R red balls * Green boxes, each containing G green balls * Blue boxes, each containing B blue balls Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes. How many triples of non-negative integers (r,g,b) achieve this? Constraints * All values in input are integers. * 1 \leq R,G,B,N \leq 3000 Input Input is given from Standard Input in the following format: R G B N Output Print the answer. Examples Input 1 2 3 4 Output 4 Input 13 1 4 3000 Output 87058
{"inputs": ["1 2 3 1", "1 2 3 2", "1 2 1 2", "2 2 1 2", "1 2 3 4", "6 3 8 87", "7 2 1 86", "8 3 8 87"], "outputs": ["1\n", "2\n", "4\n", "3\n", "4", "36\n", "296\n", "22\n"]}
198
116
coding
Solve the programming task below in a Python markdown code block. Dee is lazy but she's kind and she likes to eat out at all the nice restaurants and gastropubs in town. To make paying quick and easy she uses a simple mental algorithm she's called The Fair %20 Rule. She's gotten so good she can do this in a few seconds and it always impresses her dates but she's perplexingly still single. Like you probably. This is how she does it: - She rounds the price `P` at the tens place e.g: - 25 becomes 30 - 24 becomes 20 - 5 becomes 10 - 4 becomes 0 - She figures out the base tip `T` by dropping the singles place digit e.g: - when `P = 24` she rounds to 20 drops 0 `T = 2` - `P = 115` rounds to 120 drops 0 `T = 12` - `P = 25` rounds to 30 drops 0 `T = 3` - `P = 5` rounds to 10 drops 0 `T = 1` - `P = 4` rounds to 0 `T = 0` - She then applies a 3 point satisfaction rating `R` to `T` i.e: - When she's satisfied: `R = 1` and she'll add 1 to `T` - Unsatisfied: `R = 0` and she'll subtract 1 from `T` - Appalled: `R = -1` she'll divide `T` by 2, **rounds down** and subtracts 1 ## Your Task Implement a method `calc_tip` that takes two integer arguments for price `p` where `1 <= p <= 1000` and a rating `r` which is one of `-1, 0, 1`. The return value `T` should be a non negative integer. *Note: each step should be done in the order listed.* Dee always politely smiles and says "Thank you" on her way out. Dee is nice. Be like Dee. Also feel free to reuse/extend the following starter code: ```python def calc_tip(p, r): ```
{"functional": "_inputs = [[4, 1], [4, 0], [4, -1], [5, 1], [5, 0], [5, -1], [14, 1], [14, 0], [14, -1], [15, 1], [15, 0], [15, -1], [24, 1], [24, 0], [24, -1], [25, 1], [25, 0], [25, -1], [125, 1], [125, 0], [125, -1], [144, 1], [144, 0], [144, -1]]\n_outputs = [[1], [0], [0], [2], [0], [0], [2], [0], [0], [3], [1], [0], [3], [1], [0], [4], [2], [0], [14], [12], [5], [15], [13], [6]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(calc_tip(*i), o[0])"}
508
392
coding
Solve the programming task below in a Python markdown code block. Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi. As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi ≤ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n). In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores? Input The first input line contains three integers n, a and b (2 ≤ n ≤ 2000; a, b ≥ 1; a + b = n) — the total number of chores, the number of Petya's chores and the number of Vasya's chores. The next line contains a sequence of integers h1, h2, ..., hn (1 ≤ hi ≤ 109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different. All numbers on the lines are separated by single spaces. Output Print the required number of ways to choose an integer value of x. If there are no such ways, print 0. Examples Input 5 2 3 6 2 3 100 1 Output 3 Input 7 3 4 1 1 9 1 1 1 1 Output 0 Note In the first sample the possible values of x are 3, 4 or 5. In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4.
{"inputs": ["2 1 1\n7 7\n", "2 1 1\n7 3\n", "2 1 1\n10 2\n", "2 1 1\n7 13\n", "3 1 2\n6 5 5\n", "2 1 1\n10 13\n", "3 2 1\n4 10 8\n", "3 2 1\n7 16 0\n"], "outputs": ["0", "4\n", "8", "6\n", "1", "3\n", "4\n", "7\n"]}
420
143