task_type
stringclasses
1 value
problem
stringlengths
261
3.34k
answer
stringlengths
35
6.15k
problem_tokens
int64
62
774
answer_tokens
int64
12
2.04k
coding
Solve the programming task below in a Python markdown code block. Takahashi has decided to make a Christmas Tree for the Christmas party in AtCoder, Inc. A Christmas Tree is a tree with N vertices numbered 1 through N and N-1 edges, whose i-th edge (1\leq i\leq N-1) connects Vertex a_i and b_i. He would like to make one as follows: * Specify two non-negative integers A and B. * Prepare A Christmas Paths whose lengths are at most B. Here, a Christmas Path of length X is a graph with X+1 vertices and X edges such that, if we properly number the vertices 1 through X+1, the i-th edge (1\leq i\leq X) will connect Vertex i and i+1. * Repeat the following operation until he has one connected tree: * Select two vertices x and y that belong to different connected components. Combine x and y into one vertex. More precisely, for each edge (p,y) incident to the vertex y, add the edge (p,x). Then, delete the vertex y and all the edges incident to y. * Properly number the vertices in the tree. Takahashi would like to find the lexicographically smallest pair (A,B) such that he can make a Christmas Tree, that is, find the smallest A, and find the smallest B under the condition that A is minimized. Solve this problem for him. Constraints * 2 \leq N \leq 10^5 * 1 \leq a_i,b_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output For the lexicographically smallest (A,B), print A and B with a space in between. Examples Input 7 1 2 2 3 2 4 4 5 4 6 6 7 Output 3 2 Input 8 1 2 2 3 3 4 4 5 5 6 5 7 5 8 Output 2 5 Input 10 1 2 2 3 3 4 2 5 6 5 6 7 7 8 5 9 10 5 Output 3 4
{"inputs": ["7\n1 2\n2 3\n2 4\n2 5\n4 6\n6 7", "7\n1 4\n2 3\n2 4\n4 5\n4 6\n6 7", "7\n1 4\n2 3\n2 4\n4 5\n7 6\n6 7", "7\n1 4\n2 3\n2 4\n1 5\n7 6\n6 7", "7\n1 4\n2 3\n2 4\n1 5\n7 6\n6 5", "7\n1 4\n2 3\n2 4\n4 5\n7 3\n6 3", "7\n1 2\n2 3\n4 4\n1 5\n7 6\n6 7", "7\n1 4\n2 3\n2 4\n1 5\n5 6\n7 7"], "outputs": ["2 4\n", "2 3\n", "2 2\n", "1 4\n", "1 6\n", "3 2\n", "1 3\n", "1 5\n"]}
522
270
coding
Solve the programming task below in a Python markdown code block. Given a sequence of integers $a$, a triplet $(a[i],a[j],a[k])$ is beautiful if: $i\lt j\lt k$ $a[j]-a[i]=a[k]-a[j]=d$ Given an increasing sequenc of integers and the value of $\boldsymbol{d}$, count the number of beautiful triplets in the sequence. Example $arr=[2,2,3,4,5]$ $\boldsymbol{d}=1$ There are three beautiful triplets, by index: $[i,j,k]=[0,2,3],[1,2,3],[2,3,4]$. To test the first triplet, $ar r[j]-ar r[i]=3-2=1$ and $ar r[k]-ar r[j]=4-3=1$. Function Description Complete the beautifulTriplets function in the editor below. beautifulTriplets has the following parameters: int d: the value to match int arr[n]: the sequence, sorted ascending Returns int: the number of beautiful triplets Input Format The first line contains $2$ space-separated integers, $n$ and $\boldsymbol{d}$, the length of the sequence and the beautiful difference. The second line contains $n$ space-separated integers $arr\left[i\right]$. Constraints $1\leq n\leq10^4$ $1\leq d\leq20$ $0\leq\textit{arr}[i]\leq2\times10^4$ $ar r[i]>ar r[i-1]$ Sample Input STDIN Function ----- -------- 7 3 arr[] size n = 7, d = 3 1 2 4 5 7 8 10 arr = [1, 2, 4, 5, 7, 8, 10] Sample Output 3 Explanation There are many possible triplets $(arr[i],ar r[j],ar r[k])$, but our only beautiful triplets are $(1,4,7)$ , $(4,7,10)$ and $(2,5,8)$ by value, not index. Please see the equations below: $7-4=4-1=3=d$ $10-7=7-4=3=d$ $8-5=5-2=3=d$ Recall that a beautiful triplet satisfies the following equivalence relation: $arr[j]-arr[i]=arr[k]-arr[j]=d$ where $i\lt j\lt k$.
{"inputs": ["7 3 \n1 2 4 5 7 8 10\n"], "outputs": ["3\n"]}
572
32
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti]. You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other. Return the minimum number of groups you need to make. Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.   Please complete the following python code precisely: ```python class Solution: def minGroups(self, intervals: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]) == 3\n assert candidate(intervals = [[1,3],[5,6],[8,10],[11,13]]) == 1\n\n\ncheck(Solution().minGroups)"}
162
82
coding
Solve the programming task below in a Python markdown code block. Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'. The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition). Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000. -----Output----- Print the resulting hashtags in any of the optimal solutions. -----Examples----- Input 3 #book #bigtown #big Output #b #big #big Input 3 #book #cool #cold Output #book #co #cold Input 4 #car #cart #art #at Output # # #art #at Input 3 #apple #apple #fruit Output #apple #apple #fruit -----Note----- Word a_1, a_2, ..., a_{m} of length m is lexicographically not greater than word b_1, b_2, ..., b_{k} of length k, if one of two conditions hold: at first position i, such that a_{i} ≠ b_{i}, the character a_{i} goes earlier in the alphabet than character b_{i}, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word. For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary. According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two.
{"inputs": ["1\n#h\n", "1\n#h\n", "2\n#y\n#q\n", "2\n#y\n#q\n", "2\n#y\n#p\n", "2\n#y\n#o\n", "2\n#x\n#o\n", "2\n#x\n#p\n"], "outputs": ["#h\n", "#h\n", "#\n#q\n", "#\n#q\n", "#\n#p\n", "#\n#o\n", "#\n#o\n", "#\n#p\n"]}
698
131
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.   Please complete the following python code precisely: ```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(root1 = tree_node([2,1,4]), root2 = tree_node([1,0,3])) == [0,1,1,2,3,4]\n assert candidate(root1 = tree_node([1,None,8]), root2 = tree_node([8,1])) == [1,1,8,8]\n\n\ncheck(Solution().getAllElements)"}
132
96
coding
Solve the programming task below in a Python markdown code block. A Little Elephant from the Zoo of Lviv likes lucky strings, i.e., the strings that consist only of the lucky digits 4 and 7. The Little Elephant calls some string T of the length M balanced if there exists at least one integer X (1 ≤ X ≤ M) such that the number of digits 4 in the substring T[1, X - 1] is equal to the number of digits 7 in the substring T[X, M]. For example, the string S = 7477447 is balanced since S[1, 4] = 7477 has 1 digit 4 and S[5, 7] = 447 has 1 digit 7. On the other hand, one can verify that the string S = 7 is not balanced. The Little Elephant has the string S of the length N. He wants to know the number of such pairs of integers (L; R) that 1 ≤ L ≤ R ≤ N and the substring S[L, R] is balanced. Help him to find this number. Notes. Let S be some lucky string. Then |S| denotes the length of the string S; S[i] (1 ≤ i ≤ |S|) denotes the i^{th} character of S (the numeration of characters starts from 1); S[L, R] (1 ≤ L ≤ R ≤ |S|) denotes the string with the following sequence of characters: S[L], S[L + 1], ..., S[R], and is called a substring of S. For L > R we mean by S[L, R] an empty string. ------ Input ------ The first line of the input file contains a single integer T, the number of test cases. Each of the following T lines contains one string, the string S for the corresponding test case. The input file does not contain any whitespaces. ------ Output ------ For each test case output a single line containing the answer for this test case. ------ Constraints ------ 1 ≤ T ≤ 10 1 ≤ |S| ≤ 100000 S consists only of the lucky digits 4 and 7. ----- Sample Input 1 ------ 4 47 74 477 4747477 ----- Sample Output 1 ------ 2 2 3 23 ----- explanation 1 ------ In the first test case balance substrings are S[1, 1] = 4 and S[1, 2] = 47. In the second test case balance substrings are S[2, 2] = 4 and S[1, 2] = 74. Unfortunately, we can't provide you with the explanations of the third and the fourth test cases. You should figure it out by yourself. Please, don't ask about this in comments.
{"inputs": ["4\n7\n44\n7\n4747477", "4\n7\n7\n477\n4747477", "4\n7\n7\n447\n4747477", "4\n7\n47\n477\n4747477", "4\n4\n47\n477\n4747477", "4\n7\n44\n477\n4747477", "4\n47\n4\n477\n4747477", "4\n47\n7\n477\n4747477"], "outputs": ["0\n3\n0\n23\n", "0\n0\n3\n23\n", "0\n0\n5\n23\n", "0\n2\n3\n23\n", "1\n2\n3\n23\n", "0\n3\n3\n23\n", "2\n1\n3\n23\n", "2\n0\n3\n23\n"]}
618
250
coding
Solve the programming task below in a Python markdown code block. Today is rose day, batch mates of Kabir and Tara decided to celebrate this day by exchanging roses with each other. Note:$Note:$ exchanging means both the boy and the girl will give rose to each other. In the class there are B$B$ boys and G$G$ girls. Exchange of rose will take place if and only if at least one of them hasn't received a rose from anyone else and a rose can be exchanged only once. Tara has to bring maximum sufficient roses for everyone and is confused as she don't know how many roses to buy.You are a friend of Kabir, so help him to solve the problem so that he can impress Tara by helping her. -----Input:----- - First line will contain T$T$, number of test cases. - Each test case contains two space separated integers B$B$ (Number of boys) and G$G$ (Number of Girls). -----Output:----- For each test case, output in a single line the total number of roses exchanged. -----Constraints:----- - 1≤T≤105$1 \leq T \leq 10^5$ - 1≤B≤109$1 \leq B \leq 10^{9}$ - 1≤G≤109$1 \leq G \leq 10^{9}$ -----Sample Input:----- 1 2 3 -----Sample Output:----- 8
{"inputs": ["1\n2 3"], "outputs": ["8"]}
321
16
coding
Solve the programming task below in a Python markdown code block. Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG". Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string $s$ consisting of uppercase letters and length of at least $4$, you need to find the minimum number of operations that you need to apply, so that the genome appears in it as a substring. For one operation, you can replace any letter in the string $s$ with the next or previous in the alphabet. For example, for the letter "D" the previous one will be "C", and the next — "E". In this problem, we assume that for the letter "A", the previous one will be the letter "Z", and the next one will be "B", and for the letter "Z", the previous one is the letter "Y", and the next one is the letter "A". Help Maxim solve the problem that the teacher gave him. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. -----Input----- The first line contains a single integer $n$ ($4 \leq n \leq 50$) — the length of the string $s$. The second line contains the string $s$, consisting of exactly $n$ uppercase letters of the Latin alphabet. -----Output----- Output the minimum number of operations that need to be applied to the string $s$ so that the genome appears as a substring in it. -----Examples----- Input 4 ZCTH Output 2 Input 5 ZDATG Output 5 Input 6 AFBAKC Output 16 -----Note----- In the first example, you should replace the letter "Z" with "A" for one operation, the letter "H" — with the letter "G" for one operation. You will get the string "ACTG", in which the genome is present as a substring. In the second example, we replace the letter "A" with "C" for two operations, the letter "D" — with the letter "A" for three operations. You will get the string "ZACTG", in which there is a genome.
{"inputs": ["4\nZCTH\n", "4\nNPGT\n", "4\nAZTG\n", "4\nYCTG\n", "4\nANTG\n", "4\nOCTG\n", "4\nACHG\n", "4\nANTG\n"], "outputs": ["2", "52", "3", "2", "11", "12", "12", "11\n"]}
536
96
coding
Solve the programming task below in a Python markdown code block. You have two strings A = A_1 A_2 ... A_n and B = B_1 B_2 ... B_n of the same length consisting of 0 and 1. You can transform A using the following operations in any order and as many times as you want: * Shift A by one character to the left (i.e., if A = A_1 A_2 ... A_n, replace A with A_2 A_3 ... A_n A_1). * Shift A by one character to the right (i.e., if A = A_1 A_2 ... A_n, replace A with A_n A_1 A_2 ... A_{n-1}). * Choose any i such that B_i = 1. Flip A_i (i.e., set A_i = 1 - A_i). You goal is to make strings A and B equal. Print the smallest number of operations required to achieve this, or -1 if the goal is unreachable. Constraints * 1 \leq |A| = |B| \leq 2,000 * A and B consist of 0 and 1. Input Input is given from Standard Input in the following format: A B Output Print the smallest number of operations required to make strings A and B equal, or -1 if the goal is unreachable. Examples Input 1010 1100 Output 3 Input 1 0 Output -1 Input 11010 10001 Output 4 Input 0100100 1111111 Output 5
{"inputs": ["1\n1", "1\n0", "1010\n1110", "1010\n1111", "1010\n0000", "1010\n1010", "1010\n1011", "1010\n1001"], "outputs": ["0\n", "-1", "1\n", "2\n", "-1\n", "0\n", "1\n", "3\n"]}
366
113
coding
Solve the programming task below in a Python markdown code block. # Sort an array by value and index Your task is to sort an array of integer numbers by the product of the value and the index of the positions. For sorting the index starts at 1, NOT at 0! The sorting has to be ascending. The array will never be null and will always contain numbers. Example: ``` Input: 23, 2, 3, 4, 5 Product of value and index: 23 => 23 * 1 = 23 -> Output-Pos 4 2 => 2 * 2 = 4 -> Output-Pos 1 3 => 3 * 3 = 9 -> Output-Pos 2 4 => 4 * 4 = 16 -> Output-Pos 3 5 => 5 * 5 = 25 -> Output-Pos 5 Output: 2, 3, 4, 23, 5 ``` Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata! Also feel free to reuse/extend the following starter code: ```python def sort_by_value_and_index(arr): ```
{"functional": "_inputs = [[[1, 2, 3, 4, 5]], [[23, 2, 3, 4, 5]], [[26, 2, 3, 4, 5]], [[9, 5, 1, 4, 3]]]\n_outputs = [[[1, 2, 3, 4, 5]], [[2, 3, 4, 23, 5]], [[2, 3, 4, 5, 26]], [[1, 9, 5, 3, 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(sort_by_value_and_index(*i), o[0])"}
288
275
coding
Solve the programming task below in a Python markdown code block. Given an array $A_1, A_2, ..., A_N$, count the number of subarrays of array $A$ which are non-decreasing. A subarray $A[i, j]$, where $1 ≤ i ≤ j ≤ N$ is a sequence of integers $A_i, A_i+1, ..., A_j$. A subarray $A[i, j]$ is non-decreasing if $A_i ≤ A_i+1 ≤ A_i+2 ≤ ... ≤ A_j$. You have to count the total number of such subarrays. -----Input----- - The first line of 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 size of array. - The second line contains $N$ space-separated integers $A_1$, $A_2$, …, $A_N$ denoting the elements of the array. -----Output----- For each test case, output in a single line the required answer. -----Constraints----- - $1 ≤ T ≤ 5$ - $1 ≤ N ≤ 10^5$ - $1 ≤ A_i ≤ 10^9$ -----Subtasks----- - Subtask 1 (20 points) : $1 ≤ N ≤ 100$ - Subtask 2 (30 points) : $1 ≤ N ≤ 1000$ - Subtask 3 (50 points) : Original constraints -----Sample Input:----- 2 4 1 4 2 3 1 5 -----Sample Output:----- 6 1 -----Explanation----- Example case 1. All valid subarrays are $A[1, 1], A[1, 2], A[2, 2], A[3, 3], A[3, 4], A[4, 4]$. Note that singleton subarrays are identically non-decreasing. Example case 2. Only single subarray $A[1, 1]$ is non-decreasing.
{"inputs": ["2\n4\n1 4 2 3\n1\n5", "2\n4\n1 2 2 3\n1\n5", "2\n4\n1 4 2 2\n1\n5", "2\n4\n2 1 2 2\n1\n5", "2\n4\n2 1 3 2\n1\n5", "2\n4\n6 5 3 2\n1\n2", "2\n4\n1 4 2 2\n1\n3", "2\n4\n2 4 2 2\n1\n5"], "outputs": ["6\n1", "10\n1\n", "6\n1\n", "7\n1\n", "5\n1\n", "4\n1\n", "6\n1\n", "6\n1\n"]}
459
190
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. Bear Limak has a string S. Each character of S is a digit '0' or '1'. Help Limak and check if all the '1' digits form a single non-empty segment (consecutive subsequence) in the string. For each test case, print "YES" or "NO" accordingly. ------ Input ------ The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The only line of each test case contains one string S, consisting of digits '0' and '1' only. ------ Output ------ For each test case, output a single line containing the answer — "YES" if all the '1' digits form a single non-empty segment, and "NO" otherwise. Don't print the quotes. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ |S| ≤ 10^{5} (here, |S| denotes the length of S)$ ------ Subtasks ------ $Subtask #1 (50 points): 1 ≤ |S| ≤ 50$ $Subtask #2 (50 points): Original constraints.$ ----- Sample Input 1 ------ 6 001111110 00110011 000 1111 101010101 101111111111 ----- Sample Output 1 ------ YES NO NO YES NO NO ----- explanation 1 ------ The answer is "YES" for strings 001111110 and 1111. The answer is "NO" for 00110011 because the '1' digits form two disjoint segments (while they should all be consecutive, with no '0' digits between them). The answer is "NO" for 000 because the segment formed by the '1' digits must be non-empty (as written in the statement).
{"inputs": ["6\n001111110\n00110011\n000\n1111\n101010101\n101111111111"], "outputs": ["YES\nNO\nNO\nYES\nNO\nNO"]}
456
73
coding
Solve the programming task below in a Python markdown code block. Harry is a bright student. To prepare thoroughly for exams, he completes all the exercises in his book! Now that the exams are approaching fast, he is doing book exercises day and night. He writes down and keeps updating the remaining number of exercises on the back cover of each book. Harry has a lot of books messed on the floor. Therefore, he wants to pile up the books that still have some remaining exercises into a single pile. He will grab the books one-by-one and add the books that still have remaining exercises to the top of the pile. Whenever he wants to do a book exercise, he will pick the book with the minimum number of remaining exercises from the pile. In order to pick the book, he has to remove all the books above it. Therefore, if there are more than one books with the minimum number of remaining exercises, he will take the one which requires the least number of books to remove. The removed books are returned to the messy floor. After he picks the book, he will do all the remaining exercises and trash the book. Since number of books is rather large, he needs your help to tell him the number of books he must remove, for picking the book with the minimum number of exercises. Note that more than one book can have the same name. ------ Input ------ The first line contains a single integer N denoting the number of actions. Then N lines follow. Each line starts with an integer. If the integer is -1, that means Harry wants to do a book exercise. Otherwise, the integer is number of the remaining exercises in the book he grabs next. This is followed by a string denoting the name of the book. ------ Output ------ For each -1 in the input, output a single line containing the number of books Harry must remove, followed by the name of the book that Harry must pick. ------ Constraints ------ 1 < N ≤ 1,000,000 0 ≤ (the number of remaining exercises of each book) < 100,000 The name of each book consists of between 1 and 15 characters 'a' - 'z'. Whenever he wants to do a book exercise, there is at least one book in the pile. ----- Sample Input 1 ------ 6 9 english 6 mathematics 8 geography -1 3 graphics -1 ----- Sample Output 1 ------ 1 mathematics 0 graphics ----- explanation 1 ------ - For the first $-1$: Currently, there are $3$ books in the pile. The book with minimum exercises left amongst these is mathematics. Harry has to remove $1$ book from the top to pick mathematics book and solve the remaining exercises. - For the second $-1$: The book on the top has the least number of remaining exercises. Thus, Harry has to remove $0$ books from the top pick up graphics book.
{"inputs": ["6\n9 english\n6 mathematics\n8 geography\n-1\n3 graphics\n-1", "6\n9 english\n6 mathematics\n6 geography\n-1\n3 grcphias\n-1", "6\n9 english\n6 mathematics\n0 geography\n-1\n3 grcphias\n-1", "6\n9 english\n6 mathematics\n0 geography\n-1\n3 gscphias\n-1", "6\n9 english\n6 mathematics\n8 geography\n-1\n3 hraphics\n-1", "6\n9 english\n6 mathematics\n6 geography\n-1\n3 saihpcrg\n-1", "6\n9 english\n6 nathematics\n0 geography\n-1\n3 gscphias\n-1", "6\n9 english\n7 nathematics\n0 geography\n-1\n3 gshpcias\n-1"], "outputs": ["1 mathematics\n0 graphics", "0 geography\n0 grcphias\n", "0 mathematics\n0 grcphias\n", "0 mathematics\n0 gscphias\n", "1 mathematics\n0 hraphics\n", "0 geography\n0 saihpcrg\n", "0 nathematics\n0 gscphias\n", "0 nathematics\n0 gshpcias\n"]}
608
283
coding
Solve the programming task below in a Python markdown code block. A population of bears consists of black bears, brown bears, and white bears. The input is an array of two elements. Determine whether the offspring of the two bears will return `'black'`, `'brown'`, `'white'`, `'dark brown'`, `'grey'`, `'light brown'`, or `'unknown'`. Elements in the the array will always be a string. ## Examples: bear_fur(['black', 'black']) returns 'black' bear_fur(['brown', 'brown']) returns 'brown' bear_fur(['white', 'white']) returns 'white' bear_fur(['black', 'brown']) returns 'dark brown' bear_fur(['black', 'white']) returns 'grey' bear_fur(['brown', 'white']) returns 'light brown' bear_fur(['yellow', 'magenta']) returns 'unknown' Also feel free to reuse/extend the following starter code: ```python def bear_fur(bears): ```
{"functional": "_inputs = [[['black', 'black']], [['white', 'white']], [['brown', 'brown']], [['black', 'brown']], [['black', 'white']], [['white', 'brown']], [['pink', 'black']]]\n_outputs = [['black'], ['white'], ['brown'], ['dark brown'], ['grey'], ['light brown'], ['unknown']]\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(bear_fur(*i), o[0])"}
226
217
coding
Solve the programming task below in a Python markdown code block. You are given an integer sequence $A_1, A_2, \ldots, A_N$ and an integer $X$. Consider a $N \times N$ matrix $B$, where $B_{i,j} = A_i + A_j$ for each valid $i$ and $j$. You need to find the number of square submatrices of $B$ such that the sum of their elements is $X$. Formally, find the number of quartets $(x_1, y_1, x_2, y_2)$ such that $1 \le x_1 \le x_2 \le N$, $1 \le y_1 \le y_2 \le N$, $x_2-x_1 = y_2-y_1$ and $\sum_{i=x_1}^{x_2}\sum_{j=y_1}^{y_2} B_{i,j} = X$. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains two space-separated integers $N$ and $X$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing one integer ― the number of square submatrices with sum $X$. -----Constraints----- - $1 \le T \le 100$ - $1 \le X \le 10^6$ - $1 \le N \le 10^5$ - $1 \le A_i \le 10^6$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $10^6$ -----Subtasks----- Subtask #1 (50 points): the sum of $N$ over all test cases does not exceed $1,000$ Subtask #2 (50 points): original constraints -----Example Input----- 2 5 36 1 2 3 1 12 4 54 3 3 3 3 -----Example Output----- 6 4
{"inputs": ["2\n5 36\n1 2 3 1 12\n4 54\n3 3 3 3"], "outputs": ["6\n4"]}
499
43
coding
Solve the programming task below in a Python markdown code block. One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect – it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated – it consists of n brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly: It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains). There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false. If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid. -----Input----- The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n, a ≠ b). -----Output----- The output consists of one line, containing either yes or no depending on whether the nervous system is valid. -----Examples----- Input 4 4 1 2 2 3 3 1 4 1 Output no Input 6 5 1 2 2 3 3 4 4 5 3 6 Output yes
{"inputs": ["2 1\n1 2\n", "2 1\n1 2\n", "3 2\n1 2\n2 3\n", "3 2\n1 2\n2 3\n", "3 3\n2 1\n1 3\n3 2\n", "3 3\n2 1\n1 3\n3 2\n", "4 4\n1 2\n2 3\n3 1\n4 1\n", "7 4\n1 2\n2 3\n3 1\n4 1\n"], "outputs": ["yes\n", "yes\n", "yes\n", "yes\n", "no\n", "no\n", "no\n", "no\n"]}
423
166
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. Note that you need to maximize the answer before taking the mod and not after taking it.   Please complete the following python code precisely: ```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxProduct(self, root: Optional[TreeNode]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(root = tree_node([1,2,3,4,5,6])) == 110\n assert candidate(root = tree_node([1,None,2,3,4,None,None,5,6])) == 90\n assert candidate(root = tree_node([2,3,9,10,7,8,6,5,4,11,1])) == 1025\n assert candidate(root = tree_node([1,1])) == 1\n\n\ncheck(Solution().maxProduct)"}
185
128
coding
Solve the programming task below in a Python markdown code block. We have a string S of length N consisting of R, G, and B. Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions: - S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k. - j - i \neq k - j. -----Constraints----- - 1 \leq N \leq 4000 - S is a string of length N consisting of R, G, and B. -----Input----- Input is given from Standard Input in the following format: N S -----Output----- Print the number of triplets in question. -----Sample Input----- 4 RRGB -----Sample Output----- 1 Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.
{"inputs": ["3\nRGB\n", "4\nBGRR", "4\nGRRB", "4\nRGBR", "4\nRRBG", "4\nGBRR", "4\nRGRB", "4\nBRGR"], "outputs": ["0\n", "1\n", "2\n", "0\n", "1\n", "1\n", "1\n", "1\n"]}
228
88
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 and an integer k. Your task is to perform the following operation exactly k times in order to maximize your score: Select an element m from nums. Remove the selected element m from the array. Add a new element with a value of m + 1 to the array. Increase your score by m. Return the maximum score you can achieve after performing the operation exactly k times.   Please complete the following python code precisely: ```python class Solution: def maximizeSum(self, nums: List[int], k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,2,3,4,5], k = 3) == 18\n assert candidate(nums = [5,5,5], k = 2) == 11\n\n\ncheck(Solution().maximizeSum)"}
139
68
coding
Solve the programming task below in a Python markdown code block. Valera's finally decided to go on holiday! He packed up and headed for a ski resort. Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain. Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object. Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v_1, v_2, ..., v_{k} (k ≥ 1) and meet the following conditions: Objects with numbers v_1, v_2, ..., v_{k} - 1 are mountains and the object with number v_{k} is the hotel. For any integer i (1 ≤ i < k), there is exactly one ski track leading from object v_{i}. This track goes to object v_{i} + 1. The path contains as many objects as possible (k is maximal). Help Valera. Find such path that meets all the criteria of our hero! -----Input----- The first line contains integer n (1 ≤ n ≤ 10^5) — the number of objects. The second line contains n space-separated integers type_1, type_2, ..., type_{n} — the types of the objects. If type_{i} equals zero, then the i-th object is the mountain. If type_{i} equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel. The third line of the input contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n) — the description of the ski tracks. If number a_{i} equals zero, then there is no such object v, that has a ski track built from v to i. If number a_{i} doesn't equal zero, that means that there is a track built from object a_{i} to object i. -----Output----- In the first line print k — the maximum possible path length for Valera. In the second line print k integers v_1, v_2, ..., v_{k} — the path. If there are multiple solutions, you can print any of them. -----Examples----- Input 5 0 0 0 0 1 0 1 2 3 4 Output 5 1 2 3 4 5 Input 5 0 0 1 0 1 0 1 2 2 4 Output 2 4 5 Input 4 1 0 0 0 2 3 4 2 Output 1 1
{"inputs": ["1\n1\n0\n", "1\n1\n0\n", "2\n1 1\n0 0\n", "2\n1 1\n0 0\n", "2\n0 1\n0 0\n", "4\n1 0 0 0\n2 3 4 2\n", "4\n1 0 0 0\n2 3 4 2\n", "5\n0 0 0 0 1\n0 1 2 3 4\n"], "outputs": ["1\n1\n", "1\n1\n", "1\n1\n", "1\n1\n", "1\n2\n", "1\n1\n", "1\n1\n", "5\n1 2 3 4 5\n"]}
674
178
coding
Solve the programming task below in a Python markdown code block. Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term: `25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1` The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient of `1` or `-1` instead: `25 = 1*16 + 1*8 + 1*4 - 1*2 - 1*1` Now *this* looks binary. --- Given any positive number `n`, expand it using the true binary expansion, and return the result as an array, from the most significant digit to the least significant digit. `true_binary(25) == [1,1,1,-1,-1]` It should be trivial (the proofs are left as an exercise to the reader) to see that: - Every odd number has infinitely many true binary expansions - Every even number has no true binary expansions Hence, `n` will always be an odd number, and you should return the *least* true binary expansion for any `n`. Also, note that `n` can be very, very large, so your code should be very efficient. Also feel free to reuse/extend the following starter code: ```python def true_binary(n): ```
{"functional": "_inputs = [[25], [47], [1], [3], [1234567]]\n_outputs = [[[1, 1, 1, -1, -1]], [[1, 1, -1, 1, 1, 1]], [[1]], [[1, 1]], [[1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(true_binary(*i), o[0])"}
329
276
coding
Solve the programming task below in a Python markdown code block. Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer $x$ that $x<n$ and $x$ is not a divisor of $n$, then subtract $x$ from $n$. The goal of the player is to minimize the value of $n$ in the end. Soon, Chouti found the game trivial. Can you also beat the game? -----Input----- The input contains only one integer in the first line: $v$ ($1 \le v \le 10^9$), the initial value of $n$. -----Output----- Output a single integer, the minimum value of $n$ the player can get. -----Examples----- Input 8 Output 1 Input 1 Output 1 -----Note----- In the first example, the player can choose $x=3$ in the first turn, then $n$ becomes $5$. He can then choose $x=4$ in the second turn to get $n=1$ as the result. There are other ways to get this minimum. However, for example, he cannot choose $x=2$ in the first turn because $2$ is a divisor of $8$. In the second example, since $n=1$ initially, the player can do nothing.
{"inputs": ["8\n", "1\n", "4\n", "3\n", "2\n", "5\n", "7\n", "9\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "2\n", "1\n", "1\n", "1\n"]}
350
70
coding
Solve the programming task below in a Python markdown code block. Timothy (age: 16) really likes to smoke. Unfortunately, he is too young to buy his own cigarettes and that's why he has to be extremely efficient in smoking. It's now your task to create a function that calculates how many cigarettes Timothy can smoke out of the given amounts of `bars` and `boxes`: - a bar has 10 boxes of cigarettes, - a box has 18 cigarettes, - out of 5 stubs (cigarettes ends) Timothy is able to roll a new one, - of course the self made cigarettes also have an end which can be used to create a new one... Please note that Timothy never starts smoking cigarettes that aren't "full size" so the amount of smoked cigarettes is always an integer. Also feel free to reuse/extend the following starter code: ```python def start_smoking(bars,boxes): ```
{"functional": "_inputs = [[0, 1], [1, 0], [1, 1]]\n_outputs = [[22], [224], [247]]\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(start_smoking(*i), o[0])"}
196
181
coding
Solve the programming task below in a Python markdown code block. Imagine that you have an array of 3 integers each representing a different person. Each number can be 0, 1, or 2 which represents the number of hands that person holds up. Now imagine there is a sequence which follows these rules: * None of the people have their arms raised at first * Firstly, a person raises 1 hand; then they raise the second hand; after that they put both hands down - these steps form a cycle * Person #1 performs these steps all the time, person #2 advances only after person #1 puts their hands down, and person #3 advances only after person #2 puts their hands down The first 10 steps of the sequence represented as a table are: ``` Step P1 P2 P3 -------------------- 0 0 0 0 1 1 0 0 2 2 0 0 3 0 1 0 4 1 1 0 5 2 1 0 6 0 2 0 7 1 2 0 8 2 2 0 9 0 0 1 ``` Given a number, return an array with the number of hands raised by each person at that step. Also feel free to reuse/extend the following starter code: ```python def get_positions(n): ```
{"functional": "_inputs = [[54], [98], [3]]\n_outputs = [[[0, 0, 0]], [[2, 2, 1]], [[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(get_positions(*i), o[0])"}
340
186
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand. Return True if the array is good otherwise return False.   Please complete the following python code precisely: ```python class Solution: def isGoodArray(self, nums: List[int]) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(nums = [12,5,7,23]) == True\n assert candidate(nums = [29,6,10]) == True\n assert candidate(nums = [3,6]) == False\n\n\ncheck(Solution().isGoodArray)"}
127
69
coding
Solve the programming task below in a Python markdown code block. Write a function to split a string and convert it into an array of words. For example: ```python "Robin Singh" ==> ["Robin", "Singh"] "I love arrays they are my favorite" ==> ["I", "love", "arrays", "they", "are", "my", "favorite"] ``` Also feel free to reuse/extend the following starter code: ```python def string_to_array(s): ```
{"functional": "_inputs = [['Robin Singh'], ['CodeWars'], ['I love arrays they are my favorite'], ['1 2 3'], ['']]\n_outputs = [[['Robin', 'Singh']], [['CodeWars']], [['I', 'love', 'arrays', 'they', 'are', 'my', 'favorite']], [['1', '2', '3']], [['']]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(string_to_array(*i), o[0])"}
101
220
coding
Solve the programming task below in a Python markdown code block. Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help. Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on). To reverse the i-th string Vasiliy has to spent c_{i} units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order. String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B. For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically. -----Input----- The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers c_{i} (0 ≤ c_{i} ≤ 10^9), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000. -----Output----- If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent. -----Examples----- Input 2 1 2 ba ac Output 1 Input 3 1 3 1 aa ba ac Output 1 Input 2 5 5 bbb aaa Output -1 Input 2 3 3 aaa aa Output -1 -----Note----- In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller. In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1. In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1.
{"inputs": ["2\n1 2\nba\nac\n", "2\n1 1\naa\naa\n", "2\n1 1\naa\naa\n", "2\n1 1\naa\na`\n", "2\n1 2\nab\nac\n", "2\n2 1\naa\na`\n", "2\n1 2\n`b\nac\n", "2\n2 1\naa\n`a\n"], "outputs": ["1\n", "0\n", "0", "-1\n", "0\n", "-1\n", "0\n", "-1\n"]}
585
137
coding
Solve the programming task below in a Python markdown code block. You are given a sequence $A_1, A_2, \ldots, A_N$. For each $k$ ($1 \le k \le N$), let's define a function $f(k)$ in the following way: - Consider a sequence $B_1, B_2, \ldots, B_N$, which is created by setting $A_k = 0$. Formally, $B_k = 0$ and $B_i = A_i$ for each valid $i \neq k$. - $f(k)$ is the number of ways to split the sequence $B$ into two non-empty contiguous subsequences with equal sums. Find the sum $S = f(1) + f(2) + \ldots + f(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 line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing one integer — the sum $S$. -----Constraints----- - $1 \le T \le 10$ - $2 \le N \le 2 \cdot 10^5$ - $1 \le |A_i| \le 10^9$ for each valid $i$ -----Example Input----- 2 6 1 2 1 1 3 1 3 4 1 4 -----Example Output----- 6 2
{"inputs": ["2\n6\n1 2 1 1 3 1\n3\n4 1 4"], "outputs": ["6\n2"]}
368
36
coding
Solve the programming task below in a Python markdown code block. Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him. Input The input data contain four lines. Each of these lines contains four integers x1, y1, x2, y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — coordinates of segment's beginning and end positions. The given segments can degenerate into points. Output Output the word «YES», if the given four segments form the required rectangle, otherwise output «NO». Examples Input 1 1 6 1 1 0 6 0 6 0 6 1 1 1 1 0 Output YES Input 0 0 0 3 2 0 0 0 2 2 2 0 0 2 2 2 Output NO
{"inputs": ["0 0 0 1\n0 1 0 1\n0 1 0 0\n0 1 0 1\n", "0 0 2 2\n0 0 2 0\n2 2 2 2\n0 2 0 2\n", "0 0 1 0\n1 0 1 1\n0 1 1 1\n0 0 0 1\n", "0 0 2 0\n0 1 0 3\n0 4 3 4\n3 0 3 3\n", "0 0 0 0\n1 1 1 1\n0 1 0 1\n1 0 1 0\n", "0 0 0 0\n0 0 0 1\n0 0 1 0\n1 1 1 1\n", "0 0 4 0\n4 0 3 0\n3 0 2 0\n2 0 0 0\n", "0 0 0 1\n0 1 1 1\n1 1 1 0\n1 0 0 1\n"], "outputs": ["NO\n", "NO\n", "YES\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
293
310
coding
Solve the programming task below in a Python markdown code block. Johnny has a pool in his garden. There are several islands in the pool. Some islands are connected by bridges. Any bridge can be removed. Every day Johnny removes some bridges so that there is only one way from any island to any other. In the evening he returns removed bridges to their places. Also he has some favorite bridges which he never removes. Johnny will be happy if he is able to make a configuration of bridges on the given day which he has never made before. You have to count the amount of days he will be happy. Of course, if the favorite bridges themselves don't satisfy the happiness condition Johnny will not be happy for even single day. ------ Input ------ The first line of input file contains number t – the number of test cases. Then the description of each test case follows. The first line of each test case contains number n – the number of islands. Islands are numbered with integers from 1 to n. Then n lines follow each containing n characters defining the connectivity matrix of those islands. Character in column x of line y will be ‘1’ if the islands with numbers x and y are connected and ‘0’ otherwise. The next line is number p – the number of favorite bridges. The next p lines contain the pairs of islands that are connected by favorite bridges. ------ Output ------ For each test case print the number of days Johnny will be happy in this situation. ------ Constraints ------ 1 ≤ t ≤ 5 2 ≤ n ≤ 30 1 ≤ p ≤ min(6, n-1) ----- Sample Input 1 ------ 1 4 0111 1011 1101 1110 2 1 2 3 4 ----- Sample Output 1 ------ 4
{"inputs": ["1\n4\n0111\n1011\n1101\n1110\n2\n1 2\n3 4"], "outputs": ["4"]}
376
44
coding
Solve the programming task below in a Python markdown code block. This contest is `CODE FESTIVAL`. However, Mr. Takahashi always writes it `CODEFESTIVAL`, omitting the single space between `CODE` and `FESTIVAL`. So he has decided to make a program that puts the single space he omitted. You are given a string s with 12 letters. Output the string putting a single space between the first 4 letters and last 8 letters in the string s. Constraints * s contains exactly 12 letters. * All letters in s are uppercase English letters. Input The input is given from Standard Input in the following format: s Output Print the string putting a single space between the first 4 letters and last 8 letters in the string s. Put a line break at the end. Examples Input CODEFESTIVAL Output CODE FESTIVAL Input POSTGRADUATE Output POST GRADUATE Input ABCDEFGHIJKL Output ABCD EFGHIJKL
{"inputs": ["ETAUDARGTSOP", "AACDEFGHIJKL", "COCEFESTIVAL", "POSTGRADUATF", "ALCDEFGHIJKA", "COCEFESTIV@L", "POSTGRAUDATF", "AKJIHGFEDCLA"], "outputs": ["ETAU DARGTSOP\n", "AACD EFGHIJKL\n", "COCE FESTIVAL\n", "POST GRADUATF\n", "ALCD EFGHIJKA\n", "COCE FESTIV@L\n", "POST GRAUDATF\n", "AKJI HGFEDCLA\n"]}
221
140
coding
Solve the programming task below in a Python markdown code block. Snakeland is a well organised city. The houses of the city are organised in an orderly rectangular fashion with dimensions 2 * n, i.e. there are total two rows and n columns. The house in the i-th row and j-th column is also said to be the house at coordinates (i, j). Some of the houses are occupied by snakes, while the others are empty. You are given this information through an array s of dimension 2 * n, where, if s[i][j] = '*', it denotes that there is a snake in the house at coordinates (i, j), and if s[i][j] = '.', it denotes that the house is empty. These snakes are planning a coup against a mongoose who controls their city from outside. So, they are trying their best to meet with other snakes and spread information about the date of the coup. For spreading this information, they can just hiss from their house and usually their hiss is so loud that it will be heard in all the cells except if there is a soundproof fence built that cuts the voice. Note that the external borders of Snakeland are already built of soundproof material. The mongoose got to know about the plan, and he wants to construct sound proof fences along the borders of the houses so that no two people should be able to communicate with each other. The fence can be either vertical or horizontal. Each fence can be of any length, but the mongoose wants to minimize the number of fences to be built. Find out the minimum number of fences that the mongoose should build. -----Input----- The first line of the input contains an integer T denoting number of test cases. The descriptions of the T test cases follow. The first line of each test case contains a single integer, n. Each of the next two lines contains n characters denoting the first and the second rows of Snakeland respectively. -----Output----- For each test case, output a single integer corresponding to the minimum number of fences that the mongoose needs to build. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ n ≤ 105 -----Example----- Input 3 2 ** ** 3 *** *.. 3 *.. .*. Output 2 3 1 -----Explanation----- All the examples are shown in the pictures. The fences built are shown by red colored horizontal or vertical segments. You can see that after putting these borders no snake can talk with any another snake.
{"inputs": ["3\n2\n**\n**\n3\n***\n*..\n3\n*..\n.*."], "outputs": ["2\n3\n1"]}
523
40
coding
Solve the programming task below in a Python markdown code block. Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it. The robot can only move up, left, right, or down. When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits. The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions. Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit. -----Input----- The first line of input will contain two integers n and m (2 ≤ n, m ≤ 50), denoting the dimensions of the maze. The next n lines will contain exactly m characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string s (1 ≤ |s| ≤ 100) — the instructions given to the robot. Each character of s is a digit from 0 to 3. -----Output----- Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit. -----Examples----- Input 5 6 .....# S....# .#.... .#.... ...E.. 333300012 Output 1 Input 6 6 ...... ...... ..SE.. ...... ...... ...... 01232123212302123021 Output 14 Input 5 3 ... .S. ### .E. ... 3 Output 0 -----Note----- For the first sample, the only valid mapping is $0 \rightarrow D, 1 \rightarrow L, 2 \rightarrow U, 3 \rightarrow R$, where D is down, L is left, U is up, R is right.
{"inputs": ["2 2\n..\nSE\n0\n", "2 2\nSE\n##\n0\n", "2 2\nSE\n##\n0\n", "2 2\n..\nSE\n0\n", "2 2\n#E\nS.\n2\n", "2 2\n./\nSE\n0\n", "2 2\nS.\n/E\n1\n", "2 2\nS.\nE/\n1\n"], "outputs": ["6\n", "6\n", "6\n", "6\n", "0\n", "6\n", "0\n", "6\n"]}
611
142
coding
Solve the programming task below in a Python markdown code block. You are given a following process. There is a platform with $n$ columns. $1 \times 1$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $n$ columns have at least one square in them, the bottom row is being removed. You will receive $1$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive. -----Input----- The first line of input contain 2 integer numbers $n$ and $m$ ($1 \le n, m \le 1000$) — the length of the platform and the number of the squares. The next line contain $m$ integer numbers $c_1, c_2, \dots, c_m$ ($1 \le c_i \le n$) — column in which $i$-th square will appear. -----Output----- Print one integer — the amount of points you will receive. -----Example----- Input 3 9 1 1 2 2 2 3 1 2 3 Output 2 -----Note----- In the sample case the answer will be equal to $2$ because after the appearing of $6$-th square will be removed one row (counts of the squares on the platform will look like $[2~ 3~ 1]$, and after removing one row will be $[1~ 2~ 0]$). After the appearing of $9$-th square counts will be $[2~ 3~ 1]$, and after removing one row it will look like $[1~ 2~ 0]$. So the answer will be equal to $2$.
{"inputs": ["1 1\n1\n", "2 1\n2\n", "2 1\n1\n", "2 1\n2\n", "1 1\n1\n", "2 1\n1\n", "2 2\n2 2\n", "4 2\n1 2\n"], "outputs": ["1\n", "0\n", "0\n", "0\n", "1\n", "0\n", "0\n", "0\n"]}
412
106
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A perfectly straight street is represented by a number line. The street has building(s) on it and is represented by a 2D integer array buildings, where buildings[i] = [starti, endi, heighti]. This means that there is a building with heighti in the half-closed segment [starti, endi). You want to describe the heights of the buildings on the street with the minimum number of non-overlapping segments. The street can be represented by the 2D integer array street where street[j] = [leftj, rightj, averagej] describes a half-closed segment [leftj, rightj) of the road where the average heights of the buildings in the segment is averagej. For example, if buildings = [[1,5,2],[3,10,4]], the street could be represented by street = [[1,3,2],[3,5,3],[5,10,4]] because: From 1 to 3, there is only the first building with an average height of 2 / 1 = 2. From 3 to 5, both the first and the second building are there with an average height of (2+4) / 2 = 3. From 5 to 10, there is only the second building with an average height of 4 / 1 = 4. Given buildings, return the 2D integer array street as described above (excluding any areas of the street where there are no buldings). You may return the array in any order. The average of n elements is the sum of the n elements divided (integer division) by n. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.   Please complete the following python code precisely: ```python class Solution: def averageHeightOfBuildings(self, buildings: List[List[int]]) -> List[List[int]]: ```
{"functional": "def check(candidate):\n assert candidate(buildings = [[1,4,2],[3,9,4]]) == [[1,3,2],[3,4,3],[4,9,4]]\n assert candidate(buildings = [[1,3,2],[2,5,3],[2,8,3]]) == [[1,3,2],[3,8,3]]\n assert candidate(buildings = [[1,2,1],[5,6,1]]) == [[1,2,1],[5,6,1]]\n\n\ncheck(Solution().averageHeightOfBuildings)"}
430
139
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each digit remains a digit after rotation. For example: 0, 1, and 8 rotate to themselves, 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored), 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid. Given an integer n, return the number of good integers in the range [1, n].   Please complete the following python code precisely: ```python class Solution: def rotatedDigits(self, n: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(n = 10) == 4\n assert candidate(n = 1) == 0\n assert candidate(n = 2) == 1\n\n\ncheck(Solution().rotatedDigits)"}
197
57
coding
Solve the programming task below in a Python markdown code block. Polycarp loves ciphers. He has invented his own cipher called Right-Left. Right-Left cipher is used for strings. To encrypt the string $s=s_{1}s_{2} \dots s_{n}$ Polycarp uses the following algorithm: he writes down $s_1$, he appends the current word with $s_2$ (i.e. writes down $s_2$ to the right of the current result), he prepends the current word with $s_3$ (i.e. writes down $s_3$ to the left of the current result), he appends the current word with $s_4$ (i.e. writes down $s_4$ to the right of the current result), he prepends the current word with $s_5$ (i.e. writes down $s_5$ to the left of the current result), and so on for each position until the end of $s$. For example, if $s$="techno" the process is: "t" $\to$ "te" $\to$ "cte" $\to$ "cteh" $\to$ "ncteh" $\to$ "ncteho". So the encrypted $s$="techno" is "ncteho". Given string $t$ — the result of encryption of some string $s$. Your task is to decrypt it, i.e. find the string $s$. -----Input----- The only line of the input contains $t$ — the result of encryption of some string $s$. It contains only lowercase Latin letters. The length of $t$ is between $1$ and $50$, inclusive. -----Output----- Print such string $s$ that after encryption it equals $t$. -----Examples----- Input ncteho Output techno Input erfdcoeocs Output codeforces Input z Output z
{"inputs": ["z\n", "y\n", "x\n", "{\n", "|\n", "}\n", "~\n", "z\n"], "outputs": ["z\n", "y\n", "x\n", "{\n", "|\n", "}\n", "~\n", "z\n"]}
425
68
coding
Solve the programming task below in a Python markdown code block. A format for expressing an ordered list of integers is to use a comma separated list of either * individual integers * or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example "12,13,15-17" Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. **Example:** ```python solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]) # returns "-6,-3-1,3-5,7-11,14,15,17-20" ``` ```C# RangeExtraction.Extract(new[] {-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}); # returns "-6,-3-1,3-5,7-11,14,15,17-20" ``` *Courtesy of rosettacode.org* Also feel free to reuse/extend the following starter code: ```python def solution(args): ```
{"functional": "_inputs = [[[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]], [[-3, -2, -1, 2, 10, 15, 16, 18, 19, 20]], [[1, 2, 3, 4, 5]]]\n_outputs = [['-6,-3-1,3-5,7-11,14,15,17-20'], ['-3--1,2,10,15,16,18-20'], ['1-5']]\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(solution(*i), o[0])"}
379
324
coding
Solve the programming task below in a Python markdown code block. # Task The year of `2013` is the first year after the old `1987` with only distinct digits. Now your task is to solve the following problem: given a `year` number, find the minimum year number which is strictly larger than the given one and has only distinct digits. # Input/Output - `[input]` integer `year` `1000 ≤ year ≤ 9000` - `[output]` an integer the minimum year number that is strictly larger than the input number `year` and all its digits are distinct. Also feel free to reuse/extend the following starter code: ```python def distinct_digit_year(year): ```
{"functional": "_inputs = [[1987], [2013]]\n_outputs = [[2013], [2014]]\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(distinct_digit_year(*i), o[0])"}
161
174
coding
Solve the programming task below in a Python markdown code block. Snuke can change a string t of length N into a string t' of length N - 1 under the following rule: * For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t. There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same. Find the minimum necessary number of operations. Constraints * 1 ≤ |s| ≤ 100 * s consists of lowercase English letters. Input Input is given from Standard Input in the following format: s Output Print the minimum necessary number of operations to achieve the objective. Examples Input serval Output 3 Input jackal Output 2 Input zzz Output 0 Input whbrjpjyhsrywlqjxdbrbaomnw Output 8
{"inputs": ["zzy", "yzz", "zz{", "{zz", "{zy", "yz{", "xz{", "{zx"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
225
67
coding
Solve the programming task below in a Python markdown code block. Arthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable. In total the table Arthur bought has n legs, the length of the i-th leg is l_{i}. Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number d_{i} — the amount of energy that he spends to remove the i-th leg. A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths. Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable. -----Input----- The first line of the input contains integer n (1 ≤ n ≤ 10^5) — the initial number of legs in the table Arthur bought. The second line of the input contains a sequence of n integers l_{i} (1 ≤ l_{i} ≤ 10^5), where l_{i} is equal to the length of the i-th leg of the table. The third line of the input contains a sequence of n integers d_{i} (1 ≤ d_{i} ≤ 200), where d_{i} is the number of energy units that Arthur spends on removing the i-th leg off the table. -----Output----- Print a single integer — the minimum number of energy units that Arthur needs to spend in order to make the table stable. -----Examples----- Input 2 1 5 3 2 Output 2 Input 3 2 4 4 1 1 1 Output 0 Input 6 2 2 1 1 3 3 4 3 5 5 2 1 Output 8
{"inputs": ["1\n5\n4\n", "1\n5\n4\n", "1\n8\n4\n", "1\n8\n1\n", "1\n7\n1\n", "1\n5\n1\n", "1\n5\n2\n", "1\n8\n2\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
446
102
coding
Solve the programming task below in a Python markdown code block. Given an array of numbers, return an array, with each member of input array rounded to a nearest number, divisible by 5. For example: ``` roundToFive([34.5, 56.2, 11, 13]); ``` should return ``` [35, 55, 10, 15] ``` ```if:python Roundings have to be done like "in real life": `22.5 -> 25` ``` Also feel free to reuse/extend the following starter code: ```python def round_to_five(numbers): ```
{"functional": "_inputs = [[[1, 5, 87, 45, 8, 8]], [[3, 56.2, 11, 13]], [[22.5, 544.9, 77.5]]]\n_outputs = [[[0, 5, 85, 45, 10, 10]], [[5, 55, 10, 15]], [[25, 545, 80]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(round_to_five(*i), o[0])"}
144
255
coding
Solve the programming task below in a Python markdown code block. You're given a list of n strings a_1, a_2, ..., a_{n}. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest. Given the list of strings, output the lexicographically smallest concatenation. -----Input----- The first line contains integer n — the number of strings (1 ≤ n ≤ 5·10^4). Each of the next n lines contains one string a_{i} (1 ≤ |a_{i}| ≤ 50) consisting of only lowercase English letters. The sum of string lengths will not exceed 5·10^4. -----Output----- Print the only string a — the lexicographically smallest string concatenation. -----Examples----- Input 4 abba abacaba bcd er Output abacabaabbabcder Input 5 x xx xxa xxaa xxaaa Output xxaaaxxaaxxaxxx Input 3 c cb cba Output cbacbc
{"inputs": ["3\nc\ncb\ncba\n", "3\nb\ncb\ncba\n", "3\nb\nbb\ncba\n", "3\nb\nbb\ncab\n", "3\nb\nbb\ncaa\n", "3\nb\nbb\ndaa\n", "3\nb\nbb\naad\n", "3\nc\nbb\ndaa\n"], "outputs": ["cbacbc\n", "bcbacb\n", "bbbcba\n", "bbbcab\n", "bbbcaa\n", "bbbdaa\n", "aadbbb\n", "bbcdaa\n"]}
235
140
coding
Solve the programming task below in a Python markdown code block. You'll be given a list of two strings, and each will contain exactly one colon (`":"`) in the middle (but not at beginning or end). The length of the strings, before and after the colon, are random. Your job is to return a list of two strings (in the same order as the original list), but with the characters after each colon swapped. ## Examples ``` ["abc:123", "cde:456"] --> ["abc:456", "cde:123"] ["a:12345", "777:xyz"] --> ["a:xyz", "777:12345"] ``` Also feel free to reuse/extend the following starter code: ```python def tail_swap(strings): ```
{"functional": "_inputs = [[['abc:123', 'cde:456']], [['a:12345', '777:xyz']]]\n_outputs = [[['abc:456', 'cde:123']], [['a:xyz', '777:12345']]]\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(tail_swap(*i), o[0])"}
184
215
coding
Solve the programming task below in a Python markdown code block. In this Kata, you will be given two strings `a` and `b` and your task will be to return the characters that are not common in the two strings. For example: ```Haskell solve("xyab","xzca") = "ybzc" --The first string has 'yb' which is not in the second string. --The second string has 'zc' which is not in the first string. ``` Notice also that you return the characters from the first string concatenated with those from the second string. More examples in the tests cases. Good luck! Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) Also feel free to reuse/extend the following starter code: ```python def solve(a,b): ```
{"functional": "_inputs = [['xyab', 'xzca'], ['xyabb', 'xzca'], ['abcd', 'xyz'], ['xxx', 'xzca']]\n_outputs = [['ybzc'], ['ybbzc'], ['abcdxyz'], ['zca']]\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])"}
198
194
coding
Solve the programming task below in a Python markdown code block. Snuke has a rooted tree with N+1 vertices. The vertices are numbered 0 through N, and Vertex 0 is the root of the tree. The parent of Vertex i (1 \leq i \leq N) is Vertex p_i. Besides this tree, Snuke also has an box which is initially empty and many marbles, and playing with them. The play begins with placing one marble on some of the vertices, then proceeds as follows: - If there is a marble on Vertex 0, move the marble into the box. - Move each marble from the vertex to its parent (all at once). - For each vertex occupied by two or more marbles, remove all the marbles from the vertex. - If there exists a vertex with some marbles, go to Step 1. Otherwise, end the play. There are 2^{N+1} ways to place marbles on some of the vertices. For each of them, find the number of marbles that will be in the box at the end of the play, and compute the sum of all those numbers modulo 1,000,000,007. -----Constraints----- - 1 \leq N < 2 \times 10^{5} - 0 \leq p_i < i -----Partial Scores----- - In the test set worth 400 points, N < 2{,}000. -----Input----- Input is given from Standard Input in the following format: N p_1 p_2 ... p_{N} -----Output----- Print the answer. -----Sample Input----- 2 0 0 -----Sample Output----- 8 When we place a marble on both Vertex 1 and 2, there will be multiple marbles on Vertex 0 by step 2. In such a case, these marbles will be removed instead of being moved to the box.
{"inputs": ["2\n0 1", "2\n0 0", "2\n0 0\n", "5\n0 1 1 0 3", "5\n0 1 1 1 4", "5\n0 1 0 0 4", "5\n0 1 4 0 4", "5\n0 1 1 0 4"], "outputs": ["12\n", "8", "8\n", "128\n", "120\n", "88\n", "96\n", "96"]}
412
131
coding
Solve the programming task below in a Python markdown code block. Given any integer x, Aoki can do the operation below. Operation: Replace x with the absolute difference of x and K. You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times. -----Constraints----- - 0 ≤ N ≤ 10^{18} - 1 ≤ K ≤ 10^{18} - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N K -----Output----- Print the minimum possible value taken by N after Aoki does the operation zero or more times. -----Sample Input----- 7 4 -----Sample Output----- 1 Initially, N=7. After one operation, N becomes |7-4| = 3. After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.
{"inputs": ["7 6", "7 9", "5 9", "7 7", "7 2", "8 4", "8 7", "8 9"], "outputs": ["1\n", "2\n", "4\n", "0\n", "1\n", "0\n", "1\n", "1\n"]}
204
78
coding
Solve the programming task below in a Python markdown code block. You like the way the Python `+` operator easily handles adding different numeric types, but you need a tool to do that kind of addition without killing your program with a `TypeError` exception whenever you accidentally try adding incompatible types like strings and lists to numbers. You decide to write a function `my_add()` that takes two arguments. If the arguments can be added together it returns the sum. If adding the arguments together would raise an error the function should return `None` instead. For example, `my_add(1, 3.414)` would return `4.414`, but `my_add(42, " is the answer.")` would return `None`. Hint: using a `try` / `except` statement may simplify this kata. Also feel free to reuse/extend the following starter code: ```python def my_add(a, b): ```
{"functional": "_inputs = [[1, 3.414], [42, ' is the answer.'], [10, '2']]\n_outputs = [[4.414], [None], [None]]\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(my_add(*i), o[0])"}
194
188
coding
Solve the programming task below in a Python markdown code block. Snuke received a positive integer N from Takahashi. A positive integer m is called a favorite number when the following condition is satisfied: * The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds. Find all favorite numbers and print the sum of those. Constraints * All values in input are integers. * 1 \leq N \leq 10^{12} Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 8 Output 10 Input 1000000000000 Output 2499686339916
{"inputs": ["2", "8", "16", "1000010000000", "1000011000000", "1100011000000", "1110011000000", "1110011100000"], "outputs": ["0\n", "10", "22\n", "2716922731275\n", "3307289212967\n", "2999416055122\n", "3146654438234\n", "4080876601631\n"]}
180
184
coding
Solve the programming task below in a Python markdown code block. You are given an array $d_1, d_2, \dots, d_n$ consisting of $n$ integer numbers. Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array. Let the sum of elements of the first part be $sum_1$, the sum of elements of the second part be $sum_2$ and the sum of elements of the third part be $sum_3$. Among all possible ways to split the array you have to choose a way such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. More formally, if the first part of the array contains $a$ elements, the second part of the array contains $b$ elements and the third part contains $c$ elements, then: $$sum_1 = \sum\limits_{1 \le i \le a}d_i,$$ $$sum_2 = \sum\limits_{a + 1 \le i \le a + b}d_i,$$ $$sum_3 = \sum\limits_{a + b + 1 \le i \le a + b + c}d_i.$$ The sum of an empty array is $0$. Your task is to find a way to split the array such that $sum_1 = sum_3$ and $sum_1$ is maximum possible. -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in the array $d$. The second line of the input contains $n$ integers $d_1, d_2, \dots, d_n$ ($1 \le d_i \le 10^9$) — the elements of the array $d$. -----Output----- Print a single integer — the maximum possible value of $sum_1$, considering that the condition $sum_1 = sum_3$ must be met. Obviously, at least one valid way to split the array exists (use $a=c=0$ and $b=n$). -----Examples----- Input 5 1 3 1 1 4 Output 5 Input 5 1 3 2 1 4 Output 4 Input 3 4 1 2 Output 0 -----Note----- In the first example there is only one possible splitting which maximizes $sum_1$: $[1, 3, 1], [~], [1, 4]$. In the second example the only way to have $sum_1=4$ is: $[1, 3], [2, 1], [4]$. In the third example there is only one way to split the array: $[~], [4, 1, 2], [~]$.
{"inputs": ["2\n1 1\n", "2\n1 1\n", "2\n1 2\n", "2\n1 4\n", "2\n0 4\n", "3\n4 1 2\n", "3\n3 1 2\n", "3\n3 1 1\n"], "outputs": ["1\n", "1\n", "0\n", "0\n", "0\n", "0\n", "3\n", "0\n"]}
658
108
coding
Solve the programming task below in a Python markdown code block. There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i). We will repeat the following operation as long as possible: - Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position. We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation. -----Constraints----- - 1 \leq N \leq 10^5 - 1 \leq x_i, y_i \leq 10^5 - If i \neq j, x_i \neq x_j or y_i \neq y_j. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N x_1 y_1 : x_N y_N -----Output----- Print the maximum number of times we can do the operation. -----Sample Input----- 3 1 1 5 1 5 5 -----Sample Output----- 1 By choosing a = 1, b = 1, c = 5, d = 5, we can add a dot at (1, 5). We cannot do the operation any more, so the maximum number of operations is 1.
{"inputs": ["2\n1 4\n5 5", "2\n1 14\n5 5", "2\n3 2\n17 6", "2\n5 10\n17 4", "2\n9 10\n17 4", "2\n9 11\n17 4", "2\n7 11\n17 6", "2\n3 11\n17 6"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
333
138
coding
Solve the programming task below in a Python markdown code block. A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and when *x* = 8, *y* = 15. Therefore, if I give you any pair of co-ordinates (x1,y1) and (x2,y2) in a power law distribution, you can plot the entire rest of the distribution and tell me the value of *y* for any other value of *x*. Given a pair of co-ordinates (x1,y1) and (x2,y2) and another x co-ordinate *x3*, return the value of *y3* ``` powerLaw(x1y1, x2y2, x3) e.g. powerLaw([1,120], [2,60], 4) - when x = 1, y = 120 - when x = 2, y = 60 - therefore whenever x doubles, y halves - therefore when x = 4, y = 60 * 0.5 - therfore solution = 30 ``` (x1,y1) and (x2,y2) will be given as arrays. Answer should be to the nearest integer, but random tests will give you leeway of 1% of the reference solution to account for possible discrepancies from different methods. Also feel free to reuse/extend the following starter code: ```python def power_law(x1y1, x2y2, x3): ```
{"functional": "_inputs = [[[1, 120], [2, 60], 4], [[1, 120], [2, 60], 8], [[1, 120], [4, 30], 8], [[1, 120], [3, 60], 9], [[1, 120], [3, 60], 27], [[1, 120], [9, 30], 27], [[1, 81], [2, 27], 4], [[1, 81], [2, 27], 8], [[1, 81], [4, 9], 8], [[1, 81], [5, 27], 25], [[1, 81], [5, 27], 125], [[1, 81], [25, 9], 125], [[4, 30], [2, 60], 1], [[5, 27], [1, 81], 1], [[4, 9], [8, 3], 1], [[1, 120], [1, 120], 1], [[4, 99], [4, 99], 4], [[9, 1], [9, 1], 9]]\n_outputs = [[30], [15], [15], [30], [15], [15], [9], [3], [3], [9], [3], [3], [120], [81], [81], [120], [99], [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(power_law(*i), o[0])"}
415
532
coding
Solve the programming task below in a Python markdown code block. Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied. The classroom contains $n$ rows of seats and there are $m$ seats in each row. Then the classroom can be represented as an $n \times m$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $k$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs. -----Input----- The first line contains three positive integers $n,m,k$ ($1 \leq n, m, k \leq 2\,000$), where $n,m$ represent the sizes of the classroom and $k$ is the number of consecutive seats you need to find. Each of the next $n$ lines contains $m$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat. -----Output----- A single number, denoting the number of ways to find $k$ empty seats in the same row or column. -----Examples----- Input 2 3 2 **. ... Output 3 Input 1 2 2 .. Output 1 Input 3 3 4 .*. *.* .*. Output 0 -----Note----- In the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. $(1,3)$, $(2,3)$ $(2,2)$, $(2,3)$ $(2,1)$, $(2,2)$
{"inputs": ["1 1 1\n.\n", "1 1 1\n*\n", "1 1 1\n.\n", "1 1 1\n*\n", "1 2 2\n..\n", "1 2 1\n..\n", "1 2 3\n..\n", "1 2 2\n..\n"], "outputs": ["1\n", "0\n", "1\n", "0\n", "1\n", "2\n", "0\n", "1\n"]}
421
118
coding
Solve the programming task below in a Python markdown code block. Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are n banknote denominations on Mars: the value of i-th banknote is a_i. Natasha has an infinite number of banknotes of each denomination. Martians have k fingers on their hands, so they use a number system with base k. In addition, the Martians consider the digit d (in the number system with base k) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base k is d, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet. Determine for which values d Natasha can make the Martians happy. Natasha can use only her banknotes. Martians don't give her change. Input The first line contains two integers n and k (1 ≤ n ≤ 100 000, 2 ≤ k ≤ 100 000) — the number of denominations of banknotes and the base of the number system on Mars. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — denominations of banknotes on Mars. All numbers are given in decimal notation. Output On the first line output the number of values d for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation. Examples Input 2 8 12 20 Output 2 0 4 Input 3 10 10 20 30 Output 1 0 Note Consider the first test case. It uses the octal number system. If you take one banknote with the value of 12, you will get 14_8 in octal system. The last digit is 4_8. If you take one banknote with the value of 12 and one banknote with the value of 20, the total value will be 32. In the octal system, it is 40_8. The last digit is 0_8. If you take two banknotes with the value of 20, the total value will be 40, this is 50_8 in the octal system. The last digit is 0_8. No other digits other than 0_8 and 4_8 can be obtained. Digits 0_8 and 4_8 could also be obtained in other ways. The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.
{"inputs": ["1 3\n2\n", "1 6\n4\n", "1 2\n1\n", "1 7\n6\n", "1 5\n2\n", "1 9\n6\n", "1 8\n5\n", "1 7\n4\n"], "outputs": ["3\n0 1 2 ", "3\n0 2 4 ", "2\n0 1 ", "7\n0 1 2 3 4 5 6 ", "5\n0 1 2 3 4 ", "3\n0 3 6 ", "8\n0 1 2 3 4 5 6 7 ", "7\n0 1 2 3 4 5 6 "]}
647
171
coding
Solve the programming task below in a Python markdown code block. Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases. When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually). Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme. Input The first line of input contains a sequence consisting only of characters 'L', 'R' and 'X', where 'L' corresponds to a step with the left foot, 'R' — with the right foot, and 'X' — to a break. The length of the sequence will not exceed 106. Output Output the maximum percentage of time that Jack can spend marching correctly, rounded down to exactly six digits after the decimal point. Examples Input X Output 0.000000 Input LXRR Output 50.000000 Note In the second example, if we add two breaks to receive LXXRXR, Jack will march: LXXRXRLXXRXRL... instead of LRLRLRLRLRLRL... and will make the correct step in half the cases. If we didn't add any breaks, the sequence would be incorrect — Jack can't step on his right foot twice in a row.
{"inputs": ["X\n", "RXLR\n", "RLXR\n", "XLRR\n", "RRLX\n", "LXRR\n", "RXLLRLRR\n", "RXRLRLLR\n"], "outputs": ["0.000000\n", "50.000000\n", "50.000000\n", "50.000000\n", "50.000000\n", "50.000000\n", "58.333333\n", "70.000000\n"]}
575
147
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a pattern and a string s, find if s follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s. Specifically: Each letter in pattern maps to exactly one unique word in s. Each unique word in s maps to exactly one letter in pattern. No two letters map to the same word, and no two words map to the same letter.   Please complete the following python code precisely: ```python class Solution: def wordPattern(self, pattern: str, s: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(pattern = \"abba\", s = \"dog cat cat dog\") == True\n assert candidate(pattern = \"abba\", s = \"dog cat cat fish\") == False\n assert candidate(pattern = \"aaaa\", s = \"dog cat cat dog\") == False\n\n\ncheck(Solution().wordPattern)"}
143
78
coding
Solve the programming task below in a Python markdown code block. "Ring Ring!!" Sherlock's phone suddenly started ringing. And it was none other than Jim Moriarty.. "Long time no see ! You miss me right ? Anyway we'll talk about it later . Let me first tell you something. Dr.Watson is with me . And you've got only one chance to save him . Here's your challenge:. Given a number N and another number M, tell if the remainder of N%M is odd or even. If it's odd, then print "ODD" else print "EVEN" If Sherlock can answer the query correctly, then Watson will be set free. He has approached you for help since you being a programmer.Can you help him? -----Input----- The first line contains, T, the number of test cases.. Each test case contains an integer, N and M -----Output----- Output the minimum value for each test case -----Constraints----- 1 = T = 20 1 <= N <= 10^18 1 <= M<= 10^9 -----Subtasks----- Subtask #1 : (20 points) 1 = T = 20 1 <= N <= 100 1 <= M<= 100 Subtask 2 : (80 points) 1 = T = 20 1 <= N <= 10^18 1 <= M<= 10^9 -----Example----- Input: 2 4 4 6 5 Output: EVEN ODD
{"inputs": ["2\n4 4\n6 5"], "outputs": ["EVEN\nODD"]}
332
24
coding
Solve the programming task below in a Python markdown code block. Read problems statements in [Russian]. Chef has an array A of size N. Chef wants to choose any subsequence of size exactly \lceil \frac{N}{2} \rceil from the array such that GCD of all the elements in that sequence must be 2. Chef names such a kind of sequence as a *half-sequence*. Help Chef to find whether he would be able to select any half-sequence in the given array. As a reminder, A subsequence of an array is a sequence that can be derived from the given array by deleting zero or more elements without changing the order of the remaining elements. GCD stands for Greatest Common Divisor. The greatest common divisor of a subsequence is the largest integer d such that all the numbers in sequence are divisible by d. For more information, refer to [here]. \lceil x \rceil is the ceiling (round up) operation: \lceil 3.5 \rceil = 4 ,\lceil 2 \rceil = 2 . ------ Input Format ------ - The first line contains an integer T denoting the number of test cases. The T test cases then follow. - The first line of each test case contains a single integer N denoting the size of the array. - The second line of each test case contains N space-separated integers A_{1}, A_{2}....A_{N} denoting the given array. ------ Output Format ------ For each test case, output on one line YES if Chef can find a half-sequence, else print NO. Output is case insensitive. ------ Constraints ------ $1 ≤T ≤20$ $2 ≤N ≤10^{5}$ $1 ≤A_{i} ≤10^{9}$ - Sum of $N$ over all test cases does not exceed $10^{5}$ ----- Sample Input 1 ------ 3 5 1 2 3 4 5 4 1 2 3 4 3 30 42 70 ----- Sample Output 1 ------ NO YES NO ----- explanation 1 ------ - For the first test case, Chef wants to select $\lceil \frac{5}{2} \rceil = 3$ numbers. But for any $3$ numbers, GCD would not be $2$. Therefore the answer is NO. - For the second test case, Chef wants to select $\lceil \frac{4}{2} \rceil = 2$ numbers. Chef can select the subsequence $[2,4]$ with GCD of $2$. Therefore the answer is YES. - For the third test case, Chef wants to select $\lceil \frac{3}{2} \rceil = 2$ numbers. But for any $2$ numbers, GCD would be bigger than $2$. Therefore the answer is NO.
{"inputs": ["3\n5\n1 2 3 4 5\n4\n1 2 3 4\n3\n30 42 70"], "outputs": ["NO\nYES\nNO"]}
624
49
coding
Solve the programming task below in a Python markdown code block. A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained? Input Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106. Output Output the maximum possible length of a regular bracket sequence. Examples Input (()))( Output 4 Input ((()()) Output 6
{"inputs": ["(\n", ")\n", ")(()(\n", "()(()\n", "((())\n", "())((\n", "))(((\n", "(())(\n"], "outputs": ["0\n", "0\n", "2\n", "4\n", "4\n", "2\n", "0\n", "4\n"]}
183
79
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order. A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.   Please complete the following python code precisely: ```python class Solution: def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: ```
{"functional": "def check(candidate):\n assert candidate(words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\") == [\"mee\",\"aqq\"]\n\n\ncheck(Solution().findAndReplacePattern)"}
152
61
coding
Solve the programming task below in a Python markdown code block. In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0. You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation: - Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r. Find the minimum number of watering operations required to satisfy the condition. -----Constraints----- - 1 \leq N \leq 100 - 0 \leq h_i \leq 100 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N h_1 h_2 h_3 ...... h_N -----Output----- Print the minimum number of watering operations required to satisfy the condition. -----Sample Input----- 4 1 2 2 1 -----Sample Output----- 2 The minimum number of watering operations required is 2. One way to achieve it is: - Perform the operation with (l,r)=(1,3). - Perform the operation with (l,r)=(2,4).
{"inputs": ["1\n7\n", "4\n1 4 2 1", "4\n1 8 2 1", "4\n1 2 2 2", "4\n1 2 2 1", "4\n1 2 2 1\n", "4\n1 12 2 1", "4\n1 12 0 2"], "outputs": ["7\n", "4\n", "8\n", "2\n", "2", "2\n", "12\n", "14\n"]}
302
125
coding
Solve the programming task below in a Python markdown code block. Following from the previous kata and taking into account how cool psionic powers are compare to the Vance spell system (really, the idea of slots to dumb down the game sucks, not to mention that D&D became a smash hit among geeks, so...), your task in this kata is to create a function that returns how many power points you get as a psion [because psions are the coolest, they allow for a lot of indepth tactic playing and adjusting for psychic warriors or wilders or other non-core classes would be just an obnoxious core]. Consider both [the psion power points/days table](http://www.dandwiki.com/wiki/SRD:Psion#Making_a_Psion) and [bonus power points](http://www.d20pfsrd.com/psionics-unleashed/classes/#Table_Ability_Modifiers_and_Bonus_Power_Points) to figure out the correct reply, returned as an integer; the usual interpretation is that bonus power points stop increasing after level 20, but for the scope of this kata, we will pretend they keep increasing as they did before. To compute the total, you will be provided, both as non-negative integers: * class level (assume they are all psion levels and remember the base power points/day halts after level 20) * manifesting attribute score (Intelligence, to be more precise) to determine the total, provided the score is high enough for the character to manifest at least one power. Some examples: ```python psion_power_points(1,0) == 0 psion_power_points(1,10) == 0 psion_power_points(1,11) == 2 psion_power_points(1,20) == 4 psion_power_points(21,30) == 448 ``` *Note: I didn't explain things in detail and just pointed out to the table on purpose, as my goal is also to train the pattern recognition skills of whoever is going to take this challenges, so do not complain about a summary description. Thanks :)* In the same series: * [D&D Character generator #1: attribute modifiers and spells](https://www.codewars.com/kata/d-and-d-character-generator-number-1-attribute-modifiers-and-spells/) * [D&D Character generator #2: psion power points](https://www.codewars.com/kata/d-and-d-character-generator-number-2-psion-power-points/) * [D&D Character generator #3: carrying capacity](https://www.codewars.com/kata/d-and-d-character-generator-number-3-carrying-capacity/) Also feel free to reuse/extend the following starter code: ```python def psion_power_points(level,score): ```
{"functional": "_inputs = [[1, 0], [1, 10], [1, 11], [0, 11], [1, 20], [21, 30]]\n_outputs = [[0], [0], [2], [0], [4], [448]]\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(psion_power_points(*i), o[0])"}
594
212
coding
Solve the programming task below in a Python markdown code block. # Task You got a `scratch lottery`, you want to know how much money you win. There are `6` sets of characters on the lottery. Each set of characters represents a chance to win. The text has a coating on it. When you buy the lottery ticket and then blow it off, you can see the text information below the coating. Each set of characters contains three animal names and a number, like this: `"tiger tiger tiger 100"`. If the three animal names are the same, Congratulations, you won the prize. You will win the same bonus as the last number. Given the `lottery`, returns the total amount of the bonus. # Input/Output `[input]` string array `lottery` A string array that contains six sets of characters. `[output]` an integer the total amount of the bonus. # Example For ``` lottery = [ "tiger tiger tiger 100", "rabbit dragon snake 100", "rat ox pig 1000", "dog cock sheep 10", "horse monkey rat 5", "dog dog dog 1000" ]``` the output should be `1100`. `"tiger tiger tiger 100"` win $100, and `"dog dog dog 1000"` win $1000. `100 + 1000 = 1100` Also feel free to reuse/extend the following starter code: ```python def scratch(lottery): ```
{"functional": "_inputs = [[['tiger tiger tiger 100', 'rabbit dragon snake 100', 'rat ox pig 1000', 'dog cock sheep 10', 'horse monkey rat 5', 'dog dog dog 1000']]]\n_outputs = [[1100]]\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(scratch(*i), o[0])"}
346
210
coding
Solve the programming task below in a Python markdown code block. Given an array $A$ of length $N$, we can define rotation as follows. If we rotate $A$ to the right, all elements move to the right one unit, and the last element moves to the beginning. That is, it becomes $[A_{N}, A_{1},A_{2},\ldots,A_{N-1}]$. Similarly if we rotate $A$ to the left, it becomes $[A_{2},A_{3},\ldots,A_{N}, A_{1}]$. Given an array $A$ and an integer $x$, define $f(A,x)$ to be the array $A$ rotated by the amount $x$. If $x≥ 0$, this means we rotate it right $x$ times. If $x<0$, this means we rotate it left $|x|$ times. You are given an array $A$ of length $N$. Then $Q$ queries follow. In each query, an integer $x$ is given. To answer the query, you should replace $A$ with $A+f(A,x)$ where $+$ denotes concatenation. After this operation, you must output the sum of all elements of $A$. Since this number can be large, output it modulo $10^{9} + 7$. Note that the queries are cumulative. When you modify $A$ to answer one query, it starts that way for the next query. ------ Input ------ The first line contains an integer $N$ - the size of the initial array. The second line contains $N$ integers $A_{1},\ldots, A_{N}$ - the elements of the initial array. The third line contains an integer $Q$ - the number of queries. The fourth line contains $Q$ space-separated integers $x_{1},\ldots, x_{Q}$, where $x_{i}$ is the parameter of the $i$-th query. ------ Output ------ After each query, output in a single line the the sum of all elements of the current array modulo $10^{9}+7$. ------ Constraints ------ $ 1≤ N≤ 10^{5}$ $ 1≤ Q≤ 10^{5}$ $ -10^{9}≤ A_{i}≤ 10^{9}$ $ -10^{5} ≤ x_{i}≤ 10^{5}$ ------ Subtasks ------ Subtask #1 (100 points): original constraints ----- Sample Input 1 ------ 2 1 2 2 1 1 ----- Sample Output 1 ------ 6 12 ----- explanation 1 ------ Initially, the array is $[1,2]$. After the first query, the array becomes $[1, 2] + f([1, 2], 1) = [1, 2] + [2, 1] = [1, 2, 2, 1]$. The total sum is $6$. After the second query, the array becomes $[1, 2, 2, 1] + f([1, 2, 2, 1], 1) = [1, 2, 2, 1] + [1, 1, 2, 2] = [1, 2, 2, 1, 1, 1, 2, 2]$. The total sum is $12$.
{"inputs": ["2\n1 2\n2\n1 1"], "outputs": ["6\n12"]}
753
25
coding
Solve the programming task below in a Python markdown code block. Mr. A wants to get to the destination on the Yamanote line. After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes. How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off. Constraints * 0 <a, b, c <60 Input The input is given in one line in the following format. a b c The input consists of three integers a, b, c. a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes. Output If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1. Examples Input 10 10 5 Output 5 Input 50 40 51 Output 111 Input 20 20 20 Output 20 Input 30 30 40 Output -1
{"inputs": ["2 5 4", "2 5 5", "2 5 9", "1 0 8", "1 0 1", "1 2 3", "0 2 2", "2 5 0"], "outputs": ["64\n", "65\n", "9\n", "8\n", "1\n", "3\n", "2\n", "0\n"]}
380
96
coding
Solve the programming task below in a Python markdown code block. You are given an unrooted tree of $n$ nodes numbered from $\mbox{1}$ to $n$. Each node $\boldsymbol{i}$ has a color, $c_i$. Let $d(i,j)$ be the number of different colors in the path between node $\boldsymbol{i}$ and node $j$. For each node $\boldsymbol{i}$, calculate the value of $\textit{sum}_i$, defined as follows: $sum_{i}=\sum_{j=1}^{n}d(i,j)$ Your task is to print the value of $\textit{sum}_i$ for each node $1\leq i\leq n$. Input Format The first line contains a single integer, $n$, denoting the number of nodes. The second line contains $n$ space-separated integers, $c_1,c_2,\ldots,c_n$, where each $c_i$ describes the color of node $\boldsymbol{i}$. Each of the $n-1$ subsequent lines contains $2$ space-separated integers, $\boldsymbol{a}$ and $\boldsymbol{b}$, defining an undirected edge between nodes $\boldsymbol{a}$ and $\boldsymbol{b}$. Constraints $1\leq n\leq10^5$ $1\leq c_i\leq10^5$ Output Format Print $n$ lines, where the $i^{\mbox{th}}$ line contains a single integer denoting $\textit{sum}_i$. Sample Input 5 1 2 3 2 3 1 2 2 3 2 4 1 5 Sample Output 10 9 11 9 12 Explanation The Sample Input defines the following tree: Each $\textit{sum}_i$ is calculated as follows: $sum_1=d(1,1)+d(1,2)+d(1,3)+d(1,4)+d(1,5)=1+2+3+2+2=10$ $sum_2=d(2,1)+d(2,2)+d(2,3)+d(2,4)+d(2,5)=2+1+2+1+3=9$ $sum_3=d(3,1)+d(3,2)+d(3,3)+d(3,4)+d(3,5)=3+2+1+2+3=11$ $sum_4=d(4,1)+d(4,2)+d(4,3)+d(4,4)+d(4,5)=2+1+2+1+3=9$ $sum_5=d(5,1)+d(5,2)+d(5,3)+d(5,4)+d(5,5)=2+3+3+3+1=12$
{"inputs": ["5\n1 2 3 2 3\n1 2\n2 3\n2 4\n1 5\n"], "outputs": ["10\n9\n11\n9\n12\n"]}
646
51
coding
Solve the programming task below in a Python markdown code block. Phoenix has $n$ coins with weights $2^1, 2^2, \dots, 2^n$. He knows that $n$ is even. He wants to split the coins into two piles such that each pile has exactly $\frac{n}{2}$ coins and the difference of weights between the two piles is minimized. Formally, let $a$ denote the sum of weights in the first pile, and $b$ denote the sum of weights in the second pile. Help Phoenix minimize $|a-b|$, the absolute value of $a-b$. -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases. The first line of each test case contains an integer $n$ ($2 \le n \le 30$; $n$ is even) — the number of coins that Phoenix has. -----Output----- For each test case, output one integer — the minimum possible difference of weights between the two piles. -----Example----- Input 2 2 4 Output 2 6 -----Note----- In the first test case, Phoenix has two coins with weights $2$ and $4$. No matter how he divides the coins, the difference will be $4-2=2$. In the second test case, Phoenix has four coins of weight $2$, $4$, $8$, and $16$. It is optimal for Phoenix to place coins with weights $2$ and $16$ in one pile, and coins with weights $4$ and $8$ in another pile. The difference is $(2+16)-(4+8)=6$.
{"inputs": ["1\n2\n", "1\n2\n", "1\n4\n", "1\n6\n", "2\n2\n4\n", "2\n4\n4\n", "2\n4\n6\n", "2\n6\n4\n"], "outputs": ["2\n", "2\n", "6\n", "14\n", "2\n6\n", "6\n6\n", "6\n14\n", "14\n6\n"]}
374
105
coding
Solve the programming task below in a Python markdown code block. Given a sorted array of numbers, return the summary of its ranges. ## Examples ```python summary_ranges([1, 2, 3, 4]) == ["1->4"] summary_ranges([1, 1, 1, 1, 1]) == ["1"] summary_ranges([0, 1, 2, 5, 6, 9]) == ["0->2", "5->6", "9"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 5, 6, 7]) == ["0->7"] summary_ranges([0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10]) == ["0->7", "9->10"] summary_ranges([-2, 0, 1, 2, 3, 3, 3, 4, 4, 5, 6, 7, 7, 9, 9, 10, 12]) == ["-2", "0->7", "9->10", "12"] ``` Also feel free to reuse/extend the following starter code: ```python def summary_ranges(nums): ```
{"functional": "_inputs = [[[]], [[1, 1, 1, 1]], [[1, 2, 3, 4]], [[0, 1, 2, 5, 6, 9]], [[0, 1, 2, 3, 4, 5, 6, 7]], [[0, 1, 2, 3, 5, 6, 7]], [[0, 1, 2, 3, 4, 5, 6, 7, 9, 10]], [[-2, 0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 12]], [[-3, -2, -1, 0, 2, 3]], [[-2]]]\n_outputs = [[[]], [['1']], [['1->4']], [['0->2', '5->6', '9']], [['0->7']], [['0->3', '5->7']], [['0->7', '9->10']], [['-2', '0->7', '9->10', '12']], [['-3->0', '2->3']], [['-2']]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(summary_ranges(*i), o[0])"}
304
416
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well. There is a large tree house in an unknown world. It is ruled by the great emperor KZS. It consists of $N$ nodes numbered from $1$ to $N$ in which the people of that world reside. The nodes are organized in a tree structure rooted at node $1$. You need to assign values to the nodes according to the wishes of emperor KZS which are as follows :- The value of node $1$ is $X$. All immediate children of any node have pairwise distinct values. For every node with at least one immediate child, the $\gcd$ of the values of all immediate children is equal to the value of the node. The total sum of the values of all nodes should be minimum. The greatest common divisor $\gcd(a,b)$ of two positive integers $a$ and $b$ is equal to the largest integer $d$ such that both integers $a$ and $b$ are divisible by $d$. Print the sum of all values, modulo $10^{9} + 7$. ------ Input ------ The first line contains an integer $T$, the number of test cases. $T$ testcases follow. The first line of each test contains two integers $N$ and $X$. Each of the following $N-1$ lines contains two integers $u$ and $v$, denoting an edge between nodes $u$ and $v$. ------ Output ------ For each test case, print the sum of values, modulo $10^{9} + 7$. ------ Constraints ------ $1 ≤ T ≤ 15$ $2 ≤ N ≤ 3 \cdot 10^{5}$ $1 ≤ X ≤ 10^{9}$ $1 ≤ u, v ≤ N$ and $u \neq v$ The given edges form a tree The sum of $N$ over all test cases doesn't exceed $3 \cdot 10^{5}$. ------ Subtasks ------ Subtask #1 (100 points): Original Constraints ----- Sample Input 1 ------ 2 4 1 1 2 1 3 1 4 8 1 1 2 1 3 2 4 2 5 5 6 5 7 7 8 ----- Sample Output 1 ------ 7 11 ----- explanation 1 ------ In test case $1$, we will give values $1$, $2$, $3$ to the nodes $2$, $3$ and $4$ respectively. So, the total sum will be $1 + 1 + 2 + 3 = 7$.
{"inputs": ["2\n4 1\n1 2\n1 3\n1 4\n8 1\n1 2\n1 3\n2 4\n2 5\n5 6\n5 7\n7 8"], "outputs": ["7\n11"]}
609
63
coding
Solve the programming task below in a Python markdown code block. In this kata, you should calculate type of triangle with three given sides ``a``, ``b`` and ``c`` (given in any order). If all angles are less than ``90°``, this triangle is ``acute`` and function should return ``1``. If one angle is strictly ``90°``, this triangle is ``right`` and function should return ``2``. If one angle more than ``90°``, this triangle is ``obtuse`` and function should return ``3``. If three sides cannot form triangle, or one angle is ``180°`` (which turns triangle into segment) - function should return ``0``. Input parameters are ``sides`` of given triangle. All input values are non-negative floating point or integer numbers (or both). Acute Right Obtuse ### Examples: ```python triangle_type(2, 4, 6) # return 0 (Not triangle) triangle_type(8, 5, 7) # return 1 (Acute, angles are approx. 82°, 38° and 60°) triangle_type(3, 4, 5) # return 2 (Right, angles are approx. 37°, 53° and exactly 90°) triangle_type(7, 12, 8) # return 3 (Obtuse, angles are approx. 34°, 106° and 40°) ``` If you stuck, this can help you: http://en.wikipedia.org/wiki/Law_of_cosines. But you can solve this kata even without angle calculation. There is very small chance of random test to fail due to round-off error, in such case resubmit your solution. Also feel free to reuse/extend the following starter code: ```python def triangle_type(a, b, c): ```
{"functional": "_inputs = [[1, 2, 3], [5.5, 4.5, 10], [7, 3, 2], [5, 10, 5], [3, 3, 0], [3, 3, 1], [5, 5, 5], [122.14, 222.11, 250], [8, 5, 7], [100000, 100005, 111111], [3, 4, 5], [21, 220, 221], [8.625, 33.625, 32.5], [65, 56, 33], [68000, 285000, 293000], [2, 4, 5], [105, 100, 6], [102, 200, 250], [65, 55, 33], [7, 8, 12], [7.99999, 4, 4]]\n_outputs = [[0], [0], [0], [0], [0], [1], [1], [1], [1], [1], [2], [2], [2], [2], [2], [3], [3], [3], [3], [3], [3]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(triangle_type(*i), o[0])"}
412
488
coding
Solve the programming task below in a Python markdown code block. In genetics, a sequence’s motif is a nucleotides (or amino-acid) sequence pattern. Sequence motifs have a biological significance. For more information you can take a look [here](https://en.wikipedia.org/wiki/Sequence_motif). For this kata you need to complete the function `motif_locator`. This function receives 2 arguments - a sequence and a motif. Both arguments are strings. You should return an array that contains all the start positions of the motif (in order). A sequence may contain 0 or more repetitions of the given motif. Note that the number of the first position is 1, not 0. **Some examples:** - For the `sequence` "ACGTGGGGACTAGGGG" and the `motif` "GGGG" the result should be [5, 13]. - For the `sequence` "ACCGTACCAAGGGACC" and the `motif` "AAT" the result should be [] - For the `sequence` "GGG" and the motif "GG" the result should be [1, 2] **Note**: You can take a look to my others bio-info kata [here](http://www.codewars.com/users/nbeck/authored) Also feel free to reuse/extend the following starter code: ```python def motif_locator(sequence, motif): ```
{"functional": "_inputs = [['TTCCGGAACC', 'CC'], ['ACGTTACAACGTTAG', 'ACGT'], ['ACGTACGTACGT', 'AAA'], ['ACGT', 'ACGTGAC']]\n_outputs = [[[3, 9]], [[1, 9]], [[]], [[]]]\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(motif_locator(*i), o[0])"}
297
211
coding
Solve the programming task below in a Python markdown code block. Your are given a string $S$ containing only lowercase letter and a array of character $arr$. Find whether the given string only contains characters from the given character array. Print $1$ if the string contains characters from the given array only else print $0$. Note: string contains characters in lower case only. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains- a string $S$ of lowercase letter a integer $n$ denoting length of character array $arr$ next line contains $n$ space separated characters. -----Output:----- For each testcase, Print $1$ if the string contains characters from the given array only else print $0$. -----Constraints----- - $1 \leq T \leq 1000$ - $0 \leq n \leq 10^5$ -----Sample Input:----- 3 abcd 4 a b c d aabbbcccdddd 4 a b c d acd 3 a b d -----Sample Output:----- 1 1 0
{"inputs": ["3\nabcd\n4\na b c d\naabbbcccdddd\n4\na b c d\nacd\n3\na b d"], "outputs": ["1\n1\n0"]}
250
45
coding
Solve the programming task below in a Python markdown code block. Read problems statements [Hindi] ,[Bengali] , [Mandarin chinese] , [Russian] and [Vietnamese] as well. In the magical land of Byteland, there are three kinds of citizens: a Bit - $2\;\mathrm{ms}$ after a Bit appears, it grows up and becomes a Nibble (i.e. it disappears and a Nibble appears) a Nibble - $8\;\mathrm{ms}$ after a Nibble appears, it grows up and becomes a Byte a Byte - $16\;\mathrm{ms}$ after a Byte appears, it grows up, splits into two Bits and disappears Chef wants to know the answer to the following question: what would the population of Byteland be immediately before the time $N\;\mathrm{ms}$ if only 1 Bit appeared at time $0\;\mathrm{ms}$? Help him and find the population (number of citizens) of each type. ------ Input ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. The first and only line of each test case contains a single integer $N$. ------ Output ------ For each test case, print a single line containing three space-separated integers — the number of Bits, Nibbles and Bytes. ------ Constraints ------ $1 ≤ T ≤ 10^{4}$ $1 ≤ N ≤ 1,600$ ------ Subtasks ------ Subtask #1 (25 points): $1 ≤ N ≤ 140$ Subtask #2 (75 points): original constraints ----- Sample Input 1 ------ 2 2 3 ----- Sample Output 1 ------ 1 0 0 0 1 0 ----- explanation 1 ------ Immediately before the time $2\;\mathrm{ms}$, there is only one Bit. At $2\;\mathrm{ms}$, this Bit grows up, so immediately before $3\;\mathrm{ms}$, there is only one Nibble in Byteland.
{"inputs": ["2\n2\n3"], "outputs": ["1 0 0\n0 1 0"]}
460
26
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree. Note: The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer. A subtree of root is a tree consisting of root and all of its descendants.   Please complete the following python code precisely: ```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def averageOfSubtree(self, root: reeNode) -> int: ```
{"functional": "def check(candidate):\n assert candidate(root = tree_node([4,8,5,0,1,None,6])) == 5\n assert candidate(root = tree_node([1])) == 1\n\n\ncheck(Solution().averageOfSubtree)"}
175
60
coding
Solve the programming task below in a Python markdown code block. You're familiar with [list slicing](https://docs.python.org/3/library/functions.html#slice) in Python and know, for example, that: ```python >>> ages = [12, 14, 63, 72, 55, 24] >>> ages[2:4] [63, 72] >>> ages[2:] [63, 72, 55, 24] >>> ages[:3] [12, 14, 63] ``` write a function `inverse_slice()` that takes three arguments: a list `items`, an integer `a` and an integer `b`. The function should return a new list with the slice specified by `items[a:b]` _excluded_. For example: ```python >>>inverse_slice([12, 14, 63, 72, 55, 24], 2, 4) [12, 14, 55, 24] ``` The input will always be a valid list, `a` and `b` will always be different integers equal to or greater than zero, but they _may_ be zero or be larger than the length of the list. Also feel free to reuse/extend the following starter code: ```python def inverse_slice(items, a, b): ```
{"functional": "_inputs = [[[12, 14, 63, 72, 55, 24], 2, 4], [[12, 14, 63, 72, 55, 24], 0, 3], [['Intuition', 'is', 'a', 'poor', 'guide', 'when', 'facing', 'probabilistic', 'evidence'], 5, 13]]\n_outputs = [[[12, 14, 55, 24]], [[72, 55, 24]], [['Intuition', 'is', 'a', 'poor', 'guide']]]\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(inverse_slice(*i), o[0])"}
306
295
coding
Solve the programming task below in a Python markdown code block. Given two strings, determine if they share a common substring. A substring may be as small as one character. Example $s1=\text{'and'}$ $s2=\text{'art'}$ These share the common substring $\class{ML__boldsymbol}{\boldsymbol{a}}$. $\textbf{s1}=\textbf{'be'}$ $s2=\text{'cat'}$ These do not share a substring. Function Description Complete the function twoStrings in the editor below. twoStrings has the following parameter(s): string s1: a string string s2: another string Returns string: either YES or NO Input Format The first line contains a single integer $\boldsymbol{p}$, the number of test cases. The following $\boldsymbol{p}$ pairs of lines are as follows: The first line contains string $\mbox{s1}$. The second line contains string $\mbox{s2}$. Constraints $\mbox{s1}$ and $\mbox{s2}$ consist of characters in the range ascii[a-z]. $1\leq p\leq10$ $1\leq|s1|,|s2|\leq10^5$ Output Format For each pair of strings, return YES or NO. Sample Input 2 hello world hi world Sample Output YES NO Explanation We have $p=2$ pairs to check: $s1=\text{"hello"}$, $s2=\text{"world"}$. The substrings $\text{"o"}$ and $\text{"l"}$ are common to both strings. $a=\textsf{hi}$, $b=\text{"world"}$. $\mbox{s1}$ and $\mbox{s2}$ share no common substrings.
{"inputs": ["2\nhello\nworld\nhi\nworld\n"], "outputs": ["YES\nNO\n"]}
401
24
coding
Solve the programming task below in a Python markdown code block. In all schools in Buryatia, in the $1$ class, everyone is told the theory of Fibonacci strings. "A block is a subsegment of a string where all the letters are the same and are bounded on the left and right by the ends of the string or by letters other than the letters in the block. A string is called a Fibonacci string if, when it is divided into blocks, their lengths in the order they appear in the string form the Fibonacci sequence ($f_0 = f_1 = 1$, $f_i = f_{i-2} + f_{i-1}$), starting from the zeroth member of this sequence. A string is called semi-Fibonacci if it possible to reorder its letters to get a Fibonacci string." Burenka decided to enter the Buryat State University, but at the entrance exam she was given a difficult task. She was given a string consisting of the letters of the Buryat alphabet (which contains exactly $k$ letters), and was asked if the given string is semi-Fibonacci. The string can be very long, so instead of the string, she was given the number of appearances of each letter ($c_i$ for the $i$-th letter) in that string. Unfortunately, Burenka no longer remembers the theory of Fibonacci strings, so without your help she will not pass the exam. -----Input----- The first line contains one integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases. The following is a description of the input data sets. The first line of each test case contains one integer $k$ ($1 \leq k \leq 100$) — the number of letters in the alphabet. The second line of each test case contains $k$ integers $c_1, c_2, \ldots, c_k$ ($1 \leq c_i \leq 10^9$) — the number of occurrences of each letter in the string. -----Output----- For each test case print the string "YES" if the corresponding string is semi-Fibonacci, and "NO" if it is not. You can print "YES" and "NO" in any case (for example, the strings "yEs", "yes", "Yes" will be recognized as a positive answer). -----Examples----- Input 6 1 1 2 1 1 2 1 2 3 3 1 3 2 7 5 6 26 8 3 4 13 34 Output YES YES NO YES NO YES -----Note----- In the first test case, a one-character string is semi-Fibonacci, being itself a Fibonacci string. In the second test case, a string of two different characters is Fibonacci. In the third test case, the string "abb" (let the first of the alphabet letter be a, the second letter b) is not a semi-Fibonacci string, since no permutation of its letters ("abb", "bab", and "bba") is a Fibonacci string. In the fourth test case, two permutations of the letters of the string "abaccac" (the first letter is a, the second letter is b, the third letter is c) are Fibonacci strings — "abaaccc" and "cbccaaa".
{"inputs": ["6\n1\n1\n2\n1 1\n2\n1 2\n3\n3 1 3\n2\n7 5\n6\n26 8 3 4 13 34\n"], "outputs": ["YES\nYES\nNO\nYES\nNO\nYES\n"]}
725
71
coding
Solve the programming task below in a Python markdown code block. A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters + and 1 into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not. Let's call a regular bracket sequence "RBS". You are given a sequence $s$ of $n$ characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence. You have to replace every character ? with either ) or ( (different characters ? can be replaced with different brackets). You cannot reorder the characters, remove them, insert other characters, and each ? must be replaced. Determine if it is possible to obtain an RBS after these replacements. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. Each test case consists of one line containing $s$ ($2 \le |s| \le 100$) — a sequence of characters (, ), and/or ?. There is exactly one character ( and exactly one character ) in this sequence. -----Output----- For each test case, print YES if it is possible to obtain a regular bracket sequence, or NO otherwise}. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer). -----Examples----- Input 5 () (?) (??) ??() )?(? Output YES NO YES YES NO -----Note----- In the first test case, the sequence is already an RBS. In the third test case, you can obtain an RBS as follows: ()() or (()). In the fourth test case, you can obtain an RBS as follows: ()().
{"inputs": ["5\n()\n(?)\n(??)\n??()\n)?(?\n", "5\n()\n(?)\n)??(\n??()\n)?(?\n", "5\n()\n(?)\n(??)\n??()\n?(?)\n", "5\n()\n?()\n(??)\n??()\n)?(?\n", "5\n()\n(?)\n(??)\n)(??\n?(?)\n", "5\n)(\n?()\n(??)\n??()\n)?(?\n", "5\n)(\n(?)\n(??)\n)(??\n?(?)\n", "5\n()\n(?)\n)??(\n??()\n?(?)\n"], "outputs": ["YES\nNO\nYES\nYES\nNO\n", "YES\nNO\nNO\nYES\nNO\n", "YES\nNO\nYES\nYES\nYES\n", "YES\nNO\nYES\nYES\nNO\n", "YES\nNO\nYES\nNO\nYES\n", "NO\nNO\nYES\nYES\nNO\n", "NO\nNO\nYES\nNO\nYES\n", "YES\nNO\nNO\nYES\nYES\n"]}
392
272
coding
Solve the programming task below in a Python markdown code block. Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score. Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is $\operatorname{max}(0.3 x,(1 - \frac{m}{250}) x - 50 w)$. His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack. All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer. -----Input----- The first line of the input contains five space-separated integers m_1, m_2, m_3, m_4, m_5, where m_{i} (0 ≤ m_{i} ≤ 119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted. The second line contains five space-separated integers w_1, w_2, w_3, w_4, w_5, where w_{i} (0 ≤ w_{i} ≤ 10) is Kevin's number of wrong submissions on problem i. The last line contains two space-separated integers h_{s} and h_{u} (0 ≤ h_{s}, h_{u} ≤ 20), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively. -----Output----- Print a single integer, the value of Kevin's final score. -----Examples----- Input 20 40 60 80 100 0 1 2 3 4 1 0 Output 4900 Input 119 119 119 119 119 0 0 0 0 0 10 0 Output 4930 -----Note----- In the second sample, Kevin takes 119 minutes on all of the problems. Therefore, he gets $(1 - \frac{119}{250}) = \frac{131}{250}$ of the points on each problem. So his score from solving problems is $\frac{131}{250}(500 + 1000 + 1500 + 2000 + 2500) = 3930$. Adding in 10·100 = 1000 points from hacks, his total score becomes 3930 + 1000 = 4930.
{"inputs": ["0 0 0 0 0\n0 0 0 0 0\n0 0\n", "0 0 0 0 0\n0 0 0 0 0\n0 0\n", "0 1 0 0 0\n0 0 0 0 0\n0 0\n", "0 0 0 0 0\n0 0 0 0 0\n20 0\n", "0 0 0 0 0\n0 0 0 0 0\n20 0\n", "0 0 0 0 0\n0 0 0 0 0\n20 1\n", "119 0 0 0 0\n2 0 0 0 0\n5 5\n", "0 119 0 0 0\n0 2 0 0 0\n5 5\n"], "outputs": ["7500\n", "7500\n", "7496\n", "9500\n", "9500\n", "9450\n", "7412\n", "7174\n"]}
738
277
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well. Chef and $N-1$ more of his friends go to the night canteen. The canteen serves only three items (well, they serve more, but only these three are edible!), which are omelette, chocolate milkshake, and chocolate cake. Their prices are $A$, $B$ and $C$ respectively. However, the canteen is about to run out of some ingredients. In particular, they only have $E$ eggs and $H$ chocolate bars left. They need: $2$ eggs to make an omelette $3$ chocolate bars for a chocolate milkshake $1$ egg and $1$ chocolate bar for a chocolate cake Each of the $N$ friends wants to order one item. They can only place an order if the canteen has enough ingredients to prepare all the ordered items. Find the smallest possible total price they have to pay or determine that it is impossible to prepare $N$ items. ------ 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 six space-separated integers $N$, $E$, $H$, $A$, $B$ and $C$. ------ Output ------ For each test case, print a single line containing one integer ― the minimum cost of $N$ items, or $-1$ if it is impossible to prepare $N$ items. ------ Constraints ------ $1 ≤ T ≤ 2 \cdot 10^{5}$ $1 ≤ N ≤ 10^{6}$ $0 ≤ E, H ≤ 10^{6}$ $1 ≤ A, B, C ≤ 10^{6}$ the sum of $N$ over all test cases does not exceed $10^{6}$ ------ Subtasks ------ Subtask #1 (30 points): $1 ≤ N ≤ 100$ Subtask #2 (70 points): original constraints ----- Sample Input 1 ------ 3 5 4 4 2 2 2 4 5 5 1 2 3 4 5 5 3 2 1 ----- Sample Output 1 ------ -1 7 4 ----- explanation 1 ------ Example case 1: The maximum number of items that can be produced using $4$ eggs and $4$ chocolates is $4$, so the answer is $-1$. Example case 2: In the optimal solution, the friends should order $2$ omelettes, $1$ chocolate milkshake and $1$ chocolate cake, with cost $1 \cdot 2 + 2 \cdot 1 + 3 \cdot 1 = 7$. Example case 3: In the optimal solution, the friends should order $4$ chocolate cakes, with cost $1 \cdot 4 = 4$.
{"inputs": ["3\n5 4 4 2 2 2\n4 5 5 1 2 3\n4 5 5 3 2 1"], "outputs": ["-1\n7\n4"]}
667
53
coding
Solve the programming task below in a Python markdown code block. Flash has invited his nemesis The Turtle (He actually was a real villain! ) to play his favourite card game, SNAP. In this game a 52 card deck is dealt out so both Flash and the Turtle get 26 random cards. Each players cards will be represented by an array like below Flash’s pile: ```[ 'A', '5', 'Q', 'Q', '6', '2', 'A', '9', '10', '6', '4', '3', '10', '9', '3', '8', 'K', 'J', 'J', 'K', '7', '9', '5', 'J', '7', '2' ]``` Turtle’s pile: ```[ '8', 'A', '2', 'Q', 'K', '8', 'J', '6', '4', '8', '7', 'A', '5', 'K', '3', 'Q', '6', '9', '4', '3', '4', '10', '2', '7', '10', '5' ]``` The players take it in turn to take the top card from their deck (the first element in their array) and place it in a face up pile in the middle. Flash goes first. When a card is placed on the face up pile that matches the card it is placed on top of the first player to shout ‘SNAP!’ wins that round. Due to Flash's speed he wins every round. Face up pile in the middle: ```[ 'A', '8', '5', 'A', 'Q', '2', 'Q', 'Q',``` => SNAP! The face up pile of cards in the middle are added to the bottom of Flash's pile. Flash’s pile after one round: ```['6', '2', 'A', '9', '10', '6', '4', '3', '10', '9', '3', '8', 'K', 'J', 'J', 'K', '7', '9', '5', 'J', '7', '2', 'A', '8', '5', 'A', 'Q', '2', 'Q', 'Q' ]``` Flash then starts the next round by putting down the next card. When Turtle runs out of cards the game is over. How many times does Flash get to call Snap before Turtle runs out of cards? If both the player put down all their cards into the middle without any matches then the game ends a draw and Flash calls SNAP 0 times. Also feel free to reuse/extend the following starter code: ```python def snap(flash_pile, turtle_pile): ```
{"functional": "_inputs = [[['3', 'K', '5', 'A', '5', '6', '7', 'J', '7', '9', '10', 'Q', 'Q', '6', '8', '7', '4', 'J', '8', '9', 'K', 'J', '10', '4', 'K', '4'], ['2', '8', '9', 'Q', 'A', 'K', '6', '3', 'J', '2', '4', '3', '3', '8', 'A', '2', '6', '7', '9', '10', 'A', '5', 'Q', '10', '2', '5']], [['9', '5', '4', '4', 'A', '8', '4', '3', 'K', 'J', 'J', 'Q', 'Q', '9', '8', '5', 'J', '6', '7', '6', 'A', 'J', '9', 'K', '3', '8'], ['K', '10', '3', '4', '5', 'Q', '2', '7', 'A', 'A', 'Q', '10', '6', '5', 'K', '6', '7', '10', '2', '9', '2', '10', '7', '8', '2', '3']], [['3', '9', '8', '2', '6', 'Q', '9', '3', '6', '9', '6', 'A', '7', '10', '6', '7', 'A', 'Q', 'Q', '10', '5', '2', '9', '4', 'A', '3'], ['Q', 'K', '5', '7', '10', '4', '8', '2', '3', 'J', 'J', '5', '8', '5', '10', '8', 'K', 'K', '7', '2', 'J', '4', 'A', 'J', '4', 'K']], [['3', 'Q', '2', '4', '2', 'K', '7', '8', '6', 'K', '2', '4', '3', '8', 'A', '10', 'Q', '8', '10', 'J', 'K', '7', '6', '9', 'J', '9'], ['3', '4', '9', 'J', '5', '8', '4', '10', 'A', '7', 'Q', 'A', '9', '10', 'J', 'K', '2', 'Q', '3', '6', '5', '5', '5', 'A', '6', '7']], [['K', '5', '7', '10', '10', '10', '7', '3', '3', '9', '9', '8', '4', 'J', '6', 'J', 'Q', 'J', 'K', '9', '4', 'A', '5', '5', '2', 'J'], ['6', '4', '8', '3', '4', '10', '9', 'A', '5', 'Q', '2', 'K', 'A', '6', '2', '8', 'A', '7', '6', '7', 'Q', 'K', '8', '3', '2', 'Q']], [['8', '8', '4', '7', '7', 'A', '3', '4', '5', '2', 'J', '2', 'J', 'K', '7', 'K', 'J', '10', '5', 'A', '8', '3', '3', 'Q', '9', 'K'], ['6', '6', '5', 'A', 'A', 'Q', '6', '9', '6', '3', '10', '5', '10', '9', '8', '2', '10', '2', 'Q', 'J', '4', 'Q', '9', 'K', '4', '7']]]\n_outputs = [[2], [6], [0], [1], [2], [5]]\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(snap(*i), o[0])"}
594
1,128
coding
Solve the programming task below in a Python markdown code block. There are $n$ boxers, the weight of the $i$-th boxer is $a_i$. Each of them can change the weight by no more than $1$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number. It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique). Write a program that for given current values ​$a_i$ will find the maximum possible number of boxers in a team. It is possible that after some change the weight of some boxer is $150001$ (but no more). -----Input----- The first line contains an integer $n$ ($1 \le n \le 150000$) — the number of boxers. The next line contains $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ ($1 \le a_i \le 150000$) is the weight of the $i$-th boxer. -----Output----- Print a single integer — the maximum possible number of people in a team. -----Examples----- Input 4 3 2 4 1 Output 4 Input 6 1 1 1 4 4 4 Output 5 -----Note----- In the first example, boxers should not change their weights — you can just make a team out of all of them. In the second example, one boxer with a weight of $1$ can be increased by one (get the weight of $2$), one boxer with a weight of $4$ can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of $3$ and $5$, respectively). Thus, you can get a team consisting of boxers with weights of $5, 4, 3, 2, 1$.
{"inputs": ["1\n1\n", "1\n1\n", "1\n2\n", "1\n3\n", "1\n5\n", "2\n1 1\n", "2\n2 2\n", "2\n2 2\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "2\n", "2\n", "2\n"]}
440
92
coding
Solve the programming task below in a Python markdown code block. Read problems statements [Mandarin] , [Bengali] , [Hindi] , [Russian] and [Vietnamese] as well. Arya has a chessboard with $N$ rows (numbered $1$ through $N$) and $N$ columns (numbered $1$ through $N$); a square in row $r$ and column $c$ is denoted by $(r, c)$. Arya has already placed $K$ rooks on the chessboard in such a way that no two rooks attack each other. Note that two rooks attack each other if they are in the same row or in the same column and there is no rook between them. She is busy learning how to tame a dragon right now, so she asked you to place as many other rooks as possible on the chessboard in such a way that afterwards, no two rooks on the chessboard attack each other. Help Arya and choose the positions of these rooks. ------ Input ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. The first line of each test case contains two space-separated integers $N$ and $K$. Each of the next $K$ lines contains two space-separated integers $r$ and $c$ denoting that Arya placed a rook on the square $(r, c)$. ------ Output ------ For each test case: Let's assume that you placed $P$ rooks on squares $(r_{1}, c_{1}), (r_{2}, c_{2}), \ldots, (r_{P}, c_{P})$. You should print a single line containing $2P+1$ space-separated integers $P, r_{1}, c_{1}, \ldots, r_{P}, c_{P}$. $P$ must be maximum possible. If there are multiple possible answers, the sequence $r_{1}, c_{1}, \ldots, r_{P}, c_{P}$ should be lexicographically smallest. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 10^{6}$ $0 ≤ K ≤ N$ $1 ≤ r_{i}, c_{i} ≤ N$ for each valid $i$ no two initially placed rooks attack each other the positions of all initially placed rooks are pairwise distinct the sum of $N$ over all test cases does not exceed $10^{6}$ ------ Subtasks ------ Subtask #1 (10 points): $T = 10$ $N ≤ 8$ Subtask #2 (20 points): $T = 10$ $N ≤ 1,000$ Subtask #3 (70 points): original constraints ----- Sample Input 1 ------ 2 4 2 1 4 2 2 4 0 ----- Sample Output 1 ------ 2 3 1 4 3 4 1 1 2 2 3 3 4 4
{"inputs": ["2\n4 2\n1 4\n2 2\n4 0"], "outputs": ["2 3 1 4 3\n4 1 1 2 2 3 3 4 4"]}
679
54
coding
Solve the programming task below in a Python markdown code block. Note : This question carries $150$ $points$ There is an outcry in Middle Earth, as the greatest war between Orgs of Dark Lord Sauron and Frodo Baggins is about to begin. To end the war, Frodo decides to destroy the ring in the volcano of Mordor. There are many ships that lead Frodo to Mordor, and he is confused about which one he should board. Given two-ship numbers $M$ and $N$, Frodo has to solve a problem to find the ship which he should board. Find the number of pairs (x, y), such that $1<=x<=M$ and $1<=y<=N$, for which $x*y + x+ y = string(x)+string(y)$ is true. Also, calculate the number of distinct x satisfying the given condition. The number of pairs and the number of distinct x will help select Frodo the boat he should board. Help Frodo defeat Sauron. -----Input :----- - First line contains $T$ as number of test cases - Each test case contains two integers $M$ and $N$ -----Output :----- - For each test case, print two integers - the number of such pairs (x,y) and the number of distinct x -----Constraints :----- - 1 ≤ T ≤ 5000 - 1 ≤ M, N ≤ 10^9 -----Sample Input :----- 1 1 9 -----Sample Output :----- 1 1 -----Explanation :----- For test case two M=1 and N=9 Pair (1,9) satisfies the above condition 1*9+1+9= “19” and only x=1 satisfies the equation.
{"inputs": ["1\n1 9"], "outputs": ["1 1"]}
383
18
coding
Solve the programming task below in a Python markdown code block. ## Task Find the sum of the first `n` elements in the Recamán Sequence. Input range: ```python 1000 tests 0 <= n <= 2,500,000 ``` ___ ## Sequence The sequence is formed using the next formula: * We start with `0` * At each step `i`, we subtract `i` from the previous number * If the result is not negative, and not yet present in the sequence, it becomes the `i`th element of the sequence * Otherwise the `i`th element of the sequence will be previous number plus `i` The beginning of the sequence is `[0, 1, 3, 6, 2, ...]` because: 0) `0` <- we start with `0` 1) `1` <- `0 - 1` is negative, hence we choose `0 + 1` 2) `3` <- `1 - 2` is negative, hence we choose `1 + 2` 3) `6` <-`3 - 3` is not negative, but we already have a `0` in the sequence, hence we choose `3 + 3` 4) `2` <- `6 - 4` is positive, and is not present in the sequence yet, so we go for it ___ ## Examples ``` rec(0) == 0 rec(1) == 0 rec(2) == 1 rec(3) == 4 rec(4) == 10 rec(5) == 12 ``` Also feel free to reuse/extend the following starter code: ```python def rec(x): ```
{"functional": "_inputs = [[0], [1], [2], [5], [100], [200], [1000], [10000]]\n_outputs = [[0], [0], [1], [12], [7496], [36190], [837722], [82590002]]\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(rec(*i), o[0])"}
382
226
coding
Solve the programming task below in a Python markdown code block. You are given a string S of length N, which consists of digits from 0 to 9. You can apply the following operation to the string: Choose an integer L with 1≤ L ≤ N and apply S_{i} = (S_{i} + 1) \mod 10 for each 1 ≤ i ≤ L. For example, if S=39590, then choosing L=3 and applying the operation yields the string S=\underline{406}90. The prefix of string S of length l\;(1 ≤ l ≤ \mid S \mid ) is string S_{1} S_{2} \dots S_{l}. A prefix of length l is called good if S_{1}=0, S_{2}=0, \dots, S_{l}=0. Find the length of the longest good prefix that can be obtained in string S by applying the given operation maximum K times. ------ Input Format ------ - The first line of input contains an integer T, denoting the number of test cases. The T test cases then follow: - The first line of each test case contains two space-separated integers N, K. - The second line of each test case contains the string S. ------ Output Format ------ For each test case, output in a single line the length of the longest good prefix that can be obtained in string S by applying the given operation maximum K times. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ N ≤ 10^{5}$ $0 ≤ K ≤ 10^{9}$ $\mid S \mid = N$ $S$ contains digits from $0$ to $9$ - Sum of $N$ over all test cases does not exceed $3 \cdot 10^{5}$. ------ subtasks ------ Subtask 1 (100 points): Original constraints ----- Sample Input 1 ------ 6 3 5 380 3 9 380 4 2 0123 5 13 78712 6 10 051827 8 25 37159725 ----- Sample Output 1 ------ 0 3 1 3 2 5 ----- explanation 1 ------ Test case $1$: There is no way to obtain zeros on the prefix of the string $S = 380$ by applying the given operation maximum $5$ times. Test case $2$: The optimal strategy is: choose $L = 2$ and apply the operation twice, resulting in $S=500$, then choose $L = 1$ and apply the operation $5$ times, resulting in $S=000$. Test case $4$: One of the possible sequence of operations is the following: - Choose $L = 5$ and apply the operation thrice, resulting in $S=01045$. - Choose $L = 2$ and apply the operation $9$ times, resulting in $S=90045$. - Choose $L = 1$ and apply the operation once, resulting in $S=00045$.
{"inputs": ["6\n3 5\n380\n3 9\n380\n4 2\n0123\n5 13\n78712\n6 10\n051827\n8 25\n37159725\n\n"], "outputs": ["0\n3\n1\n3\n2\n5\n"]}
701
87
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.   Please complete the following python code precisely: ```python class Solution: def rangeBitwiseAnd(self, left: int, right: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(left = 5, right = 7) == 4\n assert candidate(left = 0, right = 0) == 0\n assert candidate(left = 1, right = 2147483647) == 0\n\n\ncheck(Solution().rangeBitwiseAnd)"}
81
81
coding
Solve the programming task below in a Python markdown code block. Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if: the Euclidean distance between A and B is one unit and neither A nor B is blocked; or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B. Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick? -----Input----- The first line contains an integer n (0 ≤ n ≤ 4·10^7). -----Output----- Print a single integer — the minimum number of points that should be blocked. -----Examples----- Input 1 Output 4 Input 2 Output 8 Input 3 Output 16
{"inputs": ["1\n", "2\n", "3\n", "4\n", "0\n", "5\n", "6\n", "7\n"], "outputs": ["4\n", "8\n", "16\n", "20\n", "1\n", "28\n", "32\n", "36\n"]}
268
75
coding
Solve the programming task below in a Python markdown code block. *This is the second Kata in the Ciphers series. This series is meant to test our coding knowledge.* ## Ciphers #2 - The reversed Cipher This is a lame method I use to write things such that my friends don't understand. It's still fairly readable if you think about it. ## How this cipher works First, you need to reverse the string. Then, the last character in the original string (the first character in the reversed string) needs to be moved to the back. Words will be separated by spaces, and punctuation marks can be counted as part of the word. ## Example This is because `"Hello"` reversed is `"olleH"` and `"o"` is moved to the back, and so on. The exclamation mark is considered to be part of the word `"World"`. Have fun (en)coding! Also feel free to reuse/extend the following starter code: ```python def encode(s): ```
{"functional": "_inputs = [['Hello World!']]\n_outputs = [['lleHo dlroW!']]\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(encode(*i), o[0])"}
206
161
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return the maximum length of a subarray with positive product.   Please complete the following python code precisely: ```python class Solution: def getMaxLen(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,-2,-3,4]) == 4\n assert candidate(nums = [0,1,-2,-3,-4]) == 3\n assert candidate(nums = [-1,-2,-3,0,1]) == 2\n\n\ncheck(Solution().getMaxLen)"}
106
78
coding
Solve the programming task below in a Python markdown code block. There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates. You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads. Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this? Constraints * 2 ≤ N ≤ 10^5 * 0 ≤ x_i,y_i ≤ 10^9 * All input values are integers. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_N y_N Output Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads. Examples Input 3 1 5 3 9 7 8 Output 3 Input 6 8 3 4 9 12 19 18 1 13 5 7 6 Output 8
{"inputs": ["3\n0 5\n3 9\n7 8", "3\n0 8\n3 9\n7 8", "3\n0 8\n3 9\n9 8", "3\n1 5\n3 9\n7 8", "3\n0 8\n3 9\n16 8", "3\n0 4\n3 9\n16 8", "3\n0 4\n3 9\n3 10", "3\n0 0\n22 26\n6 0"], "outputs": ["4\n", "1\n", "1\n", "3", "1\n", "4\n", "3\n", "16\n"]}
295
163
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an array of positive integers nums, return the number of distinct prime factors in the product of the elements of nums. Note that: A number greater than 1 is called prime if it is divisible by only 1 and itself. An integer val1 is a factor of another integer val2 if val2 / val1 is an integer.   Please complete the following python code precisely: ```python class Solution: def distinctPrimeFactors(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [2,4,3,7,10,6]) == 4\n assert candidate(nums = [2,4,8,16]) == 1\n\n\ncheck(Solution().distinctPrimeFactors)"}
118
62
coding
Solve the programming task below in a Python markdown code block. In this Kata, you will be given a lower case string and your task will be to remove `k` characters from that string using the following rule: ```Python - first remove all letter 'a', followed by letter 'b', then 'c', etc... - remove the leftmost character first. ``` ```Python For example: solve('abracadabra', 1) = 'bracadabra' # remove the leftmost 'a'. solve('abracadabra', 2) = 'brcadabra' # remove 2 'a' from the left. solve('abracadabra', 6) = 'rcdbr' # remove 5 'a', remove 1 'b' solve('abracadabra', 8) = 'rdr' solve('abracadabra',50) = '' ``` More examples in the test cases. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) Also feel free to reuse/extend the following starter code: ```python def solve(st,k): ```
{"functional": "_inputs = [['abracadabra', 0], ['abracadabra', 1], ['abracadabra', 2], ['abracadabra', 6], ['abracadabra', 8], ['abracadabra', 50], ['hxehmvkybeklnj', 5], ['cccaabababaccbc', 3], ['cccaabababaccbc', 9], ['u', 1], ['back', 3]]\n_outputs = [['abracadabra'], ['bracadabra'], ['brcadabra'], ['rcdbr'], ['rdr'], [''], ['xmvkyklnj'], ['cccbbabaccbc'], ['cccccc'], [''], ['k']]\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])"}
308
303
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.   Please complete the following python code precisely: ```python class Solution: def countSubstrings(self, s: str) -> int: ```
{"functional": "def check(candidate):\n assert candidate(s = \"abc\") == 3\n assert candidate(s = \"aaa\") == 6\n\n\ncheck(Solution().countSubstrings)"}
92
44
coding
Solve the programming task below in a Python markdown code block. For a given sequence $A = \\{a_0, a_1, ... a_{n-1}\\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program: bubbleSort(A) cnt = 0 // the number of inversions for i = 0 to A.length-1 for j = A.length-1 downto i+1 if A[j] < A[j-1] swap(A[j], A[j-1]) cnt++ return cnt For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded. Constraints * $ 1 \leq n \leq 200,000$ * $ 0 \leq a_i \leq 10^9$ * $a_i$ are all different Input In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters. Examples Input 5 3 5 2 1 4 Output 6 Input 3 3 1 2 Output 2
{"inputs": ["3\n6 1 2", "3\n6 1 0", "3\n6 2 0", "3\n6 2 1", "3\n6 2 2", "3\n6 0 1", "3\n1 0 0", "3\n1 0 1"], "outputs": ["2\n", "3\n", "3\n", "3\n", "2\n", "2\n", "2\n", "1\n"]}
326
110
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Russian] Chef has a sequence $A_{1}, A_{2}, \ldots, A_{N}$. In one operation, Chef can choose one index $i$ ($1 ≤ i ≤ N$) and change $A_{i}$ to $A_{i}^{p}$, where $p = \max(0, {\lceil \frac{A_{i}}{2} \rceil} - 1)$. Help Chef find the smallest number of operations needed to make the sum of the sequence even or determine that it is impossible. ------ Input ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. The first line of each test case contains a single integer $N$. The second line contains $N$ space-separated integers $A_{1}, A_{2}, \ldots, A_{N}$. ------ Output ------ For each test case, print a single line containing one integer — the minimum number of operations needed to make the sum of the sequence even, or $-1$ if it is impossible. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N ≤ 10^{5}$ $1 ≤ A_{i} ≤ 10^{9}$ for each valid $i$ ------ Subtasks ------ Subtask #1 (30 points): $N ≤ 100$ $1 ≤ A_{i} ≤ 10$ for each valid $i$ Subtask #2 (70 points): original constraints ----- Sample Input 1 ------ 4 4 7 3 5 1 5 4 2 7 8 10 2 9 9 3 1 1 1 ----- Sample Output 1 ------ 0 1 0 -1 ----- explanation 1 ------ Example case 1: The sum of the sequence is $16$, which is already even. Example case 2: We can change $A_{2}$ to $1$, so that the sequence becomes $[4, 1, 7, 8, 10]$. The sum of this sequence is $30$, which is even. Example case 3: The sum of the sequence is $18$, which is already even. Example case 4: It is impossible to make the sum of the sequence even.
{"inputs": ["4\n4\n7 3 5 1\n5\n4 2 7 8 10\n2\n9 9\n3\n1 1 1"], "outputs": ["0\n1\n0\n-1"]}
534
56
coding
Solve the programming task below in a Python markdown code block. A Professor of Physics gave projects to the students of his class. The students have to form a team of two for doing the project. The professor left the students to decide the teams. The number of students in a class will be even. Each student has a knowledge level. It tells how much knowledge each student has. The knowledge level of a team is the sum of the knowledge levels of both the students. The students decide to form groups such that the difference between the team with highest knowledge and the one with lowest knowledge is minimum. Input First line of the input will contain number of test cases t; In the next t lines the first number is n the number of students in the class followed by n integers denoting the knowledge levels of the n students Output Your output should be a single line containing the lowest possible difference between the team with highest knowledge and the one with lowest knowledge. SAMPLE INPUT 2 4 2 6 4 3 6 1 1 1 1 1 1 SAMPLE OUTPUT 1 0 Explanation Input Constraints are 1 ≤ t ≤ 100 1 ≤ n ≤ 100 1 ≤ knowledge level ≤ 10000
{"inputs": ["8\n4 2 6 4 3\n6 1 1 1 1 1 1\n8 4 2 4 2 1 3 3 7\n14 5 1 8 8 13 7 6 2 1 9 5 11 3 4\n50 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 1000 999 998 997 996 995 994 993 992 991 990 989 988 987 986 985 984 983 982 981 980 979 978 977 976\n50 7 9 1 3 7 9 5 6 4 9 3 4 2 1 3 6 5 3 6 5 7 1 7 7 4 996 999 1000 992 999 997 998 994 992 999 992 998 993 994 999 995 1000 1000 998 993 999 992 998 992 1000\n50 9 5 1 8 7 4 7 2 6 5 3 1 10 8 4 8 3 7 1 2 7 6 8 6 5 999 998 1000 1000 999 996 994 1000 993 999 993 993 993 993 997 997 995 991 991 992 999 992 998 994 994\n50 2 9 3 3 8 1 4 4 3 4 9 4 5 3 3 1 2 9 9 3 9 9 7 5 6 1000 1000 994 1000 993 993 999 992 993 993 993 994 994 996 992 998 997 992 992 995 1000 999 1000 995 993\n"], "outputs": ["1\n0\n2\n3\n0\n4\n2\n5\n\n"]}
264
746
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros. In one operation you can choose any subarray from initial and increment each value by one. Return the minimum number of operations to form a target array from initial. The test cases are generated so that the answer fits in a 32-bit integer.   Please complete the following python code precisely: ```python class Solution: def minNumberOperations(self, target: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(target = [1,2,3,2,1]) == 3\n assert candidate(target = [3,1,1,2]) == 4\n assert candidate(target = [3,1,5,4,2]) == 7\n assert candidate(target = [1,1,1,1]) == 1\n\n\ncheck(Solution().minNumberOperations)"}
125
96
coding
Solve the programming task below in a Python markdown code block. You are given a binary string S of length N. You can perform the following operation on S: Select an index i \ (1 ≤ i < |S|) such that S_{i}=S_{i+1}. Set S_{i} to 0 and remove S_{i+1} from the string. Note that after each operation, the length of S decreases by 1. Is it possible to reduce S to a single character by performing the mentioned operation exactly N-1 times? ------ Input Format ------ - The first line of input contains a single integer T denoting the number of test cases. The description of T test cases follows. - Each test case consists of two lines of input. - The first line of each test case contains a single integer N, the length of S. - The second line contains a binary string S of length N. ------ Output Format ------ For each test case, print the answer on a new line: YES if it is possible to perform the operation N-1 times, and NO otherwise. Each character of the output may be printed in either uppercase or lowercase, i.e, YES, yes, yEs and yES will all be treated as identical. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ N ≤ 2 \cdot 10^{5}$ - The sum of $N$ over all test cases doesn't exceed $2 \cdot 10^{5}$. ----- Sample Input 1 ------ 4 2 11 2 10 4 1100 3 101 ----- Sample Output 1 ------ YES NO YES NO ----- explanation 1 ------ Test case $1$: Perform the operation choosing $i = 1$. This sets $S_{1} = 0$ and deletes $S_{2}$ from the string, after which $S$ is now a single character. Test case $2$: It is not possible to perform any operation. Test case $3$: One sequence of operations is as follows: - Perform the operation on $i = 3$. Now, $S = 110$. - Perform the operation on $i = 1$. Now, $S = 00$. - Perform the operation on $i = 1$. Now, $S = 0$ and we are done. Test case $4$: It is not possible to perform any operation.
{"inputs": ["4\n2\n11\n2\n10\n4\n1100\n3\n101\n"], "outputs": ["YES\nNO\nYES\nNO\n"]}
526
43
coding
Solve the programming task below in a Python markdown code block. A prime number is number x which has only divisors as 1 and x itself. Harsh is playing a game with his friends, where his friends give him a few numbers claiming that they are divisors of some number x but divisor 1 and the number x itself are not being given as divisors. You need to help harsh find which number's divisors are given here. His friends can also give him wrong set of divisors as a trick question for which no number exists. Simply, We are given the divisors of a number x ( divisors except 1 and x itself ) , you have to print the number if only it is possible. You have to answer t queries. (USE LONG LONG TO PREVENT OVERFLOW) -----Input:----- - First line is T queires. - Next are T queries. - First line is N ( No of divisors except 1 and the number itself ) - Next line has N integers or basically the divisors. -----Output:----- Print the minimum possible x which has such divisors and print -1 if not possible. -----Constraints----- - 1<= T <= 30 - 1<= N <= 350 - 2<= Di <=10^6 -----Sample Input:----- 3 2 2 3 2 4 2 3 12 3 2 -----Sample Output:----- 6 8 -1 -----EXPLANATION:----- Query 1 : Divisors of 6 are ( 1,2,3,6) Therefore, Divisors except 1 and the number 6 itself are ( 2 , 3). Thus, ans = 6. Query 2 : Divisors of 8 are ( 1,2,4,8) Therefore, Divisors except 1 and the number 8 itself are ( 2 , 4). Thus, ans = 8. Query 3 : There is no such number x with only ( 1,2,3,12,x ) as the divisors.
{"inputs": ["3\n2\n2 3\n2\n4 2\n3\n12 3 2"], "outputs": ["6\n8\n-1"]}
440
38