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
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums.   Please complete the following python code precisely: ```python class Solution: def countHillValley(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [2,4,1,1,6,5]) == 3\n assert candidate(nums = [6,6,5,5,4,1]) == 0\n\n\ncheck(Solution().countHillValley)"}
179
66
coding
Solve the programming task below in a Python markdown code block. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
{"inputs": ["z\n", "abc\n", "abcc\n", "abcd\n", "xxxyyxx\n", "xxxyxxx\n", "hfihihhfh\n", "hgihihhfh\n"], "outputs": ["YES\nz", "YES\nabc", "YES\nacbc\n", "NO\n", "YES\nxxxxyxy\n", "YES\nxxxxxxy\n", "NO\n", "NO\n"]}
341
97
coding
Solve the programming task below in a Python markdown code block. You've arrived at a carnival and head straight for the duck shooting tent. Why wouldn't you? You will be given a set amount of ammo, and an aim rating of between 1 and 0. No your aim is not always perfect - hey maybe someone fiddled with the sights on the gun... Anyway your task is to calculate how many successful shots you will be able to make given the available ammo and your aim score, then return a string representing the pool of ducks, with those ducks shot marked with 'X' and those that survived left unchanged. You will always shoot left to right. Example of start and end duck string with two successful shots: Start ---> |~~~~~22~2~~~~~| **Bang!! Bang!!** End ---> |~~~~~XX~2~~~~~| All inputs will be correct type and never empty. Also feel free to reuse/extend the following starter code: ```python def duck_shoot(ammo, aim, ducks): ```
{"functional": "_inputs = [[4, 0.64, '|~~2~~~22~2~~22~2~~~~2~~~|'], [9, 0.22, '|~~~~~~~2~2~~~|'], [6, 0.41, '|~~~~~22~2~~~~~|'], [8, 0.05, '|2~~~~|'], [8, 0.92, '|~~~~2~2~~~~~22~~2~~~~2~~~2|']]\n_outputs = [['|~~X~~~X2~2~~22~2~~~~2~~~|'], ['|~~~~~~~X~2~~~|'], ['|~~~~~XX~2~~~~~|'], ['|2~~~~|'], ['|~~~~X~X~~~~~XX~~X~~~~X~~~X|']]\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(duck_shoot(*i), o[0])"}
214
328
coding
Solve the programming task below in a Python markdown code block. Kulyash stays in room that has a single bulb and N buttons. The bulb is initially on. The initial states of the buttons are stored in a binary string S of length N — if S_{i} is 0, the i-th button is off, and if S_{i} is 1, the i-th button is on. If Kulyash toggles any single button then the state of the bulb reverses i.e. the bulb lights up if it was off and vice versa. Kulyash has toggled some buttons and the final states of the buttons are stored in another binary string R of length N. He asks you to determine the final state of the bulb. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case consists of three lines of input. - The first line of each test case contains an integer N — the number of buttons. - The second line of each test case contains a binary string S — the initial states of the buttons. - The third line of each test case contains a binary string R — the final states of the buttons. ------ Output Format ------ For each test case, output on a new line the final state of the bulb (0 for off and 1 for on). ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 100$ $S$ and $R$ are binary strings, i.e, contain only the characters $0$ and $1$. ----- Sample Input 1 ------ 2 3 000 001 2 00 11 ----- Sample Output 1 ------ 0 1 ----- explanation 1 ------ Test case $1$: All the buttons are initially off and finally the state of only one button has changed so the state of the bulb reverses once i.e. it turns off. Test case $2$: All the buttons are initially off and finally the states of two buttons have changed so the state of the bulb reverses twice i.e. it remains on.
{"inputs": ["2\n3\n000\n001\n2\n00\n11\n"], "outputs": ["0\n1\n"]}
450
34
coding
Solve the programming task below in a Python markdown code block. You are given an array A of size N. In one operation, you can do the following: Select indices i and j (i\neq j) and set A_{i} = A_{j}. Find the minimum number of operations required to make all elements of the array equal. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case consists of multiple lines of input. - The first line of each test case contains an integer N — the size of the array. - The next line contains N space-separated integers, denoting the array A. ------ Output Format ------ For each test case, output on a new line, the minimum number of operations required to make all elements of the array equal. ------ Constraints ------ $1 ≤ T ≤ 1000$ $1 ≤ N ≤ 2\cdot 10^{5}$ $1 ≤ A_{i} ≤ N$ - The sum of $N$ over all test cases won't exceed $2\cdot 10^{5}$. ----- Sample Input 1 ------ 3 3 1 2 3 4 2 2 3 1 4 3 1 2 4 ----- Sample Output 1 ------ 2 2 3 ----- explanation 1 ------ Test case $1$: The minimum number of operations required to make all elements of the array equal is $2$. A possible sequence of operations is: - Select indices $1$ and $2$ and set $A_{1} = A_{2} = 2$. - Select indices $3$ and $2$ and set $A_{3} = A_{2} = 2$. Thus, the final array is $[2, 2, 2]$. Test case $2$: The minimum number of operations required to make all elements of the array equal is $2$. A possible sequence of operations is: - Select indices $3$ and $2$ and set $A_{3} = A_{2} = 2$. - Select indices $4$ and $3$ and set $A_{4} = A_{3} = 2$. Thus, the final array is $[2, 2, 2, 2]$. Test case $3$: The minimum number of operations required to make all elements of the array equal is $3$. A possible sequence of operations is: - Select indices $2$ and $1$ and set $A_{2} = A_{1} = 3$. - Select indices $3$ and $1$ and set $A_{3} = A_{1} = 3$. - Select indices $4$ and $1$ and set $A_{4} = A_{1} = 3$. Thus, the final array is $[3, 3, 3, 3]$.
{"inputs": ["3\n3\n1 2 3\n4\n2 2 3 1\n4\n3 1 2 4\n"], "outputs": ["2\n2\n3\n"]}
634
46
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. Little Churu is a naughty child, who likes to play with balls. He has N buckets. Each bucket contains one or more balls. He has numbered his buckets 1 to N (both inclusive). He has an infinite supply of extra balls, apart from the ones already in the buckets. He wants to add zero or more number of balls to each of the buckets in such a way, that number of balls in the buckets are in a non-decreasing order, and their GCD is strictly greater than 1. He wants to do it using the minimum number of extra balls. As he is too young to solve the problem, please help him with the solution. ------ Input ------ First line of input contains an integer T denoting the number of test cases. For each test case, first line contains an integer N denoting the number of buckets. Second line of each test case contains N space separated integers, where the i^{th} denotes the number of balls in the i^{th} bucket. ------ Output ------ For each test case, output a line containing a single integer — the answer for that test case. ------ Constraints ------ Subtask #1: 20 points $1 ≤ T ≤ 10, 1 ≤ N ≤ 1000, 1 ≤ number of balls in a bucket ≤ 1000$ Subtask #2: 80 points $1 ≤ T ≤ 10, 1 ≤ N ≤ 10000, 1 ≤ number of balls in a bucket ≤ 10000$ ----- Sample Input 1 ------ 1 3 11 13 15 ----- Sample Output 1 ------ 3 ----- explanation 1 ------ Add one ball to each of the buckets.
{"inputs": ["1\n3\n11 13 15", "1\n3\n11 13 15"], "outputs": ["3", "3"]}
405
40
coding
Solve the programming task below in a Python markdown code block. Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: ```python unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3] ``` Also feel free to reuse/extend the following starter code: ```python def unique_in_order(iterable): ```
{"functional": "_inputs = [[''], ['A'], ['AA'], ['AAAABBBCCDAABBB'], ['AADD'], ['AAD'], ['ADD'], ['ABBCcAD'], [[1, 2, 3, 3]], [['a', 'b', 'b']]]\n_outputs = [[[]], [['A']], [['A']], [['A', 'B', 'C', 'D', 'A', 'B']], [['A', 'D']], [['A', 'D']], [['A', 'D']], [['A', 'B', 'C', 'c', 'A', 'D']], [[1, 2, 3]], [['a', 'b']]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(unique_in_order(*i), o[0])"}
164
283
coding
Solve the programming task below in a Python markdown code block. There are N integers, A_1, A_2, ..., A_N, written on the blackboard. You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written. Find the maximum possible greatest common divisor of the N integers on the blackboard after your move. -----Constraints----- - All values in input are integers. - 2 \leq N \leq 10^5 - 1 \leq A_i \leq 10^9 -----Output----- Input is given from Standard Input in the following format: N A_1 A_2 ... A_N -----Output----- Print the maximum possible greatest common divisor of the N integers on the blackboard after your move. -----Sample Input----- 3 7 6 8 -----Sample Output----- 2 If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.
{"inputs": ["3\n7 6 7", "3\n4 8 7", "3\n4 2 5", "3\n7 6 8", "3\n7 6 8\n", "3\n4 6 9\n", "3\n9 28 18", "3\n9 28 30"], "outputs": ["7\n", "4\n", "2\n", "2", "2\n", "3\n", "9\n", "3\n"]}
234
115
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s consisting of lowercase English letters. Perform the following operation: Select any non-empty substring then replace every letter of the substring with the preceding letter of the English alphabet. For example, 'b' is converted to 'a', and 'a' is converted to 'z'. Return the lexicographically smallest string after performing the operation.   Please complete the following python code precisely: ```python class Solution: def smallestString(self, s: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(s = \"cbabc\") == \"baabc\"\n assert candidate(s = \"acbbc\") == \"abaab\"\n assert candidate(s = \"leetcode\") == \"kddsbncd\"\n\n\ncheck(Solution().smallestString)"}
117
67
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A maze consists of n rooms numbered from 1 to n, and some rooms are connected by corridors. You are given a 2D integer array corridors where corridors[i] = [room1i, room2i] indicates that there is a corridor connecting room1i and room2i, allowing a person in the maze to go from room1i to room2i and vice versa. The designer of the maze wants to know how confusing the maze is. The confusion score of the maze is the number of different cycles of length 3. For example, 1 → 2 → 3 → 1 is a cycle of length 3, but 1 → 2 → 3 → 4 and 1 → 2 → 3 → 2 → 1 are not. Two cycles are considered to be different if one or more of the rooms visited in the first cycle is not in the second cycle. Return the confusion score of the maze.   Please complete the following python code precisely: ```python class Solution: def numberOfPaths(self, n: int, corridors: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(n = 5, corridors = [[1,2],[5,2],[4,1],[2,4],[3,1],[3,4]]) == 2\n assert candidate(n = 4, corridors = [[1,2],[3,4]]) == 0\n\n\ncheck(Solution().numberOfPaths)"}
250
81
coding
Solve the programming task below in a Python markdown code block. Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game. Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner. In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw. Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! -----Input----- The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers m_{i} and c_{i} (1 ≤ m_{i}, c_{i} ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. -----Output----- If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. -----Examples----- Input 3 3 5 2 1 4 2 Output Mishka Input 2 6 1 1 6 Output Friendship is magic!^^ Input 3 1 5 3 3 2 2 Output Chris -----Note----- In the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game. In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1. In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris.
{"inputs": ["1\n1 1\n", "1\n1 1\n", "1\n1 0\n", "1\n2 1\n", "2\n6 1\n1 6\n", "2\n6 1\n1 8\n", "2\n6 1\n1 6\n", "3\n3 5\n2 1\n4 2\n"], "outputs": ["Friendship is magic!^^", "Friendship is magic!^^\n", "Mishka\n", "Mishka\n", "Friendship is magic!^^", "Friendship is magic!^^\n", "Friendship is magic!^^\n", "Mishka"]}
539
153
coding
Solve the programming task below in a Python markdown code block. Joisino is planning to record N TV programs with recorders. The TV can receive C channels numbered 1 through C. The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i. Here, there will never be more than one program that are broadcast on the same channel at the same time. When the recorder is recording a channel from time S to time T (including time S but not T), it cannot record other channels from time S-0.5 to time T (including time S-0.5 but not T). Find the minimum number of recorders required to record the channels so that all the N programs are completely recorded. -----Constraints----- - 1≤N≤10^5 - 1≤C≤30 - 1≤s_i<t_i≤10^5 - 1≤c_i≤C - If c_i=c_j and i≠j, either t_i≤s_j or s_i≥t_j. - All input values are integers. -----Input----- Input is given from Standard Input in the following format: N C s_1 t_1 c_1 : s_N t_N c_N -----Output----- When the minimum required number of recorders is x, print the value of x. -----Sample Input----- 3 2 1 7 2 7 8 1 8 12 1 -----Sample Output----- 2 Two recorders can record all the programs, for example, as follows: - With the first recorder, record Channel 2 from time 1 to time 7. The first program will be recorded. Note that this recorder will be unable to record other channels from time 0.5 to time 7. - With the second recorder, record Channel 1 from time 7 to time 12. The second and third programs will be recorded. Note that this recorder will be unable to record other channels from time 6.5 to time 12.
{"inputs": ["3 4\n1 3 2\n2 4 4\n1 4 3", "3 4\n1 3 2\n2 4 4\n1 5 3", "3 4\n1 3 2\n3 4 4\n1 4 3", "3 4\n1 3 2\n3 4 4\n1 4 3\n", "3 2\n1 7 2\n7 8 1\n8 12 1", "3 2\n1 7 2\n7 8 1\n8 12 1\n", "3 2\n1 7 2\n7 12 1\n8 12 1", "3 2\n2 7 2\n7 12 1\n8 12 1"], "outputs": ["3\n", "3\n", "3", "3\n", "2", "2\n", "2\n", "2\n"]}
446
228
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together. We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct). Return the K-Sum of the array. A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Note that the empty subsequence is considered to have a sum of 0.   Please complete the following python code precisely: ```python class Solution: def kSum(self, nums: List[int], k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [2,4,-2], k = 5) == 2\n assert candidate(nums = [1,-2,3,4,-10,12], k = 16) == 10\n\n\ncheck(Solution().kSum)"}
161
71
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Haku has been newly hired by Chef to clean tables at his restaurant. So whenever a customer wants a table, Haku must clean it. But Haku happens to be a lazy boy. So in the morning, when the restaurant is opened, all the tables are dirty from night before. The customer don't leave the table unless they are politely requested to do so. And customers can order meal later again. So if they were already having a table, they can be served on the same table [Haku doesn't have to clean :)]. But if they don't have a table then they must be given some table [Haku must clean :(] The restaurant has N tables. When a customer requires a table, he/she can occupy any unoccupied table. However if all tables are occupied, then Haku is free to ask politely any customer to leave his/her table. And the freed table can be given to the waiting customer. Now Chef has the psychic ability to tell the order of customer meal requests for the entire day. Given this list, help Haku find the minimum number of times he has to clean the tables. ------ Input ------ First line contains integer T, number of test cases. First line of each test case contains 2 integers N, number of tables and M, number of customer orders. Followed by M integers on next line, which is the order in which customers ask for meal. Customers are referenced by integer C. ------ Output ------ For each test case output the minimum number of times Haku must clean the table(s). ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 200$ $1 ≤ M ≤ 400$ $1 ≤ C ≤ 400$ ----- Sample Input 1 ------ 4 2 4 1 2 3 4 3 2 4 1 3 6 1 2 1 3 4 1 3 5 1 2 1 3 4 ----- Sample Output 1 ------ 4 2 4 4 ----- explanation 1 ------ Example case 1. In the starting all tables i.e. 2 tables are unoccupied. When customer 1 asks for table, he can be given any of the 2 tables. Haku has to clean either of the table. Next customer 2 can occupy the other free table. Haku must clean second time. When customer 3 comes Haku can ask either customer 1 or 2 to leave. Suppose he asks customer 1 to leave. Then he has to clean table for the third time. When customer 4 comes, Haku can ask customer 2 or 3 to leave. In either case Haku will have to clean the table for the fourth time. Phew!! Example case 4. Suppose the tables are listed as [-, -, -]. A possible optimal order of allocating tables can be [1, -, -] -> [1, 2, -] -> [1, 2, -] -> [1, 2, 3] -> [4, 2, 3]. So Haku will have to clean table for order no. 1, 2, 4 and 5. That is 4 times.
{"inputs": ["4\n2 4\n1 2 3 4\n3 2\n4 1\n3 6\n1 2 1 3 4 1\n3 5\n1 2 1 3 4"], "outputs": ["4\n2\n4\n4"]}
706
68
coding
Solve the programming task below in a Python markdown code block. # Introduction You are the developer working on a website which features a large counter on its homepage, proudly displaying the number of happy customers who have downloaded your companies software. You have been tasked with adding an effect to this counter to make it more interesting. Instead of just displaying the count value immediatley when the page loads, we want to create the effect of each digit cycling through its preceding numbers before stopping on the actual value. # Task As a step towards achieving this; you have decided to create a function that will produce a multi-dimensional array out of the hit count value. Each inner dimension of the array represents an individual digit in the hit count, and will include all numbers that come before it, going back to 0. ## Rules * The function will take one argument which will be a four character `string` representing hit count * The function must return a multi-dimensional array containing four inner arrays * The final value in each inner array must be the actual value to be displayed * Values returned in the array must be of the type `number` **Examples** Also feel free to reuse/extend the following starter code: ```python def counter_effect(hit_count): ```
{"functional": "_inputs = [['1250'], ['0050'], ['0000']]\n_outputs = [[[[0, 1], [0, 1, 2], [0, 1, 2, 3, 4, 5], [0]]], [[[0], [0], [0, 1, 2, 3, 4, 5], [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(counter_effect(*i), o[0])"}
257
245
coding
Solve the programming task below in a Python markdown code block. Read problems statements [Hindi] ,[Bengali] , [Mandarin chinese] , [Russian] and [Vietnamese] as well. The Euler totient function $\varphi(N)$ is defined as the number of integers between $1$ and $N$ (inclusive) which are coprime with $N$. You are given $N$ and $\varphi(N)$. Calculate the prime factorization of $N$. ------ Input ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. The first and only line of each test case contains two space-separated integers $N$ and $\varphi(N)$. ------ Output ------ For each test case, print a line containing a single integer $K$ — the number of distinct prime factors of $N$. Then, print $K$ lines. For each valid $i$, the $i$-th of these lines should contain two space-separated integers $p_{i}$ and $e_{i}$ denoting a prime divisor of $N$ and its exponent. Specifically, the following conditions should hold: $N = \prod_{i=1}^{K} p_{i}^{e_{i}}$ $p_{i} < p_{i+1}$ for each valid $i$ $e_{i} > 0$ for each valid $i$ ------ Constraints ------ $1 ≤ T ≤ 10$ $2 ≤ N ≤ 10^{500}$ ------ Subtasks ------ Subtask #1 (5 points): $2 ≤ N ≤ 10^{14}$ Subtask #2 (25 points): $2 ≤ N ≤ 10^{50}$ Subtask #3 (70 points): $2 ≤ N ≤ 10^{500}$ ----- Sample Input 1 ------ 2 6 2 8 4 ----- Sample Output 1 ------ 2 2 1 3 1 1 2 3
{"inputs": ["2\n6 2\n8 4"], "outputs": ["2\n2 1\n3 1\n1\n2 3"]}
452
34
coding
Solve the programming task below in a Python markdown code block. Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water. The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [l_{i}, r_{i}], besides, r_{i} < l_{i} + 1 for 1 ≤ i ≤ n - 1. To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that l_{i} ≤ x ≤ r_{i}, l_{i} + 1 ≤ y ≤ r_{i} + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands. -----Input----- The first line contains integers n (2 ≤ n ≤ 2·10^5) and m (1 ≤ m ≤ 2·10^5) — the number of islands and bridges. Next n lines each contain two integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^18) — the coordinates of the island endpoints. The last line contains m integer numbers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^18) — the lengths of the bridges that Andrewid got. -----Output----- If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b_1, b_2, ..., b_{n} - 1, which mean that between islands i and i + 1 there must be used a bridge number b_{i}. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case. -----Examples----- Input 4 4 1 4 7 8 9 10 12 14 4 5 3 8 Output Yes 2 3 1 Input 2 2 11 14 17 18 2 9 Output No Input 2 1 1 1 1000000000000000000 1000000000000000000 999999999999999999 Output Yes 1 -----Note----- In the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14. In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
{"inputs": ["2 1\n1 2\n5 6\n1\n", "2 1\n1 2\n5 6\n1\n", "2 1\n1 2\n5 3\n2\n", "2 1\n0 2\n5 3\n2\n", "2 1\n1 2\n5 6\n0\n", "2 1\n1 2\n5 10\n1\n", "2 1\n1 2\n5 10\n2\n", "2 1\n1 1\n100 100\n5\n"], "outputs": ["No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]}
741
172
coding
Solve the programming task below in a Python markdown code block. One day, Chef prepared D brand new dishes. He named the i-th dish by a string Si. After the cooking, he decided to categorize each of these D dishes as special or not. A dish Si is called special if it's name (i.e. the string Si) can be represented in the form of a double string by removing at most one (possibly zero) character from it's name from any position. A string is called a double string if it can be represented as a concatenation of two identical, non-empty strings. e.g. "abab" is a double string as it can be represented as "ab" + "ab" where + operation denotes concatenation. Similarly, "aa", "abcabc" are double strings whereas "a", "abba", "abc" are not. -----Input----- - First line of the input contains an integer D denoting the number of dishes prepared by Chef on that day. - Each of the next D lines will contain description of a dish. - The i-th line contains the name of i-th dish Si. -----Output----- For each of the D dishes, print a single line containing "YES" or "NO" (without quotes) denoting whether the dish can be called as a special or not. -----Constraints----- - 1 ≤ D ≤ 106 - 1 ≤ |Si| ≤ 106. - Each character of string Si will be lower case English alphabet (i.e. from 'a' to 'z'). -----Subtasks----- Subtask #1 : (20 points) - Sum of |Si| in an input file doesn't exceed 2 * 103 Subtask 2 : (80 points) - Sum of |Si| in an input file doesn't exceed 2 * 106 -----Example----- Input: 3 aba abac abcd Output: YES NO NO -----Explanation----- Example case 1. We can remove the character at position 1 (0-based index) to get "aa" which is a double string. Hence, it is a special dish. Example case 2. It is not possible to remove the character at any of the position to get the double string. Hence, it is not a special dish.
{"inputs": ["3\naba\nabac\nabcd", "3\naba\nabac\naacd", "3\nbca\nb`dc\naabd", "3\ncdd\n_a_a\n_ed[", "3\nfda\n`a`a\nb`Ze", "3\naba\nabac\ndaca", "3\naba\nabac\ndaac", "3\naba\nabac\nadac"], "outputs": ["YES\nNO\nNO", "YES\nNO\nNO\n", "NO\nNO\nNO\n", "YES\nYES\nNO\n", "NO\nYES\nNO\n", "YES\nNO\nNO\n", "YES\nNO\nNO\n", "YES\nNO\nNO\n"]}
494
163
coding
Solve the programming task below in a Python markdown code block. Given an empty array A of infinite length and a positive integer K you have to process Q queries of type: - ! l r x: Fill the value x in all the empty places in the array from index l to r (both inclusive). - ? l r: Print the number of prime factors of K which is also a prime factor of at least one number in A[l], A[l + 1], A[l + 2], … A[r]. -----Input----- - The first line contains two space separated integers K and Q respectively. - Then Q lines follow: - Each of the $i^{th}$ line contains one of the above two types of queries. -----Output----- For each query of the second type, print in a new line the answer to that query. i.e. number of prime factors of K which is also a prime factor of at least one number in A[l], A[l + 1], A[l + 2], … A[r]. -----Constraints----- - $1 \leq K, x \leq 10^9$ - $ 1 \leq l \leq r \leq 10^5$ - $ 1 \leq Q \leq 10^5$ -----Sample Input----- 20 5 ? 1 5 ! 3 5 4 ? 1 5 ! 1 4 15 ? 1 5 -----Sample Output----- 0 1 2 -----EXPLANATION----- Initially, all the places in the array are empty. i.e _ _ _ _ _ After first update the array looks like: _ _ 4 4 4 In the range [1, 5] the only factor of 20 which is also a prime factor of at least one number in _ _ 4 4 4 is 2. After the second update the array looks like: 15 15 4 4 4 In the range [1, 5] the prime factors of 20 i.e. 5 is a prime factor of 15, 15 and 2 is the prime factor of 4, 4, 4.
{"inputs": ["20 5\n? 1 5\n! 3 5 4\n? 1 5\n! 1 4 15\n? 1 5"], "outputs": ["0\n1\n2"]}
483
54
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian as well. After IOI Ilya decided to make a business. He found a social network called "TheScorpyBook.com". It currently has N registered users. As in any social network two users can be friends. Ilya wants the world to be as connected as possible, so he wants to suggest friendship to some pairs of users. He will suggest user u to have a friendship with user v if they are not friends yet and there is a user w who is friends of both of them. Note that u, v and w are different users. Ilya is too busy with IPO these days, so he asks you to count how many friendship suggestions he has to send over his social network.   ------ Input ------ The first line contains an integer number N — the number of users in the network. Next N lines contain N characters each denoting friendship relations. j^{th} character if the i^{th} lines equals one, if users i and j are friends and equals to zero otherwise. This relation is symmetric, i.e. if user a is friend of b then b is also a friend of a.   ------ Output ------ Output a single integer — number of friendship suggestions Ilya has to send.   ------ Constraints ------ $1 ≤ N ≤ 2000$ ------ Example ------ Input: 4 0111 1000 1000 1000 Output: 6 ------ Explanation ------ Each of users [2, 3, 4] should receive two friendship suggestions, while user 1 does not need any, since he already has all other users in his friend-list.
{"inputs": ["4\n0111\n1000\n1000\n1000", "4\n1111\n1000\n1000\n1000", "4\n0111\n1100\n0000\n1001", "4\n1111\n1010\n1000\n1010", "4\n0011\n0000\n0000\n1001", "4\n1111\n1100\n0000\n1001", "4\n0110\n1000\n0000\n1001", "4\n0011\n1000\n0000\n1000"], "outputs": ["6", "6\n", "2\n", "4\n", "0\n", "2\n", "2\n", "2\n"]}
362
221
coding
Solve the programming task below in a Python markdown code block. There are initially X people in a room. You are given an array A of length N which describes the following events: If A_{i} ≥ 0, then A_{i} people enter the room at i-th minute. For e.g. if A_{2} = 3, then 3 people enter the room at the 2-nd minute. If A_{i} < 0, then |A_{i}| people leave the room at i-th minute. Here |A_{i}| denotes the absolute value of A_{i}. For e.g. if A_{4} = -2, then 2 people leave the room at the 4-th minute. Determine the maximum number of people in the room at any moment of time. It is guaranteed in the input that at any moment of time, the number of people in the room does not become negative. ------ Input Format ------ - The first line will contain T - the number of test cases. Then the test cases follow. - The first line of each test case consists of two integers N and X - the length of the array A and the number of people in the room initially. - The second line of each test case contains N integers A_{1}, A_{2}, A_{3}, \dots A_{N}. ------ Output Format ------ For each testcase, output the maximum number of people in the room at any point of time. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 100$ $0 ≤ X ≤ 100$ $-100 ≤ A_{i} ≤ 100$ ----- Sample Input 1 ------ 3 5 8 0 3 3 -13 5 4 5 0 -2 2 3 3 5 -2 5 -2 ----- Sample Output 1 ------ 14 8 8 ----- explanation 1 ------ Test case-1: In the $3$-rd minute, the room contains $8 + 0 + 3 + 3 = 14$ people which is the maximum number of people in the room at any point of time. Test case-2: In the $4$-th minute, the room contains $5 + 0 - 2 + 2 + 3 = 8$ people which is the maximum number of people in the room at any point of time. Test case-3: In the $2$-nd minute, the room contains $5 - 2 + 5 = 8$ people which is the maximum number of people in the room at any point of time.
{"inputs": ["3\n5 8\n0 3 3 -13 5\n4 5\n0 -2 2 3\n3 5\n-2 5 -2\n"], "outputs": ["14\n8\n8\n"]}
572
57
coding
Solve the programming task below in a Python markdown code block. poly The poly tool returns the coefficients of a polynomial with the given sequence of roots. print numpy.poly([-1, 1, 1, 10]) #Output : [ 1 -11 9 11 -10] roots The roots tool returns the roots of a polynomial with the given coefficients. print numpy.roots([1, 0, -1]) #Output : [-1. 1.] polyint The polyint tool returns an antiderivative (indefinite integral) of a polynomial. print numpy.polyint([1, 1, 1]) #Output : [ 0.33333333 0.5 1. 0. ] polyder The polyder tool returns the derivative of the specified order of a polynomial. print numpy.polyder([1, 1, 1, 1]) #Output : [3 2 1] polyval The polyval tool evaluates the polynomial at specific value. print numpy.polyval([1, -2, 0, 2], 4) #Output : 34 polyfit The polyfit tool fits a polynomial of a specified order to a set of data using a least-squares approach. print numpy.polyfit([0,1,-1, 2, -2], [0,1,1, 4, 4], 2) #Output : [ 1.00000000e+00 0.00000000e+00 -3.97205465e-16] The functions polyadd, polysub, polymul, and polydiv also handle proper addition, subtraction, multiplication, and division of polynomial coefficients, respectively. Task You are given the coefficients of a polynomial $\mbox{P}$. Your task is to find the value of $\mbox{P}$ at point $\boldsymbol{x}$. Input Format The first line contains the space separated value of the coefficients in $\mbox{P}$. The second line contains the value of $\boldsymbol{x}$. Output Format Print the desired value. Sample Input 1.1 2 3 0 Sample Output 3.0
{"inputs": ["1.1 2 3\n0\n"], "outputs": ["3.0\n"]}
508
24
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.   Please complete the following python code precisely: ```python class Solution: def slidingPuzzle(self, board: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(board = [[1,2,3],[4,0,5]]) == 1\n assert candidate(board = [[1,2,3],[5,4,0]]) == -1\n assert candidate(board = [[4,1,2],[5,0,3]]) == 5\n\n\ncheck(Solution().slidingPuzzle)"}
168
87
coding
Solve the programming task below in a Python markdown code block. Sammy and Simmy love candies and frequently visit the local candy shop. Sammy and Simmy have bought $N$ candy packs. Packet $i$ contains $A_{i}$ candies. Sammy being the elder one is happy only if she has strictly more candies than Simmy. However Simmy, the more sensible one, is happy only if the difference between their number of candies is not more than $1$. The shopkeeper, being a generous lady, agrees to help Sammy and Simmy by distributing the candies among them in a way that makes both of them happy. The shopkeeper can open the packs and distribute the candies even within a single pack to different people. ------ Input: ------ The first line will contain $T$, the number of testcases. The first line of every test case will contain $N$, the number of candy packs. The next line has $N$ integers, the $i_{th}$ integer denoting $A_{i}$, the number of candies in the $i_{th}$ pack. ------ Output: ------ Output "YES" if its possible for the shopkeeper to make both the sisters happy otherwise output "NO". ------ Constraints ------ $1 ≤ T ≤ 10^{3}$ $1 ≤ N ≤ 10^{3}$ $1 ≤ A_{i} ≤ 100$ ----- Sample Input 1 ------ 1 2 5 2 ----- Sample Output 1 ------ YES ----- explanation 1 ------ Sammy gets 4 candies from the first pack. Simmy gets 1 candy from the first pack and 2 from the second one. So in total, Sammy has 4, and Simmy has 3. Since Sammy has strictly more candies than Simmy, Sammy is happy. And since the difference is not more then 1, Simmy is also happy. Thus both of them are happy.
{"inputs": ["1 \n2 \n5 2"], "outputs": ["YES"]}
408
22
coding
Solve the programming task below in a Python markdown code block. Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $a$ and screen height not greater than $b$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $w$, and the height of the screen is $h$, then the following condition should be met: $\frac{w}{h} = \frac{x}{y}$. There are many different TV sets in the shop. Monocarp is sure that for any pair of positive integers $w$ and $h$ there is a TV set with screen width $w$ and height $h$ in the shop. Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of positive integers $w$ and $h$, beforehand, such that $(w \le a)$, $(h \le b)$ and $(\frac{w}{h} = \frac{x}{y})$. In other words, Monocarp wants to determine the number of TV sets having aspect ratio $\frac{x}{y}$, screen width not exceeding $a$, and screen height not exceeding $b$. Two TV sets are considered different if they have different screen width or different screen height. -----Input----- The first line contains four integers $a$, $b$, $x$, $y$ ($1 \le a, b, x, y \le 10^{18}$) — the constraints on the screen width and height, and on the aspect ratio. -----Output----- Print one integer — the number of different variants to choose TV screen width and screen height so that they meet the aforementioned constraints. -----Examples----- Input 17 15 5 3 Output 3 Input 14 16 7 22 Output 0 Input 4 2 6 4 Output 1 Input 1000000000000000000 1000000000000000000 999999866000004473 999999822000007597 Output 1000000063 -----Note----- In the first example, there are $3$ possible variants: $(5, 3)$, $(10, 6)$, $(15, 9)$. In the second example, there is no TV set meeting the constraints. In the third example, there is only one variant: $(3, 2)$.
{"inputs": ["4 2 6 4\n", "1 1 1 1\n", "3 3 2 4\n", "3 3 2 6\n", "4 2 4 3\n", "5 5 1 1\n", "3 3 2 4\n", "4 2 4 3\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "0\n", "5\n", "1\n", "0\n"]}
628
118
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Russian] and [Mandarin Chinese] Chef is playing Need For Speed. Currently, his car is running on a straight road with a velocity $U$ metres per second and approaching a $90^{\circ}$ turn which is $S$ metres away from him. To successfully cross the turn, velocity of the car when entering the turn must not exceed $V$ metres per second. The brakes of Chef's car allow him to slow down with a deceleration (negative acceleration) not exceeding $A$ metres per squared second. Tell him whether he can cross the turn successfully. The velocity $v$ when entering the turn can be determined from Newton's 2nd law to be $v^{2} = U^{2} + 2 \cdot a \cdot S$ if the car is moving with a uniform acceleration $a$. ------ Input ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. The first and only line of each test case contains four space-separated integers $U$, $V$, $A$ and $S$. ------ Output ------ For each test case, print a single line containing the string "Yes" if Chef can cross the turn successfully or "No" if he cannot (without quotes). You may print each character of each string in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and "YES" will all be treated as identical). ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ U, V, A, S ≤ 10^{4}$ ------ Subtasks ------ Subtask #1 (100 points): original constraints ----- Sample Input 1 ------ 3 1 1 1 1 2 1 1 1 2 2 1 1 ----- Sample Output 1 ------ Yes No Yes ----- explanation 1 ------ Example case 1: Since $U = V = 1$, Chef does not need to brake and will be able to turn successfully. Example case 2: The smallest velocity Chef's car can have even with the maximum deceleration is $\sqrt{2 \cdot 2 - 2 \cdot 1 \cdot 1} = \sqrt{2}$, which is greater than the maximum allowed velocity for a safe turn. Example case 3: The smallest velocity Chef's car can have with the maximum deceleration is again $\sqrt{2}$, which is smaller than the maximum allowed velocity for a safe turn.
{"inputs": ["3\n1 1 1 1\n2 1 1 1\n2 2 1 1"], "outputs": ["Yes\nNo\nYes"]}
568
40
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction. Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.   Please complete the following python code precisely: ```python class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(arr = [3,5,1,2,4], m = 1) == 4\n assert candidate(arr = [3,1,5,4,2], m = 2) == -1\n assert candidate(arr = [1], m = 1) == 1\n assert candidate(arr = [2,1], m = 2) == 2\n\n\ncheck(Solution().findLatestStep)"}
197
106
coding
Solve the programming task below in a Python markdown code block. The next lecture in a high school requires two topics to be discussed. The $i$-th topic is interesting by $a_i$ units for the teacher and by $b_i$ units for the students. The pair of topics $i$ and $j$ ($i < j$) is called good if $a_i + a_j > b_i + b_j$ (i.e. it is more interesting for the teacher). Your task is to find the number of good pairs of topics. -----Input----- The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the number of topics. The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the interestingness of the $i$-th topic for the teacher. The third line of the input contains $n$ integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 10^9$), where $b_i$ is the interestingness of the $i$-th topic for the students. -----Output----- Print one integer — the number of good pairs of topic. -----Examples----- Input 5 4 8 2 6 2 4 5 4 1 3 Output 7 Input 4 1 3 2 4 1 3 2 4 Output 0
{"inputs": ["3\n2 3 4\n1 2 3\n", "3\n2 3 4\n1 2 3\n", "3\n2 3 2\n0 2 3\n", "3\n2 3 2\n1 2 3\n", "3\n2 3 2\n0 0 3\n", "3\n2 3 1\n0 0 3\n", "3\n0 3 1\n0 0 3\n", "3\n0 3 1\n0 0 2\n"], "outputs": ["3\n", "3\n", "2\n", "1\n", "3\n", "2\n", "2\n", "2\n"]}
347
166
coding
Solve the programming task below in a Python markdown code block. Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates. Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions: * The largest among the values in the i-th row (1 \leq i \leq N) is A_i. * The largest among the values in the j-th column (1 \leq j \leq M) is B_j. For him, find the number of ways to write the numbers under these conditions, modulo 10^9 + 7. Constraints * 1 \leq N \leq 1000 * 1 \leq M \leq 1000 * 1 \leq A_i \leq N \times M * 1 \leq B_j \leq N \times M * A_i and B_j are integers. Input Input is given from Standard Input in the following format: N M A_1 A_2 ... A_{N} B_1 B_2 ... B_{M} Output Print the number of ways to write the numbers under the conditions, modulo 10^9 + 7. Examples Input 2 2 4 3 3 4 Output 2 Input 3 3 5 9 7 3 6 9 Output 0 Input 2 2 4 4 4 4 Output 0 Input 14 13 158 167 181 147 178 151 179 182 176 169 180 129 175 168 181 150 178 179 167 180 176 169 182 177 175 159 173 Output 343772227
{"inputs": ["0 2\n4 3\n3 4", "2 2\n6 4\n4 4", "2 2\n6 4\n5 4", "0 2\n8 3\n3 4", "2 2\n6 1\n5 4", "0 2\n8 3\n3 0", "2 2\n6 2\n5 4", "0 2\n7 3\n3 0"], "outputs": ["1\n", "0\n", "0\n", "1\n", "0\n", "1\n", "0\n", "1\n"]}
464
142
coding
Solve the programming task below in a Python markdown code block. Valera loves his garden, where n fruit trees grow. This year he will enjoy a great harvest! On the i-th tree b_{i} fruit grow, they will ripen on a day number a_{i}. Unfortunately, the fruit on the tree get withered, so they can only be collected on day a_{i} and day a_{i} + 1 (all fruits that are not collected in these two days, become unfit to eat). Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? -----Input----- The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. -----Output----- Print a single integer — the maximum number of fruit that Valera can collect. -----Examples----- Input 2 3 1 5 2 3 Output 8 Input 5 10 3 20 2 20 1 20 4 20 5 20 Output 60 -----Note----- In the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.
{"inputs": ["1 3\n5 3\n", "1 3\n5 3\n", "1 3\n1 3\n", "1 3\n1 6\n", "1 1\n2 4\n", "1 1\n3 4\n", "1 0\n3 4\n", "1 0\n3 2\n"], "outputs": ["3\n", "3\n", "3\n", "6\n", "2\n", "2\n", "0\n", "0\n"]}
486
118
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3. Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise. The frequency of a letter x is the number of times it occurs in the string.   Please complete the following python code precisely: ```python class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(word1 = \"aaaa\", word2 = \"bccb\") == False\n assert candidate(word1 = \"abcdeef\", word2 = \"abaaacc\") == True\n assert candidate(word1 = \"cccddabba\", word2 = \"babababab\") == True\n\n\ncheck(Solution().checkAlmostEquivalent)"}
141
85
coding
Solve the programming task below in a Python markdown code block. In this Kata, you will be given a number and your task will be to return the nearest prime number. ```Haskell solve(4) = 3. The nearest primes are 3 and 5. If difference is equal, pick the lower one. solve(125) = 127 ``` We'll be testing for numbers up to `1E10`. `500` tests. More examples in test cases. Good luck! If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) Also feel free to reuse/extend the following starter code: ```python def solve(n): ```
{"functional": "_inputs = [[3], [11], [4], [110], [1110], [3000], [35000], [350000], [3500000], [10000000000]]\n_outputs = [[3], [11], [3], [109], [1109], [2999], [34981], [350003], [3499999], [10000000019]]\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])"}
186
276
coding
Solve the programming task below in a Python markdown code block. There are N islands lining up from west to east, connected by N-1 bridges. The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west. One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands: Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible. You decided to remove some bridges to meet all these M requests. Find the minimum number of bridges that must be removed. -----Constraints----- - All values in input are integers. - 2 \leq N \leq 10^5 - 1 \leq M \leq 10^5 - 1 \leq a_i < b_i \leq N - All pairs (a_i, b_i) are distinct. -----Input----- Input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M -----Output----- Print the minimum number of bridges that must be removed. -----Sample Input----- 5 2 1 4 2 5 -----Sample Output----- 1 The requests can be met by removing the bridge connecting the second and third islands from the west.
{"inputs": ["2 1\n1 2\n", "5 2\n2 4\n2 5", "5 2\n1 5\n2 5", "5 1\n1 5\n2 5", "5 1\n0 5\n2 5", "5 2\n1 4\n2 8", "5 2\n0 5\n2 5", "4 1\n1 5\n2 5"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
302
139
coding
Solve the programming task below in a Python markdown code block. Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000. Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i. If two slimes of the same color are adjacent, they will start to combine themselves. Because Takahashi likes smaller slimes, he has decided to change the colors of some of the slimes with his magic. Takahashi can change the color of one slime to any of the 10000 colors by one spell. How many spells are required so that no slimes will start to combine themselves? Constraints * 2 \leq N \leq 100 * 1 \leq a_i \leq N * All values in input are integers. Input Input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output Print the minimum number of spells required. Examples Input 5 1 1 2 2 2 Output 2 Input 3 1 2 1 Output 0 Input 5 1 1 1 1 1 Output 2 Input 14 1 2 2 3 3 3 4 4 4 4 1 2 3 4 Output 4
{"inputs": ["3\n0 2 1", "3\n1 2 2", "3\n1 4 2", "3\n1 3 2", "3\n2 3 2", "3\n2 3 1", "3\n2 2 1", "3\n2 2 2"], "outputs": ["0\n", "1\n", "0\n", "0\n", "0\n", "0\n", "1\n", "1\n"]}
341
110
coding
Solve the programming task below in a Python markdown code block. Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. Output Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. Examples Input This is Codeforces Beta Round 5 Output ************ * This is * * * *Codeforces* * Beta * * Round * * 5 * ************ Input welcome to the Codeforces Beta Round 5 and good luck Output **************** *welcome to the* * Codeforces * * Beta * * Round 5 * * * * and * * good luck * ****************
{"inputs": ["U\n", "T\n", "V\n", "W\n", "X\n", "Y\n", "Z\n", "0\n2\n"], "outputs": ["***\n*U*\n***", "***\n*T*\n***\n", "***\n*V*\n***\n", "***\n*W*\n***\n", "***\n*X*\n***\n", "***\n*Y*\n***\n", "***\n*Z*\n***\n", "***\n*0*\n*2*\n***"]}
351
127
coding
Solve the programming task below in a Python markdown code block. There is a new prodigy in town and he has challenged people to a game. They have to give him an integer N and he will immediately respond with a number which has more than N factors. What the prodigy really does is to do some complex calculations in his head to find out the smallest integer with more than N factors. However, he has a weakness - he knows to do those calculation only on numbers up to 1019, so if the answer to be reported is more than 1019, he will not be able to come up with his solution and will lose the game. Given the integer the people give to the prodigy, you need to report whether he wins the game or not. If he wins, also output his answer. -----Input----- The first line of input contains T (T ≤ 25), the number of test cases. Following this are T lines, each containing an integer N (1 ≤ N ≤ 109) - the number which is given to the prodigy. -----Output----- Output one line per test case. If the smallest integer X with more than N factors is bigger than 1019 so that the prodigy does not win, print "lose". Otherwise print "win X" (quotes for clarity). -----Example----- Input: 3 3 5 12345678 Output: win 6 win 12 lose
{"inputs": ["3\n3\n5\n12345678"], "outputs": ["win 6\nwin 12\nlose"]}
308
34
coding
Solve the programming task below in a Python markdown code block. Manao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero. Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9). Input The single line contains three space-separated integers n, m and k (2 ≤ k ≤ n ≤ 109; 0 ≤ m ≤ n). Output Print a single integer — the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9). Examples Input 5 3 2 Output 3 Input 5 4 2 Output 6 Note Sample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points. Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4. Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000 mod 1000000009, even though 2000000020 mod 1000000009 is a smaller number.
{"inputs": ["2 0 2\n", "2 2 2\n", "3 2 2\n", "2 1 2\n", "3 3 2\n", "2 2 3\n", "3 3 3\n", "6 3 2\n"], "outputs": [" 0", " 4", " 2", " 1", " 5", "2\n", "6\n", "3\n"]}
543
107
coding
Solve the programming task below in a Python markdown code block. Recently, Chef visited his doctor. The doctor advised Chef to drink at least 2000 ml of water each day. Chef drank X ml of water today. Determine if Chef followed the doctor's advice or not. ------ Input Format ------ - The first line contains a single integer T — the number of test cases. Then the test cases follow. - The first and only line of each test case contains one integer X — the amount of water Chef drank today. ------ Output Format ------ For each test case, output YES if Chef followed the doctor's advice of drinking at least 2000 ml of water. Otherwise, output NO. 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 ≤ 2000$ $1 ≤X ≤4000$ ----- Sample Input 1 ------ 3 2999 1450 2000 ----- Sample Output 1 ------ YES NO YES ----- explanation 1 ------ Test case $1$: Chef followed the doctor's advice since he drank $2999$ ml of water which is $≥ 2000$ ml. Test case $2$: Chef did not follow the doctor's advice since he drank $1450$ ml of water which is $< 2000$ ml. Test case $3$: Chef followed the doctor's advice since he drank $2000$ ml of water which is $≥ 2000$ ml.
{"inputs": ["3\n2999\n1450\n2000\n"], "outputs": ["YES\nNO\nYES\n"]}
356
33
coding
Solve the programming task below in a Python markdown code block. Chef went shopping and bought items worth X rupees (1 ≤ X ≤ 100). Unfortunately, Chef only has a single 100 rupees note. Since Chef is weak at maths, can you help Chef in calculating what money he should get back after paying 100 rupees for those items? ------ Input Format ------ - First line will contain T, the number of test cases. Then the test cases follow. - Each test case consists of a single line containing an integer X, the total price of items Chef purchased. ------ Output Format ------ For each test case, output in a single line the money Chef has to receive back. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ X ≤ 100$ ----- Sample Input 1 ------ 3 1 25 100 ----- Sample Output 1 ------ 99 75 0 ----- explanation 1 ------ Test case-1: Since chef paid $100$ rupees for items worth $1$ rupee. He should get back $99$ rupees. Test case-2: Since chef paid $100$ rupees for items worth $25$ rupees. He should get back $75$ rupees.
{"inputs": ["3\n1\n25\n100\n"], "outputs": ["99\n75\n0\n"]}
282
29
coding
Solve the programming task below in a Python markdown code block. Write function bmi that calculates body mass index (bmi = weight / height ^ 2). if bmi <= 18.5 return "Underweight" if bmi <= 25.0 return "Normal" if bmi <= 30.0 return "Overweight" if bmi > 30 return "Obese" Also feel free to reuse/extend the following starter code: ```python def bmi(weight, height): ```
{"functional": "_inputs = [[50, 1.8], [80, 1.8], [90, 1.8], [110, 1.8], [50, 1.5]]\n_outputs = [['Underweight'], ['Normal'], ['Overweight'], ['Obese'], ['Normal']]\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(bmi(*i), o[0])"}
103
212
coding
Solve the programming task below in a Python markdown code block. Complete the solution so that it returns the number of times the search_text is found within the full_text. ```python search_substr( fullText, searchText, allowOverlap = true ) ``` so that overlapping solutions are (not) counted. If the searchText is empty, it should return `0`. Usage examples: ```python search_substr('aa_bb_cc_dd_bb_e', 'bb') # should return 2 since bb shows up twice search_substr('aaabbbcccc', 'bbb') # should return 1 search_substr( 'aaa', 'aa' ) # should return 2 search_substr( 'aaa', '' ) # should return 0 search_substr( 'aaa', 'aa', false ) # should return 1 ``` Also feel free to reuse/extend the following starter code: ```python def search_substr(full_text, search_text, allow_overlap=True): ```
{"functional": "_inputs = [['aa_bb_cc_dd_bb_e', 'bb'], ['aaabbbcccc', 'bbb'], ['aaacccbbbcccc', 'cc'], ['aaa', 'aa'], ['aaa', 'aa', False], ['aaabbbaaa', 'bb', False], ['a', ''], ['', 'a'], ['', ''], ['', '', False]]\n_outputs = [[2], [1], [5], [2], [1], [1], [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(search_substr(*i), o[0])"}
199
249
coding
Solve the programming task below in a Python markdown code block. Some integral numbers are odd. All are more odd, or less odd, than others. Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`. Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :] Even numbers are always less odd than odd numbers, but they also can be more, or less, odd than other even numbers, by the same mechanism. # Task Given a _non-empty_ finite list of _unique_ integral ( not necessarily non-negative ) numbers, determine the number that is _odder than the rest_. Given the constraints, there will always be exactly one such number. # Examples ```python oddest([1,2]) => 1 oddest([1,3]) => 3 oddest([1,5]) => 5 ``` # Hint Do you _really_ want one? Point or tap here. Also feel free to reuse/extend the following starter code: ```python def oddest(a): ```
{"functional": "_inputs = [[[1, 2]], [[1, 3]], [[1, 5]], [[0]], [[1, 3, 5, 7]], [[2, 4]], [[-1]], [[-1, 0, 1]], [[-3, 3]], [[-5, 3]], [[-42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42]]]\n_outputs = [[1], [3], [5], [0], [7], [2], [-1], [-1], [3], [-5], [-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(oddest(*i), o[0])"}
265
570
coding
Solve the programming task below in a Python markdown code block. Babidi has summoned Majin Vegeta. He orders him to kill Supreme Kai. But Vegeta wants to get out of his control. Babidi has laid out a trap. Vegeta is standing at the $nth$ level of mind control. In order to defeat Babidi's trap, he needs to reach $mth$ level. The levels are continuous increasing integers. At each increment of level, $nth$ to $(n+1)th$ level, for example, the energy used is - number of distinct prime factors of $n$. Vegeta needs your help in order to figure out how much total minimum energy he needs to defeat Babidi's trap. The total energy is the sum of energy used at each increment of a level.In the calculation of energy, $n$ and $m$ are inclusive. ------ Input: ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follow. The first and only line of each test case contains the two integers $n$ and $m$, separated by a single space. ------ Output: ------ For each test case, print a single line containing one integer denoting the energy needed by Vegeta to escape Babidi's mind control and continue his battle with Kakarot. ------ Constraints ------ $1 ≤ T ≤ 2$ $1 ≤ n ≤ m ≤ 10^{6}$ ----- Sample Input 1 ------ 2 3 7 1 1023 ----- Sample Output 1 ------ 5 2177 ----- explanation 1 ------ Example case 1: Vegeta is standing at $n$=3. As he moves from 3 to 4, energy used is 1. From 4 to 5, energy used is 1. Similarly, as he continues to move towards m=7, the total energy used is 1+1+1+2=5.
{"inputs": ["2\n3 7\n1 1023"], "outputs": ["5\n2177"]}
429
28
coding
Solve the programming task below in a Python markdown code block. One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y): * point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y * point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y * point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y * point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points. Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set. Input The first input line contains the only integer n (1 ≤ n ≤ 200) — the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| ≤ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different. Output Print the only number — the number of supercentral points of the given set. Examples Input 8 1 1 4 2 3 1 1 2 0 2 0 1 1 0 1 3 Output 2 Input 5 0 0 0 1 1 0 0 -1 -1 0 Output 1 Note In the first sample the supercentral points are only points (1, 1) and (1, 2). In the second sample there is one supercental point — point (0, 0).
{"inputs": ["1\n262 5\n", "1\n357 5\n", "1\n271 5\n", "1\n520 5\n", "1\n206 5\n", "1\n206 8\n", "1\n487 56\n", "1\n143 75\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
506
120
coding
Solve the programming task below in a Python markdown code block. The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor. At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked. The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked. -----Input----- The first line contains three integers n, m, k (1 ≤ n, m, k ≤ 100). Then follow n lines describing instructions. The i-th line contains m integers: x_{i}1, x_{i}2, ..., x_{im} (0 ≤ x_{ij} ≤ k), where x_{ij} is the instruction that must be executed by the i-th core at the j-th cycle. If x_{ij} equals 0, then the corresponding instruction is «do nothing». But if x_{ij} is a number from 1 to k, then the corresponding instruction is «write information to the memory cell number x_{ij}». We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k. -----Output----- Print n lines. In the i-th line print integer t_{i}. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked. -----Examples----- Input 4 3 5 1 0 0 1 0 2 2 3 1 3 2 0 Output 1 1 3 0 Input 3 2 2 1 2 1 2 2 2 Output 1 1 0 Input 1 1 1 0 Output 0
{"inputs": ["1 1 1\n0\n", "1 1 1\n1\n", "1 1 1\n1\n", "1 1 2\n1\n", "1 1 1\n0\n", "2 1 1\n1\n1\n", "2 1 1\n1\n0\n", "2 1 1\n0\n1\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "1\n1\n", "0\n0\n", "0\n0\n"]}
602
130
coding
Solve the programming task below in a Python markdown code block. Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string s_{i} having the same length n. We denote the beauty of the i-th string by a_{i}. It can happen that a_{i} is negative — that means that Santa doesn't find this string beautiful at all. Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length n. Recall that a palindrome is a string that doesn't change after one reverses it. Since the empty string is a palindrome too, the answer can't be negative. Even if all a_{i}'s are negative, Santa can obtain the empty string. -----Input----- The first line contains two positive integers k and n divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1 ≤ k, n ≤ 100 000; n·k  ≤ 100 000). k lines follow. The i-th of them contains the string s_{i} and its beauty a_{i} ( - 10 000 ≤ a_{i} ≤ 10 000). The string consists of n lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties. -----Output----- In the only line print the required maximum possible beauty. -----Examples----- Input 7 3 abb 2 aaa -3 bba -1 zyz -4 abb 5 aaa 7 xyx 4 Output 12 Input 3 1 a 1 a 2 a 3 Output 6 Input 2 5 abcde 10000 abcde 10000 Output 0 -----Note----- In the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order).
{"inputs": ["1 1\ne -1\n", "1 2\nyy 1\n", "1 2\nyy 1\n", "1 1\ne -1\n", "1 2\nzy 1\n", "1 1\nf -1\n", "0 1\nf -1\n", "0 1\ne -1\n"], "outputs": ["0\n", "1\n", "1\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
506
118
coding
Solve the programming task below in a Python markdown code block. Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i. First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing. Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa. -----Constraints----- - 2 \leq N \leq 10^5 - 0 \leq M \leq \min(10^5, N (N-1)) - 1 \leq u_i, v_i \leq N(1 \leq i \leq M) - u_i \neq v_i (1 \leq i \leq M) - If i \neq j, (u_i, v_i) \neq (u_j, v_j). - 1 \leq S, T \leq N - S \neq T -----Input----- Input is given from Standard Input in the following format: N M u_1 v_1 : u_M v_M S T -----Output----- If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T. -----Sample Input----- 4 4 1 2 2 3 3 4 4 1 1 3 -----Sample Output----- 2 Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.
{"inputs": ["3 0\n1 2", "6 0\n1 2", "2 0\n1 2", "2 0\n1 2\n", "3 3\n1 2\n2 3\n2 1\n1 2", "3 1\n1 1\n3 3\n3 1\n1 2", "3 3\n1 1\n2 3\n3 1\n1 2", "3 3\n1 2\n2 1\n2 1\n1 2"], "outputs": ["-1\n", "-1\n", "-1", "-1\n", "1\n", "0\n", "-1\n", "1\n"]}
514
159
coding
Solve the programming task below in a Python markdown code block. # Task You're given a substring s of some cyclic string. What's the length of the smallest possible string that can be concatenated to itself many times to obtain this cyclic string? # Example For` s = "cabca"`, the output should be `3` `"cabca"` is a substring of a cycle string "abcabcabcabc..." that can be obtained by concatenating `"abc"` to itself. Thus, the answer is 3. # Input/Output - `[input]` string `s` Constraints: `3 ≤ s.length ≤ 15.` - `[output]` an integer Also feel free to reuse/extend the following starter code: ```python def cyclic_string(s): ```
{"functional": "_inputs = [['cabca'], ['aba'], ['ccccccccccc'], ['abaca']]\n_outputs = [[3], [2], [1], [4]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(cyclic_string(*i), o[0])"}
165
177
coding
Solve the programming task below in a Python markdown code block. There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i. For each square, you will perform either of the following operations once: - Decrease the height of the square by 1. - Do nothing. Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 10^5 - 1 \leq H_i \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N H_1 H_2 ... H_N -----Output----- If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No. -----Sample Input----- 5 1 2 1 1 3 -----Sample Output----- Yes You can achieve the objective by decreasing the height of only the second square from the left by 1.
{"inputs": ["1\n1\n", "4\n1 5 2 1", "4\n1 5 2 2", "4\n0 5 2 2", "4\n0 8 2 2", "4\n0 8 4 2", "4\n0 1 4 2", "4\n0 1 4 1"], "outputs": ["Yes\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]}
244
121
coding
Solve the programming task below in a Python markdown code block. Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many emeralds can Polycarp earn, if he has $a$ sticks and $b$ diamonds? -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. The only line of each test case contains two integers $a$ and $b$ ($0 \le a, b \le 10^9$) — the number of sticks and the number of diamonds, respectively. -----Output----- For each test case print one integer — the maximum number of emeralds Polycarp can earn. -----Example----- Input 4 4 4 1000000000 0 7 15 8 7 Output 2 0 7 5 -----Note----- In the first test case Polycarp can earn two emeralds as follows: craft one sword and one shovel. In the second test case Polycarp does not have any diamonds, so he cannot craft anything.
{"inputs": ["1\n2 75\n", "1\n543 1\n", "1\n531 2\n", "1\n531 0\n", "1\n6 176\n", "1\n543 0\n", "1\n2 176\n", "1\n723 1\n"], "outputs": ["2\n", "1\n", "2\n", "0\n", "6\n", "0\n", "2\n", "1\n"]}
307
117
coding
Solve the programming task below in a Python markdown code block. You are a teacher at a cram school for elementary school pupils. One day, you showed your students how to calculate division of fraction in a class of mathematics. Your lesson was kind and fluent, and it seemed everything was going so well - except for one thing. After some experiences, a student Max got so curious about how precise he could compute the quotient. He tried many divisions asking you for a help, and finally found a case where the answer became an infinite fraction. He was fascinated with such a case, so he continued computing the answer. But it was clear for you the answer was an infinite fraction - no matter how many digits he computed, he wouldn’t reach the end. Since you have many other things to tell in today’s class, you can’t leave this as it is. So you decided to use a computer to calculate the answer in turn of him. Actually you succeeded to persuade him that he was going into a loop, so it was enough for him to know how long he could compute before entering a loop. Your task now is to write a program which computes where the recurring part starts and the length of the recurring part, for given dividend/divisor pairs. All computation should be done in decimal numbers. If the specified dividend/divisor pair gives a finite fraction, your program should treat the length of the recurring part as 0. Input The input consists of multiple datasets. Each line of the input describes a dataset. A dataset consists of two positive integers x and y, which specifies the dividend and the divisor, respectively. You may assume that 1 ≤ x < y ≤ 1,000,000. The last dataset is followed by a line containing two zeros. This line is not a part of datasets and should not be processed. Output For each dataset, your program should output a line containing two integers separated by exactly one blank character. The former describes the number of digits after the decimal point before the recurring part starts. And the latter describes the length of the recurring part. Example Input 1 3 1 6 3 5 2 200 25 99 0 0 Output 0 1 1 1 1 0 2 0 0 2
{"inputs": ["1 3\n1 6\n3 9\n2 200\n7 99\n0 0", "1 3\n1 6\n6 9\n2 377\n7 99\n0 0", "1 3\n1 2\n6 9\n2 377\n7 99\n0 0", "2 3\n1 6\n6 9\n2 200\n7 24\n0 0", "1 3\n1 6\n6 18\n2 457\n7 2\n0 0", "1 5\n1 6\n6 18\n2 457\n7 2\n0 0", "2 7\n2 8\n3 4\n2 200\n2 62\n0 0", "2 7\n2 8\n5 8\n2 200\n2 62\n0 0"], "outputs": ["0 1\n1 1\n0 1\n2 0\n0 2\n", "0 1\n1 1\n0 1\n0 84\n0 2\n", "0 1\n1 0\n0 1\n0 84\n0 2\n", "0 1\n1 1\n0 1\n2 0\n3 1\n", "0 1\n1 1\n0 1\n0 152\n1 0\n", "1 0\n1 1\n0 1\n0 152\n1 0\n", "0 6\n2 0\n2 0\n2 0\n0 15\n", "0 6\n2 0\n3 0\n2 0\n0 15\n"]}
476
414
coding
Solve the programming task below in a Python markdown code block. > In information theory and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required to change one word into the other. (http://en.wikipedia.org/wiki/Levenshtein_distance) Your task is to implement a function which calculates the Levenshtein distance for two arbitrary strings. Also feel free to reuse/extend the following starter code: ```python def levenshtein(a,b): ```
{"functional": "_inputs = [['kitten', 'sitting'], ['book', 'back'], ['book', 'book'], ['qlzcfayxiz', 'vezkvgejzb'], ['nayvyedosf', 'sjxen'], ['sjxen', 'sjxen'], ['peter', 'peter']]\n_outputs = [[3], [2], [0], [9], [9], [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(levenshtein(*i), o[0])"}
137
238
coding
Solve the programming task below in a Python markdown code block. Chef wants to cross a hallway of N doors. These N doors are represented as a string. Each door is initially either open or close, represented by 1 or 0 respectively. Chef is required to go through all the doors one by one in the order that they appear, starting from the leftmost door and moving only rightwards at each step. To make the journey easier, Chef has a magic wand, using which Chef can flip the status of all the doors at once. Determine the minimum number of times Chef has to use this wand to cross the hallway of doors. For example, the doors are 10011. Chef will start from the left and enter the first door. After passing through that door, the magic wand is waved. This flips the string to 01100. Now Chef passes through the next two doors in one go. Again, just before reaching the 4th door, the magic wand is waved. Now that the string is in its original state, Chef passes through the last two doors as well. The minimum number of times the magic wand needed to be used here was 2. ------ Input Format ------ - First line will contain T, number of testcases. Then the testcases follow. - Each testcase contains of a single string S, representing the doors as given in the problem. ------ Output Format ------ For each test case, print a single line containing one integer denoting the minimum number of times the magic wand needs to be used. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ |S| ≤ 10^{5}$ - Sum of $|S|$ over all test cases $ ≤ 2 \cdot 10^{6} $ ----- Sample Input 1 ------ 3 111 010 10011 ----- Sample Output 1 ------ 0 3 2 ----- explanation 1 ------ - Test Case $1$: Since all the doors are already open, Chef doesn't need to use the magic wand at all. - Test Case $2$: Chef will use the wand the first time to open door $1$. This operation makes the string "101". Chef again needs to use the wand to open door $2$, and then one last time to open door $3$. In total, Chef used the wand $3$ times. - Testcase $3$: As explained in the problem statement above.
{"inputs": ["3\n111\n010\n10011"], "outputs": ["0\n3\n2"]}
522
30
coding
Solve the programming task below in a Python markdown code block. Consider the numbers `6969` and `9116`. When you rotate them `180 degrees` (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as `2` or `5` don't yield numbers when rotated. Given a range, return the count of upside down numbers within that range. For example, `solve(0,10) = 3`, because there are only `3` upside down numbers `>= 0 and < 10`. They are `0, 1, 8`. More examples in the test cases. Good luck! If you like this Kata, please try [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Life without primes](https://www.codewars.com/kata/59f8750ac374cba8f0000033) Please also try the performance version of this kata at [Upside down numbers - Challenge Edition ](https://www.codewars.com/kata/59f98052120be4abfa000304) Also feel free to reuse/extend the following starter code: ```python def solve(a, b): ```
{"functional": "_inputs = [[0, 10], [10, 100], [100, 1000], [1000, 10000], [10000, 15000], [15000, 20000], [60000, 70000], [60000, 130000]]\n_outputs = [[3], [4], [12], [20], [6], [9], [15], [55]]\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])"}
329
273
coding
Solve the programming task below in a Python markdown code block. The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is $r$ units. Some very rich customers asked him to complete some projects for their companies. To complete the $i$-th project, Polycarp needs to have at least $a_i$ units of rating; after he completes this project, his rating will change by $b_i$ (his rating will increase or decrease by $b_i$) ($b_i$ can be positive or negative). Polycarp's rating should not fall below zero because then people won't trust such a low rated freelancer. Polycarp can choose the order in which he completes projects. Furthermore, he can even skip some projects altogether. To gain more experience (and money, of course) Polycarp wants to choose the subset of projects having maximum possible size and the order in which he will complete them, so he has enough rating before starting each project, and has non-negative rating after completing each project. Your task is to calculate the maximum possible size of such subset of projects. -----Input----- The first line of the input contains two integers $n$ and $r$ ($1 \le n \le 100, 1 \le r \le 30000$) — the number of projects and the initial rating of Polycarp, respectively. The next $n$ lines contain projects, one per line. The $i$-th project is represented as a pair of integers $a_i$ and $b_i$ ($1 \le a_i \le 30000$, $-300 \le b_i \le 300$) — the rating required to complete the $i$-th project and the rating change after the project completion. -----Output----- Print one integer — the size of the maximum possible subset (possibly, empty) of projects Polycarp can choose. -----Examples----- Input 3 4 4 6 10 -2 8 -1 Output 3 Input 5 20 45 -6 34 -15 10 34 1 27 40 -45 Output 5 Input 3 2 300 -300 1 299 1 123 Output 3
{"inputs": ["2 4\n2 -3\n4 -3\n", "2 4\n2 -3\n4 -3\n", "2 4\n1 -3\n4 -3\n", "3 1\n3 -4\n3 4\n3 4\n", "3 1\n3 -4\n3 4\n3 4\n", "3 1\n2 -4\n3 4\n3 4\n", "3 4\n4 6\n10 -2\n8 -1\n", "3 4\n2 6\n10 -2\n8 -1\n"], "outputs": ["1\n", "1", "1\n", "0\n", "0", "0\n", "3\n", "3\n"]}
525
170
coding
Solve the programming task below in a Python markdown code block. Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences. ### Subsequence A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence. ### Example subsequence Subsequences of `"abc"` = `"a"`, `"b"`, `"c"`, `"ab"`, `"ac"`, `"bc"` and `"abc"`. ### LCS examples ```python lcs( "abcdef" , "abc" ) => returns "abc" lcs( "abcdef" , "acf" ) => returns "acf" lcs( "132535365" , "123456789" ) => returns "12356" ``` ### Notes * Both arguments will be strings * Return value must be a string * Return an empty string if there exists no common subsequence * Both arguments will have one or more characters (in JavaScript) * All tests will only have a single longest common subsequence. Don't worry about cases such as `LCS( "1234", "3412" )`, which would have two possible longest common subsequences: `"12"` and `"34"`. Note that the Haskell variant will use randomized testing, but any longest common subsequence will be valid. Note that the OCaml variant is using generic lists instead of strings, and will also have randomized tests (any longest common subsequence will be valid). ### Tips Wikipedia has an explanation of the two properties that can be used to solve the problem: - [First property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#First_property) - [Second property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Second_property) Also feel free to reuse/extend the following starter code: ```python def lcs(x, y): ```
{"functional": "_inputs = [['a', 'b'], ['a', 'a'], ['abc', 'ac'], ['abcdef', 'abc'], ['abcdef', 'acf'], ['anothertest', 'notatest'], ['132535365', '123456789'], ['finaltest', 'zzzfinallyzzz']]\n_outputs = [[''], ['a'], ['ac'], ['abc'], ['acf'], ['nottest'], ['12356'], ['final']]\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(lcs(*i), o[0])"}
424
249
coding
Solve the programming task below in a Python markdown code block. We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i. Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they will alternately perform the following action: * Draw some number of cards from the top of the deck. Then, discard the card in his hand and keep the last drawn card instead. Here, at least one card must be drawn. The game ends when there is no more card in the deck. The score of the game is the absolute difference of the integers written on the cards in the two players' hand. X will play the game so that the score will be maximized, and Y will play the game so that the score will be minimized. What will be the score of the game? Constraints * All input values are integers. * 1 \leq N \leq 2000 * 1 \leq Z, W, a_i \leq 10^9 Input Input is given from Standard Input in the following format: N Z W a_1 a_2 ... a_N Output Print the score. Examples Input 3 100 100 10 1000 100 Output 900 Input 3 100 1000 10 100 100 Output 900 Input 5 1 1 1 1 1 1 1 Output 0 Input 1 1 1 1000000000 Output 999999999
{"inputs": ["5 1 1\n1 0 1 1 1", "5 1 4\n0 1 6 0 2", "5 2 1\n1 1 1 1 1", "5 1 1\n1 0 1 1 0", "5 0 1\n0 0 2 1 1", "5 1 4\n1 1 6 0 2", "5 2 1\n1 1 1 1 0", "5 1 1\n1 0 1 1 2"], "outputs": ["0\n", "2\n", "0\n", "1\n", "0\n", "2\n", "1\n", "1\n"]}
407
174
coding
Solve the programming task below in a Python markdown code block. Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid. ## Examples ``` "()" => true ")(()))" => false "(" => false "(())((()())())" => true ``` ## Constraints `0 <= input.length <= 100` ~~~if-not:javascript,go Along with opening (`(`) and closing (`)`) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do **not** treat other forms of brackets as parentheses (e.g. `[]`, `{}`, `<>`). ~~~ Also feel free to reuse/extend the following starter code: ```python def valid_parentheses(string): ```
{"functional": "_inputs = [[')'], ['('], [''], ['hi)('], ['hi(hi)'], ['hi(hi)('], ['((())()())'], ['(c(b(a)))(d)'], ['hi(hi))('], ['())(()']]\n_outputs = [[False], [False], [True], [False], [True], [False], [True], [True], [False], [False]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(valid_parentheses(*i), o[0])"}
211
233
coding
Solve the programming task below in a Python markdown code block. Reziba has many magic gems. Each magic gem can be split into $M$ normal gems. The amount of space each magic (and normal) gem takes is $1$ unit. A normal gem cannot be split. Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is $N$ units. If a magic gem is chosen and split, it takes $M$ units of space (since it is split into $M$ gems); if a magic gem is not split, it takes $1$ unit. How many different configurations of the resulting set of gems can Reziba have, such that the total amount of space taken is $N$ units? Print the answer modulo $1000000007$ ($10^9+7$). Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ. -----Input----- The input contains a single line consisting of $2$ integers $N$ and $M$ ($1 \le N \le 10^{18}$, $2 \le M \le 100$). -----Output----- Print one integer, the total number of configurations of the resulting set of gems, given that the total amount of space taken is $N$ units. Print the answer modulo $1000000007$ ($10^9+7$). -----Examples----- Input 4 2 Output 5 Input 3 2 Output 3 -----Note----- In the first example each magic gem can split into $2$ normal gems, and we know that the total amount of gems are $4$. Let $1$ denote a magic gem, and $0$ denote a normal gem. The total configurations you can have is: $1 1 1 1$ (None of the gems split); $0 0 1 1$ (First magic gem splits into $2$ normal gems); $1 0 0 1$ (Second magic gem splits into $2$ normal gems); $1 1 0 0$ (Third magic gem splits into $2$ normal gems); $0 0 0 0$ (First and second magic gems split into total $4$ normal gems). Hence, answer is $5$.
{"inputs": ["4 2\n", "3 2\n", "1 2\n", "1 3\n", "1 4\n", "1 5\n", "2 2\n", "2 3\n"], "outputs": ["5\n", "3\n", "1\n", "1\n", "1\n", "1\n", "2\n", "1\n"]}
531
86
coding
Solve the programming task below in a Python markdown code block. You are given positive integers N and K. You have to construct an array A of length N such that : 1 ≤ A_{i} ≤ 10^{18} \sum_{i=1}^{N} \sum_{j=i}^{N} F(i,j) = K, where F(i,j) denotes the [gcd] of all elements of the subarray A[i, j]. If multiple such arrays exist, print any. Report -1 if no such array exists. Note that A[l, r] denotes the subarray [A_{l} ,A_{l+1}, \ldots, A_{r-1}, A_{r}]. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case consists of single line of input. - The only line of each test case contains two space-separated integers N and K — the number of elements and required sum. ------ Output Format ------ For each test case, output on a new line N space-separated integers, denoting array A. Report -1 if no such array exists. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 100$ $1 ≤ K ≤ 10^{18}$ - The sum of $N$ over all test cases won't exceed $1000$. ----- Sample Input 1 ------ 3 1 5 2 4 3 1 ----- Sample Output 1 ------ 5 1 2 -1 ----- explanation 1 ------ Test case $1$: The only possible array of size $1$ such that the sum of gcd of all subarrays is $5$ is $A = [5]$. Test case $2$: Consider an array of size $2$ as $A = [1, 2]$. The subarrays of the array are: - $[1]$: The gcd of this subarray is $1$. - $[1, 2]$: The gcd of this subarray is $gcd(1, 2) = 1$. - $[2]$: The gcd of this subarray is $2$. The sum of gcd of all subarrays is $1+1+2= 4$. Test case $3$: It can be proven that there exists no subarray of size $3$ such that the sum of gcd of all subarrays of the array is $1$.
{"inputs": ["3\n1 5\n2 4\n3 1\n"], "outputs": ["5\n1 2\n-1\n"]}
542
33
coding
Solve the programming task below in a Python markdown code block. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number $x$ in an array. For an array $a$ indexed from zero, and an integer $x$ the pseudocode of the algorithm is as follows: BinarySearch(a, x) left = 0 right = a.size() while left < right middle = (left + right) / 2 if a[middle] <= x then left = middle + 1 else right = middle if left > 0 and a[left - 1] == x then return true else return false Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find $x$! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size $n$ such that the algorithm finds $x$ in them. A permutation of size $n$ is an array consisting of $n$ distinct integers between $1$ and $n$ in arbitrary order. Help Andrey and find the number of permutations of size $n$ which contain $x$ at position $pos$ and for which the given implementation of the binary search algorithm finds $x$ (returns true). As the result may be extremely large, print the remainder of its division by $10^9+7$. -----Input----- The only line of input contains integers $n$, $x$ and $pos$ ($1 \le x \le n \le 1000$, $0 \le pos \le n - 1$) — the required length of the permutation, the number to search, and the required position of that number, respectively. -----Output----- Print a single number — the remainder of the division of the number of valid permutations by $10^9+7$. -----Examples----- Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 -----Note----- All possible permutations in the first test case: $(2, 3, 1, 4)$, $(2, 4, 1, 3)$, $(3, 2, 1, 4)$, $(3, 4, 1, 2)$, $(4, 2, 1, 3)$, $(4, 3, 1, 2)$.
{"inputs": ["4 1 2\n", "1 1 0\n", "2 1 1\n", "2 2 0\n", "3 1 2\n", "3 2 2\n", "3 3 1\n", "4 2 0\n"], "outputs": ["6\n", "1\n", "1\n", "0\n", "0\n", "1\n", "0\n", "2\n"]}
604
102
coding
Solve the programming task below in a Python markdown code block. In this challenge, you will be given an array $\mbox{B}$ and must determine an array $\mbox{A}$. There is a special rule: For all $\boldsymbol{i}$, $A[i]\leq B[i]$. That is, $A[i]$ can be any number you choose such that $1\leq A[i]\leq B[i]$. Your task is to select a series of $A[i]$ given $B[i]$ such that the sum of the absolute difference of consecutive pairs of $\mbox{A}$ is maximized. This will be the array's cost, and will be represented by the variable $\mbox{S}$ below. The equation can be written: $S=\sum_{i=2}^{N}|A[i]-A[i-1]|$ For example, if the array $B=[1,2,3]$, we know that $1\leq A[1]\leq1$, $1\leq A[2]\leq2$, and $1\leq A[3]\leq3$. Arrays meeting those guidelines are: [1,1,1], [1,1,2], [1,1,3] [1,2,1], [1,2,2], [1,2,3] Our calculations for the arrays are as follows: |1-1| + |1-1| = 0 |1-1| + |2-1| = 1 |1-1| + |3-1| = 2 |2-1| + |1-2| = 2 |2-1| + |2-2| = 1 |2-1| + |3-2| = 2 The maximum value obtained is $2$. Function Description Complete the cost function in the editor below. It should return the maximum value that can be obtained. cost has the following parameter(s): B: an array of integers Input Format The first line contains the integer $\boldsymbol{\boldsymbol{t}}$, the number of test cases. Each of the next $\boldsymbol{\boldsymbol{t}}$ pairs of lines is a test case where: - The first line contains an integer $n$, the length of $\mbox{B}$ - The next line contains $n$ space-separated integers $B[i]$ Constraints $1\leq t\leq20$ $1<n\leq10^5$ $1\leq B[i]\leq100$ Output Format For each test case, print the maximum sum on a separate line. Sample Input 1 5 10 1 10 1 10 Sample Output 36 Explanation The maximum sum occurs when A[1]=A[3]=A[5]=10 and A[2]=A[4]=1. That is $|1-10|+|10-1|+|1-10|+|10-1|=36$.
{"inputs": ["1\n5\n10 1 10 1 10\n"], "outputs": ["36\n"]}
681
30
coding
Solve the programming task below in a Python markdown code block. Sheldon is a little geek living in Texas. While his friends like to play outside, little Sheldon likes to play around with ICs and lasers in his house. He decides to build N clap activated toggle machines each with one power inlet and one outlet. Each machine works when its power source inlet is receiving power. When the machine is in 'ON' state and is receiving power at its inlet, it makes power available at its power outlet to which a bulb or another ToGgLe machine could be attached. Suppose Sheldon attached 2 such machines to one another with the power inlet of the first machine attached to a power source at his house and the outlet of the second machine to a bulb. Initially both machines are in 'OFF' state and power source to first machine is off too. Now the power source is switched on. The first machine receives power but being in the 'OFF' state it does not transmit any power. Now on clapping the first ToGgLe machine toggles to 'ON' and the second machine receives power. On clapping once more the first toggles to 'OFF' and the second toggles to 'ON'. But since the second ToGgLe machine receives no power the bulb does not light up yet. On clapping once more, the first machine which is still receiving power from the source toggles to 'ON' and the second which was already 'ON' does not toggle since it was not receiving power. So both the machine are in 'ON' state and the bulb lights up and little Sheldon is happy. But when Sheldon goes out for a while, his evil twin sister attaches N such ToGgLe machines (after making sure they were all in 'OFF' state) and attaches the first to a power source (the power source is initially switched off) and the last ToGgLe machine to a bulb. Sheldon is horrified to find that his careful arrangement has been disturbed. Coders, help the poor boy by finding out if clapping k times for the N ToGgLe machines (all in 'OFF' state with the first one connected to a switched off power source and last one to a bulb) would light the bulb. Hurry before Sheldon has a nervous breakdown! -----Input----- First line has number of test cases, T. Following T lines have N, k separated by a single space where N is the number of ToGgLe machines and k is the number of times Sheldon clapped. -----Output----- T lines with cach line of the form: "ON" (just the word on without the double quotes) if the bulb is 'ON' for the test case numbered n and "OFF" (just the word off without the double quotes) if the bulb is 'OFF' for the test case numbered n. -----Example----- Input: 4 4 0 4 47 1 0 1 1 Output: OFF ON OFF ON
{"inputs": ["4\n4 0\n4 47\n1 0\n1 1"], "outputs": ["OFF\nON\nOFF\nON"]}
616
35
coding
Solve the programming task below in a Python markdown code block. # Task You know the slogan `p`, which the agitators have been chanting for quite a while now. Roka has heard this slogan a few times, but he missed almost all of them and grasped only their endings. You know the string `r` that Roka has heard. You need to determine what is the `minimal number` of times agitators repeated the slogan `p`, such that Roka could hear `r`. It is guaranteed the Roka heard nothing but the endings of the slogan P repeated several times. # Example For `p = "glorytoukraine", r = "ukraineaineaine"`, the output should be `3`. The slogan was `"glorytoukraine"`, and Roka heard `"ukraineaineaine"`. He could hear it as follows: `"ukraine"` + `"aine"` + `"aine"` = `"ukraineaineaine"`. # Input/Output - `[input]` string `p` The slogan the agitators chanted, a string of lowecase Latin letters. - `[input]` string `r` The string of lowercase Latin letters Roka has heard. - `[output]` an integer The `minimum number` of times the agitators chanted. Also feel free to reuse/extend the following starter code: ```python def slogans(p,r): ```
{"functional": "_inputs = [['glorytoukraine', 'ukraineaineaine'], ['glorytoukraine', 'ukraineaineainee'], ['glorytoukraine', 'einene'], ['programming', 'ingmingmming'], ['mcoecqwmjdudc', 'dcoecqwmjdudcdcudc'], ['erjernhxvbqfjsj', 'ernhxvbqfjsjjrnhxvbqfjsjjernhxvbqfjsj'], ['dhgusdlifons', 'lifonsssdlifonsgusdlifonssnsdlifonsslifonsifonsdlifonsfonsifons']]\n_outputs = [[3], [4], [3], [3], [4], [4], [13]]\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(slogans(*i), o[0])"}
307
316
coding
Solve the programming task below in a Python markdown code block. "Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter. Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories. Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter. Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger. -----Constraints----- - 1 ≤ N ≤ 10^5 - 2 ≤ C ≤ 10^{14} - 1 ≤ x_1 < x_2 < ... < x_N < C - 1 ≤ v_i ≤ 10^9 - All values in input are integers. -----Subscores----- - 300 points will be awarded for passing the test set satisfying N ≤ 100. -----Input----- Input is given from Standard Input in the following format: N C x_1 v_1 x_2 v_2 : x_N v_N -----Output----- If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c. -----Sample Input----- 3 20 2 80 9 120 16 1 -----Sample Output----- 191 There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.
{"inputs": ["3 20\n2 80\n9 120\n16 1\n", "3 20\n2 80\n9 1\n16 120\n", "1 100000000000000\n50000000000000 1\n", "15 10000000000\n400000000 1000000000\n800000000 1000000000\n1900000000 1000000000\n2400000000 1000000000\n2900000000 1000000000\n3300000000 1000000000\n3700000000 1000000000\n3800000000 1000000000\n4000000000 1000000000\n4100000000 1000000000\n5200000000 1000000000\n6600000000 1000000000\n8000000000 1000000000\n9300000000 1000000000\n9700000000 1000000000\n"], "outputs": ["191\n", "192\n", "0\n", "6500000000\n"]}
613
463
coding
Solve the programming task below in a Python markdown code block. There are three sticks with integer lengths $l_1, l_2$ and $l_3$. You are asked to break exactly one of them into two pieces in such a way that: both pieces have positive (strictly greater than $0$) integer length; the total length of the pieces is equal to the original length of the stick; it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides. A square is also considered a rectangle. Determine if it's possible to do that. -----Input----- The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of testcases. The only line of each testcase contains three integers $l_1, l_2, l_3$ ($1 \le l_i \le 10^8$) — the lengths of the sticks. -----Output----- For each testcase, print "YES" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer). -----Examples----- Input 4 6 1 5 2 5 2 2 4 2 5 5 4 Output YES NO YES YES -----Note----- In the first testcase, the first stick can be broken into parts of length $1$ and $5$. We can construct a rectangle with opposite sides of length $1$ and $5$. In the second testcase, breaking the stick of length $2$ can only result in sticks of lengths $1, 1, 2, 5$, which can't be made into a rectangle. Breaking the stick of length $5$ can produce results $2, 3$ or $1, 4$ but neither of them can't be put into a rectangle. In the third testcase, the second stick can be broken into parts of length $2$ and $2$. The resulting rectangle has opposite sides $2$ and $2$ (which is a square). In the fourth testcase, the third stick can be broken into parts of length $2$ and $2$. The resulting rectangle has opposite sides $2$ and $5$.
{"inputs": ["1\n1 98 99\n", "1\n1 98 99\n", "1\n1 98 186\n", "1\n2 98 186\n", "1\n2 98 239\n", "1\n1 98 239\n", "1\n1 98 108\n", "1\n2465 1 1\n"], "outputs": ["YES\n", "YES\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
530
140
coding
Solve the programming task below in a Python markdown code block. ### Happy Holidays fellow Code Warriors! Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On, Donder and Blitzen! That's the order Santa wanted his reindeer...right? What do you mean he wants them in order by their last names!? Looks like we need your help Code Warrior! ### Sort Santa's Reindeer Write a function that accepts a sequence of Reindeer names, and returns a sequence with the Reindeer names sorted by their last names. ### Notes: * It's guaranteed that each string is composed of two words * In case of two identical last names, keep the original order ### Examples For this input: ``` [ "Dasher Tonoyan", "Dancer Moore", "Prancer Chua", "Vixen Hall", "Comet Karavani", "Cupid Foroutan", "Donder Jonker", "Blitzen Claus" ] ``` You should return this output: ``` [ "Prancer Chua", "Blitzen Claus", "Cupid Foroutan", "Vixen Hall", "Donder Jonker", "Comet Karavani", "Dancer Moore", "Dasher Tonoyan", ] ``` Also feel free to reuse/extend the following starter code: ```python def sort_reindeer(reindeer_names): ```
{"functional": "_inputs = [[['Kenjiro Mori', 'Susumu Tokugawa', 'Juzo Okita', 'Akira Sanada']], [[]], [['Yasuo Kodai', 'Kenjiro Sado', 'Daisuke Aihara', 'Susumu Shima', 'Akira Sanada', 'Yoshikazu Okita', 'Shiro Yabu', 'Sukeharu Nanbu', 'Sakezo Yamamoto', 'Hikozaemon Ohta', 'Juzo Mori', 'Saburo Tokugawa']], [['Daisuke Mori', 'Shiro Sanada', 'Saburo Shima', 'Juzo Yabu', 'Sukeharu Yamamoto']], [['Sukeharu Yamamoto', 'Juzo Yabu', 'Saburo Shima', 'Shiro Sanada', 'Daisuke Mori']], [['Kenjiro Mori', 'Susumu Mori', 'Akira Mori']]]\n_outputs = [[['Kenjiro Mori', 'Juzo Okita', 'Akira Sanada', 'Susumu Tokugawa']], [[]], [['Daisuke Aihara', 'Yasuo Kodai', 'Juzo Mori', 'Sukeharu Nanbu', 'Hikozaemon Ohta', 'Yoshikazu Okita', 'Kenjiro Sado', 'Akira Sanada', 'Susumu Shima', 'Saburo Tokugawa', 'Shiro Yabu', 'Sakezo Yamamoto']], [['Daisuke Mori', 'Shiro Sanada', 'Saburo Shima', 'Juzo Yabu', 'Sukeharu Yamamoto']], [['Daisuke Mori', 'Shiro Sanada', 'Saburo Shima', 'Juzo Yabu', 'Sukeharu Yamamoto']], [['Kenjiro Mori', 'Susumu Mori', 'Akira Mori']]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(sort_reindeer(*i), o[0])"}
338
548
coding
Solve the programming task below in a Python markdown code block. You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters. Your task is to add spaces to the text by the following rules: * if there is no punctuation mark between two words, then they should be separated by exactly one space * there should be no spaces before each punctuation mark * there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter. Input The input data contains of a single non-empty line — the text whose length is no more than 10000 characters. Output Print the text, edited according to the rules. In this problem you should follow the output format very strictly. For example, extra space at the end of the output line is considered as wrong answer. Note that a newline character at the end of the line doesn't matter. Examples Input galileo galilei was an italian physicist ,mathematician,astronomer Output galileo galilei was an italian physicist, mathematician, astronomer Input galileo was born in pisa Output galileo was born in pisa
{"inputs": ["x\n", "w\n", "y\n", "xx\n", "yx\n", "xy\n", "wy\n", "x,x\n"], "outputs": ["x\n", "w\n", "y\n", "xx\n", "yx\n", "xy\n", "wy\n", "x, x\n"]}
291
73
coding
Solve the programming task below in a Python markdown code block. Alice, Bob, and Charlie have X, Y, and Z chocolates respectively. Find whether you can redistribute the chocolates such that: Each person has at least one chocolate; No two people have same number of chocolates; No chocolate is left after redistribution. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - The first and only line of each test case contains three space-separated integers X, Y, and Z — the number of chocolates Alice, Bob, and Charlie have initially. ------ Output Format ------ For each test case, output on a new line YES, if you can redistribute all the chocolates such that all the given conditions are met, and NO otherwise. You may print each character in uppercase or lowercase. For example, NO, no, No and nO, are all considered identical. ------ Constraints ------ $1 ≤ T ≤ 1000$ $1 ≤ X, Y, Z ≤ 100$ ----- Sample Input 1 ------ 4 1 2 3 1 1 1 2 2 2 2 1 1 ----- Sample Output 1 ------ YES NO YES NO ----- explanation 1 ------ Test case $1$: No two people have same number of chocolates and everyone has at least one chocolate. Thus, there is no need of redistribution. Test case $2$: We cannot redistribute the chocolates such that no two people have same number of chocolates and everyone has at least one chocolate. Test case $3$: Alice can give $1$ chocolate to Charlie. The number of chocolates they have, would become $1, 2,$ and $3$ respectively. Thus, no two people have same number of chocolates and everyone has at least one chocolate. Test case $4$: We cannot redistribute the chocolates such that no two people have same number of chocolates and everyone has at least one chocolate.
{"inputs": ["4\n1 2 3\n1 1 1\n2 2 2\n2 1 1\n"], "outputs": ["YES\nNO\nYES\nNO\n"]}
412
44
coding
Solve the programming task below in a Python markdown code block. You are given a polynomial of degree N with integer coefficients: f(x)=a_Nx^N+a_{N-1}x^{N-1}+...+a_0. Find all prime numbers p that divide f(x) for every integer x. Constraints * 0 \leq N \leq 10^4 * |a_i| \leq 10^9(0\leq i\leq N) * a_N \neq 0 * All values in input are integers. Input Input is given from Standard Input in the following format: N a_N : a_0 Output Print all prime numbers p that divide f(x) for every integer x, in ascending order. Examples Input 2 7 -7 14 Output 2 7 Input 3 1 4 1 5 Output Input 0 998244353 Output 998244353
{"inputs": ["0\n8", "0\n5", "0\n3", "0\n7", "0\n63", "0\n56", "0\n15", "0\n54"], "outputs": ["2\n", "5\n", "3\n", "7\n", "3\n7\n", "2\n7\n", "3\n5\n", "2\n3\n"]}
229
90
coding
Solve the programming task below in a Python markdown code block. # Task Let's say that `"g" is happy` in the given string, if there is another "g" immediately to the right or to the left of it. Find out if all "g"s in the given string are happy. # Example For `str = "gg0gg3gg0gg"`, the output should be `true`. For `str = "gog"`, the output should be `false`. # Input/Output - `[input]` string `str` A random string of lower case letters, numbers and spaces. - `[output]` a boolean value `true` if all `"g"`s are happy, `false` otherwise. Also feel free to reuse/extend the following starter code: ```python def happy_g(s): ```
{"functional": "_inputs = [['gg0gg3gg0gg'], ['gog'], ['ggg ggg g ggg'], ['A half of a half is a quarter.'], ['good grief'], ['bigger is ggooder'], ['gggggggggg']]\n_outputs = [[True], [False], [False], [True], [False], [True], [True]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(happy_g(*i), o[0])"}
180
222
coding
Solve the programming task below in a Python markdown code block. Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on. Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank? Heidi's n friends are labeled 0 through n - 1, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly n - 1 pairs of friends who know each other directly. Jenny is given the number 0. -----Input----- The first line of the input contains the number of friends n (3 ≤ n ≤ 100). The next n - 1 lines each contain three space-separated integers u, v and c (0 ≤ u, v ≤ n - 1, 1 ≤ c ≤ 10^4), meaning that u and v are friends (know each other directly) and the cost for travelling between u and v is c. It is guaranteed that the social network of the input forms a tree. -----Output----- Output a single integer – the maximum sum of costs. -----Examples----- Input 4 0 1 4 0 2 2 2 3 3 Output 5 Input 6 1 2 3 0 2 100 1 4 2 0 3 7 3 5 10 Output 105 Input 11 1 0 1664 2 0 881 3 2 4670 4 2 1555 5 1 1870 6 2 1265 7 2 288 8 7 2266 9 2 1536 10 6 3378 Output 5551 -----Note----- In the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then friend 2 sends her to friend 1 (costing Heidi 3), and finally friend 1 relays her to friend 4 (incurring an additional cost of 2).
{"inputs": ["4\n0 1 4\n0 2 2\n2 3 3\n", "3\n1 0 5987\n2 0 8891\n", "3\n1 0 5987\n2 0 8891\n", "3\n1 0 5987\n2 1 8891\n", "4\n0 1 4\n0 2 2\n1 3 3\n", "4\n0 1 4\n0 2 4\n2 3 4\n", "4\n0 1 6\n0 2 4\n1 3 4\n", "3\n1 0 1844\n2 0 8891\n"], "outputs": ["5\n", "8891\n", "8891\n", "14878\n", "7\n", "8\n", "10\n", "8891\n"]}
639
228
coding
Solve the programming task below in a Python markdown code block. We define f(x)=\begin{cases} f(x \oplus reverse(x))+1 & \text{if } x \neq 0 \\ 0 & \text{otherwise} \end{cases} Here, \oplus denotes the [bitwise XOR operation] and reverse is a function that takes a postive integer, reverses its binary representation (without any leading zeros) and returns the resulting number. For example reverse(2)=1, reverse(6)=3, reverse(7)=7 Given an integer N, find out the value of \sum^{2^{N}-1}_{i=1} f(i) modulo 998244353 or claim that there exists a positive integer x < 2^{N} for which f is undefined. ------ Input Format ------ - The first line of input contains a single integer T - the number of test cases. The description of T test cases follows. - The first and only line of each test case contains a single integer N. ------ Output Format ------ - For each test case output a single line containing one integer : - -1 if there exists a positive integer x such that x < 2^{N} and f(x) is undefined - \sum^{2^{N}-1}_{i=1} f(i) modulo 998244353 otherwise ------ Constraints ------ $1 ≤ T ≤ 3 \cdot 10^{5}$ $1 ≤ N ≤ 10^{9}$ ----- Sample Input 1 ------ 8 1 2 3 5 8 13 21 34 ----- Sample Output 1 ------ 1 4 10 58 578 20098 5236738 24641495 ----- explanation 1 ------ Note that: - $f(1) = f(1 \oplus 1) + 1 = f(0) + 1 = 1$ - $f(2) = f(2 \oplus 1) + 1 = f(3) + 1 = (f(3 \oplus 3) + 1) + 1 = (f(0) + 1) + 1 = 2$ - $f(3) = f(3 \oplus 3) + 1 = f(0) + 1 = 1$ - Test case-1: $\sum^{2^{1}-1}_{i=1} f(i) = f(1) = 1$. So answer is $1 \text{ mod } 998244353 = 1$. - Test case-2: $\sum^{2^{2}-1}_{i=1} f(i) = f(1) + f(2) + f(3) = 1 + 2 + 1 = 4$. So answer is $4 \text{ mod } 998244353 = 4$.
{"inputs": ["8\n1\n2\n3\n5\n8\n13\n21\n34\n"], "outputs": ["1\n4\n10\n58\n578\n20098\n5236738\n24641495\n"]}
673
68
coding
Solve the programming task below in a Python markdown code block. Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? -----Input----- The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100), separated by a space. -----Output----- Print a single integer — the answer to the problem. -----Examples----- Input 2 2 Output 3 Input 9 3 Output 13 -----Note----- In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day.
{"inputs": ["2 2\n", "9 3\n", "1 2\n", "2 3\n", "4 4\n", "4 4\n", "1 2\n", "4 4\n"], "outputs": ["3\n", "13\n", "1\n", "2\n", "5\n", "5\n", "1\n", "5\n"]}
308
87
coding
Solve the programming task below in a Python markdown code block. You are given $n$ sticks with positive integral length $a_1, a_2, \ldots, a_n$. You can perform the following operation any number of times (possibly zero): choose one stick, then either increase or decrease its length by $1$. After each operation, all sticks should have positive lengths. What is the minimum number of operations that you have to perform such that it is possible to select three of the $n$ sticks and use them without breaking to form an equilateral triangle? An equilateral triangle is a triangle where all of its three sides have the same length. -----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 the test cases follows. The first line of each test case contains a single integer $n$ ($3 \le n \le 300$) — the number of sticks. The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — the lengths of the sticks. It is guaranteed that the sum of $n$ over all test cases does not exceed $300$. -----Output----- For each test case, print one integer on a single line — the minimum number of operations to be made. -----Examples----- Input 4 3 1 2 3 4 7 3 7 3 5 3 4 2 1 1 8 3 1 4 1 5 9 2 6 Output 2 4 1 1 -----Note----- In the first test case, you can increase the length of the first stick by $1$, then decrease the length of the third stick by $1$. In total, you perform $2$ operations, such that the three sticks form an equilateral triangle of side length $2$. In the fourth test case, you can decrease the length of the seventh stick by $1$. An equilateral triangle of side length $1$ can be selected and formed by the second, fourth, and seventh sticks.
{"inputs": ["4\n3\n1 2 3\n4\n7 3 7 3\n5\n3 4 2 1 1\n8\n3 1 4 1 5 9 2 6\n"], "outputs": ["2\n4\n1\n1\n"]}
482
68
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true: x % z == 0, y % z == 0, and z > threshold. Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them). Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.   Please complete the following python code precisely: ```python class Solution: def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: ```
{"functional": "def check(candidate):\n assert candidate(n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]) == [False,False,True]\n assert candidate(n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]) == [True,True,True,True,True]\n assert candidate(n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]) == [False,False,False,False,False]\n\n\ncheck(Solution().areConnected)"}
247
144
coding
Solve the programming task below in a Python markdown code block. Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Let F_{d}(x) equals to the number of digits d in decimal representation of the positive integer x. Chef interests only in functions F_{4}(x) and F_{7}(x). For the given positive integer N he wants to know the total number of different pairs (L; R) such that F_{4}(L) + F_{4}(L + 1) + ... + F_{4}(R) equals to F_{7}(L) + F_{7}(L + 1) + ... + F_{7}(R) and 1 ≤ L ≤ R ≤ N. ------ Input ------ The first line contains a single positive integer T, the number of test cases. T test cases follow. The only line of each test case contains a positive integer N . ------ Output ------ For each test case, output a single line containing the answer for the corresponding test case. ------ Constraints ------ 1 ≤ T ≤ 100000 1 ≤ N ≤ 100000 ----- Sample Input 1 ------ 3 3 10 100 ----- Sample Output 1 ------ 6 31 1266
{"inputs": ["3\n2\n6\n011", "3\n0\n6\n010", "3\n0\n3\n010", "3\n1\n3\n010", "3\n1\n1\n010", "3\n2\n1\n010", "3\n2\n1\n011", "3\n2\n1\n111"], "outputs": ["3\n9\n39\n", "0\n9\n31\n", "0\n6\n31\n", "1\n6\n31\n", "1\n1\n31\n", "3\n1\n31\n", "3\n1\n39\n", "3\n1\n1709\n"]}
323
168
coding
Solve the programming task below in a Python markdown code block. Zonal Computing Olympiad 2015, 29 Nov 2014 We say that two integers x and y have a variation of at least K, if |x − y| ≥ K (the absolute value of their difference is at least K). Given a sequence of N integers a1,a2,...,aN and K, the total variation count is the number of pairs of elements in the sequence with variation at least K, i.e. it is the size of the set of pairs {(i,j)|1≤i<j≤N and|ai−aj|≥K} For example if K = 1 and the sequence is 3,2,4 the answer is 3. If K = 1 and the sequence is 3, 1, 3 then the answer is 2. Your task is to write a program that takes a sequence and the value K as input and computes the total variation count. -----Input format----- The first line contains two positive integers N and K, separated by a space. This is followed by a line containing N integers separated by space giving the values of the sequence. -----Output format----- A single integer in a single line giving the total variation count. -----Test data----- You may assume that all integers in the input are in the range 0 to 10^8 inclusive. Subtask 1 (40 marks) : 1 ≤ N ≤ 4000, 1 ≤ K ≤ 10^8 Subtask 2 (60 marks) : 1 ≤ N ≤ 65000, 1 ≤ K ≤ 10^8 -----Sample Input----- 3 1 3 1 3 -----Sample Output----- 2
{"inputs": ["3 1\n3 1 3"], "outputs": ["2"]}
378
20
coding
Solve the programming task below in a Python markdown code block. You are given strings s and t, consisting of lowercase English letters. You will create a string s' by freely rearranging the characters in s. You will also create a string t' by freely rearranging the characters in t. Determine whether it is possible to satisfy s' < t' for the lexicographic order. -----Notes----- For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true: - N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N. - There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order. For example, xy < xya and atcoder < atlas. -----Constraints----- - The lengths of s and t are between 1 and 100 (inclusive). - s and t consists of lowercase English letters. -----Input----- Input is given from Standard Input in the following format: s t -----Output----- If it is possible to satisfy s' < t', print Yes; if it is not, print No. -----Sample Input----- yx axy -----Sample Output----- Yes We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.
{"inputs": ["x\nww", "y\nww", "y\nvw", "z\nvw", "z\nvv", "{\nvv", "z\nwv", "y\nwv"], "outputs": ["No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]}
363
80
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. All bandits are afraid of Sheriff. Sheriff constantly fights crime, but when bandits lay low, he gets bored and starts to entertain himself. This time Sheriff gathered all the bandits in his garden and ordered them to line up. After the whistle all bandits should change the order in which they stand. Sheriff gave all the bandits numbers from 1 to N. For each place i he determined the unique position j. After whistling the bandit staying on position i should run to the j-th position. Sheriff loved seeing how the bandits move around, and he continued whistling until the evening. He finished the game only when he noticed that the bandits are in the same order in which they were standing originally. Now the Sheriff asks the question: How many times has he whistled?   ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the number of bandits. The second line contains N space-separated integers A_{1}, A_{2}, ..., A_{N} denoting that the bandit staying on position i should run to the A_{i}-th position after the whistle.   ------ Output ------ For each test case, output a single line containing number of times the sheriff had to whistle, print it modulo 10^{9} + 7.   ------ Constraints ------ $1 ≤ T ≤ 5$ $1 ≤ N ≤ 100000$ $All A_{i} are distinct numbers from 1 to N$   ----- Sample Input 1 ------ 2 3 1 2 3 5 2 3 1 5 4 ----- Sample Output 1 ------ 1 6 ----- explanation 1 ------ Example case 2. the bandits positions are: 0. 1 2 3 4 5 1. 3 1 2 5 4 2. 2 3 1 4 5 3. 1 2 3 5 4 4. 3 1 2 4 5 5. 2 3 1 5 4 6. 1 2 3 4 5.
{"inputs": ["2\n3\n1 2 3\n5\n2 3 1 5 4", "2\n2\n1 2 3\n5\n2 3 1 5 4", "2\n3\n1 2 3\n5\n4 3 1 5 2", "2\n3\n2 1 3\n5\n4 3 1 5 2", "2\n2\n1 2 3\n5\n4 3 1 5 2", "2\n1\n1 2 3\n5\n2 3 1 5 4", "2\n1\n1 2 3\n5\n4 3 1 5 2", "2\n2\n2 1 3\n5\n4 3 1 5 2"], "outputs": ["1\n6", "1\n6\n", "1\n5\n", "2\n5\n", "1\n5\n", "1\n6\n", "1\n5\n", "2\n5\n"]}
516
237
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. There are n availabe seats and n students standing in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student. You may perform the following move any number of times: Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1) Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat. Note that there may be multiple seats or students in the same position at the beginning.   Please complete the following python code precisely: ```python class Solution: def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(seats = [3,1,5], students = [2,7,4]) == 4\n assert candidate(seats = [4,1,5,9], students = [1,3,2,6]) == 7\n assert candidate(seats = [2,2,6,6], students = [1,3,2,6]) == 4\n\n\ncheck(Solution().minMovesToSeat)"}
204
107
coding
Solve the programming task below in a Python markdown code block. Animesh and Mohit are playing a game. They have $N$ balls in front of them. All the balls are numbered, not necessarily in any order. Animesh picks a set of ${K}$ balls from the lot each time, checks this set, puts it back into the lot, and repeats this process until all possible selections have been made. At each draw, Mohit picks two balls from these ${K}$ balls -- the one with the maximum number and the one with the minimum number, and notes their difference on a paper. At the end of the game, Animesh has to tell the $\textit{Sum}$ of all the numbers on Mohit's paper. As value of this number can be very huge, you have to tell the value mod $10^9+7$. Input Format The first line contains two integers $N$ and ${K}$. The next line will contain a list having $N$ numbers. Output Format Print the value of $\textit{Sum}$ mod $(10^9+7)$. Constraints $1\leq N\leq10^5$ $1\leq K\leq N$ $0\leq\:\text{numbers_on_ball}\:\leq10^9$ Sample Input 4 2 10 20 30 40 Sample Output 100 Explanation There are 6 possible selections. 1. 10 20 2. 20 30 3. 30 40 4. 10 30 5. 20 40 6. 10 40 Summation = 10+10+10+20+20+30 = 100
{"inputs": ["4 2\n10 20 30 40\n"], "outputs": ["100\n"]}
406
30
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Sereja has an array A that contains n integers: A_{1}, A_{2}, ..., A_{n}. Sereja also has an array B that contains n integers B_{1}, B_{2}, ..., B_{n}. In a single step Sereja can choose two indexes i and j (1 ≤ i ≤ j ≤ n) , and increase all the elements of A with indices between i and j inclusively by one, modulo 4. In other words, we make A_{p} equal to (A_{p} + 1) modulo 4 if p is an integer from the range [i; j]. Now Sereja is interested in the following question: what is the mininal number of steps necessary in order to make the array A equal to the array B. ------ Input ------ The first line contains an integer T - the number of the testcases. Then, T tests follow. The first line of each testcase contains the integer n. The next line conatins n single space separated integers - A_{1}, A_{2}, ..., A_{n}. The next line conatin n single space separated integers - B_{1}, B_{2}, ..., B_{n}. ------ Output ------ For each testcase output an answer - the mininal number of steps necessary. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ n ≤ 10^{5}$ $0 ≤ A_{i}, B_{i} ≤ 3$ ------ Example ------ Input: 1 5 2 1 3 0 3 2 2 0 1 0 Output: 1
{"inputs": ["1\n5\n2 1 3 0 3\n2 2 0 1 0"], "outputs": ["1"]}
373
34
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A fancy string is a string where no three consecutive characters are equal. Given a string s, delete the minimum possible number of characters from s to make it fancy. Return the final string after the deletion. It can be shown that the answer will always be unique.   Please complete the following python code precisely: ```python class Solution: def makeFancyString(self, s: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(s = \"leeetcode\") == \"leetcode\"\n assert candidate(s = \"aaabaaaa\") == \"aabaa\"\n assert candidate(s = \"aab\") == \"aab\"\n\n\ncheck(Solution().makeFancyString)"}
102
64
coding
Solve the programming task below in a Python markdown code block. A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string $s$, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each character '?' with one of the three characters 'a', 'b' or 'c', such that the resulting string is beautiful. Please help him! More formally, after replacing all characters '?', the condition $s_i \neq s_{i+1}$ should be satisfied for all $1 \leq i \leq |s| - 1$, where $|s|$ is the length of the string $s$. -----Input----- The first line contains positive integer $t$ ($1 \leq t \leq 1000$) — the number of test cases. Next $t$ lines contain the descriptions of test cases. Each line contains a non-empty string $s$ consisting of only characters 'a', 'b', 'c' and '?'. It is guaranteed that in each test case a string $s$ has at least one character '?'. The sum of lengths of strings $s$ in all test cases does not exceed $10^5$. -----Output----- For each test case given in the input print the answer in the following format: If it is impossible to create a beautiful string, print "-1" (without quotes); Otherwise, print the resulting beautiful string after replacing all '?' characters. If there are multiple answers, you can print any of them. -----Example----- Input 3 a???cb a??bbc a?b?c Output ababcb -1 acbac -----Note----- In the first test case, all possible correct answers are "ababcb", "abcacb", "abcbcb", "acabcb" and "acbacb". The two answers "abcbab" and "abaabc" are incorrect, because you can replace only '?' characters and the resulting string must be beautiful. In the second test case, it is impossible to create a beautiful string, because the $4$-th and $5$-th characters will be always equal. In the third test case, the only answer is "acbac".
{"inputs": ["3\na???cb\na??bbc\na?b?c\n", "3\na???cb\na??bbc\nc?b?a\n", "3\na???cb\na??bbc\ncab??\n", "3\na???cb\na??bbb\na?b?c\n", "3\na???cb\na??bbc\nc?a?a\n", "3\na???cb\na??bbb\na?c?b\n", "3\na???cb\nbbb??a\na>c?b\n", "3\na???cb\na??bbb\na?a?c\n"], "outputs": ["ababcb\n-1\nacbac\n", "ababcb\n-1\ncabca\n", "ababcb\n-1\ncabab\n", "ababcb\n-1\nacbac\n", "ababcb\n-1\ncbaba\n", "ababcb\n-1\nabcab\n", "ababcb\n-1\na>cab\n", "ababcb\n-1\nababc\n"]}
524
244
coding
Solve the programming task below in a Python markdown code block. Little Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help. The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence. Input The first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value. Output Output one integer — minimum number of steps required to achieve the goal. Examples Input 5 3 2 -1 2 11 Output 4 Input 5 2 1 1 1 1 Output 1
{"inputs": ["1\n7\n", "1\n11\n", "1\n13\n", "1\n26\n", "1\n28\n", "2\n10 2\n", "2\n10 4\n", "2\n15 4\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "8\n", "6\n", "11\n"]}
247
100
coding
Solve the programming task below in a Python markdown code block. $n$ students are taking an exam. The highest possible score at this exam is $m$. Let $a_{i}$ be the score of the $i$-th student. You have access to the school database which stores the results of all students. You can change each student's score as long as the following conditions are satisfied: All scores are integers $0 \leq a_{i} \leq m$ The average score of the class doesn't change. You are student $1$ and you would like to maximize your own score. Find the highest possible score you can assign to yourself such that all conditions are satisfied. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 200$). The description of the test cases follows. The first line of each test case contains two integers $n$ and $m$ ($1 \leq n \leq 10^{3}$, $1 \leq m \leq 10^{5}$)  — the number of students and the highest possible score respectively. The second line of each testcase contains $n$ integers $a_1, a_2, \dots, a_n$ ($ 0 \leq a_{i} \leq m$)  — scores of the students. -----Output----- For each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ -----Example----- Input 2 4 10 1 2 3 4 4 5 1 2 3 4 Output 10 5 -----Note----- In the first case, $a = [1,2,3,4] $, with average of $2.5$. You can change array $a$ to $[10,0,0,0]$. Average remains $2.5$, and all conditions are satisfied. In the second case, $0 \leq a_{i} \leq 5$. You can change $a$ to $[5,1,1,3]$. You cannot increase $a_{1}$ further as it will violate condition $0\le a_i\le m$.
{"inputs": ["2\n4 7\n1 4 0 4\n4 5\n1 1 3 4\n", "2\n4 8\n1 2 3 4\n4 1\n1 4 2 4\n", "2\n4 4\n1 3 3 3\n4 5\n1 2 4 4\n", "2\n4 2\n1 3 3 3\n4 5\n1 2 4 4\n", "2\n4 3\n1 2 5 0\n4 8\n1 2 3 4\n", "2\n4 9\n2 3 3 4\n4 5\n1 2 3 4\n", "2\n4 9\n2 3 3 4\n4 5\n1 2 3 7\n", "2\n4 7\n1 4 0 4\n4 5\n1 1 3 8\n"], "outputs": ["7\n5\n", "8\n1\n", "4\n5\n", "2\n5\n", "3\n8\n", "9\n5\n", "9\n5\n", "7\n5\n"]}
497
278
coding
Solve the programming task below in a Python markdown code block. Write a program that will calculate the number of trailing zeros in a factorial of a given number. `N! = 1 * 2 * 3 * ... * N` Be careful `1000!` has 2568 digits... For more info, see: http://mathworld.wolfram.com/Factorial.html ## Examples ```python zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 # 12! = 479001600 --> 2 trailing zeros ``` *Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.* Also feel free to reuse/extend the following starter code: ```python def zeros(n): ```
{"functional": "_inputs = [[0], [6], [30], [100], [1000], [100000], [1000000000]]\n_outputs = [[0], [1], [7], [24], [249], [24999], [249999998]]\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(zeros(*i), o[0])"}
208
225
coding
Solve the programming task below in a Python markdown code block. Snuke found a random number generator. It generates an integer between 0 and 2^N-1 (inclusive). An integer sequence A_0, A_1, \cdots, A_{2^N-1} represents the probability that each of these integers is generated. The integer i (0 \leq i \leq 2^N-1) is generated with probability A_i / S, where S = \sum_{i=0}^{2^N-1} A_i. The process of generating an integer is done independently each time the generator is executed. Snuke has an integer X, which is now 0. He can perform the following operation any number of times: * Generate an integer v with the generator and replace X with X \oplus v, where \oplus denotes the bitwise XOR. For each integer i (0 \leq i \leq 2^N-1), find the expected number of operations until X becomes i, and print it modulo 998244353. More formally, represent the expected number of operations as an irreducible fraction P/Q. Then, there exists a unique integer R such that R \times Q \equiv P \mod 998244353,\ 0 \leq R < 998244353, so print this R. We can prove that, for every i, the expected number of operations until X becomes i is a finite rational number, and its integer representation modulo 998244353 can be defined. Constraints * 1 \leq N \leq 18 * 1 \leq A_i \leq 1000 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_0 A_1 \cdots A_{2^N-1} Output Print 2^N lines. The (i+1)-th line (0 \leq i \leq 2^N-1) should contain the expected number of operations until X becomes i, modulo 998244353. Examples Input 2 1 1 1 1 Output 0 4 4 4 Input 2 1 2 1 2 Output 0 499122180 4 499122180 Input 4 337 780 799 10 796 875 331 223 941 67 148 483 390 565 116 355 Output 0 468683018 635850749 96019779 657074071 24757563 745107950 665159588 551278361 143136064 557841197 185790407 988018173 247117461 129098626 789682908
{"inputs": ["2\n1 1 1 2", "2\n1 2 1 3", "2\n1 1 1 3", "2\n2 2 1 3", "2\n2 1 1 1", "2\n2 2 1 5", "2\n4 1 1 1", "2\n0 2 1 5"], "outputs": ["0\n166374063\n166374063\n332748121\n", "0\n532396992\n582309210\n449209962\n", "0\n499122181\n499122181\n3\n", "0\n465847369\n665496240\n798595486\n", "0\n5\n5\n5\n", "0\n903173467\n5\n237677230\n", "0\n7\n7\n7\n", "0\n522889903\n4\n190141784\n"]}
757
294
coding
Solve the programming task below in a Python markdown code block. There is an infinite 2-dimensional grid. The robot stands in cell $(0, 0)$ and wants to reach cell $(x, y)$. Here is a list of possible commands the robot can execute: move north from cell $(i, j)$ to $(i, j + 1)$; move east from cell $(i, j)$ to $(i + 1, j)$; move south from cell $(i, j)$ to $(i, j - 1)$; move west from cell $(i, j)$ to $(i - 1, j)$; stay in cell $(i, j)$. The robot wants to reach cell $(x, y)$ in as few commands as possible. However, he can't execute the same command two or more times in a row. What is the minimum number of commands required to reach $(x, y)$ from $(0, 0)$? -----Input----- The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of testcases. Each of the next $t$ lines contains two integers $x$ and $y$ ($0 \le x, y \le 10^4$) — the destination coordinates of the robot. -----Output----- For each testcase print a single integer — the minimum number of commands required for the robot to reach $(x, y)$ from $(0, 0)$ if no command is allowed to be executed two or more times in a row. -----Examples----- Input 5 5 5 3 4 7 1 0 0 2 0 Output 10 7 13 0 3 -----Note----- The explanations for the example test: We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively. In the first test case, the robot can use the following sequence: NENENENENE. In the second test case, the robot can use the following sequence: NENENEN. In the third test case, the robot can use the following sequence: ESENENE0ENESE. In the fourth test case, the robot doesn't need to go anywhere at all. In the fifth test case, the robot can use the following sequence: E0E.
{"inputs": ["1\n44 4\n", "1\n7 362\n", "1\n7 454\n", "1\n7 576\n", "1\n9 374\n", "1\n9 525\n", "1\n9 535\n", "1\n9 510\n"], "outputs": ["87\n", "723\n", "907\n", "1151\n", "747\n", "1049\n", "1069\n", "1019\n"]}
505
136
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A 0-indexed array derived with length n is derived by computing the bitwise XOR (⊕) of adjacent values in a binary array original of length n. Specifically, for each index i in the range [0, n - 1]: If i = n - 1, then derived[i] = original[i] ⊕ original[0]. Otherwise, derived[i] = original[i] ⊕ original[i + 1]. Given an array derived, your task is to determine whether there exists a valid binary array original that could have formed derived. Return true if such an array exists or false otherwise. A binary array is an array containing only 0's and 1's   Please complete the following python code precisely: ```python class Solution: def doesValidArrayExist(self, derived: List[int]) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(derived = [1,1,0]) == True\n assert candidate(derived = [1,1]) == True\n assert candidate(derived = [1,0]) == False\n\n\ncheck(Solution().doesValidArrayExist)"}
191
65
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 arr and an integer target. You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum. Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.   Please complete the following python code precisely: ```python class Solution: def minSumOfLengths(self, arr: List[int], target: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(arr = [3,2,2,4,3], target = 3) == 2\n assert candidate(arr = [7,3,4,7], target = 7) == 2\n assert candidate(arr = [4,3,2,6,2,3,4], target = 6) == -1\n assert candidate(arr = [5,5,4,4,5], target = 3) == -1\n assert candidate(arr = [3,1,1,1,5,1,2,1], target = 3) == 3\n\n\ncheck(Solution().minSumOfLengths)"}
144
155
coding
Solve the programming task below in a Python markdown code block. Mishka wants to buy some food in the nearby shop. Initially, he has $s$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $1 \le x \le s$, buy food that costs exactly $x$ burles and obtain $\lfloor\frac{x}{10}\rfloor$ burles as a cashback (in other words, Mishka spends $x$ burles and obtains $\lfloor\frac{x}{10}\rfloor$ back). The operation $\lfloor\frac{a}{b}\rfloor$ means $a$ divided by $b$ rounded down. It is guaranteed that you can always buy some food that costs $x$ for any possible value of $x$. Your task is to say the maximum number of burles Mishka can spend if he buys food optimally. For example, if Mishka has $s=19$ burles then the maximum number of burles he can spend is $21$. Firstly, he can spend $x=10$ burles, obtain $1$ burle as a cashback. Now he has $s=10$ burles, so can spend $x=10$ burles, obtain $1$ burle as a cashback and spend it too. 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. The next $t$ lines describe test cases. Each test case is given on a separate line and consists of one integer $s$ ($1 \le s \le 10^9$) — the number of burles Mishka initially has. -----Output----- For each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally. -----Example----- Input 6 1 10 19 9876 12345 1000000000 Output 1 11 21 10973 13716 1111111111
{"inputs": ["6\n1\n1\n44\n3360\n3467\n1100000000\n", "6\n1\n1\n58\n3360\n3467\n1100000000\n", "6\n2\n3\n83\n1320\n7153\n1000000000\n", "6\n1\n1\n58\n3360\n6281\n1100000000\n", "6\n1\n1\n5\n3553\n12345\n1100000100\n", "6\n1\n1\n3\n6735\n12345\n1100000000\n", "6\n1\n1\n18\n3360\n6281\n1100000000\n", "6\n1\n1\n5\n1772\n12345\n1100000100\n"], "outputs": ["1\n1\n48\n3733\n3852\n1222222222\n", "1\n1\n64\n3733\n3852\n1222222222\n", "2\n3\n92\n1466\n7947\n1111111111\n", "1\n1\n64\n3733\n6978\n1222222222\n", "1\n1\n5\n3947\n13716\n1222222333\n", "1\n1\n3\n7483\n13716\n1222222222\n", "1\n1\n19\n3733\n6978\n1222222222\n", "1\n1\n5\n1968\n13716\n1222222333\n"]}
497
502
coding
Solve the programming task below in a Python markdown code block. Chef is playing a game on the non-negative x-axis. It takes him $1$ second to reach from $i^{th}$ position to $(i-1)^{th}$ position or $(i+1)^{th}$ position. The chef never goes to the negative x-axis. Also, Chef doesn't stop at any moment of time. The movement of chef can be described as follows. - At the start he is standing at $x=0$ at time $0$. - In the first round, he moves towards $x=1$ and comes back to the $x=0$ position. - In the second round, he moves towards the $x=2$ and comes back again to $x=0$. - Generalizing, in the $k^{th}$ round, he moves from $x=0$ to $x=k$ and then returns back to $x=0$ at the end of the round. This goes on as the game progresses. For Example, the path of Chef for $3^{rd}$ round is given below. $0 - 1 - 2 - 3 - 2 - 1 - 0$ The overall path followed by Chef would look somewhat like this: $0 - 1 - 0 - 1 - 2 - 1 - 0 - 1 - 2 - 3 - 2 - 1 - 0 - 1 - 2 - 3 - 4 - 3 - …$ You are given two non-negative integers $N$ and $K$. You have to tell the time at which Chef arrives at $x=N$ for the $K^{th}$ time. Note - Chef can not skip a position while visiting the positions. -----Input:----- - The first line contains $T$ the number of test cases. Then the test cases follow. - Each test case contains a single line of two integers $N$ and $K$. -----Output:----- For each test case, print a single line containing one integer -- the time taken by the chef to arrive at $x=N$ for the $K^{th}$ time by modulo $1,000,000,007$. -----Constraints----- - $1 \le T \le 10^5$ - $0 \le N \le 10^9$ - $1 \le K \le 10^9$ -----Sample Input:----- 5 0 1 1 1 2 1 1 3 4 6 -----Sample Output:----- 0 1 4 5 46 -----Explanation:----- Test Case 1: Chef starts the journey from the $N = 0$ at time $t = 0$ and it's the first time $(K = 1)$, he is here. So, the answer is $0$. Test Case 2: Chef starts the journey from the $N = 0$ at time $t = 0$ then goes to $N = 1$ at $t = 1$ and it's the first time $(K = 1)$, he is here. So, the answer is $1$. Test Case 4: The path followed by Chef to reach $1$ for the third time is given below. $0 - 1 - 0 - 1 - 2 - 1$ He reaches $1$ for the third time at $t=5$.
{"inputs": ["5\n0 1\n1 1\n2 1\n1 3\n4 6"], "outputs": ["0\n1\n4\n5\n46"]}
742
41
coding
Solve the programming task below in a Python markdown code block. I have a lot of friends. Every friend is very small. I often go out with my friends. Put some friends in your backpack and go out together. Every morning I decide which friends to go out with that day. Put friends one by one in an empty backpack. I'm not very strong. Therefore, there is a limit to the weight of friends that can be carried at the same time. I keep friends so that I don't exceed the weight limit. The order in which you put them in depends on your mood. I won't stop as long as I still have friends to put in. I will never stop. …… By the way, how many patterns are there in total for the combination of friends in the backpack? Input N W w1 w2 .. .. .. wn On the first line of input, the integer N (1 ≤ N ≤ 200) and the integer W (1 ≤ W ≤ 10,000) are written in this order, separated by blanks. The integer N represents the number of friends, and the integer W represents the limit of the weight that can be carried at the same time. It cannot be carried if the total weight is greater than W. The next N lines contain an integer that represents the weight of the friend. The integer wi (1 ≤ wi ≤ 10,000) represents the weight of the i-th friend. Output How many possible combinations of friends are finally in the backpack? Divide the total number by 1,000,000,007 and output the remainder. Note that 1,000,000,007 are prime numbers. Note that "no one is in the backpack" is counted as one. Examples Input 4 8 1 2 7 9 Output 2 Input 4 25 20 15 20 15 Output 4 Input 6 37 5 9 13 18 26 33 Output 6
{"inputs": ["4 1\n1\n2\n7\n9", "4 1\n1\n2\n7\n2", "4 1\n1\n1\n7\n9", "3 1\n1\n2\n7\n9", "4 1\n1\n2\n8\n2", "4 1\n1\n3\n7\n2", "3 1\n1\n4\n7\n9", "4 1\n1\n2\n8\n4"], "outputs": ["1\n", "1\n", "2\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
447
142
coding
Solve the programming task below in a Python markdown code block. # Task Given some sticks by an array `V` of positive integers, where V[i] represents the length of the sticks, find the number of ways we can choose three of them to form a triangle. # Example For `V = [2, 3, 7, 4]`, the result should be `1`. There is only `(2, 3, 4)` can form a triangle. For `V = [5, 6, 7, 8]`, the result should be `4`. `(5, 6, 7), (5, 6, 8), (5, 7, 8), (6, 7, 8)` # Input/Output - `[input]` integer array `V` stick lengths `3 <= V.length <= 100` `0 < V[i] <=100` - `[output]` an integer number of ways we can choose 3 sticks to form a triangle. Also feel free to reuse/extend the following starter code: ```python def counting_triangles(V): ```
{"functional": "_inputs = [[[2, 3, 7, 4]], [[5, 6, 7, 8]], [[2, 2, 2, 2]], [[1, 2, 5]], [[1, 2, 3, 10, 20, 30, 4]], [[1, 2, 3]]]\n_outputs = [[1], [4], [4], [0], [1], [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(counting_triangles(*i), o[0])"}
249
246
coding
Solve the programming task below in a Python markdown code block. # Task The sequence of `Chando` is an infinite sequence of all Chando's numbers in ascending order. A number is called `Chando's` if it is an integer that can be represented as a sum of different positive integer powers of 5. The first Chando's numbers is 5 (5^1). And the following nth Chando's numbers are: ``` 25 (5^2) 30 (5^1 + 5^2) 125 (5^3) 130 (5^1 + 5^3) 150 (5^2 + 5^3) ... ... ``` Your task is to find the Chando's nth number for a given `n`. # Input/Output - `[input]` integer `n` `1 <= n <= 7000` - `[output]` an integer nth Chando's number Also feel free to reuse/extend the following starter code: ```python def nth_chandos_number(n): ```
{"functional": "_inputs = [[1], [2], [9], [123], [23]]\n_outputs = [[5], [25], [630], [97530], [3280]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(nth_chandos_number(*i), o[0])"}
239
195
coding
Solve the programming task below in a Python markdown code block. Write a program which identifies the number of combinations of three integers which satisfy the following conditions: * You should select three distinct integers from 1 to n. * A total sum of the three integers is x. For example, there are two combinations for n = 5 and x = 9. * 1 + 3 + 5 = 9 * 2 + 3 + 4 = 9 Note 解説 Constraints * 3 ≤ n ≤ 100 * 0 ≤ x ≤ 300 Input The input consists of multiple datasets. For each dataset, two integers n and x are given in a line. The input ends with two zeros for n and x respectively. Your program should not process for these terminal symbols. Output For each dataset, print the number of combinations in a line. Example Input 5 9 0 0 Output 2
{"inputs": ["5 7\n0 0", "2 7\n0 0", "7 9\n0 0", "5 6\n0 0", "7 6\n0 0", "2 2\n0 0", "7 2\n0 0", "6 9\n0 0"], "outputs": ["1\n", "0\n", "3\n", "1\n", "1\n", "0\n", "0\n", "3\n"]}
205
110
coding
Solve the programming task below in a Python markdown code block. Given a string, swap the case for each of the letters. e.g. CodEwArs --> cODeWaRS ### Examples ``` "" -> "" "CodeWars" -> "cODEwARS" "abc" -> "ABC" "ABC" -> "abc" "123235" -> "123235" ``` Also feel free to reuse/extend the following starter code: ```python def swap(string_): ```
{"functional": "_inputs = [['HelloWorld'], ['CodeWars'], ['ThIs iS A l0NG sENTence witH nUMbERs in IT 123 456'], [''], [' '], [' '], [' 1a1 '], ['H_E_l-l_0 WO|||Rld'], ['TeSt'], ['EeEEeeEEEeee']]\n_outputs = [['hELLOwORLD'], ['cODEwARS'], ['tHiS Is a L0ng SentENCE WITh NumBerS IN it 123 456'], [''], [' '], [' '], [' 1A1 '], ['h_e_L-L_0 wo|||rLD'], ['tEsT'], ['eEeeEEeeeEEE']]\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(swap(*i), o[0])"}
123
311
coding
Solve the programming task below in a Python markdown code block. Problem statement: Kiran P.S wrote some text on a piece of paper and now he wants to know how many star characters are in the text. If you think of the paper as the plane and a letter as a curve on the plane, then each letter divides the plane into regions. For example letters "A", "D", "O", "P", "R" divide the plane into two regions so we say these letters each have one hole. Similarly, letter "B" has two holes and letters such as "C", "E", "F", "K" have no star character. We say that the number of holes in the text is equal to the total number of holes in the letters of the text.. Help Kiran P.S. to determine what is the difference in number of holes in the upper and lower case representation of a given string. 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 a non-empty text composed only of uppercase letters of English alphabet. The length of the text is less then 100. Output For each test case, output a single line containing the difference of holes each text case. SAMPLE INPUT 2 HACKEREARTH THENATIONALINSTITUTEOFENGINEERING SAMPLE OUTPUT 0 -6
{"inputs": ["5\nBACKTOTHEFUTURE\nPIRAMIDOFEGYPT\nROMANCE\nINSTITUTEOFELECTRICALANDELECTRONICSENGINEERING\nTHISISTHETESTCASEEERING", "5\nOAXTJYRHRPXKBZCRTSQTUSTQPQZWOMXGPUPMYTOZEKFJPANKMK\nGATLIOYAJSKNAAQVRBDVCXJNLRKSGWANRIIVIEMCIIYZJJMXNSNZXWYSQLXFNHTLJKDR\nHWOKJWVEHBKRYRDIKVHLAVCCKV\nUPHWPQKUBCUDOQNVKBAPIGDCZFOZEGCDPOFAWAIQQNUFUDGYEUWHHAALFNSMJVAU\nREXLWGQCHKNVHQDQCYKJNXHATPT"], "outputs": ["0\n-1\n0\n-7\n-3", "2\n2\n2\n-3\n-1"]}
302
227