task_type
stringclasses
1 value
problem
stringlengths
209
3.39k
answer
stringlengths
35
6.15k
problem_tokens
int64
60
774
answer_tokens
int64
12
2.04k
coding
Solve the programming task below in a Python markdown code block. *Mario has reached Bowser's Castle and is inches away from rescuing Princess Peach. He has to answer the following problem at the gate to be allowed to enter. Can you help him?* Let S(M) denote the set of all [prime] [factors] of M. Given two positive integers A and B, determine whether A is divisible by all elements in S(B). ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case consists of a single line of input, A and B, as mentioned in the statement. ------ Output Format ------ For each test case, print YES if A is divisible by all elements in S(B) 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^{5}$ $1 ≤ A, B ≤ 10^{18}$ ----- Sample Input 1 ------ 3 21 63 72 72 25 20 ----- Sample Output 1 ------ YES YES NO ----- explanation 1 ------ Test case $1$: The set of all prime factors of $B = 63$ is given by $S(B) = \{3, 7\}$. Also, $A = 21$ is divisible by all elements in $S(B)$. Test case $2$: The set of all prime factors of $B = 72$ is given by $S(B) = \{2, 3\}$. Also, $A = 72$ is divisible by all elements in $S(B)$. Test case $3$: The set of all prime factors of $B = 20$ is given by $S(B) = \{2, 5\}$. Here, $A = 25$ is not divisible by $2$ in $S(B)$.
{"inputs": ["3\n21 63\n72 72\n25 20"], "outputs": ["YES\nYES\nNO"]}
451
34
coding
Solve the programming task below in a Python markdown code block. Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not. Example $grid=[\text{'abc'},\text{'ade'},\text{'efg'}]$ The grid is illustrated below. a b c a d e e f g The rows are already in alphabetical order. The columns a a e, b d f and c e g are also in alphabetical order, so the answer would be YES. Only elements within the same row can be rearranged. They cannot be moved to a different row. Function Description Complete the gridChallenge function in the editor below. gridChallenge has the following parameter(s): string grid[n]: an array of strings Returns string: either YES or NO Input Format The first line contains $\boldsymbol{\boldsymbol{t}}$, the number of testcases. Each of the next $\boldsymbol{\boldsymbol{t}}$ sets of lines are described as follows: - The first line contains $n$, the number of rows and columns in the grid. - The next $n$ lines contains a string of length $n$ Constraints $1\leq t\leq100$ $1\leq n\leq100$ Each string consists of lowercase letters in the range ascii[a-z] Output Format For each test case, on a separate line print YES if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO otherwise. Sample Input STDIN Function ----- -------- 1 t = 1 5 n = 5 ebacd grid = ['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv'] fghij olmkn trpqs xywuv Sample Output YES Explanation The $5$x$5$ grid in the $\mbox{I}$ test case can be reordered to abcde fghij klmno pqrst uvwxy This fulfills the condition since the rows 1, 2, ..., 5 and the columns 1, 2, ..., 5 are all alphabetically sorted.
{"inputs": ["1\n5\nebacd\nfghij\nolmkn\ntrpqs\nxywuv\n"], "outputs": ["YES\n"]}
519
36
coding
Solve the programming task below in a Python markdown code block. One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting of $n$ integers $[a_1,a_2,\ldots,a_n]$, define $f(l,r)=\text{gcd}(a_l,a_{l+1},\ldots,a_r)\cdot\left(\left(\sum\limits_{i=l}^r a_i\right)-\text{max}(a_l,a_{l+1},\ldots,a_r)\right).$ For example, for an input array [ 10, -5, 5, 20 ], a subsegment $f(1,1)$ would be computed as follows: What is $\max\limits_{1\leq l\leq r\leq n}f(l,r)$, i.e., the maximum value of $f(l,r)$ among all subsegments $[l,r]$? Complete the function maximumValue which takes an integer array as input and returns the maximum value of $\mbox{f}$ among all subsegments $[l,r]$. Note that: $\text{gcd}(x,y)=\text{gcd}(|x|,|y|)$ $\text{gcd}(x,0)=\text{gcd}(0,x)=|x|$ Input Format The first line contains a single integer $n$ The second line contains $n$ space-separated integers $a_1,a_2,\ldots a_n$ Constraints $1\leq n\leq50000$ $-10^6\leq a_i\leq10^6$ Output Format Print a single integer denoting the answer Sample Input 0 4 10 -5 5 20 Sample Output 0 50 Explanation 0 The maximum value occurs at $f(1,4)=50$ as shown below. Sample Input 1 5 7 12 24 6 5 Sample Output 1 144 Explanation 1 The maximum value occurs at $f(2,3)=144$.
{"inputs": ["4\n10 -5 5 20\n", "5\n7 12 24 6 5\n"], "outputs": ["50\n", "144\n"]}
529
47
coding
Solve the programming task below in a Python markdown code block. Is the number even? If the numbers is even return `true`. If it's odd, return `false`. Oh yeah... the following symbols/commands have been disabled! use of ```%``` use of ```.even?``` in Ruby use of ```mod``` in Python Also feel free to reuse/extend the following starter code: ```python def is_even(n): ```
{"functional": "_inputs = [[2], [3], [14], [15], [26], [27]]\n_outputs = [[True], [False], [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(is_even(*i), o[0])"}
94
188
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts. A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.   Please complete the following python code precisely: ```python class Solution: def minFallingPathSum(self, grid: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(grid = [[1,2,3],[4,5,6],[7,8,9]]) == 13\n assert candidate(grid = [[7]]) == 7\n\n\ncheck(Solution().minFallingPathSum)"}
108
63
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian as well. Captain Dehatti from Bawanian village is making strategy to win the Fake Cricket World Cup organised in his village. He want his team to score runs only in 4's and 6's because he believes that scoring any runs by running will make them tired. He also wants that the team does not loose more than L wickets. He now wonders in how many ways his team can score exactly R runs in B balls. Ofcourse, he assumes that the opponent bowling is awesome and will not concede any extra runs. Formally, He wonders how many ways can his team score exactly R runs in B balls, given that each ball can result in 4, 6, 0 , or W(wicket wont add anything to score). Atmost L wicktes are allowed [i.e. Atmost L 'W' can be there in B balls ]. Note: His batting order is fixed i.e. After each wicket , next player to come is fixed. ------ Input ------ First line contains T, the number of test cases. Each test case contains 3 space separated integers, R, B and L ------ Output ------ For each test cases output the number of ways modulo 1e9+7 (i.e. 1000000007) ------ Constraints ------ $1 ≤ T ≤ 25000$ $0 ≤ R ≤ 10^{9}$ $1 ≤ B ≤ 300$ $0 ≤ L ≤ 9$ Note that the answer to R = 0 , B = 2 , W =1 is 3 [ 00 , 0W , W0 ] ----- Sample Input 1 ------ 6 10 2 9 6 2 9 6 1 9 4 1 9 5 1 9 10 3 9 ----- Sample Output 1 ------ 2 4 1 1 0 12 ----- explanation 1 ------ Explanation for the sample input 1: All possible ways to face 2 deliveries: 00 04 06 0W W0 W4 W6 WW 40 44 46 4W 60 64 66 6W Only possible ways to win the match are 46 and 64. Hence answer is 2. You need to consider all sample space i.e. 4^{B}
{"inputs": ["6\n10 2 9\n6 2 9\n6 1 9\n4 1 9\n5 1 9\n10 3 9"], "outputs": ["2\n4\n1\n1\n0\n12"]}
552
61
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. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order.   Please complete the following python code precisely: ```python class Solution: def findLonely(self, nums: List[int]) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(nums = [10,6,5,8]) == [10,8]\n assert candidate(nums = [1,3,5,3]) == [1,5]\n\n\ncheck(Solution().findLonely)"}
108
64
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s, return whether s is a valid number. For example, all the following are valid numbers: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789", while the following are not valid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53". Formally, a valid number is defined using one of the following definitions: An integer number followed by an optional exponent. A decimal number followed by an optional exponent. An integer number is defined with an optional sign '-' or '+' followed by digits. A decimal number is defined with an optional sign '-' or '+' followed by one of the following definitions: Digits followed by a dot '.'. Digits followed by a dot '.' followed by digits. A dot '.' followed by digits. An exponent is defined with an exponent notation 'e' or 'E' followed by an integer number. The digits are defined as one or more digits.   Please complete the following python code precisely: ```python class Solution: def isNumber(self, s: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(s = \"0\") == True\n assert candidate(s = \"e\") == False\n assert candidate(s = \".\") == False\n\n\ncheck(Solution().isNumber)"}
316
52
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a binary array nums containing only the integers 0 and 1. Return the number of subarrays in nums that have more 1's than 0's. Since the answer may be very large, return it modulo 109 + 7. A subarray is a contiguous sequence of elements within an array.   Please complete the following python code precisely: ```python class Solution: def subarraysWithMoreZerosThanOnes(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [0,1,1,0,1]) == 9\n assert candidate(nums = [0]) == 0\n assert candidate(nums = [1]) == 1\n\n\ncheck(Solution().subarraysWithMoreZerosThanOnes)"}
123
70
coding
Solve the programming task below in a Python markdown code block. Valera has array a, consisting of n integers a_0, a_1, ..., a_{n} - 1, and function f(x), taking an integer from 0 to 2^{n} - 1 as its single argument. Value f(x) is calculated by formula $f(x) = \sum_{i = 0}^{n - 1} a_{i} \cdot b i t(i)$, where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise. For example, if n = 4 and x = 11 (11 = 2^0 + 2^1 + 2^3), then f(x) = a_0 + a_1 + a_3. Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of array elements. The next line contains n space-separated integers a_0, a_1, ..., a_{n} - 1 (0 ≤ a_{i} ≤ 10^4) — elements of array a. The third line contains a sequence of digits zero and one without spaces s_0s_1... s_{n} - 1 — the binary representation of number m. Number m equals $\sum_{i = 0}^{n - 1} 2^{i} \cdot s_{i}$. -----Output----- Print a single integer — the maximum value of function f(x) for all $x \in [ 0 . . m ]$. -----Examples----- Input 2 3 8 10 Output 3 Input 5 17 0 10 2 1 11010 Output 27 -----Note----- In the first test case m = 2^0 = 1, f(0) = 0, f(1) = a_0 = 3. In the second sample m = 2^0 + 2^1 + 2^3 = 11, the maximum value of function equals f(5) = a_0 + a_2 = 17 + 10 = 27.
{"inputs": ["1\n0\n1\n", "1\n1\n0\n", "1\n1\n1\n", "1\n0\n0\n", "1\n1\n1\n", "1\n0\n1\n", "1\n1\n0\n", "1\n0\n0\n"], "outputs": ["0\n", "0\n", "1\n", "0\n", "1\n", "0\n", "0\n", "0\n"]}
515
102
coding
Solve the programming task below in a Python markdown code block. You have an integer variable x. Initially, x=0. Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D. Find the maximum value taken by x during the operations (including before the first operation, and after the last operation). -----Constraints----- - 1≤N≤100 - |S|=N - No characters except I and D occur in S. -----Input----- The input is given from Standard Input in the following format: N S -----Output----- Print the maximum value taken by x during the operations. -----Sample Input----- 5 IIDID -----Sample Output----- 2 After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.
{"inputs": ["5\nDIDII", "5\nDIIID", "5\nIDIID", "5\nIIDDI", "5\nDIIDI", "5\nIIIDD", "5\nDDIII", "5\nIDDII"], "outputs": ["1\n", "2\n", "2\n", "2\n", "1\n", "3\n", "1\n", "1\n"]}
225
88
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin chinese, Russian and Vietnamese as well. There are $N$ workers; each worker is of one of the following three types: A *translator* translates some text from Chef's language to another langague. An *author* writes some text in Chef's language. An *author-translator* can both write a text in Chef's language and translate it to another language. Chef wants to have some text written and translated into some language (different from Chef's language). Chef can't do either of those tasks, but he can hire workers. For each $i$ ($1 ≤ i ≤ N$), if he hires the $i$-th worker, he must pay that worker $c_{i}$ coins. Help Chef find the minimum total number of coins he needs to pay to have a text written and translated. It is guaranteed that it is possible to write and translate a text. ------ Input ------ The first line of the input contains a single integer $N$ denoting the number of workers. The second line contins $N$ space-separated integers $c_{1}, c_{2}, ..., c_{N}$ denoting the numbers of coins Chef has to pay each hired worker. The third line contains $N$ space-separated integers $t_{1}, t_{2}, ..., t_{N}$ denoting the types of workers. For each valid $i$, the $i$-th worker is a translator if $t_{i} = 1$, an author if $t_{i} = 2$ or an author-translator if $t_{i} = 3$. ------ Output ------ Print a single line containing one integer — the minimum number of coins Chef has to pay. ------ Constraints ------ $1 ≤ N ≤ 1,000$ $1 ≤ c_{i} ≤ 100,000$ for each valid $i$ $1 ≤ t_{i} ≤ 3$ for each valid $i$ ------ Subtasks ------ Subtask #1 (15 points): all workers are author-translators Subtask #2 (85 points): original constraints ----- Sample Input 1 ------ 5 1 3 4 6 8 1 2 1 2 3 ----- Sample Output 1 ------ 4 ----- explanation 1 ------ Chef can hire 2 workers: worker 1, who is a translator, and worker 2, who is an author. In total, he pays them $1 + 3 = 4$ coins.
{"inputs": ["5\n1 3 4 6 8\n1 2 1 2 3"], "outputs": ["4"]}
551
32
coding
Solve the programming task below in a Python markdown code block. If we alternate the vowels and consonants in the string `"have"`, we get the following list, arranged alphabetically: `['ahev', 'aveh', 'ehav', 'evah', 'vahe', 'veha']`. These are the only possibilities in which vowels and consonants are alternated. The first element, `ahev`, is alphabetically lowest. Given a string: * alternate the vowels and consonants and return the lexicographically lowest element in the list * If any two or more vowels or consonants must follow each other, return `"failed"` * if the number of vowels and consonants are equal, the first letter of the result must be a vowel. Examples: ```Haskell solve("codewars") = "failed". However you alternate vowels and consonants, two consonants must follow each other solve("oruder") = "edorur" solve("orudere") = "ederoru". This is the only option that allows you to alternate vowels & consonants. ``` ```if c: In C, return an allocated string even if the response is "failed". ``` Vowels will be any of "aeiou". Input will be a lowercase string, no spaces. See test cases for more examples. Good luck! If you like this Kata, please try: [Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073) [Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075) Also feel free to reuse/extend the following starter code: ```python def solve(s): ```
{"functional": "_inputs = [['java'], ['oruder'], ['zodiac'], ['apple'], ['acidity'], ['codewars'], ['orudere']]\n_outputs = [['ajav'], ['edorur'], ['acidoz'], ['lapep'], ['caditiy'], ['failed'], ['ederoru']]\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])"}
389
206
coding
Solve the programming task below in a Python markdown code block. Vasya plays the Geometry Horse. The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1. Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him. Input The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types. Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly. The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes. The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. Output Print the only number — the maximum number of points Vasya can get. Examples Input 1 5 10 2 3 6 Output 70 Input 2 3 8 5 10 1 20 Output 74 Note In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points. In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
{"inputs": ["1\n1 1000\n1\n2\n", "1\n1 1000\n1\n1\n", "1\n1 1100\n1\n2\n", "1\n4 10\n2\n3 6\n", "1\n9 10\n2\n3 6\n", "1\n4 10\n2\n1 6\n", "1\n9 10\n2\n2 6\n", "1\n4 10\n2\n2 6\n"], "outputs": ["1000\n", "1000\n", "1100\n", "50\n", "180\n", "70\n", "190\n", "60\n"]}
596
174
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\n0\n", "a\n1\n", "a\n2\n", "a\n4\n", "aa\n2\n", "aa\n1\n", "ab\n1\n", "ba\n1\n"], "outputs": ["1\na\n", "0\n\n", "0\n", "0\n", "0\n\n", "1\naa\n", "1\nb\n", "1\nb\n"]}
524
96
coding
Solve the programming task below in a Python markdown code block. On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis. Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i. Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i. For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7. That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7. -----Constraints----- - 2 \leq n,m \leq 10^5 - -10^9 \leq x_1 < ... < x_n \leq 10^9 - -10^9 \leq y_1 < ... < y_m \leq 10^9 - x_i and y_i are integers. -----Input----- Input is given from Standard Input in the following format: n m x_1 x_2 ... x_n y_1 y_2 ... y_m -----Output----- Print the total area of the rectangles, modulo 10^9+7. -----Sample Input----- 3 3 1 3 4 1 3 6 -----Sample Output----- 60 The following figure illustrates this input: The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.
{"inputs": ["3 3\n1 3 4\n1 3 9", "3 3\n1 3 4\n0 3 9", "3 3\n1 3 4\n1 3 7", "3 3\n1 3 8\n0 3 9", "3 3\n0 3 4\n1 3 6", "3 3\n1 3 4\n0 3 3", "3 3\n1 3 3\n0 3 3", "3 3\n1 1 5\n0 2 3"], "outputs": ["96\n", "108\n", "72\n", "252\n", "80\n", "36\n", "24\n", "48\n"]}
394
184
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. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1. You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once. Find maximum possible value of the final array.   Please complete the following python code precisely: ```python class Solution: def maxValueAfterReverse(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [2,3,1,5,4]) == 10\n assert candidate(nums = [2,4,9,24,2,1,10]) == 68\n\n\ncheck(Solution().maxValueAfterReverse)"}
125
69
coding
Solve the programming task below in a Python markdown code block. Chef has a binary string S of length N. Chef wants to find two substrings of equal length, such that their [bitwise XOR] is maximised. Formally, Chef wants to find L_{1}, R_{1}, L_{2}, and R_{2} such that: 1 ≤ L_{1} ≤ R_{1} ≤ N and 1 ≤ L_{2} ≤ R_{2} ≤ N |R_{1} - L_{1} + 1| = |R_{2} - L_{2} + 1|, that is, the substrings have equal length; S_{L_{1} \dots R_{1}} \oplus S_{L_{2} \dots R_{2}} is maximised, where \oplus is the bitwise XOR operation. Output the maximum XOR value in decimal notation. Since the value can be large, output it module 10^{9}+7. Note that a substring is formed by deleting some (possibly zero) characters from the beginning and some (possibly zero) characters from the end of the string. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case consists of multiple lines of input. - The first line of each test case contains a single integer N denoting the length of string S. - The second line of each test case contains a binary string S of length N containing 0s and 1s only. ------ Output Format ------ For each test case, output the maximum XOR value in decimal notation. Since the value can be large, output it module 10^{9}+7. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $2 ≤ N ≤ 2 \cdot 10^{6}$ $S$ contains $0$ and $1$ only. - The sum of $N$ over all test cases won't exceed $2 \cdot 10^{6}$. ----- Sample Input 1 ------ 3 4 1010 5 11111 3 011 ----- Sample Output 1 ------ 7 0 2 ----- explanation 1 ------ Test case $1$: We can choose $L_{1} = 1, R_{1} = 3, L_{2} = 2,$ and $R_{2} = 4$. Thus, the chosen substrings are $101$ and $010$. The XOR of these substrings is $111$ whose decimal equivalent is $7$. Test case $2$: We can choose $L_{1} = 2, R_{1} = 2, L_{2} = 4,$ and $R_{2} = 4$. Thus, the chosen substrings are $1$ and $1$. The XOR of these substrings is $0$ whose decimal equivalent is $0$. Test case $3$: We can choose $L_{1} = 1, R_{1} = 2, L_{2} = 2,$ and $R_{2} = 3$. Thus, the chosen substrings are $01$ and $11$. The XOR of these substrings is $10$ whose decimal equivalent is $2$.
{"inputs": ["3\n4\n1010\n5\n11111\n3\n011\n"], "outputs": ["7\n0\n2\n"]}
715
39
coding
Solve the programming task below in a Python markdown code block. There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n. The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end. Input The first line contains two integers n and m (1 ≤ n ≤ 50, 1 ≤ m ≤ 104) — the number of walruses and the number of chips correspondingly. Output Print the number of chips the presenter ended up with. Examples Input 4 11 Output 0 Input 17 107 Output 2 Input 3 8 Output 1 Note In the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes. In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip.
{"inputs": ["1 1\n", "2 1\n", "6 8\n", "2 2\n", "1 2\n", "3 4\n", "1 4\n", "1 6\n"], "outputs": ["0", "0\n", "2\n", "1\n", "0\n", "1\n", "0\n", "0\n"]}
440
85
coding
Solve the programming task below in a Python markdown code block. The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----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, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 26$ - $1 \leq K \leq 26$ -----Sample Input:----- 2 2 4 -----Sample Output:----- A 12 A 12 ABC 1234 -----EXPLANATION:----- No need, else pattern can be decode easily.
{"inputs": ["2\n2\n4"], "outputs": ["A\n12\nA\n12\nABC\n1234"]}
186
31
coding
Solve the programming task below in a Python markdown code block. Johnny, like every mathematician, has his favorite sequence of distinct natural numbers. Let’s call this sequence $\mbox{M}$. Johnny was very bored, so he wrote down $N$ copies of the sequence $\mbox{M}$ in his big notebook. One day, when Johnny was out, his little sister Mary erased some numbers(possibly zero) from every copy of $\mbox{M}$ and then threw the notebook out onto the street. You just found it. Can you reconstruct the sequence? In the input there are $N$ sequences of natural numbers representing the $N$ copies of the sequence $\mbox{M}$ after Mary’s prank. In each of them all numbers are distinct. Your task is to construct the shortest sequence $\mbox{S}$ that might have been the original $\mbox{M}$. If there are many such sequences, return the lexicographically smallest one. It is guaranteed that such a sequence exists. Note Sequence $A[1\ldots n]$ is lexicographically less than sequence $B[1\ldots n]$ if and only if there exists $1\leq i\leq n$ such that for all $1\leq j\lt i,A[j]=B[j]\:\textit{and}\:\:A[i]\lt B[i]$. Input Format In the first line, there is one number $N$ denoting the number of copies of $\mbox{M}$. This is followed by $\mbox{K}$ and in next line a sequence of length $\mbox{K}$ representing one of sequences after Mary's prank. All numbers are separated by a single space. Constraints $1\leq N\leq10^3$ $2\leq K\leq10^3$ All values in one sequence are distinct numbers in range $[1,10^{6}]$. Output Format In one line, write the space-separated sequence $\mbox{S}$ - the shortest sequence that might have been the original $\mbox{M}$. If there are many such sequences, return the lexicographically smallest one. Sample Input 2 2 1 3 3 2 3 4 Sample Output 1 2 3 4 Explanation You have 2 copies of the sequence with some missing numbers: $[1,3]$ and $[2,3,4]$. There are two candidates for the original sequence $M:[1,2,3,4]\ \text{and}\ [2,1,3,4]$, where the first one is lexicographically least.
{"inputs": ["2\n2\n1 3\n3\n2 3 4\n"], "outputs": [" 1 2 3 4\n"]}
575
35
coding
Solve the programming task below in a Python markdown code block. The customer telephone support center of the computer sales company called JAG is now in- credibly confused. There are too many customers who request the support, and they call the support center all the time. So, the company wants to figure out how many operators needed to handle this situation. For simplicity, let us focus on the following simple simulation. Let N be a number of customers. The i-th customer has id i, and is described by three numbers, Mi, Li and Ki. Mi is the time required for phone support, Li is the maximum stand by time until an operator answers the call, and Ki is the interval time from hanging up to calling back. Let us put these in other words: It takes Mi unit times for an operator to support i-th customer. If the i-th customer is not answered by operators for Li unit times, he hangs up the call. Ki unit times after hanging up, he calls back. One operator can support only one customer simultaneously. When an operator finish a call, he can immediately answer another call. If there are more than one customer waiting, an operator will choose the customer with the smallest id. At the beginning of the simulation, all customers call the support center at the same time. The simulation succeeds if operators can finish answering all customers within T unit times. Your mission is to calculate the minimum number of operators needed to end this simulation successfully. Input The input contains multiple datasets. Each dataset has the following format: N T M1 L1 K1 . . . MN LN KN The first line of a dataset contains two positive integers, N and T (1 ≤ N ≤ 1000, 1 ≤ T ≤ 1000). N indicates the number of customers in the dataset, and T indicates the time limit of the simulation. The following N lines describe the information of customers. The i-th line contains three integers, Mi, Li and Ki (1 ≤ Mi ≤ T , 1 ≤ Li ≤ 1000, 1 ≤ Ki ≤ 1000), describing i-th customer's information. Mi indicates the time required for phone support, Li indicates the maximum stand by time until an operator answers the call, and Ki indicates the is the interval time from hanging up to calling back. The end of input is indicated by a line containing two zeros. This line is not part of any dataset and hence should not be processed. Output For each dataset, print the minimum number of operators needed to end the simulation successfully in a line. Example Input 3 300 100 50 150 100 50 150 100 50 150 3 300 100 50 150 100 50 150 200 50 150 9 18 3 1 1 3 1 1 3 1 1 4 100 1 5 100 1 5 100 1 10 5 3 10 5 3 1 7 1000 10 18 1 2 3 2 3 4 3 4 5 4 5 6 5 6 7 6 7 8 7 8 9 8 9 10 9 10 11 10 11 12 0 0 Output 2 3 3 4
{"inputs": ["3 300\n100 46 150\n110 50 150\n001 97 261\n3 300\n100 50 150\n100 50 267\n168 50 88\n9 18\n2 1 1\n3 2 1\n3 0 2\n4 010 1\n5 100 1\n5 100 1\n10 5 3\n10 5 3\n1 7 1000\n10 18\n1 3 3\n2 3 4\n3 3 5\n3 5 6\n5 6 7\n6 7 8\n7 8 9\n8 9 10\n9 10 6\n17 11 12\n0 0", "3 300\n100 46 150\n100 50 150\n101 50 150\n3 300\n100 50 150\n100 50 272\n200 50 96\n9 18\n3 1 1\n3 1 1\n3 1 1\n4 100 1\n5 100 1\n5 100 1\n10 5 3\n10 5 3\n1 7 1000\n10 18\n1 3 3\n2 3 4\n3 4 5\n4 5 6\n5 6 7\n6 7 8\n7 8 9\n8 9 10\n9 10 11\n9 11 12\n0 0", "3 300\n100 46 150\n100 50 150\n101 50 150\n3 300\n110 50 150\n100 50 150\n200 38 14\n9 18\n5 1 1\n3 1 1\n3 1 1\n4 100 1\n5 100 1\n5 100 1\n10 5 3\n10 5 3\n1 6 1000\n10 18\n1 2 3\n2 3 4\n3 4 5\n4 5 6\n5 6 7\n6 7 8\n7 8 9\n8 9 10\n9 10 11\n10 11 12\n0 0", "3 300\n100 46 150\n100 50 150\n101 50 150\n3 300\n100 84 150\n100 50 272\n200 50 150\n9 18\n2 1 1\n4 1 1\n4 0 1\n4 100 1\n5 100 1\n5 100 1\n10 5 3\n10 5 3\n1 7 1000\n10 18\n1 3 3\n2 3 7\n3 4 5\n4 5 6\n5 6 7\n6 0 8\n7 8 9\n8 9 10\n9 10 11\n5 11 12\n0 0", "3 300\n100 46 150\n100 50 150\n001 97 150\n3 300\n100 50 150\n100 50 267\n168 50 150\n9 18\n2 1 1\n3 1 1\n3 0 2\n4 010 1\n5 100 1\n5 100 1\n10 5 3\n10 5 3\n1 7 1000\n10 18\n1 3 3\n2 3 4\n3 4 5\n3 5 6\n5 6 7\n6 7 8\n7 8 9\n8 9 10\n9 10 6\n17 11 12\n0 0", "3 300\n101 51 150\n100 50 150\n100 50 150\n3 300\n101 50 31\n100 50 272\n200 50 150\n9 18\n3 1 0\n3 1 1\n3 1 1\n4 100 1\n5 100 1\n2 100 1\n10 5 3\n10 5 3\n1 4 1000\n10 18\n1 4 3\n2 3 4\n3 4 5\n4 5 6\n5 6 3\n6 7 8\n7 8 9\n8 9 10\n9 10 11\n14 11 12\n0 0", "3 492\n100 46 150\n100 50 150\n101 50 150\n3 300\n100 84 150\n100 50 272\n200 50 150\n9 18\n2 1 1\n4 0 1\n4 0 1\n4 100 1\n5 100 1\n5 100 1\n10 5 3\n10 5 3\n1 7 1000\n10 18\n1 3 3\n2 3 7\n4 3 5\n4 5 6\n5 6 9\n6 0 8\n7 8 9\n8 11 10\n1 10 11\n5 12 7\n0 0", "3 300\n100 52 150\n100 50 150\n100 50 150\n3 300\n110 50 35\n100 50 150\n200 50 150\n9 18\n3 1 1\n3 1 1\n3 1 1\n4 100 1\n5 100 1\n5 100 1\n10 5 3\n10 5 3\n1 0 1000\n10 31\n1 2 3\n2 3 4\n3 4 5\n4 6 6\n5 6 7\n6 7 8\n7 8 9\n8 9 10\n9 10 11\n10 11 12\n0 0"], "outputs": ["3\n3\n3\n9\n", "3\n3\n3\n4\n", "3\n3\n5\n4\n", "3\n3\n4\n5\n", "2\n3\n3\n9\n", "2\n3\n5\n6\n", "2\n3\n4\n3\n", "2\n3\n9\n4\n"]}
767
1,876
coding
Solve the programming task below in a Python markdown code block. In this Kata you are to implement a function that parses a string which is composed from tokens of the form 'n1-n2,n3,n4-n5:n6' where 'nX' is a positive integer. Each token represent a different range: 'n1-n2' represents the range n1 to n2 (inclusive in both ends). 'n3' represents the single integer n3. 'n4-n5:n6' represents the range n4 to n5 (inclusive in both ends) but only includes every other n6 integer. Notes: 1. The input string doesn't not have to include all the token types. 2. All integers are assumed to be positive. 3. Tokens may be separated by `','`, `', '` or ` , `. Some examples: '1-10,14, 20-25:2' -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 22, 24] '5-10' -> [5, 6, 7, 8, 9, 10] '2' -> [2] The output should be a list of integers. Also feel free to reuse/extend the following starter code: ```python def range_parser(string): ```
{"functional": "_inputs = [['1-10,14, 20-25:2'], ['5-10'], ['2'], ['1-10,3'], ['1-10:5']]\n_outputs = [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 22, 24]], [[5, 6, 7, 8, 9, 10]], [[2]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3]], [[1, 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(range_parser(*i), o[0])"}
302
300
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph. The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0. During each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1]. Additionally, it is not allowed for the Cat to travel to the Hole (node 0). Then, the game can end in three ways: If ever the Cat occupies the same node as the Mouse, the Cat wins. If ever the Mouse reaches the Hole, the Mouse wins. If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a graph, and assuming both players play optimally, return 1 if the mouse wins the game, 2 if the cat wins the game, or 0 if the game is a draw.   Please complete the following python code precisely: ```python class Solution: def catMouseGame(self, graph: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]) == 0\n assert candidate(graph = [[1,3],[0],[3],[0,2]]) == 1\n\n\ncheck(Solution().catMouseGame)"}
317
80
coding
Solve the programming task below in a Python markdown code block. You are given an integer $n$. You have to calculate the number of binary (consisting of characters 0 and/or 1) strings $s$ meeting the following constraints. For every pair of integers $(i, j)$ such that $1 \le i \le j \le n$, an integer $a_{i,j}$ is given. It imposes the following constraint on the string $s_i s_{i+1} s_{i+2} \dots s_j$: if $a_{i,j} = 1$, all characters in $s_i s_{i+1} s_{i+2} \dots s_j$ should be the same; if $a_{i,j} = 2$, there should be at least two different characters in $s_i s_{i+1} s_{i+2} \dots s_j$; if $a_{i,j} = 0$, there are no additional constraints on the string $s_i s_{i+1} s_{i+2} \dots s_j$. Count the number of binary strings $s$ of length $n$ meeting the aforementioned constraints. Since the answer can be large, print it modulo $998244353$. -----Input----- The first line contains one integer $n$ ($2 \le n \le 100$). Then $n$ lines follow. The $i$-th of them contains $n-i+1$ integers $a_{i,i}, a_{i,i+1}, a_{i,i+2}, \dots, a_{i,n}$ ($0 \le a_{i,j} \le 2$). -----Output----- Print one integer — the number of strings meeting the constraints, taken modulo $998244353$. -----Examples----- Input 3 1 0 2 1 0 1 Output 6 Input 3 1 1 2 1 0 1 Output 2 Input 3 1 2 1 1 0 1 Output 0 Input 3 2 0 2 0 1 1 Output 0 -----Note----- In the first example, the strings meeting the constraints are 001, 010, 011, 100, 101, 110. In the second example, the strings meeting the constraints are 001, 110.
{"inputs": ["2\n0 0\n2\n", "2\n1 0\n2\n", "2\n1 2\n2\n", "3\n1 0 2\n1 0\n1\n", "3\n1 1 2\n1 0\n1\n", "3\n1 2 1\n1 0\n1\n", "3\n2 0 2\n0 1\n1\n", "3\n0 0 0\n2 0\n2\n"], "outputs": ["0\n", "0\n", "0\n", "6\n", "2\n", "0\n", "0\n", "0\n"]}
543
148
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 servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.   Please complete the following python code precisely: ```python class Solution: def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(servers = [3,3,2], tasks = [1,2,3,2,1,2]) == [2,2,0,2,1,2]\n assert candidate(servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]) == [1,4,1,4,1,3,2]\n\n\ncheck(Solution().assignTasks)"}
342
113
coding
Solve the programming task below in a Python markdown code block. There are N dishes of cuisine placed in front of Takahashi and Aoki. For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N. When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness. Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat. Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end". Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end". Constraints * 1 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 : A_N B_N Output Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end". Examples Input 3 10 10 20 20 30 30 Output 20 Input 3 20 10 20 20 20 30 Output 20 Input 6 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 Output -2999999997
{"inputs": ["3\n28 0\n2 40\n8 7", "3\n28 0\n3 40\n8 7", "3\n2 0\n3 40\n8 11", "3\n4 0\n0 0\n53 12", "3\n4 0\n0 0\n86 12", "3\n0 17\n5 4\n2 53", "3\n0 17\n5 4\n3 53", "3\n0 34\n5 4\n3 53"], "outputs": ["10\n", "11\n", "-6\n", "53\n", "86\n", "-10\n", "-9\n", "-26\n"]}
456
180
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 level order traversal of its nodes' values. (i.e., from left to right, level by level).   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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ```
{"functional": "def check(candidate):\n assert candidate(root = tree_node([3,9,20,None,None,15,7])) == [[3],[9,20],[15,7]]\n assert candidate(root = tree_node([1])) == [[1]]\n assert candidate(root = tree_node([])) == []\n\n\ncheck(Solution().levelOrder)"}
134
86
coding
Solve the programming task below in a Python markdown code block. Burger Town is a city that consists of $N$ special junctions and $N-1$ pathways. There is exactly one shortest path between each pair of junctions. Junction $\boldsymbol{i}$ is located at $(x_i,y_i)$ and the distance between two junctions $i,j$ is defined by the Taxicab geometry. Tim has recently afforded a taxicab to work as a taxicab driver. His vehicle was very cheap, but has a very big flaw. It can only drive $\mbox{H}$ units horizontally and $\mbox{V}$ units vertically before refueling. If a customer wants to be brought from a junction $\boldsymbol{i}$ to another junction $j$, then this car is only capable of driving the route, iff the sum of horizontal distances and the sum of vertical distances on this path are less than or equal to $\mbox{H}$ and $\mbox{V}$ respectively. Also, there is a unique path between any two junctions. Now he has thoughts about returning the vehicle back to the seller. But he first wants to know, if it's even worth it. That's why he wants to know the number of unordered pairs $(i,j)$ such that it is not possible to drive a customer from junction $\boldsymbol{i}$ to junction $j$. Input Format On the first line you will be given $N$, $\mbox{H}$ and $\mbox{V}$ separated by a single space. Each of the next $N$ lines contains two space separated integers $x_i,y_i$, denoting the location of junction $\boldsymbol{i}$. Each of the next $N-1$ lines contains two space separated integers describing a path existing between $u_{i},v_{i}$, i.e., there is a path between $u_i$ and $v_i$. Output Format Output the number of unordered pairs $(i,j)$ such that it is not possible to drive from $\boldsymbol{i}$ to $j$. Constraints $2\leq N\leq10^5$ $0\leq H,V\leq10^{14}$ $0\leq x_i,y_i\leq10^9$ Sample Input 3 2 1 0 0 1 1 2 0 1 2 2 3 Sample Output 1 Explanation The car is only capable of driving $H=2$ units horizontally and $V=1$ unit vertically. The horizontal distance between junction 1 and 3(via 2) is equal to 2($\textbf{0}\to1\to2$), which fits under the horizontal limit of the car. The vertical distance between 1 and 3 is also equal to 2($\textbf{0}\to1\to0$), but this is not possible for this car since $2>V$.
{"inputs": ["3 2 1\n0 0\n1 1\n2 0\n1 2\n2 3\n"], "outputs": ["1\n"]}
630
38
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A train line going through a city has two routes, the regular route and the express route. Both routes go through the same n + 1 stops labeled from 0 to n. Initially, you start on the regular route at stop 0. You are given two 1-indexed integer arrays regular and express, both of length n. regular[i] describes the cost it takes to go from stop i - 1 to stop i using the regular route, and express[i] describes the cost it takes to go from stop i - 1 to stop i using the express route. You are also given an integer expressCost which represents the cost to transfer from the regular route to the express route. Note that: There is no cost to transfer from the express route back to the regular route. You pay expressCost every time you transfer from the regular route to the express route. There is no extra cost to stay on the express route. Return a 1-indexed array costs of length n, where costs[i] is the minimum cost to reach stop i from stop 0. Note that a stop can be counted as reached from either route.   Please complete the following python code precisely: ```python class Solution: def minimumCosts(self, regular: List[int], express: List[int], expressCost: int) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(regular = [1,6,9,5], express = [5,2,3,10], expressCost = 8) == [1,7,14,19]\n assert candidate(regular = [11,5,13], express = [7,10,6], expressCost = 3) == [10,15,24]\n\n\ncheck(Solution().minimumCosts)"}
291
109
coding
Solve the programming task below in a Python markdown code block. There is a grid of squares with H+1 horizontal rows and W vertical columns. You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top. For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print `-1` instead. Constraints * 1 \leq H,W \leq 2\times 10^5 * 1 \leq A_i \leq B_i \leq W Input Input is given from Standard Input in the following format: H W A_1 B_1 A_2 B_2 : A_H B_H Output Print H lines. The i-th line should contain the answer for the case k=i. Example Input 4 4 2 4 1 1 2 3 2 4 Output 1 3 6 -1
{"inputs": ["4 7\n2 4\n1 1\n2 3\n2 4", "4 4\n2 4\n1 1\n2 0\n2 4", "4 4\n3 4\n1 1\n2 3\n2 4", "4 4\n2 4\n1 1\n2 0\n3 4", "4 4\n1 4\n1 1\n2 0\n3 4", "4 5\n0 4\n0 1\n4 5\n3 4", "4 7\n2 4\n0 1\n2 3\n5 7", "4 7\n1 3\n0 1\n4 1\n3 7"], "outputs": ["1\n2\n3\n4\n", "1\n3\n4\n-1\n", "1\n2\n5\n-1\n", "1\n3\n4\n5\n", "-1\n-1\n-1\n-1\n", "1\n2\n-1\n-1\n", "1\n2\n3\n7\n", "1\n2\n3\n-1\n"]}
315
262
coding
Solve the programming task below in a Python markdown code block. Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers. Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not. Input The first line contains two integers n and m (1 ≤ n, m ≤ 12) — the number of pairs the first participant communicated to the second and vice versa. The second line contains n pairs of integers, each between 1 and 9, — pairs of numbers communicated from first participant to the second. The third line contains m pairs of integers, each between 1 and 9, — pairs of numbers communicated from the second participant to the first. All pairs within each set are distinct (in particular, if there is a pair (1,2), there will be no pair (2,1) within the same set), and no pair contains the same number twice. It is guaranteed that the two sets do not contradict the statements, in other words, there is pair from the first set and a pair from the second set that share exactly one number. Output If you can deduce the shared number with certainty, print that number. If you can with certainty deduce that both participants know the shared number, but you do not know it, print 0. Otherwise print -1. Examples Input 2 2 1 2 3 4 1 5 3 4 Output 1 Input 2 2 1 2 3 4 1 5 6 4 Output 0 Input 2 3 1 2 4 5 1 2 1 3 2 3 Output -1 Note In the first example the first participant communicated pairs (1,2) and (3,4), and the second communicated (1,5), (3,4). Since we know that the actual pairs they received share exactly one number, it can't be that they both have (3,4). Thus, the first participant has (1,2) and the second has (1,5), and at this point you already know the shared number is 1. In the second example either the first participant has (1,2) and the second has (1,5), or the first has (3,4) and the second has (6,4). In the first case both of them know the shared number is 1, in the second case both of them know the shared number is 4. You don't have enough information to tell 1 and 4 apart. In the third case if the first participant was given (1,2), they don't know what the shared number is, since from their perspective the second participant might have been given either (1,3), in which case the shared number is 1, or (2,3), in which case the shared number is 2. While the second participant does know the number with certainty, neither you nor the first participant do, so the output is -1.
{"inputs": ["2 1\n4 5 6 7\n4 7\n", "2 1\n1 2 1 3\n1 2\n", "2 1\n3 5 6 7\n4 7\n", "2 1\n1 2 2 3\n1 2\n", "2 2\n1 2 1 3\n1 2 1 3\n", "2 2\n1 2 2 4\n1 2 1 3\n", "2 2\n1 2 2 3\n2 3 3 4\n", "2 2\n1 2 3 4\n1 5 3 4\n"], "outputs": ["-1", "1", "7\n", "2\n", "1", "0", "0", "1"]}
719
193
coding
Solve the programming task below in a Python markdown code block. Hakone Ekiden is one of the Japanese New Year's traditions. In Hakone Ekiden, 10 runners from each team aim for the goal while connecting the sashes at each relay station. In the TV broadcast, the ranking change from the previous relay station is displayed along with the passing order of each team at the relay station. So, look at it and tell us how many possible passage orders for each team at the previous relay station. The number of possible transit orders can be very large, so answer by the remainder divided by 1,000,000,007. Input The input is given in the form: > n > c1 > c2 > ... > cn > The number n (1 ≤ n ≤ 200) representing the number of teams is on the first line, and the ranking changes from the previous relay station in order from the first place on the following n lines. If it is'`U`', the ranking is up, if it is'`-`', the ranking is not changed) is written. Output Please output in one line by dividing the number of passages that could have been the previous relay station by 1,000,000,007. Examples Input 3 - U D Output 1 Input 5 U U - D D Output 5 Input 8 U D D D D D D D Output 1 Input 10 U D U D U D U D U D Output 608 Input 2 D U Output 0
{"inputs": ["2\nD\nT", "2\nE\nU", "2\nF\nU", "2\nD\nS", "2\nC\nU", "2\nB\nU", "2\nD\nV", "2\nD\nR"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
375
94
coding
Solve the programming task below in a Python markdown code block. The land of Programmers Army is surrounded by many islands. A unique number is associated with each island. The king of the islands is a very generous person, he donates a certain amount of gold coins to travelers for visiting each island that they visited to. Now, you are appointed as a traveler, who will travel to all these(or some) islands as many times as the Army wants, and you will collect gold coins from the king of the island. In each trip, you will be asked to give the total sum of gold coins you have collected. -----Input:----- - The first line of the input contains a single integer $T$. $T$ denoting the number of test cases. The description of $T$ test cases is as follows. - The next line of the input contains a single integer $N$. $N$ denotes the total number of Islands. - The next line of the input contains $N$ space-separated integers $A1, A2, A3...An$ where $ith$ number denotes the maximum number of coins that the king of $ith$ island can donate. - Next line contains a single integer $Q$. $Q$ denotes the total number of times traveler have to go for the trip. - Next $Q$ lines contains, two space-separated integers $Q1,Q2$ denoting the start and end number of islands, i.e. traveler will start the trip from $Q1th$ island and will go till $Q2th$ island, in each trip. Note: islands are numbered from $1$ to $N$. -----Output:----- - For each trip print the total number of gold coins, traveler will collect(each on a new line). -----Constraints:----- - $1 \leq T \leq 100$ - $1 \leq N \leq 10^4$ - $1 \leq A1, A2, A3...An \leq 10^5$ - $1 \leq Q \leq 10^3$ - $1 \leq Q1,Q2 \leq N$ -----Sample Input:----- 1 4 10 2 5 50 2 1 3 2 4 -----Sample Output:----- 17 57 -----Explanation:----- - In 1st Trip, traveler will go from 1st Island to 3rd Island, hence the total number of coins traveler can collect is 10+2+5 = 17 - In 2 d Trip, traveler will go from 2nd Island to 4th Island, hence the total number of coins traveler can collect is 2+5+50 = 57
{"inputs": ["1\n4\n10 2 5 50\n2\n1 3\n2 4"], "outputs": ["17\n57"]}
584
38
coding
Solve the programming task below in a Python markdown code block. Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where a_{i} represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007. -----Input----- The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number a_{i} (1 ≤ a_{i} ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students. -----Output----- Print the minimum total time to finish all tasks modulo 10 007. -----Example----- Input 2 1 3 Output 6 -----Note----- In the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.
{"inputs": ["2\n1\n3\n", "2\n1\n4\n", "2\n0\n4\n", "2\n1\n1\n", "2\n1\n8\n", "2\n1\n9\n", "2\n1\n2\n", "2\n1\n6\n"], "outputs": ["6\n", "8\n", "0\n", "2\n", "16\n", "18\n", "4\n", "12\n"]}
478
105
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.   Please complete the following python code precisely: ```python class Solution: def findMaximumXOR(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [3,10,5,25,2,8]) == 28\n assert candidate(nums = [14,70,53,83,49,91,36,80,92,51,66,70]) == 127\n\n\ncheck(Solution().findMaximumXOR)"}
78
94
coding
Solve the programming task below in a Python markdown code block. "The Shell Game" involves cups upturned on a playing surface, with a ball placed underneath one of them. The index of the cups are swapped around multiple times. After that the players will try to find which cup contains the ball. Your task is as follows. Given the cup that the ball starts under, and list of swaps, return the location of the ball at the end. Cups are given like array/list indices. For example, given the starting position `0` and the swaps `[(0, 1), (1, 2), (1, 0)]`: * The first swap moves the ball from `0` to `1` * The second swap moves the ball from `1` to `2` * The final swap doesn't affect the position of the ball. So ```python find_the_ball(0, [(0, 1), (2, 1), (0, 1)]) == 2 ``` There aren't necessarily only three cups in this game, but there will be at least two. You can assume all swaps are valid, and involve two distinct indices. Also feel free to reuse/extend the following starter code: ```python def find_the_ball(start, swaps): ```
{"functional": "_inputs = [[5, []], [0, []], [9, []], [0, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], [15, 16], [16, 17], [17, 18], [18, 19], [19, 20], [20, 21], [21, 22], [22, 23], [23, 24], [24, 25], [25, 26], [26, 27], [27, 28], [28, 29], [29, 30], [30, 31], [31, 32], [32, 33], [33, 34], [34, 35], [35, 36], [36, 37], [37, 38], [38, 39], [39, 40], [40, 41], [41, 42], [42, 43], [43, 44], [44, 45], [45, 46], [46, 47], [47, 48], [48, 49], [49, 50], [50, 51], [51, 52], [52, 53], [53, 54], [54, 55], [55, 56], [56, 57], [57, 58], [58, 59], [59, 60], [60, 61], [61, 62], [62, 63], [63, 64], [64, 65], [65, 66], [66, 67], [67, 68], [68, 69], [69, 70], [70, 71], [71, 72], [72, 73], [73, 74], [74, 75], [75, 76], [76, 77], [77, 78], [78, 79], [79, 80], [80, 81], [81, 82], [82, 83], [83, 84], [84, 85], [85, 86], [86, 87], [87, 88], [88, 89], [89, 90], [90, 91], [91, 92], [92, 93], [93, 94], [94, 95], [95, 96], [96, 97], [97, 98], [98, 99], [99, 100], [100, 101]]], [0, [[1, 0], [2, 1], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6], [8, 7], [9, 8], [10, 9], [11, 10], [12, 11], [13, 12], [14, 13], [15, 14], [16, 15], [17, 16], [18, 17], [19, 18], [20, 19], [21, 20], [22, 21], [23, 22], [24, 23], [25, 24], [26, 25], [27, 26], [28, 27], [29, 28], [30, 29], [31, 30], [32, 31], [33, 32], [34, 33], [35, 34], [36, 35], [37, 36], [38, 37], [39, 38], [40, 39], [41, 40], [42, 41], [43, 42], [44, 43], [45, 44], [46, 45], [47, 46], [48, 47], [49, 48], [50, 49], [51, 50], [52, 51], [53, 52], [54, 53], [55, 54], [56, 55], [57, 56], [58, 57], [59, 58], [60, 59], [61, 60], [62, 61], [63, 62], [64, 63], [65, 64], [66, 65], [67, 66], [68, 67], [69, 68], [70, 69], [71, 70], [72, 71], [73, 72], [74, 73], [75, 74], [76, 75], [77, 76], [78, 77], [79, 78], [80, 79], [81, 80], [82, 81], [83, 82], [84, 83], [85, 84], [86, 85], [87, 86], [88, 87], [89, 88], [90, 89], [91, 90], [92, 91], [93, 92], [94, 93], [95, 94], [96, 95], [97, 96], [98, 97], [99, 98], [100, 99], [101, 100]]]]\n_outputs = [[5], [0], [9], [101], [101]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(find_the_ball(*i), o[0])"}
272
1,775
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. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). Return the maximum absolute sum of any (possibly empty) subarray of nums. Note that abs(x) is defined as follows: If x is a negative integer, then abs(x) = -x. If x is a non-negative integer, then abs(x) = x.   Please complete the following python code precisely: ```python class Solution: def maxAbsoluteSum(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,-3,2,3,-4]) == 5\n assert candidate(nums = [2,-5,1,-4,3,-2]) == 8\n\n\ncheck(Solution().maxAbsoluteSum)"}
158
62
coding
Solve the programming task below in a Python markdown code block. Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A \times B + C = N? -----Constraints----- - 2 \leq N \leq 10^6 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print the answer. -----Sample Input----- 3 -----Sample Output----- 3 There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).
{"inputs": ["4", "5", "8", "6", "2", "9", "7", "3"], "outputs": ["5\n", "8\n", "16\n", "10\n", "1\n", "20\n", "14\n", "3"]}
158
65
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.   Please complete the following python code precisely: ```python class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(n = 4, connections = [[0,1],[0,2],[1,2]]) == 1\n assert candidate(n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]) == 2\n assert candidate(n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]) == -1\n assert candidate(n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]) == 0\n\n\ncheck(Solution().makeConnected)"}
172
143
coding
Solve the programming task below in a Python markdown code block. Nim is the most famous two-player algorithm game. The basic rules for this game are as follows: The game starts with a number of piles of stones. The number of stones in each pile may not be equal. The players alternately pick up $\mbox{1}$ or more stones from $\mbox{1}$ pile The player to remove the last stone wins. For example, there are $n=3$ piles of stones having $pile=[3,2,4]$ stones in them. Play may proceed as follows: Player Takes Leaving pile=[3,2,4] 1 2 from pile[1] pile=[3,4] 2 2 from pile[1] pile=[3,2] 1 1 from pile[0] pile=[2,2] 2 1 from pile[0] pile=[1,2] 1 1 from pile[1] pile=[1,1] 2 1 from pile[0] pile=[0,1] 1 1 from pile[1] WIN Given the value of $n$ and the number of stones in each pile, determine the game's winner if both players play optimally. Function Desctription Complete the nimGame function in the editor below. It should return a string, either First or Second. nimGame has the following parameter(s): pile: an integer array that represents the number of stones in each pile Input Format The first line contains an integer, $\mathrm{~g~}$, denoting the number of games they play. Each of the next $\mathrm{~g~}$ pairs of lines is as follows: The first line contains an integer $n$, the number of piles. The next line contains $n$ space-separated integers $pile[i]$, the number of stones in each pile. Constraints $1\leq g\leq100$ $1\leq n\leq100$ $0\leq s_i\leq100$ Player 1 always goes first. Output Format For each game, print the name of the winner on a new line (i.e., either First or Second). Sample Input 2 2 1 1 3 2 1 4 Sample Output Second First Explanation In the first case, there are $n=2$ piles of $pile=[1,1]$ stones. Player $\mbox{1}$ has to remove one pile on the first move. Player $2$ removes the second for a win. In the second case, there are $n=3$ piles of $pile=[2,1,4]$ stones. If player $\mbox{1}$ removes any one pile, player $2$ can remove all but one of another pile and force a win. If player $\mbox{1}$ removes less than a pile, in any case, player $2$ can force a win as well, given optimal play.
{"inputs": ["2\n2\n1 1\n3\n2 1 4\n"], "outputs": ["Second\nFirst\n"]}
658
30
coding
Solve the programming task below in a Python markdown code block. Takahashi is hosting an sports meet. There are N people who will participate. These people are conveniently numbered 1 through N. Also, there are M options of sports for this event. These sports are numbered 1 through M. Among these options, Takahashi will select one or more sports (possibly all) to be played in the event. Takahashi knows that Person i's j-th favorite sport is Sport A_{ij}. Each person will only participate in his/her most favorite sport among the ones that are actually played in the event, and will not participate in the other sports. Takahashi is worried that one of the sports will attract too many people. Therefore, he would like to carefully select sports to be played so that the number of the participants in the sport with the largest number of participants is minimized. Find the minimum possible number of the participants in the sport with the largest number of participants. Constraints * 1 \leq N \leq 300 * 1 \leq M \leq 300 * A_{i1} , A_{i2} , ... , A_{iM} is a permutation of the integers from 1 to M. Input Input is given from Standard Input in the following format: N M A_{11} A_{12} ... A_{1M} A_{21} A_{22} ... A_{2M} : A_{N1} A_{N2} ... A_{NM} Output Print the minimum possible number of the participants in the sport with the largest number of participants. Examples Input 4 5 5 1 3 4 2 2 5 3 1 4 2 3 1 4 5 2 5 4 3 1 Output 2 Input 3 3 2 1 3 2 1 3 2 1 3 Output 3
{"inputs": ["2 3\n2 1 3\n2 1 3\n2 1 3", "1 3\n2 1 3\n2 1 3\n2 1 3", "1 3\n2 1 3\n2 1 4\n2 1 3", "3 3\n2 1 3\n2 1 3\n2 1 3", "2 5\n5 1 3 4 2\n2 5 3 1 4\n2 3 1 4 5\n2 5 4 3 1", "2 5\n5 1 3 4 2\n2 5 3 1 4\n2 3 1 6 5\n2 5 4 3 1", "2 5\n5 1 3 4 2\n2 5 3 1 4\n2 3 1 6 7\n2 5 4 3 1", "2 5\n5 1 3 4 2\n2 5 3 1 4\n2 0 1 4 5\n2 5 4 3 1"], "outputs": ["2\n", "1\n", "1\n", "3", "1\n", "1\n", "1\n", "1\n"]}
426
309
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s, find the length of the longest substring without repeating characters.   Please complete the following python code precisely: ```python class Solution: def lengthOfLongestSubstring(self, s: str) -> int: ```
{"functional": "def check(candidate):\n assert candidate(s = \"abcabcbb\") == 3\n assert candidate(s = \"bbbbb\") == 1\n assert candidate(s = \"pwwkew\") == 3\n\n\ncheck(Solution().lengthOfLongestSubstring)"}
66
64
coding
Solve the programming task below in a Python markdown code block. Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $i$-th page contains some mystery that will be explained on page $a_i$ ($a_i \ge i$). Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $i$ such that Ivan already has read it, but hasn't read page $a_i$). After that, he closes the book and continues to read it on the following day from the next page. How many days will it take to read the whole book? -----Input----- The first line contains single integer $n$ ($1 \le n \le 10^4$) — the number of pages in the book. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($i \le a_i \le n$), where $a_i$ is the number of page which contains the explanation of the mystery on page $i$. -----Output----- Print one integer — the number of days it will take to read the whole book. -----Example----- Input 9 1 3 3 6 7 6 8 8 9 Output 4 -----Note----- Explanation of the example test: During the first day Ivan will read only the first page. During the second day Ivan will read pages number $2$ and $3$. During the third day — pages $4$-$8$. During the fourth (and the last) day Ivan will read remaining page number $9$.
{"inputs": ["1\n1\n", "1\n1\n", "4\n1 2 4 4\n", "4\n1 2 4 4\n", "4\n2 2 4 4\n", "4\n2 4 4 4\n", "9\n1 3 3 6 7 6 8 8 9\n", "9\n1 3 3 6 7 6 8 8 9\n"], "outputs": ["1\n", "1\n", "3\n", "3\n", "2\n", "1\n", "4\n", "4\n"]}
393
142
coding
Solve the programming task below in a Python markdown code block. Calculate the power of an army of numbers from 1 to $N$, both included. -----Input:----- - First line will contain a single integer $N$. -----Output:----- For each testcase, output in a single line containing the answer. -----Constraints----- - $1 \leq N \leq 5000$ -----Sample Input:----- 24 -----Sample Output:----- 5
{"inputs": ["24"], "outputs": ["5"]}
97
13
coding
Solve the programming task below in a Python markdown code block. Given a tree T with n nodes, how many subtrees (T') of T have at most K edges connected to (T - T')? Input Format The first line contains two integers n and K followed by n-1 lines each containing two integers a & b denoting that there's an edge between a & b. Constraints 1 <= K <= n <= 50 Every node is indicated by a distinct number from 1 to n. Output Format A single integer which denotes the number of possible subtrees. Sample Input 3 1 2 1 2 3 Sample Output 6 Explanation There are 2^3 possible sub-trees: {} {1} {2} {3} {1, 2} {1, 3} {2, 3} {1, 2, 3} But: the sub-trees {2} and {1,3} are not valid. {2} isn't valid because it has 2 edges connecting to it's complement {1,3} whereas K = 1 in the sample test-case {1,3} isn't valid because, well, it's not a sub-tree. The nodes aren't connected.
{"inputs": ["3 1\n2 1\n2 3\n"], "outputs": ["6\n"]}
272
24
coding
Solve the programming task below in a Python markdown code block. Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on. Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active. Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake. -----Input----- The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears. The second line contains n digits a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number a_{i}. -----Output----- In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise. -----Examples----- Input 3 1 0 0 Output Yes Input 5 4 2 1 4 3 Output Yes Input 4 0 2 3 1 Output No -----Note----- In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
{"inputs": ["1\n0\n", "1\n0\n", "2\n1 0\n", "2\n0 0\n", "2\n0 1\n", "2\n1 0\n", "2\n1 1\n", "2\n1 1\n"], "outputs": ["Yes\n", "Yes\n", "Yes\n", "No\n", "Yes\n", "Yes\n", "No\n", "No\n"]}
503
98
coding
Solve the programming task below in a Python markdown code block. Jack stays in a n-storey hostel. His dorm room is on the jth floor. Every morning, he is in so much hurry for classes that he cannot not decide whether to take Lift or Stairs to reach ground-floor. He asks you to help him choose either Stairs or Lift based on total time taken to reach ground-floor. It takes him 10 seconds to get down by 1 floor using Stairs. The lift works as follows: If the lift is at the ith floor, it take 5 second to reach the (i-1) or (i+1) floor. The lift may stop at a floor to pick up persons or to drop off persons or to change the direction. If the lift stops at a floor due to one/more of these reasons, it takes 10 seconds extra at that floor. It changes its direction only at the ground floor(0th floor) or top floor(nth floor). Assume that nobody else is using the lift other than Jack. Input: First line contains T - number of test cases. Each of next T lines contains three integers n, J and L and a character either 'U' or 'D' (without quotes) where J indicates the number of the floor Jack is present at the moment, L indicates the number of floor Lift is present at the moment and 'U' or 'D' represents whether Lift is moving Up or Down. Output: Print in T lines containing 'Stairs' or 'Lift'(without quotes) followed by the minimum amount of time it would take Jack to reach the ground floor. If time taken by both the ways is same, Jack would obviously prefer the Lift. Constraints: 1 ≤ n ≤ 100 1 ≤ J ≤ n 0 ≤ L ≤ n SAMPLE INPUT 3 30 10 20 U 10 10 10 U 80 60 60 D SAMPLE OUTPUT Stairs 100 Lift 70 Lift 320 Explanation Jack is on the 10th floor. So it takes him 1010=100 seconds to reach the ground floor by stairs. The lift is on the 20th floor. As it is going up right now, it will first go to the top floor( i.e. the 30th floor)(105 seconds) + change its direction(10 seconds) + come down to 10th floor(205 seconds) + pick up Jack(10 seconds) + reach the ground floor(105 seconds) + drop Jack ( 10 seconds) ; time = (30-20)5+10+305+10 +10 = 50+10+150+20=230 seconds. Time to reach ground floor by stairs=1010=100 seconds. Here, the lift and Jack are on the same floor (i.e. the top floor). Time to reach ground floor by lift = time to change directions(10 seconds) + time to reach ground floor(105 seconds) + time to drop Jack(10 seconds)=10 + 510+10=70 seconds. * When Jack is on the top floor, there is no need to consider separately the time for Jack to climb on the lift. As he will climb when the lift stops to change directions
{"inputs": ["32\n10 5 5 U\n10 5 5 D\n10 3 3 D\n10 9 9 U\n10 10 10 U\n10 10 10 D\n100 80 20 U\n100 80 45 U\n100 80 46 U\n100 80 40 D\n100 80 0 D\n100 80 79 D\n100 100 3 U\n100 100 4 U\n100 100 5 U\n100 100 2 U\n100 100 1 D\n100 53 100 U\n100 52 100 U\n100 51 100 U\n100 54 100 U\n100 51 99 U\n100 53 99 U\n100 54 99 U\n100 55 99 U\n100 52 100 D\n100 51 100 D\n100 50 100 D\n100 50 99 D\n100 51 99 D\n100 52 99 D\n100 53 99 D", "50\n76 46 57 U\n78 44 21 D\n100 71 6 U\n66 35 18 D\n79 50 66 U\n82 49 81 D\n91 46 59 D\n86 39 59 U\n87 30 44 D\n57 36 39 U\n64 33 16 U\n98 11 79 U\n66 59 33 D\n65 15 41 U\n65 15 47 U\n59 12 15 U\n60 7 32 U\n51 9 51 D\n82 63 42 D\n51 29 47 D\n96 67 56 U\n69 52 60 D\n63 30 10 U\n93 35 56 D\n85 31 80 D\n90 26 10 U\n52 50 20 U\n79 65 54 D\n91 1 21 U\n51 21 23 D\n73 2 23 D\n91 26 56 D\n71 5 55 D\n95 62 5 D\n68 11 18 U\n98 46 47 U\n57 27 32 U\n87 62 54 U\n81 30 45 U\n73 19 42 U\n89 34 60 U\n57 46 15 D\n84 55 14 U\n63 38 56 D\n100 32 32 D\n64 63 19 U\n82 5 27 U\n61 34 43 U\n70 20 15 D\n90 83 52 U"], "outputs": ["Stairs 50\nLift 45\nStairs 30\nLift 85\nLift 70\nLift 70\nStairs 800\nStairs 800\nLift 800\nStairs 800\nStairs 800\nStairs 800\nStairs 1000\nLift 1000\nLift 995\nStairs 1000\nStairs 1000\nLift 530\nStairs 520\nStairs 510\nLift 530\nStairs 510\nStairs 530\nLift 535\nLift 535\nLift 520\nStairs 510\nStairs 500\nStairs 500\nStairs 510\nLift 515\nLift 515", "Stairs 460\nStairs 440\nStairs 710\nStairs 350\nLift 490\nLift 425\nLift 315\nStairs 390\nLift 240\nStairs 360\nStairs 330\nStairs 110\nStairs 590\nStairs 150\nStairs 150\nStairs 120\nStairs 70\nStairs 90\nStairs 630\nLift 255\nStairs 670\nLift 320\nStairs 300\nLift 300\nStairs 310\nStairs 260\nLift 450\nStairs 650\nStairs 10\nLift 135\nStairs 20\nStairs 260\nStairs 50\nStairs 620\nStairs 110\nStairs 460\nStairs 270\nStairs 620\nStairs 300\nStairs 190\nStairs 340\nStairs 460\nStairs 550\nLift 300\nLift 180\nLift 575\nStairs 50\nStairs 340\nStairs 200\nLift 670"]}
743
1,420
coding
Solve the programming task below in a Python markdown code block. A frog is initially at position $0$ on the number line. The frog has two positive integers $a$ and $b$. From a position $k$, it can either jump to position $k+a$ or $k-b$. Let $f(x)$ be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval $[0, x]$. The frog doesn't need to visit all these integers in one trip, that is, an integer is counted if the frog can somehow reach it if it starts from $0$. Given an integer $m$, find $\sum_{i=0}^{m} f(i)$. That is, find the sum of all $f(i)$ for $i$ from $0$ to $m$. -----Input----- The first line contains three integers $m, a, b$ ($1 \leq m \leq 10^9, 1 \leq a,b \leq 10^5$). -----Output----- Print a single integer, the desired sum. -----Examples----- Input 7 5 3 Output 19 Input 1000000000 1 2019 Output 500000001500000001 Input 100 100000 1 Output 101 Input 6 4 5 Output 10 -----Note----- In the first example, we must find $f(0)+f(1)+\ldots+f(7)$. We have $f(0) = 1, f(1) = 1, f(2) = 1, f(3) = 1, f(4) = 1, f(5) = 3, f(6) = 3, f(7) = 8$. The sum of these values is $19$. In the second example, we have $f(i) = i+1$, so we want to find $\sum_{i=0}^{10^9} i+1$. In the third example, the frog can't make any jumps in any case.
{"inputs": ["7 5 3\n", "6 4 5\n", "7 5 3\n", "6 4 5\n", "26 92701 7\n", "26 92701 7\n", "3 998 99486\n", "3 998 99486\n"], "outputs": ["19\n", "10\n", "19\n", "10\n", "27\n", "27\n", "4\n", "4\n"]}
488
130
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian as well. Mike takes part in programming contests. His favourite topic is dynamic programming(DP). As he said, that he likes problems on DP, because "you spend a lot of time on thinking and a little time on coding". In this problem you are to solve a version of the knapsack problem(link), one of the most famous examples of DP problem. You are given N items, each has two parameters: a weight and a cost. Let's define M as the sum of the weights of all the items. Your task is to determine the most expensive cost of a knapsack, which capacity equals to 1, 2, ..., M. A cost of a knapsack equals to the sum of the costs of all the elements of the knapsack. Also, when you have a knapsack with a capacity is equal to C, then you can fill it with items, whose sum of weights is not greater than C. ------ Input ------ The first line of the input contains one integer N, denoting the number of the items. The next N lines contain two integers W and C each, denoting the weight and the cost of the corresponding item. ------ Output ------ For each capacity C (1 ≤ C ≤ M) of the knapsack, output a single integer - the most expensive cost for that capacity. ------ Constraints ------ 3 ≤ N ≤ 100000; 1 ≤ W ≤ 2, for each item; 1 ≤ C ≤ 10^{9}, for each item. ------ Example ------ Input: 5 1 1 2 2 2 3 2 4 2 5 Output: 1 5 6 9 10 12 13 14 15 ------ Explanations ------ In the test case, M equals to 9. For C = 1, it's optimal to choose {1} items; For C = 2, it's optimal to choose {5} items; For C = 3, it's optimal to choose {1, 5} items; For C = 4, it's optimal to choose {4, 5} items; For C = 5, it's optimal to choose {1, 4, 5} items; For C = 6, it's optimal to choose {3, 4, 5} items; For C = 7, it's optimal to choose {1, 3, 4, 5} items; For C = 8, it's optimal to choose {2, 3, 4, 5} items; For C = 9, it's optimal to choose {1, 2, 3, 4, 5} items.
{"inputs": ["5\n1 1\n2 2\n2 3\n2 4\n2 5"], "outputs": ["1 5 6 9 10 12 13 14 15 "]}
599
54
coding
Solve the programming task below in a Python markdown code block. International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition. For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995. You are given a list of abbreviations. For each of them determine the year it stands for. Input The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process. Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits. Output For each abbreviation given in the input, find the year of the corresponding Olympiad. Examples Input 5 IAO'15 IAO'2015 IAO'1 IAO'9 IAO'0 Output 2015 12015 1991 1989 1990 Input 4 IAO'9 IAO'99 IAO'999 IAO'9999 Output 1989 1999 2999 9999
{"inputs": ["1\nIAO'001\n", "1\nIAO'089\n", "1\nIAO'099\n", "1\nIAO'990\n", "1\nIAO'2015\n", "1\nIAO'2000\n", "1\nIAO'11378\n", "1\nIAO'11111\n"], "outputs": ["3001\n", "3089\n", "2099\n", "2990\n", "12015\n", "12000\n", "111378\n", "111111\n"]}
395
162
coding
Solve the programming task below in a Python markdown code block. There is a sequence of words in CamelCase as a string of letters, $\boldsymbol{\mathrm{~S~}}$, having the following properties: It is a concatenation of one or more words consisting of English letters. All letters in the first word are lowercase. For each of the subsequent words, the first letter is uppercase and rest of the letters are lowercase. Given $\boldsymbol{\mathrm{~S~}}$, determine the number of words in $\boldsymbol{\mathrm{~S~}}$. Example $s=one Two Thee$ There are $3$ words in the string: 'one', 'Two', 'Three'. Function Description Complete the camelcase function in the editor below. camelcase has the following parameter(s): string s: the string to analyze Returns int: the number of words in $\boldsymbol{\mathrm{~S~}}$ Input Format A single line containing string $\boldsymbol{\mathrm{~S~}}$. Constraints $1\leq\text{length of s}\leq10^5$ Sample Input saveChangesInTheEditor Sample Output 5 Explanation String $\boldsymbol{\mathrm{~S~}}$ contains five words: save Changes In The Editor Need help? Try this problem first to get familiar with HackerRank environment.
{"inputs": ["saveChangesInTheEditor\n"], "outputs": ["5\n"]}
297
17
coding
Solve the programming task below in a Python markdown code block. King loves to go on tours with his friends. King has N cars that can seat 5 people each and M cars that can seat 7 people each. Determine the maximum number of people that can travel together in these cars. ------ Input Format ------ - The first line of input contains a single integer T, the number of test cases. - The first and only line of each test case contains two space-separated integers N and M — the number of 5-seaters and 7-seaters, respectively. ------ Output Format ------ For each test case, output on a new line the maximum number of people that can travel together. ------ Constraints ------ $1 ≤ T ≤ 100$ $0 ≤ N,M ≤ 100$ ----- Sample Input 1 ------ 4 4 8 2 13 14 5 8 8 ----- Sample Output 1 ------ 76 101 105 96 ----- explanation 1 ------ Test case $1$: King has $4$ cars that seat $5$ each and $8$ cars that seat $7$ each. So, $4\times 5 + 8\times 7 = 76$ people can travel together. Test case $2$: King has $2$ cars that seat $5$ each and $13$ cars that seat $7$ each. So, $2\times 5 + 13\times 7 = 101$ people can travel together. Test case $3$: King has $14$ cars that seat $5$ each and $5$ cars that seat $7$ each. So, $14\times 5 + 7\times 7 = 105$ people can travel together. Test case $4$: King has $8$ cars that seat $5$ each and $8$ cars that seat $7$ each. So, $8\times 5 + 8\times 7 = 96$ people can travel together.
{"inputs": ["4\n4 8\n2 13\n14 5\n8 8"], "outputs": ["76\n101\n105\n96"]}
442
42
coding
Solve the programming task below in a Python markdown code block. Read problems statements in [Hindi], [Mandarin Chinese], [Russian], [Vietnamese] and [Bengali] as well. Ada has two matrices $A$ and $B$, each with $N$ rows (numbered $1$ through $N$) and $N$ columns (numbered $1$ through $N$). Ada may perform the following operation any number of times (including zero): choose an integer $i$ ($1 ≤ i ≤ N$), then swap row $i$ and column $i$ in matrix $A$. (Formally, for each valid $j$, she swaps $A_{i, j}$ with $A_{j, i}$.) Is it possible to transform matrix $A$ into matrix $B$? ------ 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$. $N$ lines follow. For each $i$ ($1 ≤ i ≤ N$), the $i$-th of these lines contains $N$ space-separated integers $A_{i, 1}, A_{i, 2}, \ldots, A_{i, N}$. $N$ more lines follow. For each $i$ ($1 ≤ i ≤ N$), the $i$-th of these lines contains $N$ space-separated integers $B_{i, 1}, B_{i, 2}, \ldots, B_{i, N}$. ------ Output ------ For each test case, print a single line containing the string "Yes" if it is possible to transform $A$ into $B$ or "No" if it is impossible (without quotes). ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ N ≤ 2^{10}$ $1 ≤ A_{i, j}, B_{i, j} ≤ 10^{9}$ for each valid $i, j$ the sum of $N^{2}$ over all test cases does not exceed $3 \cdot 10^{6}$ ----- Sample Input 1 ------ 1 3 1 2 3 4 5 6 7 8 9 1 2 7 4 5 8 3 6 9 ----- Sample Output 1 ------ Yes ----- explanation 1 ------ Example case 1: We can swap the second row with the second column and in the resulting matrix, swap the first row with the first column.
{"inputs": ["1\n3\n1 2 3\n4 5 6\n7 8 9\n1 2 7\n4 5 8\n3 6 9"], "outputs": ["Yes"]}
571
50
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given two strings s and t, transform string s into string t using the following operation any number of times: Choose a non-empty substring in s and sort it in place so the characters are in ascending order. For example, applying the operation on the underlined substring in "14234" results in "12344". Return true if it is possible to transform s into t. Otherwise, return false. A substring is a contiguous sequence of characters within a string.   Please complete the following python code precisely: ```python class Solution: def isTransformable(self, s: str, t: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(s = \"84532\", t = \"34852\") == True\n assert candidate(s = \"34521\", t = \"23415\") == True\n assert candidate(s = \"12345\", t = \"12435\") == False\n assert candidate(s = \"1\", t = \"2\") == False\n\n\ncheck(Solution().isTransformable)"}
152
108
coding
Solve the programming task below in a Python markdown code block. Introduction It's been more than 20 minutes since the negligent waiter has taken your order for the house special prime tofu steak with a side of chili fries. Out of boredom, you start fiddling around with the condiments tray. To be efficient, you want to be familiar with the choice of sauces and spices before your order is finally served. You also examine the toothpick holder and try to analyze its inner workings when - yikes - the holder's lid falls off and all 23 picks lay scattered on the table. Being a good and hygiene oriented citizen, you decide not to just put them back in the holder. Instead of letting all the good wood go to waste, you start playing around with the picks. In the first "round", you lay down one toothpick vertically. You've used a total of one toothpick. In the second "round", at each end of the first toothpick, you add a perpendicular toothpick at its center point. You added two additional toothpicks for a total of three toothpicks. In the next rounds, you continue to add perpendicular toothpicks to each free end of toothpicks already on the table. With your 23 toothpicks, you can complete a total of six rounds: You wonder if you'd be able to implement this sequence in your favorite programming language. Because your food still hasn't arrived, you decide to take out your laptop and start implementing... Challenge Implement a script that returns the amount of toothpicks needed to complete n amount of rounds of the toothpick sequence. ``` 0 <= n <= 5000 ``` Hint You can attempt this brute force or get some inspiration from the math department. Also feel free to reuse/extend the following starter code: ```python def toothpick(n): ```
{"functional": "_inputs = [[0], [3], [16], [32], [49], [89], [327], [363], [366], [512], [656], [1038], [1052], [1222], [1235], [1302], [1735], [1757], [1974], [2048]]\n_outputs = [[0], [7], [171], [683], [1215], [3715], [52239], [60195], [62063], [174763], [209095], [699451], [700379], [757295], [762019], [832559], [1398915], [1443119], [2038207], [2796203]]\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(toothpick(*i), o[0])"}
385
391
coding
Solve the programming task below in a Python markdown code block. Spoonerize... with numbers... numberize?... numboonerize?... noonerize? ...anyway! If you don't yet know what a spoonerism is and haven't yet tried my spoonerism kata, please do [check it out](http://www.codewars.com/kata/spoonerize-me) first. You will create a function which takes an array of two positive integers, spoonerizes them, and returns the positive difference between them as a single number or ```0``` if the numbers are equal: ``` [123, 456] = 423 - 156 = 267 ``` Your code must test that all array items are numbers and return ```"invalid array"``` if it finds that either item is not a number. The provided array will always contain 2 elements. When the inputs are valid, they will always be integers, no floats will be passed. However, you must take into account that the numbers will be of varying magnitude, between and within test cases. Also feel free to reuse/extend the following starter code: ```python def noonerize(numbers): ```
{"functional": "_inputs = [[[12, 34]], [[55, 63]], [[357, 579]], [[1000000, 9999999]], [[1000000, 'hello']], [['pippi', 9999999]], [['pippi', 'hello']], [[1, 1]], [[1, 0]], [[0, 1]]]\n_outputs = [[18], [12], [178], [7000001], ['invalid array'], ['invalid array'], ['invalid array'], [0], [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(noonerize(*i), o[0])"}
259
287
coding
Solve the programming task below in a Python markdown code block. You're given an array A of N integers. You need to find the minimum cost of creating another array B of N integers with the following properties B_{i} ≥ 0 for each 1 ≤ i ≤ N The GCD of adjacent elements of B is equal to 1, i.e, \gcd(B_{i}, B_{i+1}) = 1 for each 1 ≤ i < N The cost of creating B is defined as follows: \sum_{i=1}^{N} 2^{|A_{i} - B_{i} |} Find the minimum possible cost to create the array B. Since the answer can be huge print it modulo 10^{9}+7 Note: You need to minimize the value of total cost of creating the array B, and then print this minimum value modulo 10^{9} + 7. For example, suppose there is a way to create the required B with a cost of 500, and another way to do it with a cost of 10^{9} + 7 (which is 0 \pmod {10^{9} + 7}). The output in this case would be 500 and not 0. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - The first line of each test case contains an integer N - the length of the array A - The second line of each test case contains N space-separated integers A_{1},A_{2},\ldots,A_{N} ------ Output Format ------ For each test case, output on a new line the minimum cost of creating the array B, modulo 10^{9} + 7. ------ Constraints ------ $1 ≤ T ≤ 150$ $1 ≤ N ≤ 10^{4}$ $1 ≤ A_{i} ≤ 10^{6}$ - The sum of $N$ over all test cases won't exceed $10^{4}$. ----- Sample Input 1 ------ 3 3 15 16 19 2 5 10 7 9 15 7 19 10 7 1 ----- Sample Output 1 ------ 3 3 8 ----- explanation 1 ------ Test case $1$: The given input already satisfies all the conditions, hence we can take $B = A$ with a cost of $2^{0} + 2^{0} + 2^{0} = 3$. Test case $2$: One optimal way is to choose $B$ as $ [ 5, 11 ] $, with a cost of $2^{0} + 2^{1} = 3$.
{"inputs": ["3\n3\n15 16 19\n2\n5 10\n7\n9 15 7 19 10 7 1\n"], "outputs": ["3\n3\n8"]}
603
54
coding
Solve the programming task below in a Python markdown code block. There are $N$ sabotages available in the game Among Us, initially all at level $0$. $N$ imposters are allotted the task to upgrade the level of the sabotages. The $i^{th}$ imposter $(1 \leq i \leq N)$ increases the level of $x^{th}$ sabotage $(1 \leq x \leq N)$ by one level if $gcd(i,x)=i$. You need to find the number of sabotages at LEVEL 5 after all the imposters have completed their tasks. -----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 the number of sabotages at LEVEL 5. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq N \leq 10^{18}$ -----Sample Input:----- 1 6 -----Sample Output:----- 0 -----EXPLANATION:----- The $1^{st}$ sabotage is at level $1$, the $2^{nd}$, $3^{rd}$ and $5^{th}$ sabotages are at level $2$, the $4^{th}$ sabotage is at level $3$ and the $6^{th}$ sabotage is at level $4$. None of them reach level $5$. Hence the output is $0$.
{"inputs": ["1\n6"], "outputs": ["0"]}
335
14
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are: Players take turns placing characters into empty squares ' '. The first player A always places 'X' characters, while the second player B always places 'O' characters. 'X' and 'O' characters are always placed into empty squares, never on filled ones. The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal. The game also ends if all squares are non-empty. No more moves can be played if the game is over. Given a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return "Draw". If there are still movements to play return "Pending". You can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.   Please complete the following python code precisely: ```python class Solution: def tictactoe(self, moves: List[List[int]]) -> str: ```
{"functional": "def check(candidate):\n assert candidate(moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]) == \"A\"\n assert candidate(moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]) == \"B\"\n assert candidate(moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]) == \"Draw\"\n assert candidate(moves = [[0,0],[1,1]]) == \"Pending\"\n\n\ncheck(Solution().tictactoe)"}
290
157
coding
Solve the programming task below in a Python markdown code block. A and B are preparing themselves for programming contests. The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n. Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them. As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days. Input The first line contains integer n (1 ≤ n ≤ 105) — the number of rooms in the University. The next n - 1 lines describe the corridors. The i-th of these lines (1 ≤ i ≤ n - 1) contains two integers ai and bi (1 ≤ ai, bi ≤ n), showing that the i-th corridor connects rooms ai and bi. The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Next m lines describe the queries. The j-th of these lines (1 ≤ j ≤ m) contains two integers xj and yj (1 ≤ xj, yj ≤ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj. Output In the i-th (1 ≤ i ≤ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day. Examples Input 4 1 2 1 3 2 4 1 2 3 Output 1 Input 4 1 2 2 3 2 4 2 1 2 1 3 Output 0 2 Note in the first sample there is only one room at the same distance from rooms number 2 and 3 — room number 1.
{"inputs": ["4\n1 2\n1 3\n2 4\n1\n2 3\n", "5\n1 2\n1 3\n2 5\n2 4\n1\n5 4\n", "4\n1 2\n2 3\n2 4\n2\n1 2\n1 2\n", "4\n1 3\n2 3\n2 4\n2\n1 2\n1 2\n", "4\n1 3\n2 3\n2 4\n2\n1 1\n1 2\n", "4\n1 4\n2 3\n2 4\n2\n1 1\n1 3\n", "5\n1 2\n1 3\n2 5\n2 4\n1\n5 3\n", "4\n1 4\n4 3\n2 4\n2\n1 1\n1 3\n"], "outputs": ["1\n", "3\n", "0\n0\n", "1\n1\n", "4\n1\n", "4\n0\n", "0\n", "4\n2\n"]}
482
252
coding
Solve the programming task below in a Python markdown code block. If you can't sleep, just count sheep!! ## Task: Given a non-negative integer, `3` for example, return a string with a murmur: `"1 sheep...2 sheep...3 sheep..."`. Input will always be valid, i.e. no negative integers. Also feel free to reuse/extend the following starter code: ```python def count_sheep(n): ```
{"functional": "_inputs = [[3]]\n_outputs = [['1 sheep...2 sheep...3 sheep...']]\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(count_sheep(*i), o[0])"}
94
164
coding
Solve the programming task below in a Python markdown code block. The Chef has prepared the appetizers in the shapes of letters to spell a special message for the guests. There are n appetizers numbered from 0 to n-1 such that if the appetizers are arrayed in this order, they will display the message. The Chef plans to display them in this order on a table that can be viewed by all guests as they enter. The appetizers will only be served once all guests are seated. The appetizers are not necessarily finished in the same order as they are numbered. So, when an appetizer is finished the Chef will write the number on a piece of paper and place it beside the appetizer on a counter between the kitchen and the restaurant. A server will retrieve this appetizer and place it in the proper location according to the number written beside it. The Chef has a penchant for binary numbers. The number of appetizers created is a power of 2, say n = 2^{k}. Furthermore, he has written the number of the appetizer in binary with exactly k bits. That is, binary numbers with fewer than k bits are padded on the left with zeros so they are written with exactly k bits. Unfortunately, this has unforseen complications. A binary number still "looks" binary when it is written upside down. For example, the binary number "0101" looks like "1010" when read upside down and the binary number "110" looks like "011" (the Chef uses simple vertical lines to denote a 1 bit). The Chef didn't realize that the servers would read the numbers upside down so he doesn't rotate the paper when he places it on the counter. Thus, when the server picks up an appetizer they place it the location indexed by the binary number when it is read upside down. You are given the message the chef intended to display and you are to display the message that will be displayed after the servers move all appetizers to their locations based on the binary numbers they read. ------ Input ------ The first line consists of a single integer T ≤ 25 indicating the number of test cases to follow. Each test case consists of a single line beginning with an integer 1 ≤ k ≤ 16 followed by a string of precisely 2^{k} characters. The integer and the string are separated by a single space. The string has no spaces and is composed only of lower case letters from a to z. ------ Output ------ For each test case you are to output the scrambled message on a single line. ----- Sample Input 1 ------ 2 2 chef 4 enjoyourapplepie ----- Sample Output 1 ------ cehf eayejpuinpopolre
{"inputs": ["2\n2 chef\n4 enjoyourapplepie", "2\n2 chef\n4 eipelpparuoyojne", "2\n2 chef\n4 enjoyourappmepie", "2\n2 cief\n4 enjoyourappmepie", "2\n2 cgef\n4 enjoyourapplepie", "2\n2 chef\n4 eipempparuoyojne", "2\n2 cief\n4 enjoyourpapmepie", "2\n2 cgef\n4 enjoyourapqlepie"], "outputs": ["cehf\neayejpuinpopolre", "cehf\nerlopopniupjeyae\n", "cehf\neayejpuinpopomre\n", "ceif\neayejpuinpopomre\n", "cegf\neayejpuinpopolre\n", "cehf\nermopopniupjeyae\n", "ceif\nepyejpuinaopomre\n", "cegf\neayejquinpopolre\n"]}
568
233
coding
Solve the programming task below in a Python markdown code block. Takahashi, who is A years old, is riding a Ferris wheel. It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.) Find the cost of the Ferris wheel for Takahashi. -----Constraints----- - 0 ≤ A ≤ 100 - 2 ≤ B ≤ 1000 - B is an even number. -----Input----- Input is given from Standard Input in the following format: A B -----Output----- Print the cost of the Ferris wheel for Takahashi. -----Sample Input----- 30 100 -----Sample Output----- 100 Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.
{"inputs": ["6 111", "9 100", "9 010", "1 100", "2 100", "2 101", "0 000", "3 101"], "outputs": ["55\n", "50\n", "5\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
228
96
coding
Solve the programming task below in a Python markdown code block. Your task is to return the sum of Triangular Numbers up-to-and-including the `nth` Triangular Number. Triangular Number: "any of the series of numbers (1, 3, 6, 10, 15, etc.) obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc." ``` [01] 02 [03] 04 05 [06] 07 08 09 [10] 11 12 13 14 [15] 16 17 18 19 20 [21] ``` e.g. If `4` is given: `1 + 3 + 6 + 10 = 20`. Triangular Numbers cannot be negative so return 0 if a negative number is given. Also feel free to reuse/extend the following starter code: ```python def sum_triangular_numbers(n): ```
{"functional": "_inputs = [[6], [34], [-291], [943], [-971]]\n_outputs = [[56], [7140], [0], [140205240], [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(sum_triangular_numbers(*i), o[0])"}
228
199
coding
Solve the programming task below in a Python markdown code block. Chef is given two binary strings A and B, each having length N. Chef wants to find the number of binary strings C, of length N, such that H(A, C) = H(B, C), where H(X, Y) denotes the *hamming distance* between the strings X and Y. Since the answer can be large, output it modulo 10^{9}+7. Note: [Hamming distance] between two strings of equal length is the number of positions at which the corresponding characters are different. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case consists of multiple lines of input. - The first line of each test case contains a single integer N, the length of the strings. - The second line contains the binary string A. - The third line contains the binary string B. ------ Output Format ------ For each test case, output in a new line, the number of binary strings C which satisfy the given conditions modulo 10^{9} + 7. ------ Constraints ------ $1 ≤ T ≤ 1000$ $1 ≤ N ≤ 2 \cdot 10^{5}$ $A$ and $B$ consist of $0$ and $1$ only. - Sum of $N$ over all test cases do not exceed $2 \cdot 10^{5}$. ----- Sample Input 1 ------ 3 2 11 00 5 10101 10101 3 101 011 ----- Sample Output 1 ------ 2 32 4 ----- explanation 1 ------ Test case $1$: The number of strings $C$, of length $2$, such that $H(A, C) = H(B, C)$ is $2$. The strings are: - $C = 10$: Here, $H(11, 10) = H(00, 10) = 1$, as there is only one position where the corresponding characters are different. - $C = 01$: Here, $H(11, 01) = H(00, 01) = 1$. Test case $3$: The number of strings $C$, of length $3$, such that $H(A, C) = H(B, C)$ is $4$. The strings are: - $C = 000$: Here, $H(101, 000) = H(011, 000) = 2$, as there are two positions where the corresponding characters are different. - $C = 111$: Here, $H(101, 111) = H(011, 111) = 1$, as there is only one position where the corresponding characters are different. - $C = 001$: Here, $H(101, 001) = H(011, 001) = 1$, as there is only one position where the corresponding characters are different. - $C = 110$: Here, $H(101, 110) = H(011, 110) = 2$, as there are two positions where the corresponding characters are different.
{"inputs": ["3\n2\n11\n00\n5\n10101\n10101\n3\n101\n011\n"], "outputs": ["2\n32\n4\n"]}
736
51
coding
Solve the programming task below in a Python markdown code block. JJ has an array A. He can perform the following operation on A: Divide A into two subsequences P and Q such that each A_{i} belongs to either P or Q. Set A := P\ \texttt{concat}\ Q Here \texttt{concat} denotes the concatenation operation. For e.g. [2, 1, 5] \texttt{ concat } [4, 3] = [2, 1, 5, 4, 3]. Is it possible to make A sorted in non-decreasing order after applying the above operation at most once? Note: An array X is a subsequence of an array Y if X can be obtained by deletion of several (possibly, zero or all) elements from Y. ------ Input Format ------ - The first line contains a single integer T — the number of test cases. Then the test cases follow. - The first line of each test case contains an integer N — the size of the array A. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \ldots, A_{N} denoting the array A. ------ Output Format ------ For each test case, output YES if it is possible to make the array A sorted after applying the given operation at most once. Otherwise, output NO. You may print each character of YES and NO in uppercase or lowercase (for example, yes, yEs, Yes will be considered identical). ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $2 ≤ N ≤ 10^{5}$ $1 ≤A_{i} ≤10^{9}$ - Sum of $N$ over all test cases does not exceed $2 \cdot 10^{5}$. ----- Sample Input 1 ------ 3 6 4 5 6 1 2 3 5 1 3 5 2 4 5 5 10 7 11 9 ----- Sample Output 1 ------ YES NO YES ----- explanation 1 ------ Test case $1$: We can select $P = [1, 2, 3]$ and $Q = [4, 5, 6]$. Therefore $A$ will become $[1, 2, 3, 4, 5, 6]$ which is sorted. Test case $2$: It can be proven that it is not possible to sort $A$ by using the given operation at most once. Test case $3$: We can select $P = [5, 7, 9]$ and $Q = [10, 11]$. Therefore $A$ will become $[5, 7, 9, 10, 11]$ which is sorted.
{"inputs": ["3\n6\n4 5 6 1 2 3\n5\n1 3 5 2 4\n5\n5 10 7 11 9\n"], "outputs": ["YES\nNO\nYES\n"]}
605
58
coding
Solve the programming task below in a Python markdown code block. Chef gives an integer $K$ in the input. If the given number is beautiful binary number, print it, Else find its previous beautiful binary number. A beautiful binary number is a number whose binary representation does not contain any consecutive 1s. Note: 1 is also a beautiful binary number. -----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, one integer $K$. -----Output:----- For each test case, print a beautiful number. -----Constraints----- - $1 \leq T \leq 10^5$ - $1 \leq K \leq 10^5$ -----Sample Input:----- 3 3 6 8 -----Sample Output:----- 2 5 8 -----EXPLANATION:----- For 1) 3 is not a beautiful binary number because the binary representation of 3 is "11" which has consecutive 1s. hence 2 which is less than 3 is printed. For 3) 8 is already a beautiful binary number with no consecutive 1s in its binary representation. so, print 8 as it is.
{"inputs": ["3\n3\n6\n8"], "outputs": ["2\n5\n8"]}
272
22
coding
Solve the programming task below in a Python markdown code block. Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p_1, p_2, ..., p_{n} for his birthday. Jeff hates inversions in sequences. An inversion in sequence a_1, a_2, ..., a_{n} is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality a_{i} > a_{j} holds. Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get. -----Input----- The first line contains integer n (1 ≤ n ≤ 2000). The next line contains n integers — sequence p_1, p_2, ..., p_{n} (|p_{i}| ≤ 10^5). The numbers are separated by spaces. -----Output----- In a single line print the answer to the problem — the minimum number of inversions Jeff can get. -----Examples----- Input 2 2 1 Output 0 Input 9 -2 0 -1 0 -1 2 1 0 -1 Output 6
{"inputs": ["1\n0\n", "1\n0\n", "1\n1\n", "1\n-1\n", "1\n-2\n", "1\n-3\n", "1\n-4\n", "2\n2 1\n"], "outputs": ["0\n", "0", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
281
91
coding
Solve the programming task below in a Python markdown code block. You are given two positive integers $a$ and $b$. In one move you can increase $a$ by $1$ (replace $a$ with $a+1$). Your task is to find the minimum number of moves you need to do in order to make $a$ divisible by $b$. It is possible, that you have to make $0$ moves, as $a$ is already divisible by $b$. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. The only line of the test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$). -----Output----- For each test case print the answer — the minimum number of moves you need to do in order to make $a$ divisible by $b$. -----Example----- Input 5 10 4 13 9 100 13 123 456 92 46 Output 2 5 4 333 0
{"inputs": ["1\n9 3\n", "1\n8 4\n", "1\n3 4\n", "1\n3 6\n", "1\n3 3\n", "1\n29 4\n", "1\n9 75\n", "1\n9 95\n"], "outputs": ["0\n", "0\n", "1\n", "3\n", "0\n", "3\n", "66\n", "86\n"]}
274
107
coding
Solve the programming task below in a Python markdown code block. Appy and Chef are participating in a contest. There are $N$ problems in this contest; each problem has a unique problem code between $1$ and $N$ inclusive. Appy and Chef decided to split the problems to solve between them ― Appy should solve the problems whose problem codes are divisible by $A$ but not divisible by $B$, and Chef should solve the problems whose problem codes are divisible by $B$ but not divisible by $A$ (they decided to not solve the problems whose codes are divisible by both $A$ and $B$). To win, it is necessary to solve at least $K$ problems. You have to tell Appy whether they are going to win or lose. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains four space-separated integers $N$, $A$, $B$ and $K$. -----Output----- For each test case, print a single line containing the string "Win" if they can solve at least $K$ problems or "Lose" otherwise (without quotes). -----Constraints----- - $1 \le T \le 15$ - $1 \le K \le N \le 10^{18}$ - $1 \le A, B \le 10^9$ -----Subtasks----- Subtask #1 (15 points): - $1 \le T \le 15$ - $1 \le K \le N \le 10^6$ - $1 \le A, B \le 10^3$ Subtask #2 (85 points): original constraints -----Example Input----- 1 6 2 3 3 -----Example Output----- Win -----Explanation----- Example case 1: Appy is solving the problems with codes $2$ and $4$, Chef is solving the problem with code $3$. Nobody is solving problem $6$, since $6$ is divisible by both $2$ and $3$. Therefore, they can solve $3$ problems and win.
{"inputs": ["1\n6 2 3 3"], "outputs": ["Win"]}
469
20
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall. '@' is the starting point. Lowercase letters represent keys. Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall. If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key. For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet. Return the lowest number of moves to acquire all keys. If it is impossible, return -1.   Please complete the following python code precisely: ```python class Solution: def shortestPathAllKeys(self, grid: List[str]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(grid = [\"@.a..\",\"###.#\",\"b.A.B\"]) == 8\n assert candidate(grid = [\"@..aA\",\"..B#.\",\"....b\"]) == 6\n\n\ncheck(Solution().shortestPathAllKeys)"}
251
72
coding
Solve the programming task below in a Python markdown code block. You are given $n$ words of equal length $m$, consisting of lowercase Latin alphabet letters. The $i$-th word is denoted $s_i$. In one move you can choose any position in any single word and change the letter at that position to the previous or next letter in alphabetical order. For example: you can change 'e' to 'd' or to 'f'; 'a' can only be changed to 'b'; 'z' can only be changed to 'y'. The difference between two words is the minimum number of moves required to make them equal. For example, the difference between "best" and "cost" is $1 + 10 + 0 + 0 = 11$. Find the minimum difference of $s_i$ and $s_j$ such that $(i < j)$. In other words, find the minimum difference over all possible pairs of the $n$ words. -----Input----- The first line of the input contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. The description of test cases follows. The first line of each test case contains $2$ integers $n$ and $m$ ($2 \leq n \leq 50$, $1 \leq m \leq 8$) — the number of strings and their length respectively. Then follows $n$ lines, the $i$-th of which containing a single string $s_i$ of length $m$, consisting of lowercase Latin letters. -----Output----- For each test case, print a single integer — the minimum difference over all possible pairs of the given strings. -----Examples----- Input 6 2 4 best cost 6 3 abb zba bef cdu ooo zzz 2 7 aaabbbc bbaezfe 3 2 ab ab ab 2 8 aaaaaaaa zzzzzzzz 3 1 a u y Output 11 8 35 0 200 4 -----Note----- For the second test case, one can show that the best pair is ("abb","bef"), which has difference equal to $8$, which can be obtained in the following way: change the first character of the first string to 'b' in one move, change the second character of the second string to 'b' in $3$ moves and change the third character of the second string to 'b' in $4$ moves, thus making in total $1 + 3 + 4 = 8$ moves. For the third test case, there is only one possible pair and it can be shown that the minimum amount of moves necessary to make the strings equal is $35$. For the fourth test case, there is a pair of strings which is already equal, so the answer is $0$.
{"inputs": ["1\n2 7\nabcdefg\naaaaaaa\n", "6\n2 4\nbest\ncost\n6 3\nabb\nzba\nbef\ncdu\nooo\nzzz\n2 7\naaabbbc\nbbaezfe\n3 2\nab\nab\nab\n2 8\naaaaaaaa\nzzzzzzzz\n3 1\na\nu\ny\n"], "outputs": ["21\n", "11\n8\n35\n0\n200\n4\n"]}
627
119
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.   Please complete the following python code precisely: ```python class Solution: def maximumScore(self, nums: List[int], k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,4,3,7,4,5], k = 3) == 15\n assert candidate(nums = [5,5,4,5,4,1,1,1], k = 0) == 20\n\n\ncheck(Solution().maximumScore)"}
132
79
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove.   Please complete the following python code precisely: ```python class Solution: def minimumRemoval(self, beans: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(beans = [4,1,6,5]) == 4\n assert candidate(beans = [2,10,3,2]) == 7\n\n\ncheck(Solution().minimumRemoval)"}
146
59
coding
Solve the programming task below in a Python markdown code block. C: Canisal cryptography problem Ebi-chan was given the string C obtained by encrypting a non-negative integer D with "canisal cipher". This cipher replaces each number in decimal notation with a fixed number (not necessarily different from the original). Different numbers will not be replaced with the same number, and the same number will not be rewritten to a different number depending on the position of appearance. For example, this encryption method can result in 2646 being 0545, but not 3456 being 1333 or 1333 being 3456. Now, Ebi-chan has been told that the remainder of dividing D by 10 ^ 9 + 7 is M. At this time, output one that can be considered as D. If you can think of more than one, you can output any of them. However, it is assumed that there is no extra `0` at the beginning of D. Input format M C Constraint * 0 \ leq M <10 ^ 9 + 7 * 1 \ leq | C | \ leq 10 ^ 5 Output format Print a non-negative integer that can be considered as D on one line. If it does not exist, output `-1`. Input example 1 2 1000000007 Output example 1 1000000009 The encryption method this time was to replace 0 with 0, 1 with 1, and 9 with 7. Input example 2 3 1000000007 Output example 2 -1 Input example 3 1 01 01 Output example 3 -1 There is no extra `0` at the beginning of the D. Input example 4 45 1000000023 Output example 4 6000000087 Since `1000000052` and` 2000000059` also satisfy the conditions, you can output them. Input example 5 0 940578326285963740 Output example 5 123456789864197523 Example Input 2 1000000007 Output 1000000009
{"inputs": ["2\n8", "2\n5", "2\n0", "2\n38", "2\n44", "2\n40", "2\n10", "2\n30"], "outputs": ["2", "2", "2", "-1\n", "-1\n", "-1\n", "-1\n", "-1\n"]}
564
80
coding
Solve the programming task below in a Python markdown code block. The restaurant AtCoder serves the following five dishes: - ABC Don (rice bowl): takes A minutes to serve. - ARC Curry: takes B minutes to serve. - AGC Pasta: takes C minutes to serve. - APC Ramen: takes D minutes to serve. - ATC Hanbagu (hamburger patty): takes E minutes to serve. Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered. This restaurant has the following rules on orders: - An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...). - Only one dish can be ordered at a time. - No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered. E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered. Here, he can order the dishes in any order he likes, and he can place an order already at time 0. -----Constraints----- - A, B, C, D and E are integers between 1 and 123 (inclusive). -----Input----- Input is given from Standard Input in the following format: A B C D E -----Output----- Print the earliest possible time for the last dish to be delivered, as an integer. -----Sample Input----- 29 20 7 35 120 -----Sample Output----- 215 If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows: - Order ABC Don at time 0, which will be delivered at time 29. - Order ARC Curry at time 30, which will be delivered at time 50. - Order AGC Pasta at time 50, which will be delivered at time 57. - Order ATC Hanbagu at time 60, which will be delivered at time 180. - Order APC Ramen at time 180, which will be delivered at time 215. There is no way to order the dishes in which the last dish will be delivered earlier than this.
{"inputs": ["1\n1\n1\n1\n1\n", "29\n0\n8\n5\n22", "29\n0\n8\n5\n11", "29\n1\n8\n9\n11", "29\n0\n8\n10\n2", "29\n0\n8\n17\n2", "29\n-1\n8\n0\n3", "29\n0\n2\n-1\n3"], "outputs": ["41\n", "72\n", "61\n", "71\n", "52\n", "62\n", "43\n", "42\n"]}
527
149
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. Chef is instructor of the famous course "Introduction to Algorithms" in a famous univerisity. There are n students in his class. There is not enough space in the class room, so students sit in a long hallway in a linear fashion. One day Chef was late to class. As a result, some of the students have formed pairs and are talking to each other, while the others are busy studying. This information is given to you by a string s of length n, consisting of characters '*', ', where '*' denotes that the student is studying, '>' denotes that the corresponding student is talking to the student to the right, and 'For example, consider a sample configuration of students - *>>< is also not a valid configuration, as students 2 and 3 are talking to each other, so student 1 won't be able to talk to student 2. When the students see their teacher coming, those who were talking get afraid and immediately turn around, i.e. students talking to left have now turned to the right, and the one talking to right have turned to the left. When Chef sees two students facing each other, he will assume that they were talking. A student who is busy studying will continue doing so. Chef will call each pair of students who were talking and punish them. Can you find out how many pairs of students will get punished? For example, in case *>*>, Chef sees that student 2 and 3 are talking to each other and they will be punished. ------ Input ------ The first line of the input contains an integer T denoting the number of the test cases. Each test case contains a string s denoting the activities of students before students see Chef entering the class. ------ Output ------ For each test case, output a single integer denoting the number of pairs of students that will be punished. ------ Constraints ------ 1 ≤ T ≤ 10 1 ≤ |s| ≤ 10^{5} ------ Subtasks ------ Subtask #1: (30 points) 1 ≤ T ≤ 10 1 ≤ |s| ≤ 10^{5} No student is studying. Subtask #2: (70 points) Original Constraints. ----- Sample Input 1 ------ 4 >< *><* >< *><* ----- Sample Output 1 ------ 0 0 1 2 ----- explanation 1 ------ Example case 1. The updated configuration will be . No students are talking to each other, so no one will be punished. Example case 2 and 3. These examples are already explained in the problem statement.
{"inputs": ["4\n><\n*><*\n><><\n*><><><*"], "outputs": ["0\n0\n1\n2"]}
562
35
coding
Solve the programming task below in a Python markdown code block. You are standing near a very strange machine. If you put C cents in the machine, the remaining money in your purse will transform in an unusual way. If you have A dollars and B cents remaining in your purse after depositing the C cents, then after the transformation you will have B dollars and A cents. You can repeat this procedure as many times as you want unless you don't have enough money for the machine. If at any point C > B and A > 0, then the machine will allow you to break one of the A dollars into 100 cents so you can place C cents in the machine. The machine will not allow you to exchange a dollar for 100 cents if B >= C. Of course, you want to do this to maximize your profit. For example if C=69 and you have 9 dollars and 77 cents then after you put 69 cents in the machine you will have 8 dollars and 9 cents (9.77 --> 9.08 --> 8.09). But I should warn you that you can't cheat. If you try to throw away 9 cents before the transformation (in order to obtain 99 dollars and 8 cents after), the machine will sense you are cheating and take away all of your money. You need to know how many times you should do this transformation in order to make a maximum profit. Since you are very busy man, you want to obtain the maximum possible profit in the minimum amount of time. -----Input----- The first line contains a single integer T <= 40, the number of test cases. T test cases follow. The only line of each test case contains three nonnegative integers A, B and C where A, B, C < 100. It means that you have A dollars and B cents in your purse and you need to put C cents in the machine to make the transformation. -----Output----- For each test case, output a single line containing the minimal number of times you should do this transformation in order to make a maximal profit. It is guaranteed that the answer is less than 10000. -----Example----- Input: 2 9 77 69 98 99 69 Output: 4 0 -----Explanation----- In the first test we have the following sequence: 9.77, 8.09, 40.07, 38.39, 70.37, 68.69, 0.68. After last step we have not enough money for further transformations. The maximal profit will be after 4 transformations.
{"inputs": ["2\n0 12 1\n1 1 6", "2\n0 12 0\n1 1 6", "2\n0 12 0\n2 1 6", "2\n0 56 0\n1 1 21", "2\n0 56 0\n1 0 21", "2\n0 56 1\n0 0 21", "2\n0 56 2\n0 0 21", "2\n1 33 1\n15 2 5"], "outputs": ["23\n33\n", "1\n33\n", "1\n34\n", "1\n37\n", "1\n38\n", "2\n0\n", "100\n0\n", "65\n6\n"]}
568
196
coding
Solve the programming task below in a Python markdown code block. Bob and Alice are having a lockout match between them. There are three problems in the contest worth A, B, and C points respectively. Only the first player to solve a problem gets points for that problem. It is impossible for Bob and Alice to solve a problem at the same time. Chef wants to know if there is any chance of a draw if Bob and Alice manage to solve all 3 problems. A draw occurs when both players end with equal number of points. ------ Input Format ------ - First line will contain T, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, three space separated integers A, B, and C. ------ Output Format ------ For each testcase, output YES if the match can end in a draw, 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 ≤ 1000$ $1 ≤ A, B, C ≤ 10^{6}$ ------ subtasks ------ Subtask #1 (100 points): original constraints ----- Sample Input 1 ------ 3 2 5 2 4 2 2 3 5 5 ----- Sample Output 1 ------ NO YES NO ----- explanation 1 ------ In the first and third test cases, it is impossible for Bob and Alice to solve the problems so that they have the same number of points at the end. In the second case, it is possible for Bob to solve the first problem, and Alice to solve the last two problems, in which case they will both have 4 points and the game will end in a draw.
{"inputs": ["3\n2 5 2\n4 2 2\n3 5 5"], "outputs": ["NO\nYES\nNO"]}
390
34
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server.   Please complete the following python code precisely: ```python class Solution: def countServers(self, grid: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(grid = [[1,0],[0,1]]) == 0\n assert candidate(grid = [[1,0],[1,1]]) == 3\n assert candidate(grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]) == 4\n\n\ncheck(Solution().countServers)"}
124
97
coding
Solve the programming task below in a Python markdown code block. You are given a string of length N. Calculate the number of distinct substrings of S. Constraints * 1 \leq N \leq 500,000 * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output Print the answer. Examples Input abcbcba Output 21 Input mississippi Output 53 Input ababacaca Output 33 Input aaaaa Output 5
{"inputs": ["baaaa", "baaba", "bbba`", "`babb", "`ca`b", "`_adb", "ababa", "aaabb"], "outputs": ["9\n", "11\n", "12\n", "13\n", "14\n", "15\n", "9\n", "11\n"]}
125
78
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size). The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length. Return the minimum total space wasted if you can resize the array at most k times. Note: The array can have any size at the start and does not count towards the number of resizing operations.   Please complete the following python code precisely: ```python class Solution: def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [10,20], k = 0) == 10\n assert candidate(nums = [10,20,30], k = 1) == 10\n assert candidate(nums = [10,20,15,30,20], k = 2) == 15\n\n\ncheck(Solution().minSpaceWastedKResizing)"}
236
102
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence.   Please complete the following python code precisely: ```python class Solution: def mostWordsFound(self, sentences: List[str]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(sentences = [\"alice and bob love leetcode\", \"i think so too\", \"this is great thanks very much\"]) == 6\n assert candidate(sentences = [\"please wait\", \"continue to fight\", \"continue to win\"]) == 3\n\n\ncheck(Solution().mostWordsFound)"}
103
80
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.   Please complete the following python code precisely: ```python class Solution: def countPaths(self, n: int, roads: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]) == 4\n assert candidate(n = 2, roads = [[1,0,10]]) == 1\n\n\ncheck(Solution().countPaths)"}
219
116
coding
Solve the programming task below in a Python markdown code block. There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state). You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A). You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007. -----Input----- The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers a_{i}, b_{i}, c_{i}. If c_{i} is 1, then a_{i} and b_{i} are in love, otherwise, they hate each other (1 ≤ a_{i}, b_{i} ≤ n, a_{i} ≠ b_{i}, $c_{i} \in \{0,1 \}$). Each pair of people will be described no more than once. -----Output----- Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007. -----Examples----- Input 3 0 Output 4 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 0 Output 1 Input 4 4 1 2 1 2 3 1 3 4 0 4 1 1 Output 0 -----Note----- In the first sample, the four ways are to: Make everyone love each other Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.
{"inputs": ["3 0\n", "1 0\n", "3 0\n", "100000 0\n", "100000 0\n", "9 2\n1 2 0\n2 3 0\n", "9 2\n1 2 0\n2 3 0\n", "9 2\n1 2 0\n2 3 1\n"], "outputs": ["4\n", "1\n", " 4\n", "303861760\n", " 303861760\n", "64\n", " 64\n", "64\n"]}
631
157
coding
Solve the programming task below in a Python markdown code block. Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. `"a" = 1`, `"b" = 2`, etc. ## Example ```python alphabet_position("The sunset sets at twelve o' clock.") ``` Should return `"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"` (as a string) Also feel free to reuse/extend the following starter code: ```python def alphabet_position(text): ```
{"functional": "_inputs = [[\"-.-'\"]]\n_outputs = [['']]\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(alphabet_position(*i), o[0])"}
193
157
coding
Solve the programming task below in a Python markdown code block. Chef recently opened a big e-commerce website where her recipes can be bought online. It's Chef's birthday month and so she has decided to organize a big sale in which grand discounts will be provided. In this sale, suppose a recipe should have a discount of x percent and its original price (before the sale) is p. Statistics says that when people see a discount offered over a product, they are more likely to buy it. Therefore, Chef decides to first increase the price of this recipe by x% (from p) and then offer a discount of x% to people. Chef has a total of N types of recipes. For each i (1 ≤ i ≤ N), the number of recipes of this type available for sale is quantityi, the unit price (of one recipe of this type, before the x% increase) is pricei and the discount offered on each recipe of this type (the value of x) is discounti. Please help Chef find the total loss incurred due to this sale, if all the recipes are sold out. -----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 recipe types. - N lines follow. The i-th of these lines contains three space-separated integers pricei, quantityi and discounti describing the i-th recipe type. -----Output----- For each test case, print a single line containing one real number — the total amount of money lost. Your answer will be considered correct if it has an absolute error less than 10-2. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 105 - 1 ≤ pricei, quantityi ≤ 100 for each valid i - 0 ≤ discounti ≤ 100 for each valid i -----Subtasks----- Subtask #1 (30 points): 1 ≤ N ≤ 100 Subtask #2 (70 points): original constraints -----Example----- Input: 2 2 100 5 10 100 1 50 3 10 10 0 79 79 79 100 1 100 Output: 30.000000000 3995.0081000 -----Explanation----- Example case 1: There are two recipes. There are 5 recipes of the first type, each of them has a price of 100 and there is a 10% discount provided on it. Therefore, Chef first increases the price of each recipe by 10%, from 100 to 110. After that, she decreases the price by 10%, which makes the final price 99. The amount of money lost for each unit is 1, thus losing 5 for recipes of the first type. There is only one recipe of the second type, with price 100 and a 50% discount. Therefore, Chef increases the price of the recipe by 50% from 100 to 150 and after that, she decreases its price by 50% to make its final price 75. She loses 25 for this recipe. Overall, the amount of money Chef loses is 30.
{"inputs": ["2\n2\n100 5 10\n100 1 50\n3\n10 10 0\n79 79 79\n100 1 100"], "outputs": ["30.000000000\n3995.0081000"]}
739
85
coding
Solve the programming task below in a Python markdown code block. ABCXYZ company has up to 100 employees. The company decides to create a unique identification number (UID) for each of its employees. The company has assigned you the task of validating all the randomly generated UIDs. A valid UID must follow the rules below: It must contain at least $2$ uppercase English alphabet characters. It must contain at least $3$ digits ($\mbox{0}$ - $\mbox{9}$). It should only contain alphanumeric characters ($\boldsymbol{a}$ - $z$, $\mbox{A}$ - $\mbox{Z}$ & $\mbox{0}$ - $\mbox{9}$). No character should repeat. There must be exactly $10$ characters in a valid UID. Input Format The first line contains an integer $\mathbf{T}$, the number of test cases. The next $\mathbf{T}$ lines contains an employee's UID. Output Format For each test case, print 'Valid' if the UID is valid. Otherwise, print 'Invalid', on separate lines. Do not print the quotation marks. Sample Input 2 B1CD102354 B1CDEF2354 Sample Output Invalid Valid Explanation B1CD102354: $\mbox{1}$ is repeating → Invalid B1CDEF2354: Valid
{"inputs": ["2\nB1CD102354\nB1CDEF2354\n"], "outputs": ["Invalid\nValid\n"]}
312
35
coding
Solve the programming task below in a Python markdown code block. Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer. When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes. Your task is correct the errors in the digitised text. You only have to handle the following mistakes: * `S` is misinterpreted as `5` * `O` is misinterpreted as `0` * `I` is misinterpreted as `1` The test cases contain numbers only by mistake. Also feel free to reuse/extend the following starter code: ```python def correct(string): ```
{"functional": "_inputs = [['1F-RUDYARD K1PL1NG'], ['R0BERT MERLE - THE DAY 0F THE D0LPH1N'], ['R1CHARD P. FEYNMAN - THE FEYNMAN LECTURE5 0N PHY51C5'], ['R1CHARD P. FEYNMAN - 5TAT15T1CAL MECHAN1C5'], ['5TEPHEN HAWK1NG - A BR1EF H15T0RY 0F T1ME'], ['5TEPHEN HAWK1NG - THE UN1VER5E 1N A NUT5HELL'], ['ERNE5T HEM1NGWAY - A FARWELL T0 ARM5'], ['ERNE5T HEM1NGWAY - F0R WH0M THE BELL T0LL5'], ['ERNE5T HEM1NGWAY - THE 0LD MAN AND THE 5EA'], ['J. R. R. T0LK1EN - THE L0RD 0F THE R1NG5'], ['J. D. 5AL1NGER - THE CATCHER 1N THE RYE'], [\"J. K. R0WL1NG - HARRY P0TTER AND THE PH1L050PHER'5 5T0NE\"], ['J. K. R0WL1NG - HARRY P0TTER AND THE CHAMBER 0F 5ECRET5'], ['J. K. R0WL1NG - HARRY P0TTER AND THE PR150NER 0F Azkaban'], ['J. K. R0WL1NG - HARRY P0TTER AND THE G0BLET 0F F1RE'], ['J. K. R0WL1NG - HARRY P0TTER AND THE 0RDER 0F PH0EN1X'], ['J. K. R0WL1NG - HARRY P0TTER AND THE HALF-BL00D PR1NCE'], ['J. K. R0WL1NG - HARRY P0TTER AND THE DEATHLY HALL0W5'], ['UR5ULA K. LE GU1N - A W1ZARD 0F EARTH5EA'], ['UR5ULA K. LE GU1N - THE T0MB5 0F ATUAN'], ['UR5ULA K. LE GU1N - THE FARTHE5T 5H0RE'], ['UR5ULA K. LE GU1N - TALE5 FR0M EARTH5EA']]\n_outputs = [['IF-RUDYARD KIPLING'], ['ROBERT MERLE - THE DAY OF THE DOLPHIN'], ['RICHARD P. FEYNMAN - THE FEYNMAN LECTURES ON PHYSICS'], ['RICHARD P. FEYNMAN - STATISTICAL MECHANICS'], ['STEPHEN HAWKING - A BRIEF HISTORY OF TIME'], ['STEPHEN HAWKING - THE UNIVERSE IN A NUTSHELL'], ['ERNEST HEMINGWAY - A FARWELL TO ARMS'], ['ERNEST HEMINGWAY - FOR WHOM THE BELL TOLLS'], ['ERNEST HEMINGWAY - THE OLD MAN AND THE SEA'], ['J. R. R. TOLKIEN - THE LORD OF THE RINGS'], ['J. D. SALINGER - THE CATCHER IN THE RYE'], [\"J. K. ROWLING - HARRY POTTER AND THE PHILOSOPHER'S STONE\"], ['J. K. ROWLING - HARRY POTTER AND THE CHAMBER OF SECRETS'], ['J. K. ROWLING - HARRY POTTER AND THE PRISONER OF Azkaban'], ['J. K. ROWLING - HARRY POTTER AND THE GOBLET OF FIRE'], ['J. K. ROWLING - HARRY POTTER AND THE ORDER OF PHOENIX'], ['J. K. ROWLING - HARRY POTTER AND THE HALF-BLOOD PRINCE'], ['J. K. ROWLING - HARRY POTTER AND THE DEATHLY HALLOWS'], ['URSULA K. LE GUIN - A WIZARD OF EARTHSEA'], ['URSULA K. LE GUIN - THE TOMBS OF ATUAN'], ['URSULA K. LE GUIN - THE FARTHEST SHORE'], ['URSULA K. LE GUIN - TALES FROM EARTHSEA']]\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(correct(*i), o[0])"}
147
1,124
coding
Solve the programming task below in a Python markdown code block. You've came to visit your grandma and she straight away found you a job - her Christmas tree needs decorating! She first shows you a tree with an identified number of branches, and then hands you a some baubles (or loads of them!). You know your grandma is a very particular person and she would like the baubles to be distributed in the orderly manner. You decide the best course of action would be to put the same number of baubles on each of the branches (if possible) or add one more bauble to some of the branches - starting from the beginning of the tree. In this kata you will return an array of baubles on each of the branches. For example: 10 baubles, 2 branches: [5,5] 5 baubles, 7 branches: [1,1,1,1,1,0,0] 12 baubles, 5 branches: [3,3,2,2,2] The numbers of branches and baubles will be always greater or equal to 0. If there are 0 branches return: "Grandma, we will have to buy a Christmas tree first!". Good luck - I think your granny may have some minced pies for you if you do a good job! Also feel free to reuse/extend the following starter code: ```python def baubles_on_tree(baubles, branches): ```
{"functional": "_inputs = [[5, 5], [5, 0], [6, 5], [50, 9], [0, 10]]\n_outputs = [[[1, 1, 1, 1, 1]], ['Grandma, we will have to buy a Christmas tree first!'], [[2, 1, 1, 1, 1]], [[6, 6, 6, 6, 6, 5, 5, 5, 5]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(baubles_on_tree(*i), o[0])"}
308
285
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an m x n matrix mat where every row is sorted in strictly increasing order, return the smallest common element in all rows. If there is no common element, return -1.   Please complete the following python code precisely: ```python class Solution: def smallestCommonElement(self, mat: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]) == 5\n assert candidate(mat = [[1,2,3],[2,3,4],[2,3,5]]) == 2\n\n\ncheck(Solution().smallestCommonElement)"}
87
101
coding
Solve the programming task below in a Python markdown code block. You are given a string S of length N. Your task is to delete a [subsequence] of maximum length from the string, such that, after concatenating the remaining parts of the string, it becomes a [palindrome] of length greater than 1. If this is possible, print the maximum length of the subsequence that can be deleted. Otherwise, print -1. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case consists of 2 lines of input: - The first line consists the a single integer N - the length of string S. - The second line contains string S, consisting of lowercase english alphabets. ------ Output Format ------ For each test case, if it is possible to delete a subsequence under the given conditions, print a single integer, denoting the maximum length of the subsequence that can be deleted. Otherwise, print -1. ------ Constraints ------ $1 ≤ T ≤ 2500$ $3 ≤ N ≤ 100$ $S$ consists of lowercase english alphabets. ------ subtasks ------ Subtask 1 (10 points): $1 ≤ M ≤ 10$ Subtask 2 (20 points): The sum of $N$ across all test cases won't exceed $20$. Subtask 3 (70 points): No further constraints. ----- Sample Input 1 ------ 3 6 babkhj 3 abc 4 qtoo ----- Sample Output 1 ------ 4 -1 2 ----- explanation 1 ------ Test case $1$: Possible ways to delete a subsequence are: - Delete subsequence khj to get palindrome bab. - Delete subsequence akhj to get palindrome bb. The subsequence having maximum length that can be deleted is akhj, having length $4$. Test case $2$: We cannot delete any subsequence under the given conditions. Test case $3$: We can delete the subsequence qt to obtain the string oo, which is a palindrome. This is the only subsequence that can be deleted and it has length $2$.
{"inputs": ["3\n6\nbabkhj\n3 \nabc \n4 \nqtoo"], "outputs": ["4\n-1\n2 \n"]}
469
37
coding
Solve the programming task below in a Python markdown code block. # Back-Story Every day I travel on the freeway. When I am more bored than usual I sometimes like to play the following counting game I made up: * As I join the freeway my count is ```0``` * Add ```1``` for every car that I overtake * Subtract ```1``` for every car that overtakes me * Stop counting when I reach my exit What an easy game! What fun! # Kata Task You will be given * The distance to my exit (km) * How fast I am going (kph) * Information about a lot of other cars * Their time (relative to me) as I join the freeway. For example, * ```-1.5``` means they already passed my starting point ```1.5``` minutes ago * ```2.2``` means they will pass my starting point ```2.2``` minutes from now * How fast they are going (kph) Find what is my "score" as I exit the freeway! # Notes * Assume all cars travel at a constant speeds  Safety Warning  If you plan to play this "game" remember that it is not really a game. You are in a **real** car. There may be a temptation to try to beat your previous best score. Please don't do that... Also feel free to reuse/extend the following starter code: ```python def freeway_game(dist_km_to_exit, my_speed_kph, other_cars): ```
{"functional": "_inputs = [[50.0, 130.0, [[-1.0, 120.0], [-1.5, 120.0]]], [50.0, 110.0, [[1.0, 120.0], [1.5, 125.0]]], [50.0, 120.0, [[-1.0, 115.0], [-1.5, 110.0], [1.0, 130.0], [1.5, 130.0]]], [30.0, 100.0, [[-1.0, 110.0], [-0.7, 102.0], [-1.5, 108.0]]], [30.0, 130.0, [[1.0, 120.0], [0.7, 125.0], [1.5, 110.0]]], [50.0, 110.0, [[-1.0, 110.0], [0.5, 110.0], [1.0, 110.0], [1.5, 110.0]]], [50.0, 110.0, [[0.0, 110.0]]], [50.0, 130.0, []]]\n_outputs = [[2], [-2], [0], [0], [0], [0], [0], [0]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(freeway_game(*i), o[0])"}
323
519
coding
Solve the programming task below in a Python markdown code block. Construct an N \times M matrix with entries having positive integers such that: If M > 1, i^{th} row is strictly increasing from left to right with a fixed common difference d_{i} for all 1≤ i ≤ N. If N > 1, j^{th} column is strictly increasing from top to bottom with a fixed common difference c_{j} for all 1≤ j ≤ M. All the common differences should be distinct. In the case of multiple answers, find an arrangement that minimizes the maximum element of the matrix. ------ Input Format ------ - First line will contain T, number of test cases. Then the test cases follow. - Each test case contains a single line of input, two space-separated integers N and M - the dimensions of the matrix. ------ Output Format ------ For each test case, output N lines with each line having M space-separated integers representing the answer. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N, M ≤ 10^{5}$ - Sum $N \cdot M$ over all cases is atmost $10^{5}$. ----- Sample Input 1 ------ 3 3 3 1 2 1 1 ----- Sample Output 1 ------ 1 2 3 3 6 9 5 10 15 1 2 1 ----- explanation 1 ------ Test case $1$: The values $d_{1}, d_{2},$ and $d_{3}$ are $1, 3,$ and $5$ respectively. The values $c_{1}, c_{2},$ and $c_{3}$ are $2, 4,$ and $6$ respectively. Note that all these common differences $\{d_{1}, d_{2}, d_{3}, c_{1}, c_{2}, c_{3}\}$ are distinct. Moreover, it can be shown that over all valid matrices, $15$ is the minimal value of the maximum element of the matrix one can achieve. Test case $2$: The values $d_{1}$ is $1$. It can be shown that over all valid matrices, $2$ is the minimal value of the maximum element of the matrix one can achieve.
{"inputs": ["3\n3 3\n1 2\n1 1\n"], "outputs": ["1 2 3\n3 6 9\n5 10 15\n1 2\n1\n"]}
488
50
coding
Solve the programming task below in a Python markdown code block. Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav. -----Input----- The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value. -----Output----- In a single line print the answer to the problem — the maximum sum that Yaroslav can get. -----Examples----- Input 2 50 50 50 Output 150 Input 2 -1 -100 -1 Output 100 -----Note----- In the first sample you do not need to change anything. The sum of elements equals 150. In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.
{"inputs": ["2\n-1 -1 1\n", "2\n-1 -1 1\n", "2\n-1 -1 0\n", "2\n50 50 50\n", "2\n50 50 63\n", "2\n-1 -1 -1\n", "2\n50 98 63\n", "2\n50 50 50\n"], "outputs": ["3\n", "3\n", "2\n", "150\n", "163\n", "1\n", "211\n", "150\n"]}
291
142
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Chef had a hard day and want to play little bit. The game is called "Chain". Chef has the sequence of symbols. Each symbol is either '-' or '+'. The sequence is called Chain if each two neighboring symbols of sequence are either '-+' or '+-'. For example sequence '-+-+-+' is a Chain but sequence '-+-+--+' is not. Help Chef to calculate the minimum number of symbols he need to replace (ex. '-' to '+' or '+' to '-') to receive a Chain sequence. ------ Input ------ First line contains single integer T denoting the number of test cases. Line of each test case contains the string S consisting of symbols '-' and '+'. ------ Output ------ For each test case, in a single line print single interger - the minimal number of symbols Chef needs to replace to receive a Chain. ------ Constraints ------ $1 ≤ T ≤ 7$ $1 ≤ |S| ≤ 10^{5}$ ------ Subtasks ------ $Subtask 1 ≤ |S| ≤ 10, 1 ≤ T ≤ 7 Points: 20 $ $Subtask 1 ≤ |S| ≤ 1000, 1 ≤ T ≤ 7 Points: 30 $ $Subtask 1 ≤ |S| ≤ 10^{5}, 1 ≤ T ≤ 7Points: 50 $ ----- Sample Input 1 ------ 2 ---+-+-+++ ------- ----- Sample Output 1 ------ 2 3 ----- explanation 1 ------ Example case 1. We can change symbol 2 from '-' to '+' and symbol 9 from '+' to '-' and receive '-+-+-+-+-+'. Example case 2. We can change symbols 2, 4 and 6 from '-' to '+' and receive '-+-+-+-'.
{"inputs": ["2\n---+-+-+++\n-------", "2\n+++-+-+---\n-------", "2\n-+--+++--+\n-------", "2\n-+-+-+-+-+\n-------", "2\n--++---+++\n-----+-", "2\n---+-+-+++\n-----+-", "2\n+-+-+-+--+\n-------", "2\n---+++-+-+\n-------"], "outputs": ["2\n3", "2\n3\n", "4\n3\n", "0\n3\n", "4\n2\n", "2\n2\n", "2\n3\n", "2\n3\n"]}
401
139
coding
Solve the programming task below in a Python markdown code block. Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions. You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order. Restore the original password. -----Constraints----- - O and E consists of lowercase English letters (a - z). - 1 \leq |O|,|E| \leq 50 - |O| - |E| is either 0 or 1. -----Input----- Input is given from Standard Input in the following format: O E -----Output----- Print the original password. -----Sample Input----- xyz abc -----Sample Output----- xaybzc The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.
{"inputs": ["xyz\nacc", "xyz\nadc", "xyy\nadc", "xyy\nacd", "yyx\nacd", "xyy\ncad", "xyz\ncad", "zyx\ncad"], "outputs": ["xayczc\n", "xaydzc\n", "xaydyc\n", "xaycyd\n", "yaycxd\n", "xcyayd\n", "xcyazd\n", "zcyaxd\n"]}
262
110
coding
Solve the programming task below in a Python markdown code block. In a world, a mysterious snake made of only letters lives. Two types of snakes are currently identified, type A and type B, but there may be other types as well. For class A, after ">'" is followed by one or more "=", "#" comes, and after the same number of "=" as before, "~" (half-width tilde) finish. Class B ends with "~~" after "> ^" followed by one or more "Q =". Example of type A:>'==== # ==== ~>'== # == ~ Example of B type:> ^ Q = Q = Q = Q = ~~> ^ Q = Q = ~~ Receives a snake as character string data, determines what kind it is, and outputs "A" for type A, "B" for type B, and "NA" for other types. Please create a program to do. Input The input is given in the following format: n S1 S2 :: Sn The number of snakes identified on the first line n (1 ≤ n ≤ 10000), and the following n lines contain the i-th snake string Si (200 characters or less, without spaces) on each line. Is given to. Output Print the i-th snake type A, B or NA on line i. Example Input 3 >'======#======~ >^Q=Q=Q=Q=Q=Q=Q=Q=Q=~~ >'===#====~ Output A B NA
{"inputs": ["3\n>'======#======~\n>^Q=Q=Q=Q=Q=Q=Q=Q=Q=~~\n>'===#===>~", "3\n>'======#======~\n>QQ=^=Q=Q=Q=Q=Q=Q=Q=~~\n>'===#===>~", "3\n>(======#======~\n~~=Q=Q=Q=Q=Q=Q=Q=^=QQ>\n>'===#==~>=", "3\n>'======#======~\n>QQ=^=Q=Q=Q=Q=Q=Q=Q=~~\n>'===#==~>=", "3\n>'======#======~\n~~=Q=Q=Q=Q=Q=Q=Q=^=QQ>\n>'===#==~>=", "3\n>(======#======~\n~~=Q=Q=Q=Q===Q=Q=^QQQ>\n>'===#==~>=", "3\n>(======#======~\n~~=P=Q=Q=Q===Q=Q=^QQQ>\n>'===#==~>=", "3\n>(======#======~\n~~=P=Q===Q=Q=Q=Q=^QQQ>\n>'===#==~>="], "outputs": ["A\nB\nNA\n", "A\nNA\nNA\n", "NA\nNA\nNA\n", "A\nNA\nNA\n", "A\nNA\nNA\n", "NA\nNA\nNA\n", "NA\nNA\nNA\n", "NA\nNA\nNA\n"]}
331
373
coding
Solve the programming task below in a Python markdown code block. There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN". Find the number of cows that can currently show their hands without affecting any betting decisions. -----Input----- The first line contains a single integer, n (2 ≤ n ≤ 2·10^5). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED". -----Output----- The first line should contain a single integer denoting the number of players that can currently show their hands. -----Examples----- Input 6 AFFAAA Output 4 Input 3 AFI Output 1 -----Note----- In the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.
{"inputs": ["2\nFA\n", "2\nFF\n", "2\nIF\n", "2\nFA\n", "2\nFF\n", "2\nFA\n", "2\nIF\n", "2\nAF\n"], "outputs": ["1\n", "0\n", "1\n", "1\n", "0", "1", "1", "1\n"]}
336
83