diff --git a/.gitignore b/.gitignore index a9b278f..4971f1e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,6 @@ .idea/ logs/ hoareprompt-env/ -src/__pycache__ \ No newline at end of file +src/__pycache__ +src/postprocessing_neww.py +helper_runners/test_verify_yh.sh \ No newline at end of file diff --git a/configs/naive_test_qwen7.json b/configs/naive_test_qwen7.json new file mode 100644 index 0000000..aa45fff --- /dev/null +++ b/configs/naive_test_qwen7.json @@ -0,0 +1,13 @@ +{ + "model": "qwen2.5-7b-instruct", + "temperature": 1.0, + "assessment-mode": "naive-test", + "postcondition-mode": "hoarecot", + "postcondition-cot-prompt": "node-based-style", + "annotated_type" : "simple", + "loop-unrolling-count": 3, + "entailment-mode": "verify-answer", + "cex-mode": "with-postcondition", + "annotated" : false, + "fsl": false +} \ No newline at end of file diff --git a/configs/naive_test_qwen72.json b/configs/naive_test_qwen72.json new file mode 100644 index 0000000..e8e71c9 --- /dev/null +++ b/configs/naive_test_qwen72.json @@ -0,0 +1,13 @@ +{ + "model": "qwen2.5-72b-instruct", + "temperature": 1.0, + "assessment-mode": "naive-test", + "postcondition-mode": "hoarecot", + "postcondition-cot-prompt": "node-based-style", + "annotated_type" : "simple", + "loop-unrolling-count": 3, + "entailment-mode": "verify-answer", + "cex-mode": "with-postcondition", + "annotated" : false, + "fsl": false +} \ No newline at end of file diff --git a/helper runners/run_multiple.sh b/helper_runners/run_multiple.sh similarity index 100% rename from helper runners/run_multiple.sh rename to helper_runners/run_multiple.sh diff --git a/helper runners/run_multiple_help1.sh b/helper_runners/run_multiple_help1.sh similarity index 100% rename from helper runners/run_multiple_help1.sh rename to helper_runners/run_multiple_help1.sh diff --git a/helper runners/run_multiple_help2.sh b/helper_runners/run_multiple_help2.sh similarity index 100% rename from helper runners/run_multiple_help2.sh rename to helper_runners/run_multiple_help2.sh diff --git a/helper runners/run_multiple_help3.sh b/helper_runners/run_multiple_help3.sh similarity index 100% rename from helper runners/run_multiple_help3.sh rename to helper_runners/run_multiple_help3.sh diff --git a/helper runners/test.sh b/helper_runners/test.sh similarity index 100% rename from helper runners/test.sh rename to helper_runners/test.sh diff --git a/helper runners/test_confidence.sh b/helper_runners/test_confidence.sh similarity index 100% rename from helper runners/test_confidence.sh rename to helper_runners/test_confidence.sh diff --git a/helper runners/test_confidence_logprobs.sh b/helper_runners/test_confidence_logprobs.sh similarity index 100% rename from helper runners/test_confidence_logprobs.sh rename to helper_runners/test_confidence_logprobs.sh diff --git a/helper runners/test_fast.sh b/helper_runners/test_fast.sh similarity index 100% rename from helper runners/test_fast.sh rename to helper_runners/test_fast.sh diff --git a/helper runners/test_fast_75.sh b/helper_runners/test_fast_75.sh similarity index 100% rename from helper runners/test_fast_75.sh rename to helper_runners/test_fast_75.sh diff --git a/helper runners/test_verify.sh b/helper_runners/test_verify.sh similarity index 100% rename from helper runners/test_verify.sh rename to helper_runners/test_verify.sh diff --git a/helper runners/test_yihan.sh b/helper_runners/test_yihan.sh similarity index 100% rename from helper runners/test_yihan.sh rename to helper_runners/test_yihan.sh diff --git a/new_data/add_json.py b/new_data/add_json.py new file mode 100644 index 0000000..c44692c --- /dev/null +++ b/new_data/add_json.py @@ -0,0 +1,56 @@ +import json +import os + +def add_to_jsonl(num: int, alp: str, input_data: str, output_data: str) -> None: + """ + Append data to a specified JSONL file. + + Args: + num (int): Numeric part, used to generate the filename. + alp (str): Alphabetic part, used to generate the filename. + input_data (str): Value for the 'input' key in the JSON object. + output_data (str): Value for the 'output' key in the JSON object. + """ + filename = f"./test/{num}_{alp}.jsonl" + + # Create the data object to add + data = { + "input": input_data, + "output": output_data + } + + try: + # Write data to the file in append mode + with open(filename, 'a', encoding='utf-8') as f: + # Ensure non-ASCII characters (like Chinese) are written correctly + f.write(json.dumps(data, ensure_ascii=False) + '\n') + print(f"Successfully added data to {filename}") + except Exception as e: + print(f"Error while adding data: {e}") + +def get_multiline_input(prompt: str) -> str: + """Get multiline input from the user until an empty line is entered.""" + print(prompt) + lines = [] + while True: + line = input() + if line == '': # Empty line indicates end of input + break + lines.append(line) + # Join all lines with newline characters + return '\n'.join(lines) + +if __name__ == "__main__": + # Get input from keyboard + try: + num = int(input("Enter numeric part (num): ")) + alp = input("Enter alphabetic part (alp): ") + + input_data = get_multiline_input("Enter value for the 'input' field (finish with an empty line):") + output_data = get_multiline_input("Enter value for the 'output' field (finish with an empty line):") + + add_to_jsonl(num, alp, input_data, output_data) + except ValueError: + print("Error: Numeric part must be an integer.") + except Exception as e: + print(f"An unexpected error occurred: {e}") diff --git a/new_data/filtered_merged_cor.json b/new_data/filtered_merged_cor.json new file mode 100644 index 0000000..2d9f888 --- /dev/null +++ b/new_data/filtered_merged_cor.json @@ -0,0 +1,849 @@ +[ + { + "task_name": "1919_A", + "description": "Alice and Bob are bored, so they decide to play a game with their wallets.\nAlice has a coins in her wallet, while Bob has b coins in his wallet.\n\nBoth players take turns playing, with Alice making the first move. In each\nturn, the player will perform the following steps in order:\n\n 1. Choose to exchange wallets with their opponent, or to keep their current wallets. \n 2. Remove 1 coin from the player's current wallet. The current wallet cannot have 0 coins before performing this step. \n\nThe player who cannot make a valid move on their turn loses. If both Alice and\nBob play optimally, determine who will win the game.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 1000 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first and only line of each test case contains two integers a and b (1 \\le\na, b \\le 10^9 ) — the number of coins in Alice's and Bob's wallets,\nrespectively.\n\nOutput\n\nFor each test case, output \"Alice\" if Alice will win the game, and \"Bob\" if\nBob will win the game.\n\nExample\n\nInput\n\n 10\n \n 1 1\n \n 1 4\n \n 5 3\n \n 4 5\n \n 11 9\n \n 83 91\n \n 1032 9307\n \n 839204 7281\n \n 1000000000 1000000000\n \n 53110 2024\n\nOutput\n\n Bob\n Alice\n Bob\n Alice\n Bob\n Bob\n Alice\n Alice\n Bob\n Bob\n \nNote\n\nIn the first test case, an example of the game is shown below:\n\n * Alice chooses to not swap wallets with Bob in step 1 of her move. Now, a=0 and b=1 . \n * Since Alice's wallet is empty, Bob must choose to not swap their wallets in step 1 of his move. Now, a=0 and b=0 . \n * Since both Alice's and Bob's wallets are empty, Alice is unable to make a move. Hence, Bob wins. \n\nIn the second test case, an example of the game is shown below:\n\n * Alice chooses to swap wallets with Bob in step 1 of her move. Now, a=3 and b=1 . \n * Bob chooses to swap wallets with Alice in step 1 of his move. Now, a=1 and b=2 . \n * Alice chooses to not swap wallets with Bob in step 1 of her move. Now, a=0 and b=2 . \n * Since Alice's wallet is empty, Bob can only choose to not swap wallets with Alice in step 1 of his move. Now, a=0 and b=1 . \n * Since Alice's wallet is empty, Alice can only choose to swap wallets with Bob in step 1 of her move. Now, a=0 and b=0 . \n * Since both Alice's wallet and Bob's wallet are empty, Bob is unable to make a move. Hence, Alice wins.", + "generated_code": [ + "t = int(input())\n \nfor i in range(t):\n a,b= list(map(int,input().split(\" \")))\n \n if abs(a-b) %2 ==0:\n print(\"Bob\")\n else:\n print(\"Alice\")", + "t = int(input())\nfor i in range(t): \n s = input() \n a = int(list(s.split())[0])\n b = int(list(s.split())[1])\n \n if (a+b)%2==0:\n print(\"Bob\")\n else:\n print(\"Alice\")", + "test = int(input())\nfor t in range(test):\n a,b=map(int,input().split())\n if (a+b)&1==0:\n print(\"Bob\")\n else:\n print(\"Alice\")" + ] + }, + { + "task_name": "1919_B", + "description": "You are given a string s of length n consisting of characters \"+\" and \"-\". s\nrepresents an array a of length n defined by a_i=1 if s_i= \"+\" and a_i=-1 if\ns_i= \"-\".\n\nYou will do the following process to calculate your penalty:\n\n 1. Split a into non-empty arrays b_1,b_2,\\ldots,b_k such that b_1+b_2+\\ldots+b_k=a^\\dagger , where + denotes array concatenation. \n 2. The penalty of a single array is the absolute value of its sum multiplied by its length. In other words, for some array c of length m , its penalty is calculated as p(c)=|c_1+c_2+\\ldots+c_m| \\cdot m . \n 3. The total penalty that you will receive is p(b_1)+p(b_2)+\\ldots+p(b_k) . \n\nIf you perform the above process optimally, find the minimum possible penalty\nyou will receive.\n\n^\\dagger Some valid ways to split a=[3,1,4,1,5] into (b_1,b_2,\\ldots,b_k) are\n([3],[1],[4],[1],[5]) , ([3,1],[4,1,5]) and ([3,1,4,1,5]) while some invalid\nways to split a are ([3,1],[1,5]) , ([3],[\\,],[1,4],[1,5]) and ([3,4],[5,1,1])\n.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 1000 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 5000\n) — the length of string s .\n\nThe second line of each test case contains string s (s_i \\in \\\\{ \\mathtt{+},\n\\mathtt{-} \\\\} , |s| = n ).\n\nNote that there are no constraints on the sum of n over all test cases.\n\nOutput\n\nFor each test case, output a single integer representing the minimum possible\npenalty you will receive.\n\nExample\n\nInput\n\n 5\n \n 1\n \n +\n \n 5\n \n -----\n \n 6\n \n +-+-+-\n \n 10\n \n --+++++++-\n \n 20\n \n +---++++-+++++---++-\n\nOutput\n\n 1\n 5\n 0\n 4\n 4\n \nNote\n\nIn the first test case, we have a=[1] . We can split array a into ([1]) .\nThen, the sum of penalties of the subarrays is p([1]) = 1 .\n\nIn the second test case, we have a=[-1,-1,-1,-1,-1] . We can split array a\ninto ([-1],[-1],[-1],[-1],[-1]) . Then, the sum of penalties of the subarrays\nis p([-1]) + p([-1]) + p([-1]) + p([-1]) + p([-1]) = 1 + 1 + 1 + 1 + 1 = 5 .\n\nIn the third test case, we have a=[1,-1,1,-1,1,-1] . We can split array a into\n([1,-1,1,-1],[1,-1]) . Then, the sum of penalties of the subarrays is\np([1,-1,1,-1]) + p([1,-1]) = 0 + 0 = 0 .", + "generated_code": [ + "def solve(expression, length):\n count = 0\n \n for char in expression:\n if char == '+':\n count += 1\n sub = length-count\n return abs(sub-count)\n \nt = int(input())\n \nfor i in range(t):\n length = int(input())\n expression = input().strip()\n print(solve(expression, length))", + "def solve():\n\tn = int(input())\n\ts = input()\n\tneg = 0\n\tfor i in s:\n\t\tif i=='-':neg+=1\n\tprint(abs(n-2*neg) if n!=neg else n)\nt = int(input())\nwhile t:\n\tsolve()\n\tt-=1", + "for i in range(int(input())):\n s = int(input())\n e = input()\n P = 0\n M = 0\n for q in e:\n if q == '+':\n P += 1\n else:\n M += 1\n print(abs(P-M))" + ] + }, + { + "task_name": "1919_C", + "description": "You are given an array a of size n . You will do the following process to\ncalculate your penalty:\n\n 1. Split array a into two (possibly empty) subsequences^\\dagger s and t such that every element of a is either in s or t^\\ddagger . \n 2. For an array b of size m , define the penalty p(b) of an array b as the number of indices i between 1 and m - 1 where b_i < b_{i + 1} . \n 3. The total penalty you will receive is p(s) + p(t) . \n\nIf you perform the above process optimally, find the minimum possible penalty\nyou will receive.\n\n^\\dagger A sequence x is a subsequence of a sequence y if x can be obtained\nfrom y by the deletion of several (possibly, zero or all) elements.\n\n^\\ddagger Some valid ways to split array a=[3,1,4,1,5] into (s,t) are\n([3,4,1,5],[1]) , ([1,1],[3,4,5]) and ([\\,],[3,1,4,1,5]) while some invalid\nways to split a are ([3,4,5],[1]) , ([3,1,4,1],[1,5]) and ([1,3,4],[5,1]) .\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^4 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1\\le n\\le 2\\cdot\n10^5 ) — the size of the array a .\n\nThe second line contains n integers a_1, a_2, \\ldots, a_n (1 \\le a_i \\le n ) —\nthe elements of the array a .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2\\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single integer representing the minimum possible\npenalty you will receive.\n\nExample\n\nInput\n\n 5\n \n 5\n \n 1 2 3 4 5\n \n 8\n \n 8 2 3 1 1 7 4 3\n \n 5\n \n 3 3 3 3 3\n \n 1\n \n 1\n \n 2\n \n 2 1\n\nOutput\n\n 3\n 1\n 0\n 0\n 0\n \nNote\n\nIn the first test case, a possible way to split a is s=[2,4,5] and t=[1,3] .\nThe penalty is p(s)+p(t)=2 + 1 =3 .\n\nIn the second test case, a possible way to split a is s=[8,3,1] and\nt=[2,1,7,4,3] . The penalty is p(s)+p(t)=0 + 1 =1 .\n\nIn the third test case, a possible way to split a is s=[\\,] and t=[3,3,3,3,3]\n. The penalty is p(s)+p(t)=0 + 0 =0 .", + "generated_code": [ + "for _ in range (int(input())):\n n = int(input());\n lit = list(map(int, input().split()));\n a, b = [], [];\n cp = 0;\n for i in range (0, n):\n if len(a) == 0: \n x = float('inf');\n else:\n x = a[-1];\n if len(b) == 0: \n y = float('inf');\n else:\n y = b[-1];\n if x > y:\n if y >= lit[i]:\n b.append(lit[i]);\n else:\n if lit[i] > x:\n b.append(lit[i]);\n elif x >= lit[i] and lit[i] > y:\n a.append(lit[i]);\n elif x == y:\n a.append(lit[i]);\n elif x < y:\n if x >= lit[i]:\n a.append(lit[i]);\n else:\n if lit[i] > y:\n a.append(lit[i]);\n elif y >= lit[i] and lit[i] > x:\n b.append(lit[i]);\n s = 0;\n for i in range (1, len(a)):\n if a[i] > a[i-1]: s += 1;\n for i in range (1, len(b)):\n if b[i] > b[i-1]: s += 1;\n print (s);", + "def solve():\n\tpass\n\t\nt = int(input())\nwhile t:\n\tn = int(input())\n\t*inp, = map(int, input().split())\n\tla=lb=n+1\n\tans=0\n\tfor i in inp:\n\t\tif i<=la: la=i\n\t\telif i<=lb:lb=i\n\t\telse:la=lb;lb=i;ans+=1\n\tprint(ans)\n\tt-=1", + "for _ in range(int(input())):\n n=int(input())\n l=list(map(int,input().split()))\n a,b=float('inf'),float('inf')\n c=0\n \n for x in range(n):\n if a>b:\n a,b=b,a\n \n if l[x]<=a:\n a=l[x]\n elif l[x]<=b:\n b=l[x]\n else:\n a=l[x]\n c+=1\n \n print(c)" + ] + }, + { + "task_name": "1920_A", + "description": "Alex is solving a problem. He has n constraints on what the integer k can be.\nThere are three types of constraints:\n\n 1. k must be greater than or equal to some integer x ; \n 2. k must be less than or equal to some integer x ; \n 3. k must be not equal to some integer x . \n\nHelp Alex find the number of integers k that satisfy all n constraints. It is\nguaranteed that the answer is finite (there exists at least one constraint of\ntype 1 and at least one constraint of type 2 ). Also, it is guaranteed that no\ntwo constraints are the exact same.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 500 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (2 \\leq n \\leq\n100 ) — the number of constraints.\n\nThe following n lines describe the constraints. Each line contains two\nintegers a and x (a \\in \\\\{1,2,3\\\\}, \\, 1 \\leq x \\leq 10^9 ). a denotes the\ntype of constraint. If a=1 , k must be greater than or equal to x . If a=2 , k\nmust be less than or equal to x . If a=3 , k must be not equal to x .\n\nIt is guaranteed that there is a finite amount of integers satisfying all n\nconstraints (there exists at least one constraint of type 1 and at least one\nconstraint of type 2 ). It is also guaranteed that no two constraints are the\nexact same (in other words, all pairs (a, x) are distinct).\n\nOutput\n\nFor each test case, output a single integer — the number of integers k that\nsatisfy all n constraints.\n\nExample\n\nInput\n\n 6\n \n 4\n \n 1 3\n \n 2 10\n \n 3 1\n \n 3 5\n \n 2\n \n 1 5\n \n 2 4\n \n 10\n \n 3 6\n \n 3 7\n \n 1 2\n \n 1 7\n \n 3 100\n \n 3 44\n \n 2 100\n \n 2 98\n \n 1 3\n \n 3 99\n \n 6\n \n 1 5\n \n 2 10\n \n 1 9\n \n 2 2\n \n 3 2\n \n 3 9\n \n 5\n \n 1 1\n \n 2 2\n \n 3 1\n \n 3 2\n \n 3 3\n \n 6\n \n 1 10000\n \n 2 900000000\n \n 3 500000000\n \n 1 100000000\n \n 3 10000\n \n 3 900000001\n\nOutput\n\n 7\n 0\n 90\n 0\n 0\n 800000000\n \nNote\n\nIn the first test case, k \\geq 3 and k \\leq 10 . Furthermore, k \\neq 1 and k\n\\neq 5 . The possible integers k that satisfy the constraints are\n3,4,6,7,8,9,10 . So the answer is 7 .\n\nIn the second test case, k \\ge 5 and k \\le 4 , which is impossible. So the\nanswer is 0 .", + "generated_code": [ + "t = int(input())\nr = []\nfor _ in range(t):\n n = int(input())\n \n cx = set()\n ax = int(1e9 + 7)\n bx = -1\n for _ in range(n):\n a, x = map(int, input().split())\n if a == 1:\n bx = max(x, bx)\n elif a == 2:\n ax = min(x, ax)\n else:\n cx.add(x)\n \n if bx > ax:\n r.append(0)\n else:\n tmp = 0\n for i in cx:\n if i >= bx and i <= ax:\n tmp += 1\n r.append(ax - bx + 1 - tmp)\n \nprint(*r, sep=\"\\n\")", + "loop = int(input())\nfor iterable in range(loop):\n less = []\n big = []\n no = []\n num = 0\n innerLoop = int(input())\n for iterable2 in range(innerLoop):\n x , a = map(int ,input().split())\n if(x == 1):big.append(a)\n elif(x == 2):less.append(a)\n else:no.append(a)\n # for i in range(min(less) ,max(big) ,-1):\n # if(i not in no):\n # num = i\n # break\n num = min(less)-max(big)+1\n if num<1:\n print(0)\n continue\n for i in no:\n if i<=min(less) and i>=max(big):\n num-=1\n print(num)", + "import math\nimport re\n \ndef input_n(isOne=False):\n if not isOne: return int(input())\n else: return 1\ndef input_list(space=True, to_int = True):\n line = input()\n if space:\n items = line.split()\n else:\n items = list(line)\n \n if to_int:\n return [int(i) for i in items]\n else:\n return items\n \ndef list_to_string(arr, sym):\n string = \"\"\n for i in arr:\n string += str(i) + sym\n return string\n \n \ndef find_all_indices_string(string, substring):\n indices = []\n index = string.find(substring)\n while index != -1:\n indices.append(index)\n index = string.find(substring, index + 1)\n return indices\n \ndef find_all_indices_arr(arr, element):\n return [index for index, value in enumerate(arr) if value == element]\n \ndef find_arr_in_arr(arr, index, value):\n for subArray in arr:\n if subArray[index]==value:\n return subArray\n return None\n \n \ndef solve():\n n = int(input())\n start = -1\n end = int(1e9)\n num = []\n for i in range(n):\n t,v = tuple(map(int, input().split()))\n if t ==1:\n if start < v: start = v\n if t == 2:\n if end > v: end =v\n if t ==3: num.append(v)\n count_num = 0\n for i in num:\n if i < start or i > end: continue\n else: count_num+=1\n return end - start + 1 - count_num if start <= end else 0\n \n \n \nn = input_n()\nans = []\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\n \nfor i in range(n):\n ans.append(solve())\nfor i in ans:\n print(i)" + ] + }, + { + "task_name": "1920_B", + "description": "Alice and Bob are playing a game. They have an array a_1, a_2,\\ldots,a_n . The\ngame consists of two steps:\n\n * First, Alice will remove at most k elements from the array. \n * Second, Bob will multiply at most x elements of the array by -1 . \n\nAlice wants to maximize the sum of elements of the array while Bob wants to\nminimize it. Find the sum of elements of the array after the game if both\nplayers play optimally.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^4 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains three integers n , k , and x (1 \\leq\nn \\leq 2 \\cdot 10^5 , 1 \\leq x,k \\leq n ) — the number of elements in the\narray, the limit on the number of elements of the array that Alice can remove,\nand the limit on the number of elements of the array that Bob can multiply -1\nto.\n\nThe second line of each test case contains n integers a_1, a_2,\\ldots, a_n (1\n\\leq a_i \\leq 1000 ) — the elements of the array.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single integer — the sum of elements of the array\nafter the game if both players play optimally.\n\nExample\n\nInput\n\n 8\n \n 1 1 1\n \n 1\n \n 4 1 1\n \n 3 1 2 4\n \n 6 6 3\n \n 1 4 3 2 5 6\n \n 6 6 1\n \n 3 7 3 3 32 15\n \n 8 5 3\n \n 5 5 3 3 3 2 9 9\n \n 10 6 4\n \n 1 8 2 9 3 3 4 5 3 200\n \n 2 2 1\n \n 4 3\n \n 2 1 2\n \n 1 3\n\nOutput\n\n 0\n 2\n 0\n 3\n -5\n -9\n 0\n -1\n \nNote\n\nIn the first test case, it is optimal for Alice to remove the only element of\nthe array. Then, the sum of elements of the array is 0 after the game is over.\n\nIn the second test case, it is optimal for Alice to not remove any elements.\nBob will then multiply 4 by -1 . So the final sum of elements of the array is\n3+1+2-4=2 .\n\nIn the fifth test case, it is optimal for Alice to remove 9, 9 . Bob will then\nmultiply 5, 5, 3 by -1 . So the final sum of elements of the array is\n-5-5-3+3+3+2=-5 .", + "generated_code": [ + "for _ in range(int(input())):\n n,k,x = map(int,input().split())\n a = list(map(int,input().split()))\n a.sort()\n a.reverse()\n sum1 = sum(a)\n ans = []\n for i in range(k+1):\n if i==0:\n sums = sum1- 2*sum(a[:x])\n ans.append(sums)\n else:\n if i+x-1 int:\n cats_to_add = sum(1 for i in range(n) if s1[i] == '0' and s2[i] == '1')\n cats_to_remove = sum(1 for i in range(n) if s1[i] == '1' and s2[i] == '0')\n return max(cats_to_add, cats_to_remove)\n \n# Input and output handling\nt = int(input())\nfor _ in range(t):\n n = int(input())\n s1 = input()\n s2 = input()\n print(solution(n, s1, s2))", + "t = int(input())\n \nfor _ in range(t):\n n = int(input())\n s1 = input()\n s2 = input()\n \n hd = 0\n for i in range(n):\n if s1[i] != s2[i]: hd += 1\n res = abs(s1.count(\"1\") - s2.count(\"1\"))\n print(res + abs(hd - res) // 2)", + "for _ in range(int(input())):\n n=int(input())\n s=input()\n t=input()\n a=b=0\n for i in range(n):\n a+=s[i]>t[i]\n b+=s[i]0):\n n,f,a,b=map(int,input(\"\").split(\" \"))\n ls=[0]+list(map(int,input(\"\").split(\" \")))\n for i in range(1,n+1):\n f=f-min(a*(ls[i]-ls[i-1]),b)\n if(f>0):\n print(\"YES\")\n else:\n print(\"NO\")\n t-=1", + "test_cases=int(input())\nfor i in range (test_cases):\n feat=[int(i) for i in input(). split(' ')]\n n=feat[0]\n f=feat[1]\n a=feat[2]\n b=feat[-1]\n arr=[int(i) for i in input().split(' ')]\n array2=[]\n for i in range (0,n):\n if i==0:\n if arr[0] y1:\n y1 += 1\n x1 += 1\n else:\n y1 -= 1\n x1 += 1\n \n if y1 == y2:\n print(\"Alice\")\n return\n \n if y1 >= y2:\n a = y2 - 1\n else:\n a = m - y2\n \n b = x2 - x1\n t = abs(y2 - y1)\n x1 += a\n x2 -= a\n \n if x2 <= x1 or x1 < 1 or x2 > n:\n print(\"draw\")\n return\n \n if y2<=y1:\n y2 = 1\n y1 -= a\n c = y1 - 1\n else:\n y2 = m\n y1 += a\n c = m - y1\n \n if (b // 2) > a and abs(x2 - c) >= (x1 + c) and 1 <= y1 <= m and 1 <= x1 <= n:\n print(\"Alice\")\n return\n else:\n print(\"draw\")\n return\n \n else:\n if y1 == y2:\n print(\"bob\")\n return\n \n if y2 >= y1:\n a = y1 - 1\n else:\n a = m - y1\n \n b = x2 - x1\n t = abs(y2 - y1)\n x1 += a\n x2 -= a\n \n if x2 <= x1 or x1 < 1 or x2 > n:\n print(\"draw\")\n return\n \n if y1<=y2:\n y1 = 1\n y2 -= a\n c = y2 - 1\n else:\n y1 = m\n y2 += a\n c = m - y2\n \n if (b // 2) > a and abs(x2 - c) >= (x1 + c) and 1 <= y1 <= m and 1 <= x1 <= n:\n print(\"bob\")\n return\n else:\n print(\"draw\")\n return\n \n \ntt = int(input())\nfor _ in range(tt):\n pushp_()", + "t = int(input())\nfor _ in range(t):\n r,w,a,b,c,d = list(map(int,input().split()))\n if a>c:\n print(\"Draw\")\n else:\n x = abs(a-c) // 2\n if abs(a-c)%2:\n l = max(1,d-x)\n r = min(w,d+x)\n print(*(['Draw'],['Alice'])[abs(l-b)<=x+1 and abs(r-b)<=x+1])\n else:\n l = max(1,b-x)\n r = min(w,b+x)\n print(*(['Draw'],['Bob'])[abs(l-d)<=x and abs(r-d)<=x])\n \n \n# for i in range(int(input())):\n# h,w,xa,ya,xb,yb= map(int,input().split())\n \n# if xa>xb: print('Draw')\n# else:\n# x=abs(xa-xb)//2\n# if abs(xa-xb)%2:\n# l=max(1,yb-x)\n# r=min(w,yb+x)\n# # print('###',l,r,x,abs(xa-xb),abs(l-ya),abs(r-ya))\n# print(*(['Draw'],['Alice'])[abs(l-ya)<=x+1 and abs(r-ya)<=x+1])\n# else:\n# l=max(1,ya-x)\n# r=min(w,yb+x)\n# # print('@@@',l,r,x,abs(xa-xb),abs(l-yb),abs(r-yb))\n# print(*(['Draw'],['Bob'])[abs(l-yb)<=x and abs(r-yb)<=x])", + "test_cases = int(input())\nanswers = []\nfor i in range(test_cases):\n clues = list(map(int,input().split(\" \")))\n if clues[2] > clues[4] or clues[0]==1:\n answers.append(\"Draw\")\n elif(clues[2]%2==0 and clues[4]%2==0) or (clues[2]%2!=0 and clues[4]%2!=0):\n if clues[3] == clues[5]:\n answers.append(\"Bob\")\n elif clues[3] abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Bob\")\n elif clues[3]>clues[5]:\n if clues[1]-clues[5] > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Bob\")\n else:\n if clues[3] == clues[5]:\n answers.append(\"Alice\")\n elif abs(clues[3]-clues[5])==1:\n answers.append(\"Alice\")\n elif clues[3] abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Alice\")\n elif clues[3]>clues[5]:\n if clues[3]-1 > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Alice\")\nfor j in answers:\n print(j)" + ] + }, + { + "task_name": "1922_A", + "description": "You are given an integer n and three strings a, b, c , each consisting of n\nlowercase Latin letters.\n\nLet a template be a string t consisting of n lowercase and/or uppercase Latin\nletters. The string s matches the template t if the following conditions hold\nfor all i from 1 to n :\n\n * if the i -th letter of the template is lowercase, then s_i must be the same as t_i ; \n * if the i -th letter of the template is uppercase, then s_i must be different from the lowercase version of t_i . For example, if there is a letter 'A' in the template, you cannot use the letter 'a' in the corresponding position of the string. \n\nAccordingly, the string doesn't match the template if the condition doesn't\nhold for at least one i .\n\nDetermine whether there exists a template t such that the strings a and b\nmatch it, while the string c does not.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 1000 ) — the number of test\ncases.\n\nThe first line of each test case contains an integer n (1 \\le n \\le 20 ) — the\nlength of the given strings.\n\nThe next three lines contain the strings a, b and c . Each string consists of\nexactly n lowercase Latin letters.\n\nOutput\n\nFor each testcase, print \"YES\" if there exists a template t such that the\nstrings a and b match it, while the string c does not. Otherwise, print \"NO\".\n\nExample\n\nInput\n\n 4\n \n 1\n \n a\n \n b\n \n c\n \n 2\n \n aa\n \n bb\n \n aa\n \n 10\n \n mathforces\n \n luckforces\n \n adhoccoder\n \n 3\n \n acc\n \n abd\n \n abc\n\nOutput\n\n YES\n NO\n YES\n NO\n \nNote\n\nIn the first test case, you can use the template \"C\". The first letter of\nstrings a and b differ from 'c', so they match the template. The first letter\nof string c equals 'c', so it doesn't match.\n\nIn the third test case, you can use the template \"CODEforces\".", + "generated_code": [ + "def can_create_template(n, a, b, c):\n for i in range(n):\n if a[i] != c[i] and b[i] != c[i]:\n return \"YES\"\n return \"NO\"\n \ndef main():\n t = int(input().strip())\n results = []\n for _ in range(t):\n n = int(input().strip())\n a = input().strip()\n b = input().strip()\n c = input().strip()\n results.append(can_create_template(n, a, b, c))\n \n for result in results:\n print(result)\n \nif __name__ == \"__main__\":\n main()", + "tests = int(input())\nfor i in range(tests):\n slength = int(input())\n a = input()\n b = input()\n c = input()\n no = True\n if c == a or c == b:\n no = False\n print(\"NO\")\n else:\n counter = 0\n for x in c:\n if x not in a[counter] and x not in b[counter]:\n no = False\n print(\"YES\")\n break\n counter += 1\n if no:\n print(\"NO\")", + "def solve():\n t = int(input())\n for _ in range(t):\n n = int(input())\n a = input().strip()\n b = input().strip()\n c = input().strip()\n \n possible = False\n \n for i in range(n):\n if a[i] == b[i]:\n if c[i] != a[i]:\n possible = True\n break\n else:\n if c[i] == a[i] or c[i] == b[i]:\n continue\n else:\n possible = True\n break\n \n if possible:\n print(\"YES\")\n else:\n print(\"NO\")\n \nsolve()" + ] + }, + { + "task_name": "1922_B", + "description": "You have n sticks, numbered from 1 to n . The length of the i -th stick is\n2^{a_i} .\n\nYou want to choose exactly 3 sticks out of the given n sticks, and form a non-\ndegenerate triangle out of them, using the sticks as the sides of the\ntriangle. A triangle is called non-degenerate if its area is strictly greater\nthan 0 .\n\nYou have to calculate the number of ways to choose exactly 3 sticks so that a\ntriangle can be formed out of them. Note that the order of choosing sticks\ndoes not matter (for example, choosing the 1 -st, 2 -nd and 4 -th stick is the\nsame as choosing the 2 -nd, 4 -th and 1 -st stick).\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nEach test case consists of two lines:\n\n * the first line contains one integer n (1 \\le n \\le 3 \\cdot 10^5 ); \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_i \\le n ). \n\nAdditional constraint on the input: the sum of n over all test cases does not\nexceed 3 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print one integer — the number of ways to choose exactly 3\nsticks so that a triangle can be formed out of them.\n\nExample\n\nInput\n\n 4\n \n 7\n \n 1 1 1 1 1 1 1\n \n 4\n \n 3 2 1 3\n \n 3\n \n 1 2 3\n \n 1\n \n 1\n\nOutput\n\n 35\n 2\n 0\n 0\n \nNote\n\nIn the first test case of the example, any three sticks out of the given 7 can\nbe chosen.\n\nIn the second test case of the example, you can choose the 1 -st, 2 -nd and 4\n-th stick, or the 1 -st, 3 -rd and 4 -th stick.\n\nIn the third test case of the example, you cannot form a triangle out of the\ngiven sticks with lengths 2 , 4 and 8 .", + "generated_code": [ + "def main():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n idx = 0\n t = int(data[idx])\n idx += 1\n results = []\n \n for _ in range(t):\n n = int(data[idx])\n idx += 1\n \n v = [0] * (n + 1)\n for _ in range(n):\n x = int(data[idx])\n idx += 1\n v[x] += 1\n \n cnt = 0\n ans = 0\n for i in range(n + 1):\n if v[i] >= 2:\n ans += cnt * v[i] * (v[i] - 1) // 2\n if v[i] >= 3:\n ans += v[i] * (v[i] - 1) * (v[i] - 2) // 6\n cnt += v[i]\n \n results.append(str(ans))\n \n print(\"\\n\".join(results))\n \nif __name__ == \"__main__\":\n main()", + "t=int(input())\nbuffer=[]\nfor i in range(t):\n n=int(input())\n w=[int(k) for k in input().split()]\n if n>=3:\n q=[0 for j in range(n+1)]\n for j in range(n):\n q[w[j]]+=1\n eta=[]\n for j in range(n+1):\n if q[j]>0:\n eta.append(j)\n eta_ln=len(eta)\n rho=q[eta[0]]\n if eta_ln==1:\n print(n*(n-1)*(n-2)//6)\n else:\n res=q[eta[0]]*(q[eta[0]]-1)*(q[eta[0]]-2)//6\n for j in range(1, eta_ln):\n res+=q[eta[j]]*(q[eta[j]]-1)*(q[eta[j]]-2)//6\n res+=q[eta[j]]*(q[eta[j]]-1)//2*rho\n rho+=q[eta[j]]\n print(res)\n else:\n print(0)", + "def cntcmbn():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n current_index = 0\n t = int(data[current_index])\n current_index += 1\n \n results = []\n \n for _ in range(t):\n hashing = {}\n n = int(data[current_index])\n current_index += 1\n a = []\n for i in range(n):\n a.append(int(data[current_index]))\n current_index += 1\n \n a.sort()\n ans = 0\n for i in range(n - 1):\n if a[i] not in hashing:\n hashing[a[i]] = 0\n hashing[a[i]] += i\n if a[i] == a[i + 1]:\n ans += hashing[a[i]]\n \n results.append(ans)\n \n for result in results:\n print(result)\n \n \ncntcmbn()" + ] + }, + { + "task_name": "1922_C", + "description": "There are n cities located on the number line, the i -th city is in the point\na_i . The coordinates of the cities are given in ascending order, so a_1 < a_2\n< \\dots < a_n .\n\nThe distance between two cities x and y is equal to |a_x - a_y| .\n\nFor each city i , let's define the closest city j as the city such that the\ndistance between i and j is not greater than the distance between i and each\nother city k . For example, if the cities are located in points [0, 8, 12, 15,\n20] , then:\n\n * the closest city to the city 1 is the city 2 ; \n * the closest city to the city 2 is the city 3 ; \n * the closest city to the city 3 is the city 4 ; \n * the closest city to the city 4 is the city 3 ; \n * the closest city to the city 5 is the city 4 . \n\nThe cities are located in such a way that for every city, the closest city is\nunique. For example, it is impossible for the cities to be situated in points\n[1, 2, 3] , since this would mean that the city 2 has two closest cities (1\nand 3 , both having distance 1 ).\n\nYou can travel between cities. Suppose you are currently in the city x . Then\nyou can perform one of the following actions:\n\n * travel to any other city y , paying |a_x - a_y| coins; \n * travel to the city which is the closest to x , paying 1 coin. \n\nYou are given m queries. In each query, you will be given two cities, and you\nhave to calculate the minimum number of coins you have to spend to travel from\none city to the other city.\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nEach test case is given in the following format:\n\n * the first line contains one integer n (2 \\le n \\le 10^5 ); \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_1 < a_2 < \\dots < a_n \\le 10^9 ); \n * the third line contains one integer m (1 \\le m \\le 10^5 ); \n * then m lines follow; the i -th of them contains two integers x_i and y_i (1 \\le x_i, y_i \\le n ; x_i \\ne y_i ), denoting that in the i -th query, you have to calculate the minimum number of coins you have to spend to travel from the city x_i to the city y_i . \n\nAdditional constraints on the input:\n\n * in every test case, for each city, the closest city is determined uniquely; \n * the sum of n over all test cases does not exceed 10^5 ; \n * the sum of m over all test cases does not exceed 10^5 . \n\nOutput\n\nFor each query, print one integer — the minimum number of coins you have to\nspend.\n\nExample\n\nInput\n\n 1\n \n 5\n \n 0 8 12 15 20\n \n 5\n \n 1 4\n \n 1 5\n \n 3 4\n \n 3 2\n \n 5 1\n\nOutput\n\n 3\n 8\n 1\n 4\n 14\n \nNote\n\nLet's consider the first two queries in the example from the statement:\n\n * in the first query, you are initially in the city 1 . You can travel to the closest city (which is the city 2 ), paying 1 coin. Then you travel to the closest city (which is the city 3 ) again, paying 1 coin. Then you travel to the closest city (which is the city 4 ) again, paying 1 coin. In total, you spend 3 coins to get from the city 1 to the city 4 ; \n * in the second query, you can use the same way to get from the city 1 to the city 4 , and then spend 5 coins to travel from the city 4 to the city 5 .", + "generated_code": [ + "r=lambda : map(int,input().split())\nt,=r()\nwhile t:\n t-=1\n r()\n a=-1e9,*r(),2e9\n b=[0,0]\n # print(a)\n for w,x,y,z in zip(a,a[1:],a[2:],a[3:]):\n v=y-x\n b+=b[-2]+v**(v>(x-w)),b[-1]+v**(v>(z-y))\n # print(b,\"B\")\n u,=r()\n while u:\n u-=1\n c,d=r()\n # print(c,d)\n if cx:\n print(d1[y]-d1[x])\n else:\n print(d2[y]-d2[x])", + "t = int(input())\ndef go_through(cities, n):\n\tprog_cities = [0] * (n-1)\n\tfor i in range(n-1):\n\t\tback = -99999999999999999999\n\t\tforward = 999999999999999999\n\t\tif i > 0:\n\t\t\tback = cities[i-1]\n\t\tif i < n-1:\n\t\t\tforward = cities[i+1]\n\t\t\n\t\tif abs(forward - cities[i]) < abs(cities[i] - back):\n\t\t\tprog_cities[i] = 1\n\t\telse:\n\t\t\tprog_cities[i] = abs(forward - cities[i])\n\treturn prog_cities\n \nfor _ in range(t):\n\tn = int(input())\n\tcities = input().split()\n\tfor i in range(n):\n\t\tcities[i] = int(cities[i])\n\t\n\tforward_cities = go_through(cities, n)\n\tcities.reverse()\n\tbackward_cities = go_through(cities, n)\n \n\tpref_sum_f = [0]\n\tpref_sum_b = [0]\n \n\tfor i in range(n-1):\n\t\tpref_sum_f.append(pref_sum_f[i]+forward_cities[i])\n\t\tpref_sum_b.append(pref_sum_b[i]+backward_cities[i])\n \n \n\tpref_sum_b.reverse()\n \n\tm = int(input())\n \n\tfor i in range(m):\n\t\ta, b = input().split()\n\t\ta, b = int(a), int(b)\n \n\t\tif a < b:\n\t\t\tprint(pref_sum_f[b-1] - pref_sum_f[a-1])\n\t\t\n\t\telse:\n\t\t\tprint(pref_sum_b[b-1] - pref_sum_b[a-1])" + ] + }, + { + "task_name": "1923_A", + "description": "There is a ribbon divided into n cells, numbered from 1 to n from left to\nright. Each cell either contains a chip or is free.\n\nYou can perform the following operation any number of times (possibly zero):\nchoose a chip and move it to the closest free cell to the left. You can choose\nany chip that you want, provided that there is at least one free cell to the\nleft of it. When you move the chip, the cell where it was before the operation\nbecomes free.\n\nYour goal is to move the chips in such a way that they form a single block,\nwithout any free cells between them. What is the minimum number of operations\nyou have to perform?\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 1000 ) — the number of test\ncases.\n\nEach test case consists of two lines:\n\n * the first line contains one integer n (2 \\le n \\le 50 ) — the number of cells; \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_i \\le 1 ); a_i = 0 means that the i -th cell is free; a_i = 1 means that the i -th cell contains a chip. \n\nAdditional constraint on the input: in each test case, at least one cell\ncontains a chip.\n\nOutput\n\nFor each test case, print one integer — the minimum number of operations you\nhave to perform so that all chips form a single block without any free cells\nbetween them.\n\nExample\n\nInput\n\n 5\n \n 8\n \n 0 1 1 1 0 1 1 0\n \n 6\n \n 0 1 0 0 0 0\n \n 6\n \n 1 1 1 1 1 1\n \n 5\n \n 1 0 1 0 1\n \n 9\n \n 0 1 1 0 0 0 1 1 0\n\nOutput\n\n 1\n 0\n 0\n 2\n 3\n \nNote\n\nIn the first example, you can perform the operation on the chip in the 7 -th\ncell. The closest free cell to the left is the 5 -th cell, so it moves there.\nAfter that, all chips form a single block.\n\nIn the second example, all chips are already in a single block. Same for the\nthird example.", + "generated_code": [ + "t=int(input(\"\"))\nfor _ in range(t):\n n=int(input(\"\"))\n arr=\"\".join(input(\"\").split())\n x=arr.find(\"1\")\n y=(arr[::-1]).find(\"1\")\n z=arr[x:n-y]\n print(z.count(\"0\"))", + "t=int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int,input().split()))\n res = 0\n \n while a and a[0]== 0:\n a.pop(0)\n \n while a and a[-1] == 0:\n a.pop()\n \n for i in range(len(a)):\n if a[i]==0:\n res += 1 \n print(res)", + "t = int(input())\n \nfor _ in range(t):\n length = int(input())\n arrs = list(map(int, input().split()))\n \n sIdx = 0\n eIdx = length - 1\n \n \n while sIdx < length and arrs[sIdx] == 0:\n sIdx += 1\n \n while eIdx >= 0 and arrs[eIdx] == 0:\n eIdx -= 1\n \n cnt0 = 0\n \n for i in range(sIdx, eIdx + 1):\n if arrs[i] == 0:\n cnt0 += 1\n \n print(cnt0)" + ] + }, + { + "task_name": "1923_B", + "description": "You are playing a computer game. The current level of this game can be modeled\nas a straight line. Your character is in point 0 of this line. There are n\nmonsters trying to kill your character; the i -th monster has health equal to\na_i and is initially in the point x_i .\n\nEvery second, the following happens:\n\n * first, you fire up to k bullets at monsters. Each bullet targets exactly one monster and decreases its health by 1 . For each bullet, you choose its target arbitrary (for example, you can fire all bullets at one monster, fire all bullets at different monsters, or choose any other combination). Any monster can be targeted by a bullet, regardless of its position and any other factors; \n * then, all alive monsters with health 0 or less die; \n * then, all alive monsters move 1 point closer to you (monsters to the left of you increase their coordinates by 1 , monsters to the right of you decrease their coordinates by 1 ). If any monster reaches your character (moves to the point 0 ), you lose. \n\nCan you survive and kill all n monsters without letting any of them reach your\ncharacter?\n\nInput\n\nThe first line of the input contains one integer t (1 \\le t \\le 3 \\cdot 10^4 )\n— the number of test cases.\n\nEach test case consists of three lines:\n\n * the first line contains two integers n and k (1 \\le n \\le 3 \\cdot 10^5 ; 1 \\le k \\le 2 \\cdot 10^9 ); \n * the second line contains n integers a_1, a_2, \\dots, a_n (1 \\le a_i \\le 10^9 ); \n * the third line contains n integers x_1, x_2, \\dots, x_n (-n \\le x_1 < x_2 < x_3 < \\dots < x_n \\le n ; x_i \\ne 0 ). \n\nAdditional constraint on the input: the sum of n over all test cases does not\nexceed 3 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print YES if you can kill all n monsters before they reach\nyour character, or NO otherwise.\n\nYou can output each letter of the answer in any case (upper or lower). For\nexample, the strings yEs, yes, Yes, and YES will all be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 5\n \n 3 2\n \n 1 2 3\n \n -1 2 3\n \n 2 1\n \n 1 1\n \n -1 1\n \n 4 10\n \n 3 4 2 5\n \n -3 -2 1 3\n \n 5 3\n \n 2 1 3 2 5\n \n -3 -2 3 4 5\n \n 2 1\n \n 1 2\n \n 1 2\n\nOutput\n\n YES\n NO\n YES\n YES\n NO\n \nNote\n\nIn the first example, you can act as follows:\n\n * during the 1 -st second, fire 1 bullet at the 1 -st monster and 1 bullet at the 3 -rd monster. Then the 1 -st monster dies, the 2 -nd and the 3 -rd monster move closer; \n * during the 2 -nd second, fire 2 bullets at the 2 -nd monster. Then the 2 -nd monster dies, the 3 -rd monster moves closer; \n * during the 3 -rd second, fire 2 bullets at the 3 -rd monster. Then the 3 -rd monster dies. \n\nIn the second example, you can fire only 1 bullet, so you can kill only one of\nthe two monsters during the 1 -st second. Then, the remaining monster moves\ncloser and kills your character.", + "generated_code": [ + "def solve(a, x, k):\n n = len(a)\n sorted_indices = sorted(range(n), key=lambda i: abs(x[i]))\n \n distance = 0\n pos = 0\n while pos != len(sorted_indices):\n if abs(x[sorted_indices[pos]]) == distance:\n return False\n \n rest = k\n while rest != 0 and pos != len(sorted_indices):\n delta = min(rest, a[sorted_indices[pos]])\n rest -= delta\n a[sorted_indices[pos]] -= delta\n if a[sorted_indices[pos]] == 0:\n pos += 1\n \n distance += 1\n \n return True\n \ndef main():\n t = int(input())\n for _ in range(t):\n n, k = map(int, input().split())\n a = list(map(int, input().split()))\n x = list(map(int, input().split()))\n \n print(\"YES\" if solve(a, x, k) else \"NO\")\n \nif __name__ == \"__main__\":\n main()", + "def solve():\n t = int(input())\n for _ in range(t):\n n, k = map(int, input().split())\n a = list(map(int, input().split()))\n x = list(map(int, input().split()))\n \n # Combine the health and position into tuples, and sort by distance from 0.\n monsters = sorted(zip(x, a), key=lambda p: abs(p[0]))\n \n bullets_used = 0\n can_survive = True\n \n for pos, health in monsters:\n distance = abs(pos)\n # Total bullets needed by now\n total_bullets_needed = bullets_used + health\n \n # If the total bullets needed exceed the time available, we can't survive\n if total_bullets_needed > distance * k:\n can_survive = False\n break\n \n # Update the number of bullets used\n bullets_used += health\n \n print(\"YES\" if can_survive else \"NO\")\n \nif __name__ == \"__main__\":\n solve()" + ] + }, + { + "task_name": "1923_C", + "description": "An array a of length m is considered good if there exists an integer array b\nof length m such that the following conditions hold:\n\n 1. \\sum\\limits_{i=1}^{m} a_i = \\sum\\limits_{i=1}^{m} b_i ; \n 2. a_i \\neq b_i for every index i from 1 to m ; \n 3. b_i > 0 for every index i from 1 to m . \n\nYou are given an array c of length n . Each element of this array is greater\nthan 0 .\n\nYou have to answer q queries. During the i -th query, you have to determine\nwhether the subarray c_{l_{i}}, c_{l_{i}+1}, \\dots, c_{r_{i}} is good.\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThe first line of each test case contains two integers n and q (1 \\le n, q \\le\n3 \\cdot 10^5 ) — the length of the array c and the number of queries.\n\nThe second line of each test case contains n integers c_1, c_2, \\dots, c_n (1\n\\le c_i \\le 10^9 ).\n\nThen q lines follow. The i -th of them contains two integers l_i and r_i (1\n\\le l_i \\le r_i \\le n ) — the borders of the i -th subarray.\n\nAdditional constraints on the input: the sum of n over all test cases does not\nexceed 3 \\cdot 10^5 ; the sum of q over all test cases does not exceed 3 \\cdot\n10^5 .\n\nOutput\n\nFor each query, print YES if the subarray is good. Otherwise, print NO.\n\nYou can output each letter of the answer in any case (upper or lower). For\nexample, the strings yEs, yes, Yes, and YES will all be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 1\n \n 5 4\n \n 1 2 1 4 5\n \n 1 5\n \n 4 4\n \n 3 4\n \n 1 3\n\nOutput\n\n YES\n NO\n YES\n NO", + "generated_code": [ + "for _ in range(int(input())):\n n,m=map(int,input().split())\n l=list(map(int,input().split()))\n p=[0]\n c=[0]\n i,j=0,0\n \n for x in l:\n if x==1:\n j+=1\n i+=x\n \n p.append(i)\n c.append(j)\n \n for _ in range(m):\n a,b=map(int,input().split())\n i=c[b]-c[a-1]\n s=p[b]-p[a-1]\n \n if b-a+1>1 and s-(b-a+1)>=i:\n print('YES')\n else:\n print('NO')", + "from itertools import accumulate\ndef solve():\n n,q=map(int,input().split())\n a=[0]+[int(x) for x in input().split()]\n b=[0]*(n+1)\n for i in range(1,n+1):\n x = 1 if a[i]>1 else 2\n b[i]=b[i-1] + x\n a=list(accumulate(a))\n \n for _ in range(q):\n x,y=map(int,input().split())\n print(\"NO\") if a[y]-a[x-1]= n:\n print('YES')\n else:\n print('NO')\n tmp = ''\n for i in range(k):\n if cur & (1 << i) == 0:\n tmp = chr(ord('a')+i)\n break\n ans += tmp\n ans += 'a'*(n-cnt-1)\n print(ans)", + "def tandhif(s,k,n):\n s1=\"\"\n s2=\"\"\n alphabet={chr(i) for i in range(97,97+k)}\n for i in s:\n if i in alphabet:\n if len(alphabet)!=1:\n alphabet.remove(i) \n \n else:\n s2+=i\n alphabet={chr(i) for i in range(97,97+k)}\n s1+=i\n r=len(s1)//k\n return len(s1)>=n*k,s1[r*k:],s2\n \nt=int(input())\nOUT=[]\nfor _ in range(t):\n n,k,m=map(int,input().split())\n s=input()\n b,s1,s2=tandhif(s,k,n)\n if not b:\n OUT.append(\"No\")\n i=97\n while i<=k+97:\n if chr(i) not in s1:\n break\n i+=1\n be9i=chr(i)*(n-len(s2))\n OUT.append(s2+be9i)\n else:\n OUT.append(\"Yes\")\nfor i in OUT:\n print(i)", + "from collections import *\nfrom math import *\nfrom heapq import *\nimport sys\nfrom bisect import *\nfrom random import randint\nrrr = randint(8888,88888)\n \n \ndef sol():\n n,k,m = tuple(map(int,input().split()))\n \n s = input()\n us = set(chr(i+97) for i in range(k))\n win = set()\n ans = []\n ps = 0\n for i in s:\n if i in us:\n win.add(i)\n if len(win) == k:\n ans.append(i)\n ps += 1\n win.clear()\n \n # print(ps)\n if ps >= n:return print(\"YES\")\n \n print(\"NO\")\n \n for i in us:\n if i not in win:\n return print(\"\".join(ans)+i + (\"a\" * (n - len(ans) - 1)))\n \n \n \nfor _ in range(int(input())):\n sol()" + ] + }, + { + "task_name": "1925_A", + "description": "You are given two positive integers n and k .\n\nYour task is to find a string s such that all possible strings of length n\nthat can be formed using the first k lowercase English alphabets occur as a\nsubsequence of s .\n\nIf there are multiple answers, print the one with the smallest length. If\nthere are still multiple answers, you may print any of them.\n\nNote: A string a is called a subsequence of another string b if a can be\nobtained by deleting some (possibly zero) characters from b without changing\nthe order of the remaining characters.\n\nInput\n\nThe first line of input contains a single integer t (1\\leq t\\leq 676 )\ndenoting the number of test cases.\n\nEach test case consists of a single line of input containing two integers n\n(1\\leq n\\leq 26 ) and k (1\\leq k\\leq 26 ).\n\nOutput\n\nFor each test case, print a single line containing a single string s which\nsatisfies the above property. If there are multiple answers, print the one\nwith the smallest length. If there are still multiple answers, you may print\nany of them.\n\nExample\n\nInput\n\n 4\n \n 1 2\n \n 2 1\n \n 2 2\n \n 2 3\n\nOutput\n\n ab\n aa\n baab\n abcbac\n \nNote\n\nFor the first test case, there are two strings of length 1 which can be formed\nusing the first 2 lowercase English alphabets, and they are present in s as a\nsubsequence as follows:\n\n * \\texttt{a}: {\\color{red}{\\texttt{a}}}\\texttt{b} \n * \\texttt{b}: \\texttt{a}{\\color{red}{\\texttt{b}}} \n\nFor the second test case, there is only one string of length 2 which can be\nformed using the first lowercase English alphabet, and it is present in s as a\nsubsequence as follows:\n\n * \\texttt{aa}: {\\color{red}{\\texttt{aa}}} \n\nFor the third test case, there are 4 strings of length 2 which can be formed\nusing the first 2 lowercase English alphabets, and they are present in s as a\nsubsequence as follows:\n\n * \\texttt{aa}: \\texttt{b}{\\color{red}{\\texttt{aa}}}\\texttt{b} \n * \\texttt{ab}: \\texttt{ba}{\\color{red}{\\texttt{ab}}} \n * \\texttt{ba}: {\\color{red}{\\texttt{ba}}}\\texttt{ab} \n * \\texttt{bb}: {\\color{red}{\\texttt{b}}}\\texttt{aa}{\\color{red}{\\texttt{b}}} \n\nFor the fourth test case, there are 9 strings of length 2 which can be formed\nusing the first 3 lowercase English alphabets, and they are present in s as a\nsubsequence as follows:\n\n * \\texttt{aa}: {\\color{red}{\\texttt{a}}}\\texttt{bcb}{\\color{red}{\\texttt{a}}}\\texttt{c} \n * \\texttt{ab}: {\\color{red}{\\texttt{ab}}}\\texttt{cbac} \n * \\texttt{ac}: \\texttt{abcb}{\\color{red}{\\texttt{ac}}} \n * \\texttt{ba}: \\texttt{abc}{\\color{red}{\\texttt{ba}}}\\texttt{c} \n * \\texttt{bb}: \\texttt{a}{\\color{red}{\\texttt{b}}}\\texttt{c}{\\color{red}{\\texttt{b}}}\\texttt{ac} \n * \\texttt{bc}: \\texttt{a}{\\color{red}{\\texttt{bc}}}\\texttt{bac} \n * \\texttt{ca}: \\texttt{ab}{\\color{red}{\\texttt{c}}}\\texttt{b}{\\color{red}{\\texttt{a}}}\\texttt{c} \n * \\texttt{cb}: \\texttt{ab}{\\color{red}{\\texttt{cb}}}\\texttt{ac} \n * \\texttt{cc}: \\texttt{ab}{\\color{red}{\\texttt{c}}}\\texttt{ba}{\\color{red}{\\texttt{c}}}", + "generated_code": [ + "import collections\nfrom collections import Counter\nfrom collections import defaultdict\nimport math\nfrom math import log\n \ndef solve(): \n n,k=map(int, input().split())\n s='abcdefghijklmnopqrstuvwxyz'\n return s[:k]*(n)\nt = int(input())\nfor i in range(t):\n res = solve()\n print(res)", + "t=int(input())\nfor i in range(t):\n n,k=map(int,input().split())\n print('abcdefghijklmnopqrstuvwxyz'[:k]*n)" + ] + }, + { + "task_name": "1925_D", + "description": "There are n children in a class, m pairs among them are friends. The i -th\npair who are friends have a friendship value of f_i .\n\nThe teacher has to go for k excursions, and for each of the excursions she\nchooses a pair of children randomly, equiprobably and independently. If a pair\nof children who are friends is chosen, their friendship value increases by 1\nfor all subsequent excursions (the teacher can choose a pair of children more\nthan once). The friendship value of a pair who are not friends is considered 0\n, and it does not change for subsequent excursions.\n\nFind the expected value of the sum of friendship values of all k pairs chosen\nfor the excursions (at the time of being chosen). It can be shown that this\nanswer can always be expressed as a fraction \\dfrac{p}{q} where p and q are\ncoprime integers. Calculate p\\cdot q^{-1} \\bmod (10^9+7) .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 5 \\cdot 10^4 ). Description of the test cases\nfollows.\n\nThe first line of each test case contains 3 integers n , m and k (2 \\le n \\le\n10^5 , 0 \\le m \\le \\min \\Big(10^5 , \\frac{n(n-1)}{2} \\Big) , 1 \\le k \\le 2\n\\cdot 10^5 ) — the number of children, pairs of friends and excursions\nrespectively.\n\nThe next m lines contain three integers each — a_i , b_i , f_i — the indices\nof the pair of children who are friends and their friendship value. (a_i \\neq\nb_i , 1 \\le a_i,b_i \\le n , 1 \\le f_i \\le 10^9 ). It is guaranteed that all\npairs of friends are distinct.\n\nIt is guaranteed that the sum of n and sum m over all test cases does not\nexceed 10^5 and the sum of k over all test cases does not exceed 2 \\cdot 10^5\n.\n\nOutput\n\nFor each test case, print one integer — the answer to the problem.\n\nExample\n\nInput\n\n 4\n \n 100 0 24\n \n 2 1 10\n \n 1 2 1\n \n 3 1 2\n \n 2 1 1\n \n 5 2 4\n \n 1 2 25\n \n 3 2 24\n\nOutput\n\n 0\n 55\n 777777784\n 40000020\n \nNote\n\nFor the first test case, there are no pairs of friends, so the friendship\nvalue of all pairs is 0 and stays 0 for subsequent rounds, hence the\nfriendship value for all excursions is 0 .\n\nFor the second test case, there is only one pair possible (1, 2) and its\nfriendship value is initially 1 , so each turn they are picked and their\nfriendship value increases by 1 . Therefore, the total sum is 1+2+3+\\ldots+10\n= 55 .\n\nFor the third test case, the final answer is \\frac{7}{9} = 777\\,777\\,784\\bmod\n(10^9+7) .", + "generated_code": [ + "for i in range(int(input())):\n n,m,k=map(int,input().split())\n M=10**9+7\n c=pow(n*(n-1)//2,-1,M)\n s=0\n a=0\n for i in range(m):\n u,v,f=map(int,input().split())\n a+=f\n for i in range(k):\n s=s+c*i*c*m+c*a\n print(s%M)", + "import math\n \nt = int(input())\n \nM = 10 ** 9 + 7\n \nfor i in range(t):\n n, m, k = map(int, input().split())\n sum_f = 0\n for j in range(m):\n a, b, f = map(int, input().split())\n sum_f += f\n cn2 = n * (n - 1) // 2\n p = 2 * k * cn2 * sum_f + m * k * (k - 1)\n q = 2 * (cn2 ** 2)\n gcd = math.gcd(p, q)\n p = p // gcd\n q = q // gcd\n # print(p, q)\n print(int((p * pow(q, -1, M)) % M))", + "import math\n \nMOD = 1000000007\n \nT = int(input())\nfor _ in range(T):\n n, p, k = map(int,input().split())\n S = 0\n for i in range(p):\n S += int(input().split()[2]) # ignore the actual indices\n C = (n * (n - 1)) // 2\n num = p * k * k - p * k + 2 * k * C * S\n den = 2 * C * C\n \n g = math.gcd(num, den)\n num = num // g\n den = den // g\n den = pow(den, -1, MOD)\n ans = (num * den) % MOD\n print(ans)" + ] + }, + { + "task_name": "1926_A", + "description": "Vladislav has a string of length 5 , whose characters are each either\n\\texttt{A} or \\texttt{B} .\n\nWhich letter appears most frequently: \\texttt{A} or \\texttt{B} ?\n\nInput\n\nThe first line of the input contains an integer t (1 \\leq t \\leq 32 ) — the\nnumber of test cases.\n\nThe only line of each test case contains a string of length 5 consisting of\nletters \\texttt{A} and \\texttt{B} .\n\nAll t strings in a test are different (distinct).\n\nOutput\n\nFor each test case, output one letter (\\texttt{A} or \\texttt{B} ) denoting the\ncharacter that appears most frequently in the string.\n\nExample\n\nInput\n\n 8\n \n ABABB\n \n ABABA\n \n BBBAB\n \n AAAAA\n \n BBBBB\n \n BABAA\n \n AAAAB\n \n BAAAA\n\nOutput\n\n B\n A\n B\n A\n B\n A\n A\n A", + "generated_code": [ + "t=int(input())\nfor i in range(t):\n a=input()\n l=0\n h=0\n for j in a :\n if(j=='A'):\n l+=1\n else:\n h+=1\n if(l>h):\n print('A')\n else:\n print('B')", + "import math\nt = int(input())\nfor q in range(t) :\n ac = 0\n bc = 0\n s = input()\n for i in s :\n if i=='A':\n ac+=1\n else : bc+=1\n if ac>bc :\n print(\"A\")\n else : print(\"B\")" + ] + }, + { + "task_name": "1926_B", + "description": "Vladislav has a binary square grid of n \\times n cells. A triangle or a square\nis drawn on the grid with symbols \\texttt{1} . As he is too busy being cool,\nhe asks you to tell him which shape is drawn on the grid.\n\n * A triangle is a shape consisting of k (k>1 ) consecutive rows, where the i -th row has 2 \\cdot i-1 consecutive characters \\texttt{1} , and the central 1s are located in one column. An upside down triangle is also considered a valid triangle (but not rotated by 90 degrees).\n\n![](https://espresso.codeforces.com/6528b67bef9e7966366c8ff95b57ba96a1f44217.png)\nTwo left pictures contain examples of triangles: k=4 , k=3 . The two right\npictures don't contain triangles.\n\n * A square is a shape consisting of k (k>1 ) consecutive rows, where the i -th row has k consecutive characters \\texttt{1} , which are positioned at an equal distance from the left edge of the grid.\n\n![](https://espresso.codeforces.com/4b06bb9ff8f408edc96077ace0d5e299065a3c50.png)\nExamples of two squares: k=2 , k=4 .\n\nFor the given grid, determine the type of shape that is drawn on it.\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 100 ) — the number\nof test cases.\n\nThe first line of each test case contains a single integer n (2 \\leq n \\leq 10\n) — the size of the grid.\n\nThe next n lines each contain n characters \\texttt{0} or \\texttt{1} .\n\nThe grid contains exactly one triangle or exactly one square that contains all\nthe \\texttt{1} s in the grid. It is guaranteed that the size of the triangle\nor square is greater than 1 (i.e., the shape cannot consist of exactly one 1).\n\nOutput\n\nFor each test case, output \"SQUARE\" if all the \\texttt{1} s in the grid form a\nsquare, and \"TRIANGLE\" otherwise (without quotes).\n\nExample\n\nInput\n\n 6\n \n 3\n \n 000\n \n 011\n \n 011\n \n 4\n \n 0000\n \n 0000\n \n 0100\n \n 1110\n \n 2\n \n 11\n \n 11\n \n 5\n \n 00111\n \n 00010\n \n 00000\n \n 00000\n \n 00000\n \n 10\n \n 0000000000\n \n 0000000000\n \n 0000000000\n \n 0000000000\n \n 0000000000\n \n 1111111110\n \n 0111111100\n \n 0011111000\n \n 0001110000\n \n 0000100000\n \n 3\n \n 111\n \n 111\n \n 111\n\nOutput\n\n SQUARE\n TRIANGLE\n SQUARE\n TRIANGLE\n TRIANGLE\n SQUARE", + "generated_code": [ + "a=int(input())\nfor i in range(a):\n k=[]\n for _ in range(int(input())):\n b=input()\n if '1' in b:\n k.append(b.count('1'))\n if k[0]==k[1]:\n print(\"SQUARE\")\n else:\n print('TRIANGLE')", + "t=int(input())\nfor i in range(t):\n n=int(input())\n a=0\n b=''\n for j in range(n):\n s=input()\n if s.count(\"1\")==1:\n a='TRIANGLE'\n elif s.count(\"1\")>1:\n b='SQUARE'\n if a!=0:\n print(a)\n else:\n print(b)" + ] + }, + { + "task_name": "1926_C", + "description": "Please note that the time limit for this problem is only 0.5 seconds per test.\n\nVladislav wrote the integers from 1 to n , inclusive, on the board. Then he\nreplaced each integer with the sum of its digits.\n\nWhat is the sum of the numbers on the board now?\n\nFor example, if n=12 then initially the numbers on the board are:\n\nThen after the replacement, the numbers become:\n\nThe sum of these numbers is 1+2+3+4+5+6+7+8+9+1+2+3=51 . Thus, for n=12 the\nanswer is 51 .\n\nInput\n\nThe first line contains an integer t (1 \\leq t \\leq 10^4 ) — the number of\ntest cases.\n\nThe only line of each test case contains a single integer n (1 \\leq n \\leq 2\n\\cdot 10^5 ) — the largest number Vladislav writes.\n\nOutput\n\nFor each test case, output a single integer — the sum of the numbers at the\nend of the process.\n\nExample\n\nInput\n\n 7\n \n 12\n \n 1\n \n 2\n \n 3\n \n 1434\n \n 2024\n \n 200000\n\nOutput\n\n 51\n 1\n 3\n 6\n 18465\n 28170\n 4600002", + "generated_code": [ + "def convertNumber(num):\n a =0\n while num!=0:\n a = a+num%10\n num=int(num/10)\n return a\n \nA=[]\nsum =0\nfor i in range(1,200001):\n a=convertNumber(i)\n sum=sum+a\n A.append(sum)\n \n \nfor t in range(int(input())):\n n= int(input())\n print(A[n-1])", + "N = int(2 * 10e4) + 1\n \nt = int(input())\n \npd = [0 for _ in range(N)]\n \nfor i in range(1, N):\n pd[i] += pd[i - 1] \n for j in str(i):\n pd[i] += int(j)\n \nfor _ in range(t): \n n = int(input())\n print(pd[n])", + "def main():\n \n inf = 2 * (10 ** 5) + 1\n \n t = int(input())\n \n values = [0] * inf\n \n for i in range(1, inf):\n sum_value_digits = 0\n for x in str(i):\n sum_value_digits += int(x)\n values[i] = values[i - 1] + sum_value_digits\n \n for _ in range(t):\n value = int(input())\n print(values[value])\n \n \nmain()" + ] + }, + { + "task_name": "1926_D", + "description": "Vladislav has n non-negative integers, and he wants to divide all of them into\nseveral groups so that in any group, any pair of numbers does not have\nmatching bit values among bits from 1 -st to 31 -st bit (i.e., considering the\n31 least significant bits of the binary representation).\n\nFor an integer k , let k_2(i) denote the i -th bit in its binary\nrepresentation (from right to left, indexing from 1). For example, if k=43 ,\nsince 43=101011_2 , then 43_2(1)=1 , 43_2(2)=1 , 43_2(3)=0 , 43_2(4)=1 ,\n43_2(5)=0 , 43_2(6)=1 , 43_2(7)=0 , 43_2(8)=0, \\dots, 43_2(31)=0 .\n\nFormally, for any two numbers x and y in the same group, the condition x_2(i)\n\\neq y_2(i) must hold for all 1 \\leq i < 32 .\n\nWhat is the minimum number of groups Vlad needs to achieve his goal? Each\nnumber must fall into exactly one group.\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 10^4 ) — the number\nof test cases.\n\nThe first line of each test case contains a single integer n (1 \\leq n \\leq 2\n\\cdot 10^5 ) — the total number of integers.\n\nThe second line of each test case contains n given integers a_1, \\ldots, a_n\n(0 \\leq a_j < 2^{31} ).\n\nThe sum of n over all test cases in a test does not exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of groups\nrequired to satisfy the condition.\n\nExample\n\nInput\n\n 9\n \n 4\n \n 1 4 3 4\n \n 2\n \n 0 2147483647\n \n 5\n \n 476319172 261956880 2136179468 1671164475 1885526767\n \n 3\n \n 1335890506 811593141 1128223362\n \n 4\n \n 688873446 627404104 1520079543 1458610201\n \n 4\n \n 61545621 2085938026 1269342732 1430258575\n \n 4\n \n 0 0 2147483647 2147483647\n \n 3\n \n 0 0 2147483647\n \n 8\n \n 1858058912 289424735 1858058912 2024818580 1858058912 289424735 122665067 289424735\n\nOutput\n\n 4\n 1\n 3\n 2\n 2\n 3\n 2\n 2\n 4\n \nNote\n\nIn the first test case, any two numbers have the same last 31 bits, so we need\nto place each number in its own group.\n\nIn the second test case, a_1=0000000000000000000000000000000_2 ,\na_2=1111111111111111111111111111111_2 so they can be placed in the same group\nbecause a_1(i) \\ne a_2(i) for each i between 1 and 31 , inclusive.", + "generated_code": [ + "times = int(input())\ncheck = 2**31 -1\nfor _ in range(times):\n n = int(input())\n data = list(map(int,input().split()))\n dic = dict()\n ans = 0\n check = 2**31-1\n for i in data:\n s=i^check\n if i in dic:\n dic[i] -= 1\n if dic[i] == 0:\n del(dic[i])\n else:\n if s not in dic:\n dic[s] = 0\n dic[s] += 1\n ans += 1\n print(ans)", + "def solve(n,a):\n res =0\n count={}\n for num in a:\n if num not in count:\n count[((1 << 31) - 1) ^ num] = count.get(((1 << 31) - 1) ^ num, 0) + 1\n res+=1\n else:\n count[num] -= 1\n if count[num] == 0:\n del count[num]\n return res\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a= list(map(int,input().split()))\n print(solve(n,a))" + ] + }, + { + "task_name": "1926_E", + "description": "Vladislav has n cards numbered 1, 2, \\dots, n . He wants to lay them down in a\nrow as follows:\n\n * First, he lays down all the odd-numbered cards from smallest to largest. \n * Next, he lays down all cards that are twice an odd number from smallest to largest (i.e. 2 multiplied by an odd number). \n * Next, he lays down all cards that are 3 times an odd number from smallest to largest (i.e. 3 multiplied by an odd number). \n * Next, he lays down all cards that are 4 times an odd number from smallest to largest (i.e. 4 multiplied by an odd number). \n * And so on, until all cards are laid down. \n\nWhat is the k -th card he lays down in this process? Once Vladislav puts a\ncard down, he cannot use that card again.\n\nInput\n\nThe first line contains an integer t (1 \\leq t \\leq 5 \\cdot 10^4 ) — the\nnumber of test cases.\n\nThe only line of each test case contains two integers n and k (1 \\leq k \\leq n\n\\leq 10^9 ) — the number of cards Vlad has, and the position of the card you\nneed to output.\n\nOutput\n\nFor each test case, output a single integer — the k -th card Vladislav lays\ndown.\n\nExample\n\nInput\n\n 11\n \n 7 1\n \n 7 2\n \n 7 3\n \n 7 4\n \n 7 5\n \n 7 6\n \n 7 7\n \n 1 1\n \n 34 14\n \n 84 19\n \n 1000000000 1000000000\n\nOutput\n\n 1\n 3\n 5\n 7\n 2\n 6\n 4\n 1\n 27\n 37\n 536870912\n \nNote\n\nIn the first seven test cases, n=7 . Vladislav lays down the cards as follows:\n\n * First — all the odd-numbered cards in the order 1 , 3 , 5 , 7 . \n * Next — all cards that are twice an odd number in the order 2 , 6 . \n * Next, there are no remaining cards that are 3 times an odd number. (Vladislav has only one of each card.) \n * Next — all cards that are 4 times an odd number, and there is only one such card: 4 . \n * There are no more cards left, so Vladislav stops. \n\nThus the order of cards is 1 , 3 , 5 , 7 , 2 , 6 , 4 .", + "generated_code": [ + "for _ in range(int(input())):\n n, k = map(int, input().split())\n s = 0\n i = 0\n d = n\n h = n\n p = 1\n g = 0\n \n if k > (n + 1) // 2:\n while s < k and d > 0:\n s += (d + 1) // 2\n d -= (d + 1) // 2\n i += 1\n \n while p <= (i - 1):\n g += (h + 1) // 2\n h -= (h + 1) // 2\n p += 1\n \n f = k - g\n y = (2**(i-1)) *(2*f-1)\n print(y)\n else:\n print(2*k - 1)", + "t=int(input())\nfor _ in range(t):\n n,k=map(int,input().split())\n L=[]\n while n:\n m=(n+1)//2\n n-=m\n L.append(m)\n tot=0;pow=1\n for a in L:\n if tot k // 2:\n results.append(\"NO\")\n continue\n \n if len(only_b) > k // 2:\n results.append(\"NO\")\n continue\n \n total_distinct = len(only_a) + len(only_b) + len(both)\n if total_distinct < k:\n results.append(\"NO\")\n continue\n \n results.append(\"YES\")\n \n return results\n \n \n# Ввод данных\nt = int(input())\ncases = []\n \nfor _ in range(t):\n n, m, k = map(int, input().split())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n cases.append((n, m, k, a, b))\n \n# Получение результатов\nresults = can_choose(t, cases)\n \n# Вывод результатов\nfor result in results:\n print(result)", + "for t in range(int(input())):\n n,m,k=map(int,input().split())\n a=frozenset(map(int,input().split()))\n b=frozenset(map(int,input().split()))\n \n leftOnes=0\n aOnes=0\n bOnes=0\n newk=k//2\n i=1\n \n while i<=k:\n if i in a and i in b:\n leftOnes+=1\n elif i in a:\n aOnes+=1\n elif i in b:\n bOnes+=1\n else:\n break\n i+=1\n \n i=0\n while i 1 . In particular, this means\nthat the settling does not exist for k = 1 .\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 100 ) — the number of test cases. This is followed by\nthe description of the test cases.\n\nThe only line of each test case contains two integers n and x (1 \\le x < n \\le\n10^9 ) — Vasya's position in the line and the number Vasya received during the\nsettling.\n\nOutput\n\nFor each test case, output a single integer — the number of different k that\nfit under the given constraints.\n\nIt can be proven that under the given constraints, the answer is finite.\n\nExample\n\nInput\n\n 5\n \n 10 2\n \n 3 1\n \n 76 4\n \n 100 99\n \n 1000000000 500000000\n\nOutput\n\n 4\n 1\n 9\n 0\n 1\n \nNote\n\nIn the first test case, k equals 2, 3, 5, 6 are suitable.\n\nAn example of settling for these k :\n\nk / №| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 \n---|---|---|---|---|---|---|---|---|---|--- \n2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 \n3 | 1 | 2 | 3 | 2 | 1 | 2 | 3 | 2 | 1 | 2 \n5 | 1 | 2 | 3 | 4 | 5 | 4 | 3 | 2 | 1 | 2 \n6 | 1 | 2 | 3 | 4 | 5 | 6 | 5 | 4 | 3 | 2 \n \nIn the second test case, k = 2 is suitable.", + "generated_code": [ + "def sep_num(x):\n output1 = []\n output2 = []\n for i in range(1, int(x ** 0.5) + 1):\n if x % i == 0:\n output1.append(i)\n output2.append(int(x / i))\n output1.reverse()\n return output2 + output1\n \nt = int(input())\n \nfor i in range(t):\n n, x = map(int, input().split())\n output = []\n if (n + x - 2) % 2 == 0:\n sep = sep_num(n + x - 2)\n for s in sep:\n if (s + 2) % 2 == 0 and (s + 2) / 2 >= x:\n output.append((s + 2) / 2)\n if (n - x) % 2 == 0:\n sep = sep_num(n - x)\n for s in sep:\n if (s + 2) % 2 == 0 and (s + 2) / 2 >= x:\n output.append((s + 2) / 2)\n output = list(set(output))\n print(len(output))", + "def divisors(n):\n # get factors and their counts\n factors = {}\n nn = n\n i = 2\n while i*i <= nn:\n while nn % i == 0:\n factors[i] = factors.get(i, 0) + 1\n nn //= i\n i += 1\n if nn > 1:\n factors[nn] = factors.get(nn, 0) + 1\n \n primes = list(factors.keys())\n \n # generates factors from primes[k:] subset\n def generate(k):\n if k == len(primes):\n yield 1\n else:\n rest = generate(k+1)\n prime = primes[k]\n for factor in rest:\n prime_to_i = 1\n # prime_to_i iterates prime**i values, i being all possible exponents\n for _ in range(factors[prime] + 1):\n yield factor * prime_to_i\n prime_to_i *= prime\n \n # in python3, `yield from generate(0)` would also work\n for factor in generate(0):\n yield factor\n \nfor _ in range(int(input())):\n # n = int(input())\n n, x = map(int, input().split())\n # arr = list(map(int, input().split()))\n \n ans = 1\n \n h = n-x\n ans = set(k for k in divisors(h) if not k%2 and k/2+1 >= x) # divisors of h >= max(x, 2)\n \n # print(list(divisors(h)))\n \n ans2 = set()\n if x!=1:\n h = n + x-2\n ans2 = set(k for k in divisors(h) if not k%2 and k/2+1 >= x)\n \n # for f in sorted(ans):\n # print(f//2+1, end='\\t')\n # print()\n \n # print(sorted(ans))\n # print(sorted(ans2))\n ans = ans.union(ans2)\n print(len(ans))\n # print()", + "import math\ndef factors(q,x):\n M=[]\n w=math.sqrt(q)\n if w==w//1 and w>=x-1:\n M+=[w]\n i=1\n while i=x-1:\n M+=[i]\n if (q//i)>=x-1:\n M+=[q//i]\n i+=1\n return M\n \nt=int(input())\nfor _ in range(t):\n L=list(map(int, input().split()))\n n=L[0]\n x=L[1]\n ans=0\n y=(n+x)\n if y%2!=0:\n print(0)\n continue\n else:\n L1=factors((y-2)//2,x)\n if n>=3*x-2:\n L1+=factors((n-x)//2,x)\n L1=list(set(L1))\n print(len(L1))\n continue" + ] + }, + { + "task_name": "1929_A", + "description": "Sasha decided to give his girlfriend an array a_1, a_2, \\ldots, a_n . He found\nout that his girlfriend evaluates the beauty of the array as the sum of the\nvalues (a_i - a_{i - 1}) for all integers i from 2 to n .\n\nHelp Sasha and tell him the maximum beauty of the array a that he can obtain,\nif he can rearrange its elements in any way.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 500 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (2 \\leq n \\leq\n100 ) — the length of the array a .\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\leq a_i \\leq 10^9 ) — the elements of the array a .\n\nOutput\n\nFor each test case, output a single integer — the maximum beauty of the array\na that can be obtained.\n\nExample\n\nInput\n\n 5\n \n 3\n \n 2 1 3\n \n 3\n \n 69 69 69\n \n 5\n \n 100 54 80 43 90\n \n 4\n \n 3 4 3 3\n \n 2\n \n 2 1\n\nOutput\n\n 2\n 0\n 57\n 1\n 1\n \nNote\n\nIn the first test case, the elements of the array a can be rearranged to make\na = [1, 2, 3] . Then its beauty will be equal to (a_2 - a_1) + (a_3 - a_2) =\n(2 - 1) + (3 - 2) = 2 .\n\nIn the second test case, there is no need to rearrange the elements of the\narray a . Then its beauty will be equal to 0 .", + "generated_code": [ + "ntest=int(input())\nfor itest in range(0,ntest,1):\n n=int(input())\n a=list(map(int,input().split()))\n a.sort()\n print(a[len(a)-1]-a[0])", + "def max_beauty(array):\n # Sort the array to maximize the absolute differences between consecutive elements\n array.sort()\n # Calculate the maximum beauty by summing the differences between consecutive sorted elements\n beauty = 0\n for i in range(1, len(array)):\n beauty += abs(array[i] - array[i-1])\n return beauty\n \ndef main():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n t = int(data[0]) # Number of test cases\n index = 1\n results = []\n \n for _ in range(t):\n n = int(data[index]) # Length of the array\n index += 1\n array = list(map(int, data[index:index+n]))\n index += n\n \n # Calculate the maximum beauty for this array\n result = max_beauty(array)\n results.append(result)\n \n for result in results:\n print(result)\n \nif __name__ == \"__main__\":\n main()", + "for _ in range(int(input())):\n n = int(input())\n ar = list(sorted(list(map(int,input().split()))))\n print(sum([ar[i] -ar[i-1] for i in range(1, n)]))" + ] + }, + { + "task_name": "1930_A", + "description": "There are 2n positive integers written on a whiteboard. Being bored, you\ndecided to play a one-player game with the numbers on the whiteboard.\n\nYou start with a score of 0 . You will increase your score by performing the\nfollowing move exactly n times:\n\n * Choose two integers x and y that are written on the whiteboard. \n * Add \\min(x,y) to your score. \n * Erase x and y from the whiteboard. \n\nNote that after performing the move n times, there will be no more integers\nwritten on the whiteboard.\n\nFind the maximum final score you can achieve if you optimally perform the n\nmoves.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 5000 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\leq n \\leq 50\n) — the number of integers written on the whiteboard is 2n .\n\nThe second line of each test case contains 2n integers a_1,a_2,\\ldots,a_{2n}\n(1 \\leq a_i \\leq 10^7 ) — the numbers written on the whiteboard.\n\nOutput\n\nFor each test case, output the maximum final score that you can achieve.\n\nExample\n\nInput\n\n 3\n \n 1\n \n 2 3\n \n 2\n \n 1 1 2 1\n \n 3\n \n 1 1 1 1 1 1\n\nOutput\n\n 2\n 2\n 3\n \nNote\n\nIn the first test case, you can only make one move. You select x=2 and y=3 ,\nand your score will be \\min(x,y)=2 .\n\nIn the second test case, the following is a sequence of moves that achieves a\nfinal score of 2 :\n\n * In the first move, select x=1 and y=1 . Then, add \\min(x,y)=1 to the score. After erasing x and y , the integers left on the whiteboard are 1 and 2 . \n * In the second move, select x=1 and y=2 . Then, add \\min(x,y)=1 to the score. After removing x and y , no more integers will be left on the whiteboard. \n\nIt can be proved that it is not possible to get a score greater than 2 .\n\nIn the third test case, you will perform the move thrice, adding 1 to the\nscore each time.", + "generated_code": [ + "t = int(input())\nwhile(t):\n\tn = int(input())\n\tA = list(map(int, input().split()))\n\tA.sort()\n\tprint(sum(A[::2]))\n\tt = t - 1", + "for _ in range(int(input())):\n\tn = int(input())\n\tl = sorted(list(map(int, input().split())))\n\tscore = 0\n\tfor i in range(0,2*n,2):\n\t\tscore+=l[i]\n \n\tprint(score)", + "n=input()\nfinal=[]\nfor num in range(int(n)):\n s=0\n list2=[]\n a=input()\n list1=[]\n b=input()\n list1=b.split()\n for str in list1:\n list2.append(int(str))\n \n list2.sort()\n for i in range(0,len(list2),2):\n s=s+int(list2[i])\n \n \n final.append(s)\n \nfor fin in final:\n print(fin)" + ] + }, + { + "task_name": "1930_C", + "description": "Stack has an array a of length n . He also has an empty set S . Note that S is\nnot a multiset.\n\nHe will do the following three-step operation exactly n times:\n\n 1. Select an index i such that 1 \\leq i \\leq |a| . \n 2. Insert^\\dagger a_i + i into S . \n 3. Delete a_i from a . Note that the indices of all elements to the right of a_i will decrease by 1 . \n\nNote that after n operations, a will be empty.\n\nStack will now construct a new array b which is S sorted in decreasing order.\nFormally, b is an array of size |S| where b_i is the i -th largest element of\nS for all 1 \\leq i \\leq |S| .\n\nFind the lexicographically largest^\\ddagger b that Stack can make.\n\n^\\dagger A set can only contain unique elements. Inserting an element that is\nalready present in a set will not change the elements of the set.\n\n^\\ddagger An array p is lexicographically larger than a sequence q if and only\nif one of the following holds:\n\n * q is a prefix of p , but p \\ne q ; or \n * in the first position where p and q differ, the array p has a larger element than the corresponding element in q . \n\nNote that [3,1,4,1,5] is lexicographically larger than [3,1,3] , [\\,] , and\n[3,1,4,1] but not [3,1,4,1,5,9] , [3,1,4,1,5] , and [4] .\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^4 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\leq n \\leq 3\n\\cdot 10^5 ) — the length of array a .\n\nThe second line of each test case contains n integers a_1,a_2,\\ldots,a_{n} (1\n\\leq a_i \\leq 10^9 ) — the elements of array a .\n\nThe sum of n over all test cases does not exceed 3 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output the lexicographically largest b .\n\nExample\n\nInput\n\n 3\n \n 2\n \n 2 1\n \n 5\n \n 1 100 1000 1000000 1000000000\n \n 3\n \n 6 4 8\n\nOutput\n\n 3 2 \n 1000000005 1000004 1003 102 2 \n 11 7 6 \n \nNote\n\nIn the first test case, select i=1 in the first operation, insert a_1 + 1 = 3\nin S , and delete a_1 from a . After the first operation, a becomes a=[1] . In\nthe second operation, we select i=1 again and insert a_1 + 1 = 2 in S . Thus\nS=\\\\{2, 3\\\\} , and b = [3, 2] .\n\nNote that if you select i=2 in the first operation, and i=1 in the second\noperation, S=\\\\{3\\\\} as 3 will be inserted twice, resulting in b=[3] .\n\nAs [3,2] is lexicographically larger than [3] , we should select i=1 in the\nfirst operation.\n\nIn the second test case, in each operation, select the last element.", + "generated_code": [ + "from collections import Counter\n \ndef solve():\n n = int(input())\n a = list(map(int, input().split()))\n for i in range(n):\n a[i] += i+1\n counter = Counter(a)\n \n cur = 0\n a = list(set(a))\n a.sort(reverse=True)\n cnt = n-len(a)\n ans = []\n for i in range(len(a)):\n if i > 0:\n adv = min(a[i-1]-a[i]-1, cnt, cur)\n for j in range(adv):\n ans.append(a[i-1]-j-1)\n cnt -= adv\n cur -= adv\n ans.append(a[i])\n counter[a[i]] -= 1\n cur += counter[a[i]]\n \n for _ in range(cnt):\n ans.append(ans[-1]-1)\n \n print(*ans)\n \n \nt = int(input())\nfor _ in range(t):\n solve()", + "def solve() -> None:\n n = int(input())\n arr = list(map(sum, enumerate(map(int, input().split()), start=1)))\n arr.sort(reverse=True)\n ans = [arr[0]]\n for x in arr[1:]:\n if x >= ans[-1]:\n ans.append(ans[-1] - 1)\n else:\n ans.append(x)\n print(*ans)\n \n \nfor _ in range(int(input())):\n solve()" + ] + }, + { + "task_name": "1931_A", + "description": "Nikita had a word consisting of exactly 3 lowercase Latin letters. The letters\nin the Latin alphabet are numbered from 1 to 26 , where the letter \"a\" has the\nindex 1 , and the letter \"z\" has the index 26 .\n\nHe encoded this word as the sum of the positions of all the characters in the\nalphabet. For example, the word \"cat\" he would encode as the integer 3 + 1 +\n20 = 24 , because the letter \"c\" has the index 3 in the alphabet, the letter\n\"a\" has the index 1 , and the letter \"t\" has the index 20 .\n\nHowever, this encoding turned out to be ambiguous! For example, when encoding\nthe word \"ava\", the integer 1 + 22 + 1 = 24 is also obtained.\n\nDetermine the lexicographically smallest word of 3 letters that could have\nbeen encoded.\n\nA string a is lexicographically smaller than a string b if and only if one of\nthe following holds:\n\n * a is a prefix of b , but a \\ne b ;\n * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b .\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 100 ) —\nthe number of test cases in the test.\n\nThis is followed by the descriptions of the test cases.\n\nThe first and only line of each test case contains an integer n (3 \\le n \\le\n78 ) — the encoded word.\n\nOutput\n\nFor each test case, output the lexicographically smallest three-letter word\nthat could have been encoded on a separate line.\n\nExample\n\nInput\n\n 5\n \n 24\n \n 70\n \n 3\n \n 55\n \n 48\n\nOutput\n\n aav\n rzz\n aaa\n czz\n auz", + "generated_code": [ + "import string\n \nalphabet = string.ascii_lowercase\n \nfor i in range(int(input())):\n n = int(input())\n word = \"\"\n if n > 52:\n word += alphabet[n - 53] + \"zz\"\n elif n > 27:\n word += \"a\" + alphabet[n - 28] + \"z\"\n elif n == 27:\n word = \"aay\"\n else:\n word += \"aa\" + alphabet[n - 3]\n print(word)", + "cases=int(input())\ninfo=[]\nfor i in range(cases):\n arr=[]\n lex=int(input())\n for j in range(2):\n if(lex<28):\n arr.append(1)\n lex=lex-1\n elif(lex<52):\n arr.append(26)\n lex=lex-26\n elif(lex<=78):\n arr.append(26)\n lex=lex-26\n arr.append(lex)\n arr.sort()\n info.append(arr)\nfor i in range(cases):\n temp=''\n for j in range(3):\n temp=temp+chr(info[i][j]+96)\n print(temp)" + ] + }, + { + "task_name": "1931_D", + "description": "Polycarp has two favorite integers x and y (they can be equal), and he has\nfound an array a of length n .\n\nPolycarp considers a pair of indices \\langle i, j \\rangle (1 \\le i < j \\le n )\nbeautiful if:\n\n * a_i + a_j is divisible by x ; \n * a_i - a_j is divisible by y . \n\nFor example, if x=5 , y=2 , n=6 , a= [1, 2, 7, 4, 9, 6 ], then the only\nbeautiful pairs are:\n\n * \\langle 1, 5 \\rangle : a_1 + a_5 = 1 + 9 = 10 (10 is divisible by 5 ) and a_1 - a_5 = 1 - 9 = -8 (-8 is divisible by 2 ); \n * \\langle 4, 6 \\rangle : a_4 + a_6 = 4 + 6 = 10 (10 is divisible by 5 ) and a_4 - a_6 = 4 - 6 = -2 (-2 is divisible by 2 ). \n\nFind the number of beautiful pairs in the array a .\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. Then the descriptions of the test cases follow.\n\nThe first line of each test case contains three integers n , x , and y (2 \\le\nn \\le 2 \\cdot 10^5 , 1 \\le x, y \\le 10^9 ) — the size of the array and\nPolycarp's favorite integers.\n\nThe second line of each test case contains n integers a_1, a_2, \\dots, a_n (1\n\\le a_i \\le 10^9 ) — the elements of the array.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single integer — the number of beautiful pairs in\nthe array a .\n\nExample\n\nInput\n\n 7\n \n 6 5 2\n \n 1 2 7 4 9 6\n \n 7 9 5\n \n 1 10 15 3 8 12 15\n \n 9 4 10\n \n 14 10 2 2 11 11 13 5 6\n \n 9 5 6\n \n 10 7 6 7 9 7 7 10 10\n \n 9 6 2\n \n 4 9 7 1 2 2 13 3 15\n \n 9 2 3\n \n 14 6 1 15 12 15 8 2 15\n \n 10 5 7\n \n 13 3 3 2 12 11 3 7 13 14\n\nOutput\n\n 2\n 0\n 1\n 3\n 5\n 7\n 0", + "generated_code": [ + "def count_beautiful_pairs(test_cases):\n results = []\n \n for n, x, y, arr in test_cases:\n count = 0\n residue_map = {}\n \n for num in arr:\n # Calculate the required residues for the current number\n r_x = (-num) % x\n r_y = num % y\n \n # Count the pairs that satisfy both conditions\n count += residue_map.get((r_x, r_y), 0)\n \n # Update the residue map with the current number's residues\n current_key = (num % x, num % y)\n residue_map[current_key] = residue_map.get(current_key, 0) + 1\n \n results.append(count)\n \n return results\n \n \n# Input Reading\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \n# Parse input\nt = int(data[0])\nindex = 1\ntest_cases = []\n \nfor _ in range(t):\n n, x, y = map(int, data[index:index+3])\n index += 3\n arr = list(map(int, data[index:index+n]))\n index += n\n test_cases.append((n, x, y, arr))\n \n# Solve and output results\nresults = count_beautiful_pairs(test_cases)\nprint(\"\\n\".join(map(str, results)))", + "def count_beautiful_pairs(test_cases):\n results = []\n \n for n, x, y, arr in test_cases:\n freq = {}\n count = 0\n \n for a in arr:\n # Calculate required remainders\n rx = (-a % x + x) % x # Required remainder for x\n ry = a % y # Required remainder for y\n \n # Count pairs matching the remainders\n if (rx, ry) in freq:\n count += freq[(rx, ry)]\n \n # Update frequency of current remainders\n current_pair = (a % x, a % y)\n if current_pair in freq:\n freq[current_pair] += 1\n else:\n freq[current_pair] = 1\n \n results.append(count)\n \n return results\n \n \n# Input and output handling\ndef main():\n import sys\n input = sys.stdin.read\n data = input().splitlines()\n \n t = int(data[0])\n test_cases = []\n idx = 1\n \n for _ in range(t):\n n, x, y = map(int, data[idx].split())\n arr = list(map(int, data[idx + 1].split()))\n test_cases.append((n, x, y, arr))\n idx += 2\n \n results = count_beautiful_pairs(test_cases)\n \n for result in results:\n print(result)\n \n \nif __name__ == \"__main__\":\n main()", + "# Note that this problem was helped by many Youtbers and classmates to help me solve and understand Python and this problem\n \nfrom collections import defaultdict\n \ndef count_beautiful_pairs(t, test_cases):\n results = []\n \n # Process each test case\n for case in test_cases:\n n, x, y = case['params']\n a = case['array']\n \n # Dictionary \n freq = defaultdict(int)\n beautiful_count = 0\n \n # Define each part\n for num in a:\n mod_x = num % x\n mod_y = num % y\n \n # The requirements for this test\n required_mod_x = (x - mod_x) % x\n required_mod_y = mod_y\n \n # beauttiful pairs\n if (required_mod_x, required_mod_y) in freq:\n beautiful_count += freq[(required_mod_x, required_mod_y)]\n \n # mod,x and mod,y\n freq[(mod_x, mod_y)] += 1\n \n # Store the result test\n results.append(beautiful_count)\n \n return results\n \nt = int(input()) # Number of test cases\ntest_cases = []\n \nfor _ in range(t):\n n, x, y = map(int, input().split())\n a = list(map(int, input().split()))\n test_cases.append({'params': (n, x, y), 'array': a})\n \nresults = count_beautiful_pairs(t, test_cases)\n \n \nfor result in results:\n print(result)" + ] + }, + { + "task_name": "1931_E", + "description": "Sasha gave Anna a list a of n integers for Valentine's Day. Anna doesn't need\nthis list, so she suggests destroying it by playing a game.\n\nPlayers take turns. Sasha is a gentleman, so he gives Anna the right to make\nthe first move.\n\n * On her turn, Anna must choose an element a_i from the list and reverse the sequence of its digits. For example, if Anna chose the element with a value of 42 , it would become 24 ; if Anna chose the element with a value of 1580 , it would become 851 . Note that leading zeros are removed. After such a turn, the number of elements in the list does not change.\n * On his turn, Sasha must extract two elements a_i and a_j (i \\ne j ) from the list, concatenate them in any order and insert the result back into the list. For example, if Sasha chose the elements equal to 2007 and 19 , he would remove these two elements from the list and add the integer 200719 or 192007 . After such a turn, the number of elements in the list decreases by 1 .\n\nPlayers can't skip turns. The game ends when Sasha can't make a move, i.e.\nafter Anna's move there is exactly one number left in the list. If this\ninteger is not less than 10^m (i.e., \\ge 10^m ), Sasha wins. Otherwise, Anna\nwins.\n\nIt can be shown that the game will always end. Determine who will win if both\nplayers play optimally.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThen follows the description of the test cases.\n\nThe first line of each test case contains integers n , m (1 \\le n \\le 2 \\cdot\n10^5 , 0 \\le m \\le 2 \\cdot 10^6 ) — the number of integers in the list and the\nparameter determining when Sasha wins.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the list that Sasha gave to Anna.\n\nIt is guaranteed that the sum of n for all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output:\n\n * \"Sasha\", if Sasha wins with optimal play; \n * \"Anna\", if Anna wins with optimal play. \n\nExample\n\nInput\n\n 9\n \n 2 2\n \n 14 2\n \n 3 5\n \n 9 56 1\n \n 4 10\n \n 1 2007 800 1580\n \n 4 5\n \n 5000 123 30 4\n \n 10 10\n \n 6 4 6 2 3 1 10 9 10 7\n \n 1 1\n \n 6\n \n 1 1\n \n 10\n \n 8 9\n \n 1 2 9 10 10 2 10 2\n \n 4 5\n \n 10 10 10 10\n\nOutput\n\n Sasha\n Anna\n Anna\n Sasha\n Sasha\n Anna\n Anna\n Anna\n Sasha\n \nNote\n\nConsider the first test case.\n\nAnna can reverse the integer 2 , then Sasha can concatenate the integers 2 and\n14 , obtaining the integer 214 , which is greater than 10^2 = 100 . If Anna\nhad reversed the integer 14 , Sasha would have concatenated the integers 41\nand 2 , obtaining the integer 412 , which is greater than 10^2 = 100 . Anna\nhas no other possible moves, so she loses.", + "generated_code": [ + "def solve(n, m, nums):\n \n def zerocnts(num):\n num = str(num)\n tot = 0\n for i in range(len(num)-1,-1,-1):\n if num[i] != '0': break\n tot += 1\n return tot\n \n tot = sum(len(val) for val in map(str, nums))\n cntvals = sorted((zerocnts(val) for val in nums), reverse=True)\n for i in range(0, len(cntvals), 2): tot -= cntvals[i]\n \n return 'Sasha' if tot >= m+1 else 'Anna'\n \nfor _ in range(int(input())):\n n, m = map(int, input().split())\n nums = list(map(int, input().split()))\n \n print(solve(n, m, nums))", + "n_test = int(input())\n \nanswers = [None] * n_test\ndef count_zero(num):\n counter = 0\n for i in range(len(num)-1,-1,-1):\n if num[i] == \"0\":\n counter+=1\n else:\n break\n return counter\n \n \nfor test in range(n_test):\n \n n,m = tuple(map(int,input().split()))\n array = input().split()\n total_digits = 0\n zeros = []\n for item in array:\n total_digits += len(item)\n if count_zero(item)>0:\n zeros.append(count_zero(item))\n zeros = sorted(zeros,reverse=True)\n subtract_zero = 0\n for i in range(0,len(zeros),2):\n subtract_zero += zeros[i]\n if abs(total_digits-subtract_zero) >= m+1:\n answers[test] = \"Sasha\"\n else:\n answers[test] = \"Anna\"\n \n \nfor answer in answers:\n print(answer)", + "for y in range(int(input())):\n rev_res = ''\n list_len, max_power = input().split()\n operational_list = sorted(input().split(),key = lambda x : len(x.rstrip(\"0\")) - len(x))\n # print(operational_list)\n for x in range(int(list_len)):\n if x % 2 == 0:\n rev_res += operational_list[x].rstrip(\"0\")\n # print(\"Even\",rev_res)\n else:\n rev_res += operational_list[x]\n # print(\"Odd\",rev_res)\n \n \n if len(rev_res) >= int(max_power)+1:\n print('Sasha')\n else:\n print('Anna')" + ] + }, + { + "task_name": "1931_F", + "description": "There are n people in the programming contest chat. Chat participants are\nordered by activity, but each person sees himself at the top of the list.\n\nFor example, there are 4 participants in the chat, and their order is [2, 3,\n1, 4] . Then\n\n * 1 -st user sees the order [1, 2, 3, 4] . \n * 2 -nd user sees the order [2, 3, 1, 4] . \n * 3 -rd user sees the order [3, 2, 1, 4] . \n * 4 -th user sees the order [4, 2, 3, 1] . \n\nk people posted screenshots in the chat, which show the order of participants\nshown to this user. The screenshots were taken within a short period of time,\nand the order of participants has not changed.\n\nYour task is to determine whether there is a certain order that all\nscreenshots correspond to.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ninput test cases. The descriptions of test cases follow.\n\nThe first line of the description of each test case contains two integers n\nand k (1 \\le k \\le n \\le 2 \\cdot 10^5, n \\cdot k \\le 2 \\cdot 10^5 ) — the\nnumber of chat participants and the number of participants who posted\nscreenshots.\n\nThe following k lines contain descriptions of screenshots posted by the\nparticipants.\n\nThe i -th row contains n integers a_{ij} each (1 \\le a_{ij} \\le n , all a_{ij}\nare different) — the order of participants shown to the participant a_{i0} ,\nwhere a_{i0} — the author of the screenshot. You can show that in the\nscreenshot description it will always be at the top of the list.\n\nIt is guaranteed that the sum of n \\cdot k for all test cases does not exceed\n2 \\cdot 10^5 . It is also guaranteed that all the authors of the screenshots\nare different.\n\nOutput\n\nOutput t lines, each of which is the answer to the corresponding test case. As\nan answer, output \"YES\" if there exists at least one order of participants,\nunder which all k screenshots could have been obtained. Otherwise, output\n\"NO\".\n\nYou can output the answer in any case (upper or lower). For example, the\nstrings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 10\n \n 5 1\n \n 1 2 3 4 5\n \n 4 4\n \n 1 2 3 4\n \n 2 3 1 4\n \n 3 2 1 4\n \n 4 2 3 1\n \n 6 2\n \n 1 3 5 2 4 6\n \n 6 3 5 2 1 4\n \n 3 3\n \n 1 2 3\n \n 2 3 1\n \n 3 2 1\n \n 10 2\n \n 1 2 3 4 5 6 7 8 9 10\n \n 10 9 8 7 6 5 4 3 2 1\n \n 1 1\n \n 1\n \n 5 2\n \n 1 2 3 5 4\n \n 2 1 3 5 4\n \n 3 3\n \n 3 1 2\n \n 2 3 1\n \n 1 3 2\n \n 5 4\n \n 3 5 1 4 2\n \n 2 5 1 4 3\n \n 1 5 4 3 2\n \n 5 1 4 3 2\n \n 3 3\n \n 1 3 2\n \n 2 1 3\n \n 3 2 1\n\nOutput\n\n YES\n YES\n YES\n YES\n NO\n YES\n YES\n YES\n YES\n NO", + "generated_code": [ + "from heapq import *\n \nt = int(input())\n \n \nfor _ in range(t):\n n, m = map(int, input().split())\n if m == 1:\n input()\n print(\"yes\")\n continue\n a1, *l1 = map(int, input().split())\n a2, *l2 = map(int, input().split())\n l11 = [i for i in l1 if i != a2]\n l22 = [i for i in l2 if i != a1]\n if l11 != l22:\n for _ in range(m - 2):\n input()\n print(\"no\")\n continue\n idx1 = idx2 = -1\n p1 = p2 = 0\n for i in range(n - 1):\n if i + max(p1, p2) == n - 1:\n break\n if l1[i + p1] != l2[i + p2]:\n if l1[i + p1] == a2 and l2[i + p2] == a1:\n idx1 = idx2 = i\n break\n else:\n if l1[i + p1] == a2:\n idx1 = i\n p1 = 1\n else:\n idx2 = i\n p2 = 1\n if idx1 >= 0 and idx2 >= 0:\n break\n val = []\n if idx1 == -1 and idx2 != -1:\n idx1 = n - 2\n if idx2 == -1 and idx1 != -1:\n idx2 = n - 2\n if idx1 < idx2:\n l2.insert(idx1, a2)\n l = l2\n elif idx1 > idx2:\n l1.insert(idx2, a1)\n l = l1\n else:\n if m == 2:\n print(\"yes\")\n continue\n a3, *l3 = map(int, input().split())\n if l3.index(a1) < l3.index(a2):\n l1.insert(idx2, a1)\n l = l1\n else:\n l2.insert(idx1, a2)\n l = l2\n val.append((a3, l3))\n m -= 1\n for _ in range(m - 2):\n a3, *l3 = map(int, input().split())\n val.append((a3, l3))\n for a3, l3 in val:\n if l3 != [i for i in l if i != a3]:\n print(\"no\")\n break\n else:\n print(\"yes\")" + ] + }, + { + "task_name": "1932_A", + "description": "During your journey through computer universes, you stumbled upon a very\ninteresting world. It is a path with n consecutive cells, each of which can\neither be empty, contain thorns, or a coin. In one move, you can move one or\ntwo cells along the path, provided that the destination cell does not contain\nthorns (and belongs to the path). If you move to the cell with a coin, you\npick it up.\n\n![](https://espresso.codeforces.com/34bd88a4aba4a1ae98e5681455c4a47900b7b9a8.png)\nHere, green arrows correspond to legal moves, and the red arrow corresponds to\nan illegal move.\n\nYou want to collect as many coins as possible. Find the maximum number of\ncoins you can collect in the discovered world if you start in the leftmost\ncell of the path.\n\nInput\n\nThe first line of input contains a single integer t (1 \\le t \\le 1000 ) — the\nnumber of test cases. Then the descriptions of the test cases follow.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 50 )\n— the length of the path.\n\nThe second line of each test case contains a string of n characters, the\ndescription of the path. The character '.' denotes an empty cell, '@' denotes\na cell with a coin, and '*' denotes a cell with thorns. It is guaranteed that\nthe first cell is empty.\n\nOutput\n\nFor each test case, output a single integer, the maximum number of coins you\ncan collect.\n\nExample\n\nInput\n\n 3\n \n 10\n \n .@@*@.**@@\n \n 5\n \n .@@@@\n \n 15\n \n .@@..@***..@@@*\n\nOutput\n\n 3\n 4\n 3\n \nNote\n\nThe picture for the first example is in the problem statement.\n\nHere is the picture for the second example:\n\n![](https://espresso.codeforces.com/68fd7116585f37e79535fbc164a552cc8e148b75.png)\n\nAnd here is the picture for the third example:\n\n![](https://espresso.codeforces.com/1695fc45669a1bf1d6e1b3d4901cdd3cda38273c.png)", + "generated_code": [ + "class Solution:\n def Coins(self, n: int, s: str) -> int:\n res = 0\n i = 0\n while i < n:\n if s[i] == '@':\n res += 1\n if i + 1 < n and s[i + 1] != '*':\n i += 1\n elif i + 2 < n and s[i + 2] != '*':\n i += 2\n else:\n break\n return res\n \nsolution = Solution()\n \nt = int(input())\n \nfor _ in range(t):\n n = int(input())\n a = input()\n print(solution.Coins(n, a))", + "a = int(input())\ns = 0\n \nfor i in range(a):\n d = int(input()) \n b = input()\n for j in range(len(b)):\n if b[j] == '@':\n s = s+1\n elif b[j] == '*':\n if j==len(b) - 1:\n break\n elif b[j+1] == '*':\n break\n \n print(s)\n s = 0", + "for _ in range(int(input())):\n len = int(input())\n s = list(input())\n ret = 0\n thorn =0\n for i in s:\n if(i=='@'):\n thorn=0\n ret+=1\n elif(i=='*'):\n thorn+=1\n if(thorn==2):\n break\n \n else:\n thorn=0\n print(ret)" + ] + }, + { + "task_name": "1932_B", + "description": "The Chaya tribe believes that there are n signs of the apocalypse. Over time,\nit has been found out that the i -th sign occurs every a_i years (in years a_i\n, 2 \\cdot a_i , 3 \\cdot a_i , \\dots ).\n\nAccording to the legends, for the apocalypse to happen, the signs must occur\nsequentially. That is, first they wait for the first sign to occur, then\nstrictly after it, the second sign will occur, and so on. That is, if the i\n-th sign occurred in the year x , the tribe starts waiting for the occurrence\nof the (i+1) -th sign, starting from the year x+1 .\n\nIn which year will the n -th sign occur and the apocalypse will happen?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 1000 ) —\nthe number of test cases. Then follow the descriptions of the test cases.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 100\n) — the number of signs.\n\nThe second line of each test case contains n integers a_1, a_2, a_3, \\dots,\na_n (1 \\le a_i \\le 10^6 ) — the periodicities of the signs.\n\nOutput\n\nFor each test case, output a single integer — the year in which all n signs\nwill occur.\n\nExample\n\nInput\n\n 4\n \n 6\n \n 3 2 4 5 9 18\n \n 5\n \n 1 2 3 4 5\n \n 5\n \n 1 1 1 1 1\n \n 6\n \n 50 30 711 200 503 1006\n\nOutput\n\n 36\n 5\n 5\n 2012\n \nNote\n\nIn the first set of input data of the example:\n\n * The tribe will wait for the first sign in the 3 -rd year; \n * the tribe will wait for the second sign in the 4 -th year (since year 2 have already passed); \n * the tribe will wait for the third sign in the 8 -th year (since the second sign has already occurred in the 4 -th year); \n * the tribe will wait for the fourth sign in the 10 -th year (since year 5 have already passed); \n * the tribe will wait for the fifth sign in the 18 -th year (since year 9 have already passed); \n * the tribe will wait for the sixth sign in the 36 -th year (since the fifth sign has already occurred in the 18 -th year).", + "generated_code": [ + "def main():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n index = 0\n T = int(data[index])\n index += 1\n results = []\n \n for _ in range(T):\n n = int(data[index])\n index += 1\n a = list(map(int, data[index:index+n]))\n index += n\n \n # Start with the first sign\n last_year = a[0]\n \n # Process each subsequent sign\n for i in range(1, n):\n # Calculate the next possible year for the current sign\n # It must be greater than last_year\n next_year = ((last_year + 1 + a[i] - 1) // a[i]) * a[i]\n last_year = next_year\n \n # The year the last sign occurs is the answer for this test case\n results.append(str(last_year))\n \n # Output all results\n sys.stdout.write(\"\\n\".join(results) + \"\\n\")\n \nif __name__ == \"__main__\":\n main()", + "def apocalypse(t, test_cases):\n results = []\n for test in test_cases:\n n, a = test\n current_year = 0\n for ai in a:\n # Find the next year when the sign ai occurs\n if current_year % ai == 0:\n next_year = current_year + ai\n else:\n next_year = ((current_year // ai) + 1) * ai\n current_year = next_year\n results.append(current_year)\n return results\n \n# Read input\nt = int(input().strip())\ntest_cases = []\nfor _ in range(t):\n n = int(input().strip())\n a = list(map(int, input().strip().split()))\n test_cases.append((n, a))\n \n# Get results\nresults = apocalypse(t, test_cases)\n \n# Print results\nfor result in results:\n print(result)", + "num_tests = int(input())\n \nwhile num_tests > 0:\n num_tests -= 1\n \n n = int(input())\n nums = [int(x) for x in input().split(\" \")] \n \n start_year = 0\n for x in range(0, len(nums)):\n start_year = ((start_year)//nums[x] + 1)*(nums[x])\n print(start_year)" + ] + }, + { + "task_name": "1937_A", + "description": "You are given an array a_1, a_2, \\ldots, a_n . Initially, a_i=i for each 1 \\le\ni \\le n .\n\nThe operation \\texttt{swap}(k) for an integer k \\ge 2 is defined as follows:\n\n * Let d be the largest divisor^\\dagger of k which is not equal to k itself. Then swap the elements a_d and a_k . \n\nSuppose you perform \\texttt{swap}(i) for each i=2,3,\\ldots, n in this exact\norder. Find the position of 1 in the resulting array. In other words, find\nsuch j that a_j = 1 after performing these operations.\n\n^\\dagger An integer x is a divisor of y if there exists an integer z such that\ny = x \\cdot z .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 10^4 ). The description of the test cases follows.\n\nThe only line of each test case contains one integer n (1 \\le n \\le 10^9 ) —\nthe length of the array a .\n\nOutput\n\nFor each test case, output the position of 1 in the resulting array.\n\nExample\n\nInput\n\n 4\n \n 1\n \n 4\n \n 5\n \n 120240229\n\nOutput\n\n 1\n 4\n 4\n 67108864\n \nNote\n\nIn the first test case, the array is [1] and there are no operations\nperformed.\n\nIn the second test case, a changes as follows:\n\n * Initially, a is [1,2,3,4] . \n * After performing \\texttt{swap}(2) , a changes to [\\underline{2},\\underline{1},3,4] (the elements being swapped are underlined). \n * After performing \\texttt{swap}(3) , a changes to [\\underline{3},1,\\underline{2},4] . \n * After performing \\texttt{swap}(4) , a changes to [3,\\underline{4},2,\\underline{1}] . \n\nFinally, the element 1 lies on index 4 (that is, a_4 = 1 ). Thus, the answer\nis 4 .", + "generated_code": [ + "from math import log2\nn_cases = int(input())\n \nfor i in range(n_cases):\n n = int(input())\n if n == 1:\n print(1)\n else:\n power = 1\n n = log2(n)\n while power < n:\n power += 1\n \n if power == n:\n print(2 ** power)\n else:\n power -= 1\n print(2 ** power)" + ] + }, + { + "task_name": "1937_D", + "description": "There is a one-dimensional grid of length n . The i -th cell of the grid\ncontains a character s_i , which is either '<' or '>'.\n\nWhen a pinball is placed on one of the cells, it moves according to the\nfollowing rules:\n\n * If the pinball is on the i -th cell and s_i is '<', the pinball moves one cell to the left in the next second. If s_i is '>', it moves one cell to the right. \n * After the pinball has moved, the character s_i is inverted (i. e. if s_i used to be '<', it becomes '>', and vice versa). \n * The pinball stops moving when it leaves the grid: either from the left border or from the right one. \n\nYou need to answer n independent queries. In the i -th query, a pinball will\nbe placed on the i -th cell. Note that we always place a pinball on the\ninitial grid.\n\nFor each query, calculate how many seconds it takes the pinball to leave the\ngrid. It can be shown that the pinball will always leave the grid within a\nfinite number of steps.\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 10^5 ). The description of the test cases follows.\n\nThe first line of each test case contains an integer n (1 \\le n \\le 5 \\cdot\n10^5 ).\n\nThe second line of each test case contains a string s_1s_2 \\ldots s_{n} of\nlength n consisting of characters '<' and '>'.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 5 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, for each i (1 \\le i \\le n ) output the answer if a pinball\nis initially placed on the i -th cell.\n\nExample\n\nInput\n\n 3\n \n 3\n \n ><<\n \n 4\n \n <<<<\n \n 6\n \n <><<<>\n\nOutput\n\n 3 6 5 \n 1 2 3 4 \n 1 4 7 10 8 1 \n \nNote\n\nIn the first test case, the movement of the pinball for i=1 is shown in the\nfollowing pictures. It takes the pinball 3 seconds to leave the grid.\n\n![](https://espresso.codeforces.com/775b656d27e63ce8901e1ef80487972d536b4a54.png)\n\nThe movement of the pinball for i=2 is shown in the following pictures. It\ntakes the pinball 6 seconds to leave the grid.\n\n![](https://espresso.codeforces.com/515bd5576868cf33d4190893928faa21e69dd5c7.png)", + "generated_code": [ + "from itertools import accumulate\n \ndef last(arr, times):\n n = len(arr)\n return arr[-1] - arr[max(-n, -1-times)]\n \ndef solve(s1, n):\n pre = [i+1 for i,el in enumerate(s1) if el==\">\"]\n totalOne = len(pre)\n preOne = list(accumulate(pre, initial=0))\n suffZero = [0]\n \n ans = [0]*n\n for i in range(n-1, -1, -1):\n el = s1[i]\n if el == \">\":\n ## this is a one\n ol, zr = totalOne, len(suffZero) - 1\n if ol <= zr:\n ## exit on the left\n zeroInd = 2*last(suffZero, ol)\n oneInd = 2*preOne[-1] - last(preOne, 1)\n ans[i] = zeroInd - oneInd\n else:\n ## exit on the right\n zeroInd = 2*suffZero[-1]\n oneInd = last(preOne, zr) + last(preOne, zr+1)\n oneInd -= last(preOne, 1)\n fi = last(preOne, zr+1) - last(preOne, zr)\n ans[i] = zeroInd - oneInd + n+1 - fi\n preOne.pop()\n totalOne -= 1\n else:\n ## this is a zero\n suffZero.append(suffZero[-1] + i+1)\n ol, zr = totalOne, len(suffZero) - 1\n if zr <= ol:\n ## zr is atleast 1\n ## exit on the right\n zeroInd = suffZero[-1] + suffZero[-2]\n oneInd = 2*last(preOne, zr)\n ans[i] = zeroInd - oneInd + n+1\n else:\n ## exit on the left\n ## ol can be zero\n zeroInd = 2*last(suffZero, ol+1) - last(suffZero, 1)\n oneInd = 2*preOne[-1]\n ans[i] = zeroInd - oneInd\n \n print(*ans)\nfor case in range(int(input())):\n n = int(input())\n s1 = input()\n solve(s1, n)", + "t = int(input())\n \n \n \ndef solve(s):\n n = len(s)\n A = [] \n idx_A = []\n for i in range(0, n):\n if s[i] == '>':\n if (len(idx_A) == 0):\n A.append(0)\n else:\n x = A[len(A) - 1] + (i - idx_A[len(idx_A) - 1]) * len(idx_A)\n A.append(x)\n idx_A.append(i)\n B = []\n idx_B = []\n for j in range(0, n):\n i = n - 1 - j\n if s[i] == '<':\n if (len(idx_B) == 0):\n B.append(0)\n else:\n x = B[len(B) - 1] + (idx_B[len(B) - 1] - i) * len(idx_B)\n B.append(x)\n idx_B.append(i)\n l = 0\n r = len(B)\n \n \n for i in range(0, n):\n if (s[i] == '>'):\n if l < r:\n a = A[l]\n x = r - (l + 2)\n b = B[r - 1]\n if x >= 0:\n b = b - B[x]\n b = b - (idx_B[x] - idx_B[r - 1]) * (x + 1)\n b = b + (idx_B[r - 1] - i) * (l + 1)\n print(a * 2 + b * 2 + i + 1, end = \" \")\n else:\n if (r == 0):\n print(n - i, end = \" \")\n else:\n a = B[r - 1] + (idx_B[r - 1] - i) * r\n b = A[l - 1]\n if l - r > 0:\n b = b - A[l - r - 1]\n b = b - (idx_A[l - 1] - idx_A[l - r - 1]) * (l - r)\n b = b + (i - idx_A[l - 1]) * r\n print(a * 2 + b * 2 + (n - i), end = \" \")\n l += 1\n else:\n r -= 1\n if (l <= r):\n if (l == 0):\n print(i + 1, end = \" \")\n else:\n a = A[l - 1]\n a = a + (i - idx_A[l - 1]) * l\n b = B[r]\n if r - l >= 0:\n b = b - B[r - l]\n b = b - (idx_B[r - l] - i) * (r - l)\n b = b + (idx_B[r] - i) * l\n print(a * 2 + b * 2 + i + 1, end = \" \")\n else:\n if (r == 0):\n print((n - i) + (i - idx_A[l - 1]) * 2, end = \" \")\n else:\n a = B[r]\n b = A[l - 1]\n if l - r - 1 > 0:\n b = b - A[l - r - 2]\n b = b - (idx_A[l - 1] - idx_A[l - r - 2]) * (l - r - 1)\n b = b + (i - idx_A[l - 1]) * (r + 1)\n print(a * 2 + b * 2 + (n - i), end = \" \")\n \n \nfor i in range(0, t):\n n = int(input())\n s = input()\n solve(s)\n print()" + ] + }, + { + "task_name": "1941_B", + "description": "Rudolf has an array a of n integers, the elements are numbered from 1 to n .\n\nIn one operation, he can choose an index i (2 \\le i \\le n - 1 ) and assign:\n\n * a_{i - 1} = a_{i - 1} - 1 \n * a_i = a_i - 2 \n * a_{i + 1} = a_{i + 1} - 1 \n\nRudolf can apply this operation any number of times. Any index i can be used\nzero or more times.\n\nCan he make all the elements of the array equal to zero using this operation?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases in the test.\n\nThe first line of each case contains a single integer n (3 \\le n \\le 2 \\cdot\n10^5 ) — the number of elements in the array.\n\nThe second line of each case contains n integers a_1, a_2, \\dots, a_n (0 \\le\na_j \\le 10^9 ) — the elements of the array.\n\nIt is guaranteed that the sum of the values of n over all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output \"YES\" if it is possible to make all the elements of\nthe array zero using the described operations. Otherwise, output \"NO\".\n\nYou can output each letter in any case (lowercase or uppercase). For example,\nthe strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be accepted as a positive\nanswer.\n\nExample\n\nInput\n\n 7\n \n 5\n \n 1 3 5 5 2\n \n 5\n \n 2 4 4 5 1\n \n 5\n \n 0 1 3 3 1\n \n 6\n \n 5 6 0 2 3 0\n \n 4\n \n 1 2 7 2\n \n 3\n \n 7 1 0\n \n 4\n \n 1 1 1 1\n\nOutput\n\n YES\n NO\n YES\n NO\n NO\n NO\n NO\n \nNote\n\nIn the first example, the original array is [1, 3, 5, 5, 2] , to make all its\nelements zero, Rudolf can act as follows:\n\n * apply the operation at i=4 and get the array [1, 3, 4, 3, 1] ; \n * apply the operation at i=3 and get the array [1, 2, 2, 2, 1] ; \n * apply the operation at i=2 and get the array [0, 0, 1, 2, 1] ; \n * apply the operation at i=4 and get the array [0, 0, 0, 0, 0] .", + "generated_code": [ + "for _ in range(int(input())):\n a = int(input())\n b = list(map(int, input().split()))\n for i in range(0, a - 2):\n if b[i] < 0:\n print(\"NO\")\n break\n b[i + 1] -= b[i] * 2\n b[i + 2] -= b[i]\n b[i] -= b[i]\n else:\n if b[-1] != 0 or b[-2] != 0:\n print(\"NO\")\n else:\n print(\"YES\")", + "def isempty(list,n): \n for i in range(n):\n if list[i]!=0:\n return False\n return True\n \ndef rudolf(list,n):\n for i in range(1,n-1):\n while list[i]>1 and list[i-1]>0 and list[i+1]>0:\n list[i+1]-=1*list[i-1]\n list[i]-=2*list[i-1]\n list[i-1]-=1*list[i-1]\n if list[i-1]!=0:\n print(\"no\")\n return\n if isempty(list,n):\n print(\"YES\")\n else :\n print(\"NO\")\n \n \n \nt = int(input())\nfor i in range(t):\n n = int(input())\n l = input()\n lst = list(map(int,l.split()))\n rudolf(lst,n)", + "numTest = int(input())\n \nfor _ in range (0, numTest):\n n = int(input())\n a = [int(x) for x in input().split()]\n stop = False\n for i in range (0, n-2):\n if a[i] < 0:\n print(\"NO\")\n stop = True\n break\n opNum = a[i]\n a[i] -= opNum\n a[i+1] -= 2*opNum\n a[i+2] -= opNum\n if stop == True:\n continue\n if a[len(a)-1]!=0 or a[len(a)-2]!=0:\n print(\"NO\")\n else:\n print(\"YES\")" + ] + }, + { + "task_name": "1941_C", + "description": "Rudolf has a string s of length n . Rudolf considers the string s to be ugly\nif it contains the substring^\\dagger \"pie\" or the substring \"map\", otherwise\nthe string s will be considered beautiful.\n\nFor example, \"ppiee\", \"mmap\", \"dfpiefghmap\" are ugly strings, while \"mathp\",\n\"ppiiee\" are beautiful strings.\n\nRudolf wants to shorten the string s by removing some characters to make it\nbeautiful.\n\nThe main character doesn't like to strain, so he asks you to make the string\nbeautiful by removing the minimum number of characters. He can remove\ncharacters from any positions in the string (not just from the beginning or\nend of the string).\n\n^\\dagger String a is a substring of b if there exists a consecutive segment of\ncharacters in string b equal to a .\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases. The descriptions of the test cases follow.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 10^6\n) — the length of the string s .\n\nThe next line of each test case contains the string s of length n . The string\ns consists of lowercase Latin letters.\n\nThe sum of n over all test cases does not exceed 10^6 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of characters\nthat need to be deleted to make the string s beautiful. If the string is\ninitially beautiful, then output 0 .\n\nExample\n\nInput\n\n 6\n \n 9\n \n mmapnapie\n \n 9\n \n azabazapi\n \n 8\n \n mappppie\n \n 18\n \n mapmapmapmapmapmap\n \n 1\n \n p\n \n 11\n \n pppiepieeee\n\nOutput\n\n 2\n 0\n 2\n 6\n 0\n 2\n \nNote\n\nIn the first test case, for example, you can delete the 4 th and 9 th\ncharacters to make the string beautiful.\n\nIn the second test case, the string is already beautiful.", + "generated_code": [ + "for _ in range(int(input())):\n a=int(input()) \n s=input() \n x=s.count(\"map\") \n y=s.count(\"pie\") \n z=s.count(\"mapie\")\n print(x+y-z)", + "for _ in range(int(input())):\n n = int(input())\n a = input()\n ans = 0\n i = 0\n while i1:\n tree[i>>1] = tree[i]+tree[i^1] \n i >>=1\n # Calculating the values of prev nodes. (eg if node 9 is changed 9>>1 = 4 takes values of node i(9) and node i^1(8))\n \n def range_sum(tree,l, r): # calculates the sum of values in the range [l,r-1] (l and r take 0 based indexing) //O(logn)//\n l += len(tree)//2\n r += len(tree)//2\n sum = 0\n while l>= 1\n r >>= 1\n return sum\n \n############################################# Common functions #######################################################\n \ndef freq(l): # Returns count of a number in a list/string // O(nlog(n)) //\n d = {}\n for i in l:\n d[i] = d.get(i,0)+1\n return d\n \ndef prefix_sum_2d(l): #Returns the 2d prefix sum array of size (n+1)*(m+1) with 0 padded on first row and first col for easy calc.\n n = len(l)\n m = len(l[0])\n p = [[0 for i in range(m+1)] for j in range(n+1)]\n \n for i in range(1,n+1):\n for j in range(1,m+1):\n p[i][j] = p[i-1][j]+p[i][j-1]+l[i-1][j-1]-p[i-1][j-1]\n return p \n \n # //O(nm)//\n \n############################################### Number Theory #########################################################\n \ndef is_pow2(x): #Checks if a number is a power of 2 // O(1) //\n return max(1-(x&(x-1)),0)\n \ndef lgcd(l): # Returns gcd of a list // O(nlog(n)) //\n a = 0\n for i in l:\n a = gcd(a,i)\n return a\n \ndef SieveOfEratosthenes(num): # Returns an array with Prime numbers upto num // O(nlog(log(n))) //\n prime = [True for i in range(num+1)]\n Highest_Prime = [0 for i in range(num+1)] # Returns an array with the highest prime factor of each i between 0 and Num \n Lowest_Prime = [0 for i in range(num+1)] # Returns an array with the lowest prime factor of each i between 0 and Num\n prime[0] = prime[1] = False\n p = 2\n while (p <= num):\n if (prime[p] == True):\n Lowest_Prime[p] = p\n Highest_Prime[p] = p\n for i in range(2*p, num+1, p):\n prime[i] = False\n Highest_Prime[i] = p\n if Lowest_Prime[i] == 0:\n Lowest_Prime[i] = p\n p += 1\n # print(prime,'\\n',Highest_Prime,'\\n',Lowest_Prime) #Checker\n # return Lowest_Prime #An array containing the lowest prime factors of all numbers till num\n \n # return Highest_Prime # An array containing the highest prime factors of all numbers till num\n \n # return prime # An array with boolean values indicating if the number is prime/not prime\n p = []\n for i in range(num+1):\n if prime[i]:\n p.append(i)\n return p # An array with just prime numbers till the given number\n \ndef PrimeFactors(num,Prime_array):# Returns a dictionary with prime factors mapped with their respective powers // O(nlogn) //\n \n # COmplexity is O(logn) for this code, but this requires that u have a Prime array which could be highest or lowest prime which can be calculated from the prev Sieve of Erastothenes) hence over complexity is O(nlogn)\n \n d = {}\n while num != 1: \n x = Prime_array[num]\n d[x] = d.get(x,0)+1\n num//=x\n return d\n \ndef facotrization(n): #returns a dict with prime factors and their powers for a given number in // O(sqrt(n)) // \n #Use this approach if you don't have a prime array\n \n d = {}\n x = 2\n while x*x<=n:\n while n%x == 0:\n d[x] = d.get(x,0)+1\n n//=x\n x += 1\n if n>1:\n d[n] = d.get(n,0)+1\n return d\n \ndef ETF(d):\n #d is the dict contaiing prime factors\n s = 0\n for i in d:\n s += pow(i,d[i]-1)*(i-1)\n return s\n \n################################################## Combinatorics ############################################################\n \ndef fact(n,mod): #Returns the factorial of all numvers from 1 to n % mod\n f = [1]\n for i in range(1,n+1):\n f.append((f[i-1]*i%mod)%mod)\n return f\n \ndef dearrange(n,mod): #Returns an array containing the dearragements of all numbers from 1 to n % mod\n if mod == -1:\n dearr = [1,0]\n for i in range(2,n+1):\n dearr.append((i-1)*(dearr[i-1]+dearr[i-2]))\n else:\n dearr = [1,0]\n for i in range(2,n+1):\n dearr.append(((i-1)%mod*(dearr[i-1]+dearr[i-2])%mod)%mod)\n return dearr\n \n################################################ Binary Arithmetic ##########################################################\n \ndef bin_search(p,x): #Returns -1 if the element doesn't exist in the list and its index if it does. //O(logn)//\n i = bisect_left(p, x)\n if i != len(p) and p[i] == x:\n return i\n else:\n return -1\n \ndef bin_left(p,x): #Returns the index of max element less than x and -1 if all elements r greater than x // O(logn) //\n n = len(p)\n l,r = 0,n-1\n if p[0]>x:\n return -1\n while l<=r:\n mid = (l+r)//2\n if p[mid] <= x:\n if mid != n-1:\n if p[mid+1]>x:\n break\n else:\n l = mid+1\n else:\n mid = n-1\n break\n else:\n r = mid-1\n return mid\n \ndef bin_right(p,x): #Returns the index of min element greater than x and n if all elements r less than x // O(logn) //\n n = len(p)\n l,r = 0,n-1\n if p[-1]= x:\n if mid != 0:\n if p[mid-1]x:\n r = mid-1\n elif y == x:\n return mid\n else:\n if ((mid+1)*(mid+1))>x:\n return mid\n else:\n l = mid+1\n \ndef bin_exp(a,b,mod): #Returns (a^b) mod m where 0 <= a,b <= 10^18 // O(log(b)) //\n ans = 1\n a %= mod\n while b:\n if b&1:\n ans = (ans*a)% mod\n a = (a*a)%mod\n b >>= 1\n return ans\n############################################################ DP #############################################################\n \ndef lcs(a, b): # Returns the longest common subsequence of two strings in //O(n^2)//\n dp = [[0]*(len(b)+1) for _ in range(len(a)+1)]\n for i in range(1,len(a)+1):\n for j in range(1,len(b)+1):\n if a[i-1] == b[j-1]:\n dp[i][j] = dp[i-1][j-1] + 1\n else:\n dp[i][j] = max(dp[i-1][j],dp[i][j-1])\n i,j = len(a),len(b)\n l = []\n while i!=0 and j!=0:\n if dp[i][j] == dp[i][j-1]:\n j-=1\n elif dp[i][j] == dp[i-1][j]:\n i-=1\n else:\n i-=1\n j-=1\n l.append(a[i])\n s = ''.join(l)\n # return len(s) \n return s[::-1]\n \ndef lis(arr): # Returns the length of longest increasing subsequence in an array of intigers/characters. // O(nlogn) //\n l = []\n for i in arr:\n pos = bisect_left(l,i)\n if pos == len(l): \n l.append(i) # we can have a new, longer increasing subsequence!\n else:\n l[pos] = i # At least we can make the ending element smaller\n return len(l)\n \n######################################################## Graph Algos ########################################################\n \ngraph = [] # Adjacenceny lists\nvis = [] # Visited array\n \ndef dfs(ver): # Ver = vertex on which dfs is applied\n stack = []\n stack.append(ver)\n vis[ver] = 1\n \n while (len(stack)):\n ver = stack.pop()\n print(ver,end = ' ')\n \n for node in graph[ver]:\n if (not vis[node]):\n stack.append(node)\n vis[node] = 1\n \ndef bfs(ver): # Ver = vertex on which dfs is applied\n q = deque()\n q.append(ver)\n vis[ver] = 1\n \n while (len(q)):\n ver = q.popleft()\n print(ver,end = ' ')\n \n for node in graph[ver]:\n if (not vis[node]):\n q.append(node)\n vis[node] = 1\n \nfor _ in range(int(input())):\n n,x,y=map(int,input().split())\n ans=x-2\n arr=list(map(int,input().split()))\n arr.sort()\n for i in range(1,x):\n if(arr[i-1]+2==arr[i]):\n ans+=1\n # print(i)\n if(arr[x-1]==n-1 and arr[0]==1):\n ans+=1\n if(arr[x-1]==n and arr[0]==2):\n ans+=1\n \n print(ans)", + "# main()\nT=int(input())\nfor _ in range(T):\n n,x,y=map(int,input().split())\n list0=list(map(int,input().split()))\n list0=sorted(list0)\n count=0\n for i in range(x-1):\n num=list0[i+1]-list0[i]-1\n if num==1:\n count+=1\n num=(list0[0]+n)-(list0[-1])-1\n if num==1:\n count+=1\n print(count+x-2)", + "if __name__ == \"__main__\":\n t=int(input())\n while(t>0):\n t-=1\n [n,x,y]=map(int,input().split())\n arr=input().split()\n arr=[int(arr[i]) for i in range(x)]\n arr.sort()\n arr.append(n+arr[0])\n ans=x-2\n for i in range(1,x+1):\n if(arr[i]-arr[i-1]==2):\n ans+=1\n print(ans)" + ] + }, + { + "task_name": "1943_C", + "description": "You are given a tree with n vertices numbered 1, 2, \\ldots, n . Initially, all\nvertices are colored white.\n\nYou can perform the following two-step operation:\n\n 1. Choose a vertex v (1 \\leq v \\leq n ) and a distance d (0 \\leq d \\leq n-1 ). \n 2. For all vertices u (1 \\leq u \\leq n ) such that \\text{dist}^\\dagger(u,v)=d , color u black. \n\nConstruct a sequence of operations to color all the nodes in the tree black\nusing the minimum possible number of operations. It can be proven that it is\nalways possible to do so using at most n operations.\n\n^\\dagger \\text{dist}(x, y) denotes the number of edges on the (unique) simple\npath between vertices x and y on the tree.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 200 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 2\n\\cdot 10^3 ) — the number of vertices of the tree.\n\nThe following n - 1 lines of each test case describe the edges of the tree.\nThe i -th of these lines contains two integers u_i and v_i (1 \\le u_i, v_i \\le\nn , u_i \\neq v_i ), the indices of the vertices connected by the i -th edge.\n\nIt is guaranteed that the given edges form a tree.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^3 .\n\nOutput\n\nFor each test case, first output a single integer op (1 \\le op \\le n) , the\nminimum number of operations needed to color all vertices of the tree black.\n\nThen, output op lines, each containing 2 integers. The i -th line should\ncontain the values of v and d chosen for the i -th operation (1 \\le v \\le n ,\n0 \\le d \\le n - 1 )\n\nYou must guarantee that at the end of op operations, all vertices are colored\nblack.\n\nIf there are multiple solutions, you may output any one of them.\n\nExample\n\nInput\n\n 4\n \n 1\n \n 2\n \n 1 2\n \n 4\n \n 1 2\n \n 1 3\n \n 1 4\n \n 7\n \n 2 7\n \n 3 2\n \n 6 4\n \n 5 7\n \n 1 6\n \n 6 7\n\nOutput\n\n 1\n 1 0\n 2\n 1 1\n 2 1\n 2\n 1 1\n 2 1\n 3\n 6 1\n 7 1\n 2 1\n\nNote\n\nIn the first test case, there is only one possible operation, and performing\nit gives us a valid answer.\n\nIn the second test case, the first operation colors vertex 2 black, and the\nsecond operation colors vertex 1 black. It can be shown that it is impossible\nto color both vertices black in one operation, so the minimum number of\noperations needed is 2 . Another possible solution is to use the 2 operations:\n(u, r) = (1, 0) and (u, r) = (2, 0) .\n\nIn the third test case, the first operation colors vertices 2 , 3 and 4 black,\nand the second operation colors vertex 1 black. Again, it can be shown that it\nis impossible to color all vertices black in 1 operation, so the minimum\nnumber of operations needed is 2 .\n\nIn the fourth test case, the first operation colors vertices 4 , 1 and 7\nblack, the second operation colors vertices 2 , 5 and 6 black while the third\noperation colors vertices 3 and 7 black. Notice that it is allowed to color\nvertex 7 black twice.\n\nThus, each node was marked at least once, with node 7 marked twice. It can be\nshown that it is impossible to color all vertices black in fewer than 3 moves.", + "generated_code": [ + "def argmax(l):\n return max(range(len(l)), key=lambda x: l[x])\n \ndef alg():\n n = int(input())\n u2vs = [[] for _ in range(n)]\n for _ in range(n - 1):\n u, v = tuple(map(int, input().split()))\n u-=1; v-=1\n u2vs[u].append(v)\n u2vs[v].append(u)\n \n \n # find diameter of tree\n def bfs(s):\n nonlocal n\n d = [-1 for _ in range(n)]\n prev = [ -1 for _ in range(n)]\n q = [s]\n d[s] = 0\n \n \n while len(q) > 0:\n u = q.pop(0)\n du = d[u]\n for v in u2vs[u]:\n if d[v] == -1:\n d[v] = du + 1\n prev[v] = u\n q.append(v)\n return d, prev\n \n d, _ = bfs(0); a = argmax(d)\n d, previous = bfs(a); b = argmax(d)\n \n path_ba = [b]\n while True:\n n = previous[path_ba[-1]]\n if n == -1:\n break\n path_ba.append(n)\n \n # print(path_ba)\n # end of find diameter, path_ab - diameter\n \n # generate commands\n \n # if len(path_ba) - odd => find centre and propagate commands from it\n ops = []\n if len(path_ba) % 2 == 1:\n ci = len(path_ba) // 2\n c = path_ba[ci]\n for i in range(ci+1):\n ops.append((c, i))\n \n # if len(path_ba) - even => find 2 centres and ?????\n else:\n ci2 = len(path_ba) // 2\n ci1 = ci2 - 1\n c1 = path_ba[ci1]\n c2 = path_ba[ci2]\n for i in range(1, len(path_ba) - ci1, 2): \n ops.append((c1, i))\n ops.append((c2, i))\n \n # end of generate commands \n \n \n # print\n \n print(len(ops))\n \n print(*map(lambda x: f\"{x[0]+1} {x[1]}\" , ops), sep=\"\\n\")\n \n \n return None\n \n \n \nif __name__ == \"__main__\":\n for _ in range(int(input())):\n alg()" + ] + }, + { + "task_name": "1944_A", + "description": "There are n islands, numbered 1, 2, \\ldots, n . Initially, every pair of\nislands is connected by a bridge. Hence, there are a total of \\frac{n (n -\n1)}{2} bridges.\n\nEverule lives on island 1 and enjoys visiting the other islands using bridges.\nDominater has the power to destroy at most k bridges to minimize the number of\nislands that Everule can reach using (possibly multiple) bridges.\n\nFind the minimum number of islands (including island 1 ) that Everule can\nvisit if Dominater destroys bridges optimally.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^3 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first and only line of each test case contains two integers n and k (1 \\le\nn \\le 100 , 0 \\le k \\le \\frac{n \\cdot (n - 1)}{2} ).\n\nOutput\n\nFor each test case, output the minimum number of islands that Everule can\nvisit if Dominater destroys bridges optimally.\n\nExample\n\nInput\n\n 6\n \n 2 0\n \n 2 1\n \n 4 1\n \n 5 10\n \n 5 3\n \n 4 4\n\nOutput\n\n 2\n 1\n 4\n 1\n 5\n 1\n \nNote\n\nIn the first test case, since no bridges can be destroyed, all the islands\nwill be reachable.\n\nIn the second test case, you can destroy the bridge between islands 1 and 2 .\nEverule will not be able to visit island 2 but can still visit island 1 .\nTherefore, the total number of islands that Everule can visit is 1 .\n\nIn the third test case, Everule always has a way of reaching all islands\ndespite what Dominater does. For example, if Dominater destroyed the bridge\nbetween islands 1 and 2 , Everule can still visit island 2 by traveling by 1\n\\to 3 \\to 2 as the bridges between 1 and 3 , and between 3 and 2 are not\ndestroyed.\n\nIn the fourth test case, you can destroy all bridges since k = \\frac{n \\cdot\n(n - 1)}{2} . Everule will be only able to visit 1 island (island 1 ).", + "generated_code": [ + "t=int(input())\nimport math\nfor i in range(0,t,1):\n n,k=map(int,input().split())\n if k>=n-1:\n print(1)\n else:\n print(n)", + "for _ in range(int(input())):\n n, k = map(int, input().split())\n print(n if n-k>1 else 1)", + "def fun(n, k):\n \n \n if k>=n-1:\n return 1\n else:\n return n\n \n \n \nt = int(input())\nfor _ in range(t):\n n, k = map(int, input().split())\n print(fun(n, k))" + ] + }, + { + "task_name": "1945_A", + "description": "The organizing committee plans to take the participants of the Olympiad on a\nhike after the tour. Currently, the number of tents needed to be taken is\nbeing calculated. It is known that each tent can accommodate up to 3 people.\n\nAmong the participants, there are a introverts, b extroverts, and c\nuniversals:\n\n * Each introvert wants to live in a tent alone. Thus, a tent with an introvert must contain exactly one person — only the introvert himself. \n * Each extrovert wants to live in a tent with two others. Thus, the tent with an extrovert must contain exactly three people. \n * Each universal is fine with any option (living alone, with one other person, or with two others). \n\nThe organizing committee respects the wishes of each participant very much, so\nthey want to fulfill all of them.\n\nTell us the minimum number of tents needed to be taken so that all\nparticipants can be accommodated according to their preferences. If it is\nimpossible to accommodate the participants in a way that fulfills all the\nwishes, output -1 .\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. This is followed by\nthe descriptions of the test cases.\n\nEach test case is described by a single line containing three integers a , b ,\nc (0 \\le a, b, c \\le 10^9 ) — the number of introverts, extroverts, and\nuniversals, respectively.\n\nOutput\n\nFor each test case, output a single integer — the minimum number of tents, or\n-1 if it is impossible to accommodate the participants.\n\nExample\n\nInput\n\n 10\n \n 1 2 3\n \n 1 4 1\n \n 1 4 2\n \n 1 1 1\n \n 1 3 2\n \n 19 7 18\n \n 0 0 0\n \n 7 0 0\n \n 0 24 0\n \n 1000000000 1000000000 1000000000\n\nOutput\n\n 3\n -1\n 3\n -1\n 3\n 28\n 0\n 7\n 8\n 1666666667\n \nNote\n\nIn the first test case, 1 tent will be given to the introverts, 1 tent will be\nshared by two extroverts and one universal, and the last tent will be shared\nby two universals. In total, 3 tents are needed.\n\nIn the second test case, three extroverts will take 1 tent, and 1 tent will be\ntaken by an introvert. Then, one extrovert and one universal will be left.\nThis extrovert will not be able to live with two others.", + "generated_code": [ + "from math import ceil\nfrom typing import Optional\n \n \n# Each introvert wants to live in a tent alone. Thus, a tent with an introvert must contain exactly one person — only the introvert himself.\n# Each extrovert wants to live in a tent with two others. Thus, the tent with an extrovert must contain exactly three people.\n# Each universal is fine with any option(living alone, with one other person, or with two others).\n \n \ndef f(extroverts: int, universals: int) -> Optional[int]:\n if extroverts % 3 != 0:\n if extroverts % 3 + universals < 3:\n return None\n return ceil((extroverts + universals) / 3)\n \n \ndef g(introverts: int, extroverts: int, universals: int) -> int:\n ret = f(extroverts, universals)\n return -1 if ret is None else introverts+ret\n \ntest_case_n = int(input())\nfor _ in range(test_case_n):\n (introverts, extroverts, universals) = map(int, input().split(' '))\n # return min area\n print(g(introverts, extroverts, universals))\n \n \n# for line in '''1 2 3\n# 1 4 1\n# 1 4 2\n# 1 1 1\n# 1 3 2\n# 19 7 18\n# 0 0 0\n# 7 0 0\n# 0 24 0\n# 1000000000 1000000000 1000000000'''.splitlines():\n# (introverts, extroverts, universals) = map(int, line.split(' '))\n# print('line:', line)\n# print('ret:', g(introverts, extroverts, universals))", + "for s in[*open(0)][1:]:a,b,c=map(int,s.split());b+=c;print((a--b//3,-1)[c b:\n print(2 + m//b)\n elif m < b and m > a:\n print(2 + m//a)\n else:\n print(m//a + m//b + 2)", + "t=int(input())\nfor i in range(t):\n a,b,m=map(int,input().split())\n print(m//a+m//b+2)" + ] + }, + { + "task_name": "1945_C", + "description": "In the village of Letovo, there are n houses. The villagers decided to build a\nbig road that will divide the village into left and right sides. Each resident\nwants to live on either the right or the left side of the street, which is\ndescribed as a sequence a_1, a_2, \\dots, a_n , where a_j = 0 if the resident\nof the j -th house wants to live on the left side of the street; otherwise,\na_j = 1 .\n\nThe road will pass between two houses. The houses to the left of it will be\ndeclared the left-side, and the houses to the right will be declared the\nright-side. More formally, let the road pass between houses i and i+1 . Then\nthe houses at positions between 1 and i will be on the left side of the\nstreet, and at positions between i+1 and n will be on the right side. The road\nalso may pass before the first and after the last house; in this case, the\nentire village is declared to be either the right or left side, respectively.\n\nTo make the design fair, it was decided to lay the road so that at least half\nof the residents on each side of the village are satisfied with the choice.\nThat is, among x residents on one side, at least \\lceil\\frac{x}{2}\\rceil\nshould want to live on that side, where \\lceil x \\rceil denotes rounding up a\nreal number x .\n\n![](https://espresso.codeforces.com/75baa17903d65a630fb0d3334683e857d5fdc345.png)\nTo the left of the road, there will be i houses, among the corresponding a_j\nthere must be at least \\lceil\\frac{i}{2}\\rceil zeros. To the right of the\nroad, there will be n-i houses, among the corresponding a_j there must be at\nleast \\lceil\\frac{n-i}{2}\\rceil ones.\n\nDetermine after which house i the road should be laid in order to satisfy the\ndescribed condition and be as close to the middle of the village as possible.\nFormally, among all suitable positions i , minimize \\left|\\frac{n}{2} -\ni\\right| .\n\nIf there are multiple suitable positions i with the minimum \\left|\\frac{n}{2}\n- i\\right| , output the smaller one.\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 2\\cdot 10^4 ). The description of the test cases\nfollows.\n\nThe first line of each test case contains a single integer n (3 \\le n \\le\n3\\cdot 10^5 ). The next line of each test case contains a string a of length n\n, consisting only of 0 and 1 .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 3\\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single number i — the position of the house after\nwhich the road should be laid (if it should be laid before the first house,\noutput 0 ). We can show that the answer always exists.\n\nExample\n\nInput\n\n 7\n \n 3\n \n 101\n \n 6\n \n 010111\n \n 6\n \n 011001\n \n 3\n \n 000\n \n 3\n \n 110\n \n 3\n \n 001\n \n 4\n \n 1100\n\nOutput\n\n 2\n 3\n 2\n 3\n 0\n 1\n 0\n \nNote\n\nLet's consider the first example of input data.\n\nIf we lay the road after the first house, there will be one house a_1 = 1 on\nthe left side of the street, the resident of which would like to live on the\nright side of the street. Then 0 out of 1 residents on the even side will be\nsatisfied with the choice, which means that the road cannot be laid after\nhouse 1 .\n\nIf we lay the road after the second house, 1 out of 2 residents on the left\nside (with preferences a_1 = 1 , a_2 = 0 ) and 1 out of 1 resident on the\nright side (with preference a_3 = 1 ) will be satisfied with the choice. More\nthan half of the residents on each side are satisfied with the choice, which\nmeans that the road can be laid after house 2 . We can show that this is the\noptimal answer.", + "generated_code": [ + "from heapq import heappush, heappop, heapify\nfrom collections import defaultdict, deque,Counter\nfrom math import ceil, floor, sqrt, factorial,gcd,cos,sin,pi\nfrom itertools import permutations, combinations,product\nfrom bisect import bisect_left, bisect_right\nfrom copy import deepcopy\nfrom fractions import Fraction\nimport sys\n#from functools import cache,lru_cache #@lru_cache(maxsize=None)\n# sys.setrecursionlimit(10**6)\n# input = sys.stdin.readline\nvector1 = [[0, -1], [1, 0], [0, 1], [-1, 0]]\nvector2 = [[0, 1], [1, 0], [-1, 0], [0, -1],\n [1,-1], [-1, 1], [1, 1], [-1, -1]]\n \n \n \ndef solve():\n \n n = int(input())\n a = input()\n S = [[0,0]]\n for s in a:\n x, y = S[-1]\n if s == \"0\":\n x += 1\n else:\n y += 1\n S.append([x,y])\n ans = -1\n for i in range(n+1):\n left = S[i][0]\n lsum = i\n right = S[-1][1] - S[i][1]\n rsum = n - i\n #print(left,right)\n if left*2 < lsum or right*2 < rsum:\n continue\n elif abs(n/2 - i) < abs(n/2 - ans):\n ans = i\n \n print(ans)\n #print(S)\n \n \ndef main():\n for _ in range(int(input())):\n solve()\n \n \n \n \n \nif __name__ == '__main__':\n main()", + "t = int(input())\nfor _ in range(t):\n n = int(input())\n s = input()\n \n mid = n // 2\n leftZero = 0\n rightZero = 0\n leftOne = 0\n rightOne = 0\n tleftZero = 0\n trightZero = 0\n tleftOne = 0\n trightOne = 0\n \n for i in range(mid):\n if s[i] == '0':\n leftZero += 1\n tleftZero += 1\n else:\n leftOne += 1\n tleftOne += 1\n \n for i in range(mid, n):\n if s[i] == '0':\n rightZero += 1\n trightZero += 1\n else:\n rightOne += 1\n trightOne += 1\n \n left = mid\n leftMove = 0\n while left > 0 and (leftZero < (left+1)//2 or rightOne < (n-left+1)//2):\n if s[left-1] == '0':\n leftZero -= 1\n rightZero += 1\n else:\n leftOne -= 1\n rightOne += 1\n left -= 1\n \n right = mid\n while right < n and (tleftZero < (right+1)//2 or trightOne < (n-right+1)//2):\n if s[right] == '0':\n tleftZero += 1\n trightZero -= 1\n else:\n tleftOne += 1\n trightOne -= 1\n right += 1\n \n if left == 0:\n if right != n:\n print(right)\n else:\n if rightOne >= (n+1)//2:\n print(left)\n else:\n print(right)\n elif right == n:\n if left != 0:\n print(left)\n else:\n if tleftZero >= (n+1)//2:\n print(right)\n else:\n print(left)\n else:\n if abs((n+1)//2-left) <= abs((n+1)//2-right):\n print(left)\n else:\n print(right)", + "t=int(input())\nfor _ in range(t):\n n=int(input())\n s=input()\n \n if n%2==0:\n pk=n/2\n else:\n pk=(n/2) \n \n sl=list(s)\n o=sl.count(\"1\")\n z=sl.count(\"0\")\n \n zero,one=0,0\n lst=[]\n mini=pow(10,8)\n for i in range(n-1):\n if s[i]==\"0\":\n zero+=1\n else:\n one+=1\n \n zero_perc=(zero*100)//(i+1)\n one_perc=((o-one)*100)//(n-i-1)\n #print(zero_perc,one_perc,\"hulu\",i)\n if zero_perc>=50 and one_perc>=50:\n lst.append(i+1)\n #print(lst)\n \n #print(mini,\"le\")\n #print(lst)\n #print(pk)\n for ele in lst:\n mini=min(mini,abs(pk-ele))\n final=[]\n #print(mini,\"88\")\n for elem in lst:\n if abs(pk-elem)==mini:\n final.append(elem)\n \n final.sort()\n if len(final)==0:\n c1=(o*100)//n\n if c1>=50:\n final.append(0)\n else:\n final.append(n)\n \n print(final[0])" + ] + }, + { + "task_name": "1945_D", + "description": "The guys lined up in a queue of n people, starting with person number i = 1 ,\nto ask Serafim the Owl about the meaning of life. Unfortunately, Kirill was\nvery busy writing the legend for this problem, so he arrived a little later\nand stood at the end of the line after the n -th person. Kirill is completely\ndissatisfied with this situation, so he decided to bribe some people ahead of\nhim.\n\nFor the i -th person in the queue, Kirill knows two values: a_i and b_i . If\nat the moment Kirill is standing at position i , then he can choose any\nposition j such that j < i and exchange places with the person at position j .\nIn this case, Kirill will have to pay him a_j coins. And for each k such that\nj < k < i , Kirill will have to pay b_k coins to the person at position k .\nKirill can perform this action any number of times.\n\nKirill is thrifty, so he wants to spend as few coins as possible, but he\ndoesn't want to wait too long, so Kirill believes he should be among the first\nm people in line.\n\nHelp Kirill determine the minimum number of coins he will have to spend in\norder to not wait too long.\n\nInput\n\nEach test consists of several sets of input data. The first line contains a\nsingle integer t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows\nthe description of the test case.\n\nThe first line of each test case contains two integers n and m (1 \\le m \\le n\n\\le 200\\,000 ) — the number of people in the queue besides Kirill and the\nmaximum allowable final position of Kirill, respectively.\n\nThe second line contains n integers a_1, a_2, \\dots, a_n separated by spaces\n(1 \\le a_i \\le 10^9 ).\n\nThe third line contains n integers b_1, b_2, \\dots, b_n separated by spaces (1\n\\le b_i \\le 10^9 ).\n\nIt is guaranteed that the sum of the values of n over all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of coins\nKirill needs to spend.\n\nExample\n\nInput\n\n 4\n \n 4 2\n \n 7 3 6 9\n \n 4 3 8 5\n \n 6 2\n \n 6 9 7 1 8 3\n \n 5 8 8 1 4 1\n \n 7 7\n \n 7 2 9 2 6 5 9\n \n 9 1 10 7 1 4 9\n \n 2 1\n \n 2 3\n \n 1 1\n\nOutput\n\n 14\n 22\n 9\n 3", + "generated_code": [ + "def solve(n, k, a, b):\n c = [min(a[i], b[i]) for i in range(n)]\n \n suff = [0] * (n + 1)\n for i in range(n - 1, -1, -1):\n suff[i] = suff[i + 1] + c[i]\n \n ans = float('inf')\n for i in range(k):\n ans = min(ans, a[i] + suff[i + 1])\n \n print(ans)\n \nt = int(input())\nfor _ in range(t):\n n, k = map(int, input().split())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n \n solve(n, k, a, b)", + "import sys\n \ncases = int(input())\n \nfor c in range(cases):\n na_frente, pos_final = map(int, input().split())\n custo_pra_trocar_a = list(map(int, input().split()))\n custo_pra_passar_b = list(map(int, input().split()))\n \n na_frente -= 1\n pos_final -= 1\n \n total = 0\n best = sys.float_info.max\n for v in range(na_frente, -1, -1):\n if(v <= pos_final):\n if(best > total + custo_pra_trocar_a[v]):\n best = total + custo_pra_trocar_a[v]\n \n if(custo_pra_trocar_a[v] < custo_pra_passar_b[v]):\n total += custo_pra_trocar_a[v]\n else:\n total += custo_pra_passar_b[v]\n else:\n if(custo_pra_trocar_a[v] < custo_pra_passar_b[v]):\n total += custo_pra_trocar_a[v]\n else:\n total += custo_pra_passar_b[v]\n \n print(best)", + "def seraphim(pergunta,a,b,n,m):\n x = 0\n for i in range(n-1,-1,-1):\n if i` is an Apache2 licensed Python sorted\ncollections library, written in pure-Python, and fast as C-extensions. The\n:doc:`introduction` is the best way to get started.\n \nSorted list implementations:\n \n.. currentmodule:: sortedcontainers\n \n* :class:`SortedList`\n* :class:`SortedKeyList`\n \n\"\"\"\n# pylint: disable=too-many-lines\n \nimport sys\nimport traceback\n \nfrom bisect import bisect_left, bisect_right, insort\nfrom itertools import chain, repeat, starmap\nfrom math import log2\nfrom operator import add, eq, ne, gt, ge, lt, le, iadd\nfrom textwrap import dedent\n \n###############################################################################\n# BEGIN Python 2/3 Shims\n###############################################################################\n \ntry:\n from collections.abc import Sequence, MutableSequence\nexcept ImportError:\n from collections import Sequence, MutableSequence\n \nfrom functools import wraps\nfrom sys import hexversion\n \nif hexversion < 0x03000000:\n from itertools import imap as map # pylint: disable=redefined-builtin\n from itertools import izip as zip # pylint: disable=redefined-builtin\n \n try:\n from thread import get_ident\n except ImportError:\n from dummy_thread import get_ident\nelse:\n from functools import reduce\n \n try:\n from _thread import get_ident\n except ImportError:\n from _dummy_thread import get_ident\n \n \ndef recursive_repr(fillvalue=\"...\"):\n \"Decorator to make a repr function return fillvalue for a recursive call.\"\n # pylint: disable=missing-docstring\n # Copied from reprlib in Python 3\n # https://hg.python.org/cpython/file/3.6/Lib/reprlib.py\n \n def decorating_function(user_function):\n repr_running = set()\n \n @wraps(user_function)\n def wrapper(self):\n key = id(self), get_ident()\n if key in repr_running:\n return fillvalue\n repr_running.add(key)\n try:\n result = user_function(self)\n finally:\n repr_running.discard(key)\n return result\n \n return wrapper\n \n return decorating_function\n \n \n###############################################################################\n# END Python 2/3 Shims\n###############################################################################\n \n \nclass SortedList(MutableSequence):\n \"\"\"Sorted list is a sorted mutable sequence.\n \n Sorted list values are maintained in sorted order.\n \n Sorted list values must be comparable. The total ordering of values must\n not change while they are stored in the sorted list.\n \n Methods for adding values:\n \n * :func:`SortedList.add`\n * :func:`SortedList.update`\n * :func:`SortedList.__add__`\n * :func:`SortedList.__iadd__`\n * :func:`SortedList.__mul__`\n * :func:`SortedList.__imul__`\n \n Methods for removing values:\n \n * :func:`SortedList.clear`\n * :func:`SortedList.discard`\n * :func:`SortedList.remove`\n * :func:`SortedList.pop`\n * :func:`SortedList.__delitem__`\n \n Methods for looking up values:\n \n * :func:`SortedList.bisect_left`\n * :func:`SortedList.bisect_right`\n * :func:`SortedList.count`\n * :func:`SortedList.index`\n * :func:`SortedList.__contains__`\n * :func:`SortedList.__getitem__`\n \n Methods for iterating values:\n \n * :func:`SortedList.irange`\n * :func:`SortedList.islice`\n * :func:`SortedList.__iter__`\n * :func:`SortedList.__reversed__`\n \n Methods for miscellany:\n \n * :func:`SortedList.copy`\n * :func:`SortedList.__len__`\n * :func:`SortedList.__repr__`\n * :func:`SortedList._check`\n * :func:`SortedList._reset`\n \n Sorted lists use lexicographical ordering semantics when compared to other\n sequences.\n \n Some methods of mutable sequences are not supported and will raise\n not-implemented error.\n \n \"\"\"\n \n DEFAULT_LOAD_FACTOR = 1000\n \n def __init__(self, iterable=None, key=None):\n \"\"\"Initialize sorted list instance.\n \n Optional `iterable` argument provides an initial iterable of values to\n initialize the sorted list.\n \n Runtime complexity: `O(n*log(n))`\n \n >>> sl = SortedList()\n >>> sl\n SortedList([])\n >>> sl = SortedList([3, 1, 2, 5, 4])\n >>> sl\n SortedList([1, 2, 3, 4, 5])\n \n :param iterable: initial values (optional)\n \n \"\"\"\n assert key is None\n self._len = 0\n self._load = self.DEFAULT_LOAD_FACTOR\n self._lists = []\n self._maxes = []\n self._index = []\n self._offset = 0\n \n if iterable is not None:\n self._update(iterable)\n \n def __new__(cls, iterable=None, key=None):\n \"\"\"Create new sorted list or sorted-key list instance.\n \n Optional `key`-function argument will return an instance of subtype\n :class:`SortedKeyList`.\n \n >>> sl = SortedList()\n >>> isinstance(sl, SortedList)\n True\n >>> sl = SortedList(key=lambda x: -x)\n >>> isinstance(sl, SortedList)\n True\n >>> isinstance(sl, SortedKeyList)\n True\n \n :param iterable: initial values (optional)\n :param key: function used to extract comparison key (optional)\n :return: sorted list or sorted-key list instance\n \n \"\"\"\n # pylint: disable=unused-argument\n if key is None:\n return object.__new__(cls)\n else:\n if cls is SortedList:\n return object.__new__(SortedKeyList)\n else:\n raise TypeError(\"inherit SortedKeyList for key argument\")\n \n @property\n def key(self): # pylint: disable=useless-return\n \"\"\"Function used to extract comparison key from values.\n \n Sorted list compares values directly so the key function is none.\n \n \"\"\"\n return None\n \n def _reset(self, load):\n \"\"\"Reset sorted list load factor.\n \n The `load` specifies the load-factor of the list. The default load\n factor of 1000 works well for lists from tens to tens-of-millions of\n values. Good practice is to use a value that is the cube root of the\n list size. With billions of elements, the best load factor depends on\n your usage. It's best to leave the load factor at the default until you\n start benchmarking.\n \n See :doc:`implementation` and :doc:`performance-scale` for more\n information.\n \n Runtime complexity: `O(n)`\n \n :param int load: load-factor for sorted list sublists\n \n \"\"\"\n values = reduce(iadd, self._lists, [])\n self._clear()\n self._load = load\n self._update(values)\n \n def clear(self):\n \"\"\"Remove all values from sorted list.\n \n Runtime complexity: `O(n)`\n \n \"\"\"\n self._len = 0\n del self._lists[:]\n del self._maxes[:]\n del self._index[:]\n self._offset = 0\n \n _clear = clear\n \n def add(self, value):\n \"\"\"Add `value` to sorted list.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList()\n >>> sl.add(3)\n >>> sl.add(1)\n >>> sl.add(2)\n >>> sl\n SortedList([1, 2, 3])\n \n :param value: value to add to sorted list\n \n \"\"\"\n _lists = self._lists\n _maxes = self._maxes\n \n if _maxes:\n pos = bisect_right(_maxes, value)\n \n if pos == len(_maxes):\n pos -= 1\n _lists[pos].append(value)\n _maxes[pos] = value\n else:\n insort(_lists[pos], value)\n \n self._expand(pos)\n else:\n _lists.append([value])\n _maxes.append(value)\n \n self._len += 1\n \n def _expand(self, pos):\n \"\"\"Split sublists with length greater than double the load-factor.\n \n Updates the index when the sublist length is less than double the load\n level. This requires incrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n \n \"\"\"\n _load = self._load\n _lists = self._lists\n _index = self._index\n \n if len(_lists[pos]) > (_load << 1):\n _maxes = self._maxes\n \n _lists_pos = _lists[pos]\n half = _lists_pos[_load:]\n del _lists_pos[_load:]\n _maxes[pos] = _lists_pos[-1]\n \n _lists.insert(pos + 1, half)\n _maxes.insert(pos + 1, half[-1])\n \n del _index[:]\n else:\n if _index:\n child = self._offset + pos\n while child:\n _index[child] += 1\n child = (child - 1) >> 1\n _index[0] += 1\n \n def update(self, iterable):\n \"\"\"Update sorted list by adding all values from `iterable`.\n \n Runtime complexity: `O(k*log(n))` -- approximate.\n \n >>> sl = SortedList()\n >>> sl.update([3, 1, 2])\n >>> sl\n SortedList([1, 2, 3])\n \n :param iterable: iterable of values to add\n \n \"\"\"\n _lists = self._lists\n _maxes = self._maxes\n values = sorted(iterable)\n \n if _maxes:\n if len(values) * 4 >= self._len:\n _lists.append(values)\n values = reduce(iadd, _lists, [])\n values.sort()\n self._clear()\n else:\n _add = self.add\n for val in values:\n _add(val)\n return\n \n _load = self._load\n _lists.extend(values[pos : (pos + _load)] for pos in range(0, len(values), _load))\n _maxes.extend(sublist[-1] for sublist in _lists)\n self._len = len(values)\n del self._index[:]\n \n _update = update\n \n def __contains__(self, value):\n \"\"\"Return true if `value` is an element of the sorted list.\n \n ``sl.__contains__(value)`` <==> ``value in sl``\n \n Runtime complexity: `O(log(n))`\n \n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> 3 in sl\n True\n \n :param value: search for value in sorted list\n :return: true if `value` in sorted list\n \n \"\"\"\n _maxes = self._maxes\n \n if not _maxes:\n return False\n \n pos = bisect_left(_maxes, value)\n \n if pos == len(_maxes):\n return False\n \n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n \n return _lists[pos][idx] == value\n \n def discard(self, value):\n \"\"\"Remove `value` from sorted list if it is a member.\n \n If `value` is not a member, do nothing.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> sl.discard(5)\n >>> sl.discard(0)\n >>> sl == [1, 2, 3, 4]\n True\n \n :param value: `value` to discard from sorted list\n \n \"\"\"\n _maxes = self._maxes\n \n if not _maxes:\n return\n \n pos = bisect_left(_maxes, value)\n \n if pos == len(_maxes):\n return\n \n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n \n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n \n def remove(self, value):\n \"\"\"Remove `value` from sorted list; `value` must be a member.\n \n If `value` is not a member, raise ValueError.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList([1, 2, 3, 4, 5])\n >>> sl.remove(5)\n >>> sl == [1, 2, 3, 4]\n True\n >>> sl.remove(0)\n Traceback (most recent call last):\n ...\n ValueError: 0 not in list\n \n :param value: `value` to remove from sorted list\n :raises ValueError: if `value` is not in sorted list\n \n \"\"\"\n _maxes = self._maxes\n \n if not _maxes:\n raise ValueError(\"{0!r} not in list\".format(value))\n \n pos = bisect_left(_maxes, value)\n \n if pos == len(_maxes):\n raise ValueError(\"{0!r} not in list\".format(value))\n \n _lists = self._lists\n idx = bisect_left(_lists[pos], value)\n \n if _lists[pos][idx] == value:\n self._delete(pos, idx)\n else:\n raise ValueError(\"{0!r} not in list\".format(value))\n \n def _delete(self, pos, idx):\n \"\"\"Delete value at the given `(pos, idx)`.\n \n Combines lists that are less than half the load level.\n \n Updates the index when the sublist length is more than half the load\n level. This requires decrementing the nodes in a traversal from the\n leaf node to the root. For an example traversal see\n ``SortedList._loc``.\n \n :param int pos: lists index\n :param int idx: sublist index\n \n \"\"\"\n _lists = self._lists\n _maxes = self._maxes\n _index = self._index\n \n _lists_pos = _lists[pos]\n \n del _lists_pos[idx]\n self._len -= 1\n \n len_lists_pos = len(_lists_pos)\n \n if len_lists_pos > (self._load >> 1):\n _maxes[pos] = _lists_pos[-1]\n \n if _index:\n child = self._offset + pos\n while child > 0:\n _index[child] -= 1\n child = (child - 1) >> 1\n _index[0] -= 1\n elif len(_lists) > 1:\n if not pos:\n pos += 1\n \n prev = pos - 1\n _lists[prev].extend(_lists[pos])\n _maxes[prev] = _lists[prev][-1]\n \n del _lists[pos]\n del _maxes[pos]\n del _index[:]\n \n self._expand(prev)\n elif len_lists_pos:\n _maxes[pos] = _lists_pos[-1]\n else:\n del _lists[pos]\n del _maxes[pos]\n del _index[:]\n \n def _loc(self, pos, idx):\n \"\"\"Convert an index pair (lists index, sublist index) into a single\n index number that corresponds to the position of the value in the\n sorted list.\n \n Many queries require the index be built. Details of the index are\n described in ``SortedList._build_index``.\n \n Indexing requires traversing the tree from a leaf node to the root. The\n parent of each node is easily computable at ``(pos - 1) // 2``.\n \n Left-child nodes are always at odd indices and right-child nodes are\n always at even indices.\n \n When traversing up from a right-child node, increment the total by the\n left-child node.\n \n The final index is the sum from traversal and the index in the sublist.\n \n For example, using the index from ``SortedList._build_index``::\n \n _index = 14 5 9 3 2 4 5\n _offset = 3\n \n Tree::\n \n 14\n 5 9\n 3 2 4 5\n \n Converting an index pair (2, 3) into a single index involves iterating\n like so:\n \n 1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify\n the node as a left-child node. At such nodes, we simply traverse to\n the parent.\n \n 2. At node 9, position 2, we recognize the node as a right-child node\n and accumulate the left-child in our total. Total is now 5 and we\n traverse to the parent at position 0.\n \n 3. Iteration ends at the root.\n \n The index is then the sum of the total and sublist index: 5 + 3 = 8.\n \n :param int pos: lists index\n :param int idx: sublist index\n :return: index in sorted list\n \n \"\"\"\n if not pos:\n return idx\n \n _index = self._index\n \n if not _index:\n self._build_index()\n \n total = 0\n \n # Increment pos to point in the index to len(self._lists[pos]).\n \n pos += self._offset\n \n # Iterate until reaching the root of the index tree at pos = 0.\n \n while pos:\n # Right-child nodes are at odd indices. At such indices\n # account the total below the left child node.\n \n if not pos & 1:\n total += _index[pos - 1]\n \n # Advance pos to the parent node.\n \n pos = (pos - 1) >> 1\n \n return total + idx\n \n def _pos(self, idx):\n \"\"\"Convert an index into an index pair (lists index, sublist index)\n that can be used to access the corresponding lists position.\n \n Many queries require the index be built. Details of the index are\n described in ``SortedList._build_index``.\n \n Indexing requires traversing the tree to a leaf node. Each node has two\n children which are easily computable. Given an index, pos, the\n left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 +\n 2``.\n \n When the index is less than the left-child, traversal moves to the\n left sub-tree. Otherwise, the index is decremented by the left-child\n and traversal moves to the right sub-tree.\n \n At a child node, the indexing pair is computed from the relative\n position of the child node as compared with the offset and the remaining\n index.\n \n For example, using the index from ``SortedList._build_index``::\n \n _index = 14 5 9 3 2 4 5\n _offset = 3\n \n Tree::\n \n 14\n 5 9\n 3 2 4 5\n \n Indexing position 8 involves iterating like so:\n \n 1. Starting at the root, position 0, 8 is compared with the left-child\n node (5) which it is greater than. When greater the index is\n decremented and the position is updated to the right child node.\n \n 2. At node 9 with index 3, we again compare the index to the left-child\n node with value 4. Because the index is the less than the left-child\n node, we simply traverse to the left.\n \n 3. At node 4 with index 3, we recognize that we are at a leaf node and\n stop iterating.\n \n 4. To compute the sublist index, we subtract the offset from the index\n of the leaf node: 5 - 3 = 2. To compute the index in the sublist, we\n simply use the index remaining from iteration. In this case, 3.\n \n The final index pair from our example is (2, 3) which corresponds to\n index 8 in the sorted list.\n \n :param int idx: index in sorted list\n :return: (lists index, sublist index) pair\n \n \"\"\"\n if idx < 0:\n last_len = len(self._lists[-1])\n \n if (-idx) <= last_len:\n return len(self._lists) - 1, last_len + idx\n \n idx += self._len\n \n if idx < 0:\n raise IndexError(\"list index out of range\")\n elif idx >= self._len:\n raise IndexError(\"list index out of range\")\n \n if idx < len(self._lists[0]):\n return 0, idx\n \n _index = self._index\n \n if not _index:\n self._build_index()\n \n pos = 0\n child = 1\n len_index = len(_index)\n \n while child < len_index:\n index_child = _index[child]\n \n if idx < index_child:\n pos = child\n else:\n idx -= index_child\n pos = child + 1\n \n child = (pos << 1) + 1\n \n return (pos - self._offset, idx)\n \n def _build_index(self):\n \"\"\"Build a positional index for indexing the sorted list.\n \n Indexes are represented as binary trees in a dense array notation\n similar to a binary heap.\n \n For example, given a lists representation storing integers::\n \n 0: [1, 2, 3]\n 1: [4, 5]\n 2: [6, 7, 8, 9]\n 3: [10, 11, 12, 13, 14]\n \n The first transformation maps the sub-lists by their length. The\n first row of the index is the length of the sub-lists::\n \n 0: [3, 2, 4, 5]\n \n Each row after that is the sum of consecutive pairs of the previous\n row::\n \n 1: [5, 9]\n 2: [14]\n \n Finally, the index is built by concatenating these lists together::\n \n _index = [14, 5, 9, 3, 2, 4, 5]\n \n An offset storing the start of the first row is also stored::\n \n _offset = 3\n \n When built, the index can be used for efficient indexing into the list.\n See the comment and notes on ``SortedList._pos`` for details.\n \n \"\"\"\n row0 = list(map(len, self._lists))\n \n if len(row0) == 1:\n self._index[:] = row0\n self._offset = 0\n return\n \n head = iter(row0)\n tail = iter(head)\n row1 = list(starmap(add, zip(head, tail)))\n \n if len(row0) & 1:\n row1.append(row0[-1])\n \n if len(row1) == 1:\n self._index[:] = row1 + row0\n self._offset = 1\n return\n \n size = 2 ** (int(log2(len(row1) - 1)) + 1)\n row1.extend(repeat(0, size - len(row1)))\n tree = [row0, row1]\n \n while len(tree[-1]) > 1:\n head = iter(tree[-1])\n tail = iter(head)\n row = list(starmap(add, zip(head, tail)))\n tree.append(row)\n \n reduce(iadd, reversed(tree), self._index)\n self._offset = size * 2 - 1\n \n def __delitem__(self, index):\n \"\"\"Remove value at `index` from sorted list.\n \n ``sl.__delitem__(index)`` <==> ``del sl[index]``\n \n Supports slicing.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList('abcde')\n >>> del sl[2]\n >>> sl\n SortedList(['a', 'b', 'd', 'e'])\n >>> del sl[:2]\n >>> sl\n SortedList(['d', 'e'])\n \n :param index: integer or slice for indexing\n :raises IndexError: if index out of range\n \n \"\"\"\n if isinstance(index, slice):\n start, stop, step = index.indices(self._len)\n \n if step == 1 and start < stop:\n if start == 0 and stop == self._len:\n return self._clear()\n elif self._len <= 8 * (stop - start):\n values = self._getitem(slice(None, start))\n if stop < self._len:\n values += self._getitem(slice(stop, None))\n self._clear()\n return self._update(values)\n \n indices = range(start, stop, step)\n \n # Delete items from greatest index to least so\n # that the indices remain valid throughout iteration.\n \n if step > 0:\n indices = reversed(indices)\n \n _pos, _delete = self._pos, self._delete\n \n for index in indices:\n pos, idx = _pos(index)\n _delete(pos, idx)\n else:\n pos, idx = self._pos(index)\n self._delete(pos, idx)\n \n def __getitem__(self, index):\n \"\"\"Lookup value at `index` in sorted list.\n \n ``sl.__getitem__(index)`` <==> ``sl[index]``\n \n Supports slicing.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList('abcde')\n >>> sl[1]\n 'b'\n >>> sl[-1]\n 'e'\n >>> sl[2:5]\n ['c', 'd', 'e']\n \n :param index: integer or slice for indexing\n :return: value or list of values\n :raises IndexError: if index out of range\n \n \"\"\"\n _lists = self._lists\n \n if isinstance(index, slice):\n start, stop, step = index.indices(self._len)\n \n if step == 1 and start < stop:\n # Whole slice optimization: start to stop slices the whole\n # sorted list.\n \n if start == 0 and stop == self._len:\n return reduce(iadd, self._lists, [])\n \n start_pos, start_idx = self._pos(start)\n start_list = _lists[start_pos]\n stop_idx = start_idx + stop - start\n \n # Small slice optimization: start index and stop index are\n # within the start list.\n \n if len(start_list) >= stop_idx:\n return start_list[start_idx:stop_idx]\n \n if stop == self._len:\n stop_pos = len(_lists) - 1\n stop_idx = len(_lists[stop_pos])\n else:\n stop_pos, stop_idx = self._pos(stop)\n \n prefix = _lists[start_pos][start_idx:]\n middle = _lists[(start_pos + 1) : stop_pos]\n result = reduce(iadd, middle, prefix)\n result += _lists[stop_pos][:stop_idx]\n \n return result\n \n if step == -1 and start > stop:\n result = self._getitem(slice(stop + 1, start + 1))\n result.reverse()\n return result\n \n # Return a list because a negative step could\n # reverse the order of the items and this could\n # be the desired behavior.\n \n indices = range(start, stop, step)\n return list(self._getitem(index) for index in indices)\n else:\n if self._len:\n if index == 0:\n return _lists[0][0]\n elif index == -1:\n return _lists[-1][-1]\n else:\n raise IndexError(\"list index out of range\")\n \n if 0 <= index < len(_lists[0]):\n return _lists[0][index]\n \n len_last = len(_lists[-1])\n \n if -len_last < index < 0:\n return _lists[-1][len_last + index]\n \n pos, idx = self._pos(index)\n return _lists[pos][idx]\n \n _getitem = __getitem__\n \n def __setitem__(self, index, value):\n \"\"\"Raise not-implemented error.\n \n ``sl.__setitem__(index, value)`` <==> ``sl[index] = value``\n \n :raises NotImplementedError: use ``del sl[index]`` and\n ``sl.add(value)`` instead\n \n \"\"\"\n message = \"use ``del sl[index]`` and ``sl.add(value)`` instead\"\n raise NotImplementedError(message)\n \n def __iter__(self):\n \"\"\"Return an iterator over the sorted list.\n \n ``sl.__iter__()`` <==> ``iter(sl)``\n \n Iterating the sorted list while adding or deleting values may raise a\n :exc:`RuntimeError` or fail to iterate over all values.\n \n \"\"\"\n return chain.from_iterable(self._lists)\n \n def __reversed__(self):\n \"\"\"Return a reverse iterator over the sorted list.\n \n ``sl.__reversed__()`` <==> ``reversed(sl)``\n \n Iterating the sorted list while adding or deleting values may raise a\n :exc:`RuntimeError` or fail to iterate over all values.\n \n \"\"\"\n return chain.from_iterable(map(reversed, reversed(self._lists)))\n \n def reverse(self):\n \"\"\"Raise not-implemented error.\n \n Sorted list maintains values in ascending sort order. Values may not be\n reversed in-place.\n \n Use ``reversed(sl)`` for an iterator over values in descending sort\n order.\n \n Implemented to override `MutableSequence.reverse` which provides an\n erroneous default implementation.\n \n :raises NotImplementedError: use ``reversed(sl)`` instead\n \n \"\"\"\n raise NotImplementedError(\"use ``reversed(sl)`` instead\")\n \n def islice(self, start=None, stop=None, reverse=False):\n \"\"\"Return an iterator that slices sorted list from `start` to `stop`.\n \n The `start` and `stop` index are treated inclusive and exclusive,\n respectively.\n \n Both `start` and `stop` default to `None` which is automatically\n inclusive of the beginning and end of the sorted list.\n \n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n \n >>> sl = SortedList('abcdefghij')\n >>> it = sl.islice(2, 6)\n >>> list(it)\n ['c', 'd', 'e', 'f']\n \n :param int start: start index (inclusive)\n :param int stop: stop index (exclusive)\n :param bool reverse: yield values in reverse order\n :return: iterator\n \n \"\"\"\n _len = self._len\n \n if not _len:\n return iter(())\n \n start, stop, _ = slice(start, stop).indices(self._len)\n \n if start >= stop:\n return iter(())\n \n _pos = self._pos\n \n min_pos, min_idx = _pos(start)\n \n if stop == _len:\n max_pos = len(self._lists) - 1\n max_idx = len(self._lists[-1])\n else:\n max_pos, max_idx = _pos(stop)\n \n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n \n def _islice(self, min_pos, min_idx, max_pos, max_idx, reverse):\n \"\"\"Return an iterator that slices sorted list using two index pairs.\n \n The index pairs are (min_pos, min_idx) and (max_pos, max_idx), the\n first inclusive and the latter exclusive. See `_pos` for details on how\n an index is converted to an index pair.\n \n When `reverse` is `True`, values are yielded from the iterator in\n reverse order.\n \n \"\"\"\n _lists = self._lists\n \n if min_pos > max_pos:\n return iter(())\n \n if min_pos == max_pos:\n if reverse:\n indices = reversed(range(min_idx, max_idx))\n return map(_lists[min_pos].__getitem__, indices)\n \n indices = range(min_idx, max_idx)\n return map(_lists[min_pos].__getitem__, indices)\n \n next_pos = min_pos + 1\n \n if next_pos == max_pos:\n if reverse:\n min_indices = range(min_idx, len(_lists[min_pos]))\n max_indices = range(max_idx)\n return chain(\n map(_lists[max_pos].__getitem__, reversed(max_indices)),\n map(_lists[min_pos].__getitem__, reversed(min_indices)),\n )\n \n min_indices = range(min_idx, len(_lists[min_pos]))\n max_indices = range(max_idx)\n return chain(\n map(_lists[min_pos].__getitem__, min_indices),\n map(_lists[max_pos].__getitem__, max_indices),\n )\n \n if reverse:\n min_indices = range(min_idx, len(_lists[min_pos]))\n sublist_indices = range(next_pos, max_pos)\n sublists = map(_lists.__getitem__, reversed(sublist_indices))\n max_indices = range(max_idx)\n return chain(\n map(_lists[max_pos].__getitem__, reversed(max_indices)),\n chain.from_iterable(map(reversed, sublists)),\n map(_lists[min_pos].__getitem__, reversed(min_indices)),\n )\n \n min_indices = range(min_idx, len(_lists[min_pos]))\n sublist_indices = range(next_pos, max_pos)\n sublists = map(_lists.__getitem__, sublist_indices)\n max_indices = range(max_idx)\n return chain(\n map(_lists[min_pos].__getitem__, min_indices),\n chain.from_iterable(sublists),\n map(_lists[max_pos].__getitem__, max_indices),\n )\n \n def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False):\n \"\"\"Create an iterator of values between `minimum` and `maximum`.\n \n Both `minimum` and `maximum` default to `None` which is automatically\n inclusive of the beginning and end of the sorted list.\n \n The argument `inclusive` is a pair of booleans that indicates whether\n the minimum and maximum ought to be included in the range,\n respectively. The default is ``(True, True)`` such that the range is\n inclusive of both minimum and maximum.\n \n When `reverse` is `True` the values are yielded from the iterator in\n reverse order; `reverse` defaults to `False`.\n \n >>> sl = SortedList('abcdefghij')\n >>> it = sl.irange('c', 'f')\n >>> list(it)\n ['c', 'd', 'e', 'f']\n \n :param minimum: minimum value to start iterating\n :param maximum: maximum value to stop iterating\n :param inclusive: pair of booleans\n :param bool reverse: yield values in reverse order\n :return: iterator\n \n \"\"\"\n _maxes = self._maxes\n \n if not _maxes:\n return iter(())\n \n _lists = self._lists\n \n # Calculate the minimum (pos, idx) pair. By default this location\n # will be inclusive in our calculation.\n \n if minimum is None:\n min_pos = 0\n min_idx = 0\n else:\n if inclusive[0]:\n min_pos = bisect_left(_maxes, minimum)\n \n if min_pos == len(_maxes):\n return iter(())\n \n min_idx = bisect_left(_lists[min_pos], minimum)\n else:\n min_pos = bisect_right(_maxes, minimum)\n \n if min_pos == len(_maxes):\n return iter(())\n \n min_idx = bisect_right(_lists[min_pos], minimum)\n \n # Calculate the maximum (pos, idx) pair. By default this location\n # will be exclusive in our calculation.\n \n if maximum is None:\n max_pos = len(_maxes) - 1\n max_idx = len(_lists[max_pos])\n else:\n if inclusive[1]:\n max_pos = bisect_right(_maxes, maximum)\n \n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_lists[max_pos])\n else:\n max_idx = bisect_right(_lists[max_pos], maximum)\n else:\n max_pos = bisect_left(_maxes, maximum)\n \n if max_pos == len(_maxes):\n max_pos -= 1\n max_idx = len(_lists[max_pos])\n else:\n max_idx = bisect_left(_lists[max_pos], maximum)\n \n return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)\n \n def __len__(self):\n \"\"\"Return the size of the sorted list.\n \n ``sl.__len__()`` <==> ``len(sl)``\n \n :return: size of sorted list\n \n \"\"\"\n return self._len\n \n def bisect_left(self, value):\n \"\"\"Return an index to insert `value` in the sorted list.\n \n If the `value` is already present, the insertion point will be before\n (to the left of) any existing values.\n \n Similar to the `bisect` module in the standard library.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList([10, 11, 12, 13, 14])\n >>> sl.bisect_left(12)\n 2\n \n :param value: insertion index of value in sorted list\n :return: index\n \n \"\"\"\n _maxes = self._maxes\n \n if not _maxes:\n return 0\n \n pos = bisect_left(_maxes, value)\n \n if pos == len(_maxes):\n return self._len\n \n idx = bisect_left(self._lists[pos], value)\n return self._loc(pos, idx)\n \n def bisect_right(self, value):\n \"\"\"Return an index to insert `value` in the sorted list.\n \n Similar to `bisect_left`, but if `value` is already present, the\n insertion point will be after (to the right of) any existing values.\n \n Similar to the `bisect` module in the standard library.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList([10, 11, 12, 13, 14])\n >>> sl.bisect_right(12)\n 3\n \n :param value: insertion index of value in sorted list\n :return: index\n \n \"\"\"\n _maxes = self._maxes\n \n if not _maxes:\n return 0\n \n pos = bisect_right(_maxes, value)\n \n if pos == len(_maxes):\n return self._len\n \n idx = bisect_right(self._lists[pos], value)\n return self._loc(pos, idx)\n \n bisect = bisect_right\n _bisect_right = bisect_right\n \n def count(self, value):\n \"\"\"Return number of occurrences of `value` in the sorted list.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])\n >>> sl.count(3)\n 3\n \n :param value: value to count in sorted list\n :return: count\n \n \"\"\"\n _maxes = self._maxes\n \n if not _maxes:\n return 0\n \n pos_left = bisect_left(_maxes, value)\n \n if pos_left == len(_maxes):\n return 0\n \n _lists = self._lists\n idx_left = bisect_left(_lists[pos_left], value)\n pos_right = bisect_right(_maxes, value)\n \n if pos_right == len(_maxes):\n return self._len - self._loc(pos_left, idx_left)\n \n idx_right = bisect_right(_lists[pos_right], value)\n \n if pos_left == pos_right:\n return idx_right - idx_left\n \n right = self._loc(pos_right, idx_right)\n left = self._loc(pos_left, idx_left)\n return right - left\n \n def copy(self):\n \"\"\"Return a shallow copy of the sorted list.\n \n Runtime complexity: `O(n)`\n \n :return: new sorted list\n \n \"\"\"\n return self.__class__(self)\n \n __copy__ = copy\n \n def append(self, value):\n \"\"\"Raise not-implemented error.\n \n Implemented to override `MutableSequence.append` which provides an\n erroneous default implementation.\n \n :raises NotImplementedError: use ``sl.add(value)`` instead\n \n \"\"\"\n raise NotImplementedError(\"use ``sl.add(value)`` instead\")\n \n def extend(self, values):\n \"\"\"Raise not-implemented error.\n \n Implemented to override `MutableSequence.extend` which provides an\n erroneous default implementation.\n \n :raises NotImplementedError: use ``sl.update(values)`` instead\n \n \"\"\"\n raise NotImplementedError(\"use ``sl.update(values)`` instead\")\n \n def insert(self, index, value):\n \"\"\"Raise not-implemented error.\n \n :raises NotImplementedError: use ``sl.add(value)`` instead\n \n \"\"\"\n raise NotImplementedError(\"use ``sl.add(value)`` instead\")\n \n def pop(self, index=-1):\n \"\"\"Remove and return value at `index` in sorted list.\n \n Raise :exc:`IndexError` if the sorted list is empty or index is out of\n range.\n \n Negative indices are supported.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList('abcde')\n >>> sl.pop()\n 'e'\n >>> sl.pop(2)\n 'c'\n >>> sl\n SortedList(['a', 'b', 'd'])\n \n :param int index: index of value (default -1)\n :return: value\n :raises IndexError: if index is out of range\n \n \"\"\"\n if not self._len:\n raise IndexError(\"pop index out of range\")\n \n _lists = self._lists\n \n if index == 0:\n val = _lists[0][0]\n self._delete(0, 0)\n return val\n \n if index == -1:\n pos = len(_lists) - 1\n loc = len(_lists[pos]) - 1\n val = _lists[pos][loc]\n self._delete(pos, loc)\n return val\n \n if 0 <= index < len(_lists[0]):\n val = _lists[0][index]\n self._delete(0, index)\n return val\n \n len_last = len(_lists[-1])\n \n if -len_last < index < 0:\n pos = len(_lists) - 1\n loc = len_last + index\n val = _lists[pos][loc]\n self._delete(pos, loc)\n return val\n \n pos, idx = self._pos(index)\n val = _lists[pos][idx]\n self._delete(pos, idx)\n return val\n \n def index(self, value, start=None, stop=None):\n \"\"\"Return first index of value in sorted list.\n \n Raise ValueError if `value` is not present.\n \n Index must be between `start` and `stop` for the `value` to be\n considered present. The default value, None, for `start` and `stop`\n indicate the beginning and end of the sorted list.\n \n Negative indices are supported.\n \n Runtime complexity: `O(log(n))` -- approximate.\n \n >>> sl = SortedList('abcde')\n >>> sl.index('d')\n 3\n >>> sl.index('z')\n Traceback (most recent call last):\n ...\n ValueError: 'z' is not in list\n \n :param value: value in sorted list\n :param int start: start index (default None, start of sorted list)\n :param int stop: stop index (default None, end of sorted list)\n :return: index of value\n :raises ValueError: if value is not present\n \n \"\"\"\n _len = self._len\n \n if not _len:\n raise ValueError(\"{0!r} is not in list\".format(value))\n \n if start is None:\n start = 0\n if start < 0:\n start += _len\n if start < 0:\n start = 0\n \n if stop is None:\n stop = _len\n if stop < 0:\n stop += _len\n if stop > _len:\n stop = _len\n \n if stop <= start:\n raise ValueError(\"{0!r} is not in list\".format(value))\n \n _maxes = self._maxes\n pos_left = bisect_left(_maxes, value)\n \n if pos_left == len(_maxes):\n raise ValueError(\"{0!r} is not in list\".format(value))\n \n _lists = self._lists\n idx_left = bisect_left(_lists[pos_left], value)\n \n if _lists[pos_left][idx_left] != value:\n raise ValueError(\"{0!r} is not in list\".format(value))\n \n stop -= 1\n left = self._loc(pos_left, idx_left)\n \n if start <= left:\n if left <= stop:\n return left\n else:\n right = self._bisect_right(value) - 1\n \n if start <= right:\n return start\n \n raise ValueError(\"{0!r} is not in list\".format(value))\n \n def __add__(self, other):\n \"\"\"Return new sorted list containing all values in both sequences.\n \n ``sl.__add__(other)`` <==> ``sl + other``\n \n Values in `other` do not need to be in sorted order.\n \n Runtime complexity: `O(n*log(n))`\n \n >>> sl1 = SortedList('bat')\n >>> sl2 = SortedList('cat')\n >>> sl1 + sl2\n SortedList(['a', 'a', 'b', 'c', 't', 't'])\n \n :param other: other iterable\n :return: new sorted list\n \n \"\"\"\n values = reduce(iadd, self._lists, [])\n values.extend(other)\n return self.__class__(values)\n \n __radd__ = __add__\n \n def __iadd__(self, other):\n \"\"\"Update sorted list with values from `other`.\n \n ``sl.__iadd__(other)`` <==> ``sl += other``\n \n Values in `other` do not need to be in sorted order.\n \n Runtime complexity: `O(k*log(n))` -- approximate.\n \n >>> sl = SortedList('bat')\n >>> sl += 'cat'\n >>> sl\n SortedList(['a', 'a', 'b', 'c', 't', 't'])\n \n :param other: other iterable\n :return: existing sorted list\n \n \"\"\"\n self._update(other)\n return self\n \n def __mul__(self, num):\n \"\"\"Return new sorted list with `num` shallow copies of values.\n \n ``sl.__mul__(num)`` <==> ``sl * num``\n \n Runtime complexity: `O(n*log(n))`\n \n >>> sl = SortedList('abc')\n >>> sl * 3\n SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])\n \n :param int num: count of shallow copies\n :return: new sorted list\n \n \"\"\"\n values = reduce(iadd, self._lists, []) * num\n return self.__class__(values)\n \n __rmul__ = __mul__\n \n def __imul__(self, num):\n \"\"\"Update the sorted list with `num` shallow copies of values.\n \n ``sl.__imul__(num)`` <==> ``sl *= num``\n \n Runtime complexity: `O(n*log(n))`\n \n >>> sl = SortedList('abc')\n >>> sl *= 3\n >>> sl\n SortedList(['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'])\n \n :param int num: count of shallow copies\n :return: existing sorted list\n \n \"\"\"\n values = reduce(iadd, self._lists, []) * num\n self._clear()\n self._update(values)\n return self\n \n def __make_cmp(seq_op, symbol, doc):\n \"Make comparator method.\"\n \n def comparer(self, other):\n \"Compare method for sorted list and sequence.\"\n if not isinstance(other, Sequence):\n return NotImplemented\n \n self_len = self._len\n len_other = len(other)\n \n if self_len != len_other:\n if seq_op is eq:\n return False\n if seq_op is ne:\n return True\n \n for alpha, beta in zip(self, other):\n if alpha != beta:\n return seq_op(alpha, beta)\n \n return seq_op(self_len, len_other)\n \n seq_op_name = seq_op.__name__\n comparer.__name__ = \"__{0}__\".format(seq_op_name)\n doc_str = \"\"\"Return true if and only if sorted list is {0} `other`.\n \n ``sl.__{1}__(other)`` <==> ``sl {2} other``\n \n Comparisons use lexicographical order as with sequences.\n \n Runtime complexity: `O(n)`\n \n :param other: `other` sequence\n :return: true if sorted list is {0} `other`\n \n \"\"\"\n comparer.__doc__ = dedent(doc_str.format(doc, seq_op_name, symbol))\n return comparer\n \n __eq__ = __make_cmp(eq, \"==\", \"equal to\")\n __ne__ = __make_cmp(ne, \"!=\", \"not equal to\")\n __lt__ = __make_cmp(lt, \"<\", \"less than\")\n __gt__ = __make_cmp(gt, \">\", \"greater than\")\n __le__ = __make_cmp(le, \"<=\", \"less than or equal to\")\n __ge__ = __make_cmp(ge, \">=\", \"greater than or equal to\")\n __make_cmp = staticmethod(__make_cmp)\n \n def __reduce__(self):\n values = reduce(iadd, self._lists, [])\n return (type(self), (values,))\n \n @recursive_repr()\n def __repr__(self):\n \"\"\"Return string representation of sorted list.\n \n ``sl.__repr__()`` <==> ``repr(sl)``\n \n :return: string representation\n \n \"\"\"\n return \"{0}({1!r})\".format(type(self).__name__, list(self))\n \n def _check(self):\n \"\"\"Check invariants of sorted list.\n \n Runtime complexity: `O(n)`\n \n \"\"\"\n try:\n assert self._load >= 4\n assert len(self._maxes) == len(self._lists)\n assert self._len == sum(len(sublist) for sublist in self._lists)\n \n # Check all sublists are sorted.\n \n for sublist in self._lists:\n for pos in range(1, len(sublist)):\n assert sublist[pos - 1] <= sublist[pos]\n \n # Check beginning/end of sublists are sorted.\n \n for pos in range(1, len(self._lists)):\n assert self._lists[pos - 1][-1] <= self._lists[pos][0]\n \n # Check _maxes index is the last value of each sublist.\n \n for pos in range(len(self._maxes)):\n assert self._maxes[pos] == self._lists[pos][-1]\n \n # Check sublist lengths are less than double load-factor.\n \n double = self._load << 1\n assert all(len(sublist) <= double for sublist in self._lists)\n \n # Check sublist lengths are greater than half load-factor for all\n # but the last sublist.\n \n half = self._load >> 1\n for pos in range(0, len(self._lists) - 1):\n assert len(self._lists[pos]) >= half\n \n if self._index:\n assert self._len == self._index[0]\n assert len(self._index) == self._offset + len(self._lists)\n \n # Check index leaf nodes equal length of sublists.\n \n for pos in range(len(self._lists)):\n leaf = self._index[self._offset + pos]\n assert leaf == len(self._lists[pos])\n \n # Check index branch nodes are the sum of their children.\n \n for pos in range(self._offset):\n child = (pos << 1) + 1\n if child >= len(self._index):\n assert self._index[pos] == 0\n elif child + 1 == len(self._index):\n assert self._index[pos] == self._index[child]\n else:\n child_sum = self._index[child] + self._index[child + 1]\n assert child_sum == self._index[pos]\n except:\n traceback.print_exc(file=sys.stdout)\n print(\"len\", self._len)\n print(\"load\", self._load)\n print(\"offset\", self._offset)\n print(\"len_index\", len(self._index))\n print(\"index\", self._index)\n print(\"len_maxes\", len(self._maxes))\n print(\"maxes\", self._maxes)\n print(\"len_lists\", len(self._lists))\n print(\"lists\", self._lists)\n raise\ndef solve():\n n=int(input())\n a=list(map(int,input().split()))\n b=list(map(int,input().split()))\n sl=SortedList(a)\n ans=0\n score=0\n for i in range(1,n+1):\n if len(sl)score):\n score=cur\n ans=i\n sl.discard(a[b[i-1]-1])\n \n print(score,ans)\n \nt=int(input())\nfor _ in range(t):\n solve()", + "import math\nfrom bisect import bisect_left, bisect_right\nfrom typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional\nT = TypeVar('T')\n \nclass SortedMultiset(Generic[T]):\n BUCKET_RATIO = 16\n SPLIT_RATIO = 24\n \n def __init__(self, a: Iterable[T] = []) -> None:\n \"Make a new SortedMultiset from iterable. / O(N) if sorted / O(N log N)\"\n a = list(a)\n n = self.size = len(a)\n if any(a[i] > a[i + 1] for i in range(n - 1)):\n a.sort()\n num_bucket = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO)))\n self.a = [a[n * i // num_bucket : n * (i + 1) // num_bucket] for i in range(num_bucket)]\n \n def __iter__(self) -> Iterator[T]:\n for i in self.a:\n for j in i: yield j\n \n def __reversed__(self) -> Iterator[T]:\n for i in reversed(self.a):\n for j in reversed(i): yield j\n \n def __eq__(self, other) -> bool:\n return list(self) == list(other)\n \n def __len__(self) -> int:\n return self.size\n \n def __repr__(self) -> str:\n return \"SortedMultiset\" + str(self.a)\n \n def __str__(self) -> str:\n s = str(list(self))\n return \"{\" + s[1 : len(s) - 1] + \"}\"\n \n def _position(self, x: T) -> Tuple[List[T], int, int]:\n \"return the bucket, index of the bucket and position in which x should be. self must not be empty.\"\n for i, a in enumerate(self.a):\n if x <= a[-1]: break\n return (a, i, bisect_left(a, x))\n \n def __contains__(self, x: T) -> bool:\n if self.size == 0: return False\n a, _, i = self._position(x)\n return i != len(a) and a[i] == x\n \n def count(self, x: T) -> int:\n \"Count the number of x.\"\n return self.index_right(x) - self.index(x)\n \n def add(self, x: T) -> None:\n \"Add an element. / O(√N)\"\n if self.size == 0:\n self.a = [[x]]\n self.size = 1\n return\n a, b, i = self._position(x)\n a.insert(i, x)\n self.size += 1\n if len(a) > len(self.a) * self.SPLIT_RATIO:\n mid = len(a) >> 1\n self.a[b:b+1] = [a[:mid], a[mid:]]\n \n def _pop(self, a: List[T], b: int, i: int) -> T:\n ans = a.pop(i)\n self.size -= 1\n if not a: del self.a[b]\n return ans\n \n def discard(self, x: T) -> bool:\n \"Remove an element and return True if removed. / O(√N)\"\n if self.size == 0: return False\n a, b, i = self._position(x)\n if i == len(a) or a[i] != x: return False\n self._pop(a, b, i)\n return True\n \n def lt(self, x: T) -> Optional[T]:\n \"Find the largest element < x, or None if it doesn't exist.\"\n for a in reversed(self.a):\n if a[0] < x:\n return a[bisect_left(a, x) - 1]\n \n def le(self, x: T) -> Optional[T]:\n \"Find the largest element <= x, or None if it doesn't exist.\"\n for a in reversed(self.a):\n if a[0] <= x:\n return a[bisect_right(a, x) - 1]\n \n def gt(self, x: T) -> Optional[T]:\n \"Find the smallest element > x, or None if it doesn't exist.\"\n for a in self.a:\n if a[-1] > x:\n return a[bisect_right(a, x)]\n \n def ge(self, x: T) -> Optional[T]:\n \"Find the smallest element >= x, or None if it doesn't exist.\"\n for a in self.a:\n if a[-1] >= x:\n return a[bisect_left(a, x)]\n \n def __getitem__(self, i: int) -> T:\n \"Return the i-th element.\"\n if i < 0:\n for a in reversed(self.a):\n i += len(a)\n if i >= 0: return a[i]\n else:\n for a in self.a:\n if i < len(a): return a[i]\n i -= len(a)\n raise IndexError\n \n def pop(self, i: int = -1) -> T:\n \"Pop and return the i-th element.\"\n if i < 0:\n for b, a in enumerate(reversed(self.a)):\n i += len(a)\n if i >= 0: return self._pop(a, ~b, i)\n else:\n for b, a in enumerate(self.a):\n if i < len(a): return self._pop(a, b, i)\n i -= len(a)\n raise IndexError\n \n def index(self, x: T) -> int:\n \"Count the number of elements < x.\"\n ans = 0\n for a in self.a:\n if a[-1] >= x:\n return ans + bisect_left(a, x)\n ans += len(a)\n return ans\n \n def index_right(self, x: T) -> int:\n \"Count the number of elements <= x.\"\n ans = 0\n for a in self.a:\n if a[-1] > x:\n return ans + bisect_right(a, x)\n ans += len(a)\n return ans\n \n \n \nt = int(input())\nfor _ in range(t):\n n = int(input())\n v = list(map(int,input().split()))\n p = list(map(int,input().split()))\n a = []\n for i in range(n):\n a.append(-v[p[i]-1])\n r = SortedMultiset(a)\n ans = -1\n idx = 1\n for i in range((n+1)//2):\n x = (i+1)* -r[i] \n if x >ans:\n ans = x\n idx = i +1\n r.discard(a[i]) \n print(ans,idx)" + ] + }, + { + "task_name": "1946_A", + "description": "You are given an array a of n integers.\n\nThe median of an array q_1, q_2, \\ldots, q_k is the number p_{\\lceil\n\\frac{k}{2} \\rceil} , where p is the array q sorted in non-decreasing order.\nFor example, the median of the array [9, 5, 1, 2, 6] is 5 , as in the sorted\narray [1, 2, 5, 6, 9] , the number at index \\lceil \\frac{5}{2} \\rceil = 3 is 5\n, and the median of the array [9, 2, 8, 3] is 3 , as in the sorted array [2,\n3, 8, 9] , the number at index \\lceil \\frac{4}{2} \\rceil = 2 is 3 .\n\nYou are allowed to choose an integer i (1 \\le i \\le n ) and increase a_i by 1\nin one operation.\n\nYour task is to find the minimum number of operations required to increase the\nmedian of the array.\n\nNote that the array a may not necessarily contain distinct numbers.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows the\ndescription of the test cases.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 10^5\n) — the length of the array a .\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the array a .\n\nIt is guaranteed that the sum of the values of n over all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of operations\nrequired to increase the median of the array.\n\nExample\n\nInput\n\n 8\n \n 3\n \n 2 2 8\n \n 4\n \n 7 3 3 1\n \n 1\n \n 1000000000\n \n 5\n \n 5 5 5 4 5\n \n 6\n \n 2 1 2 3 1 4\n \n 2\n \n 1 2\n \n 2\n \n 1 1\n \n 4\n \n 5 5 5 5\n\nOutput\n\n 1\n 2\n 1\n 3\n 2\n 1\n 2\n 3\n \nNote\n\nIn the first test case, you can apply one operation to the first number and\nobtain the array [3, 2, 8] , the median of this array is 3 , as it is the\nnumber at index \\lceil \\frac{3}{2} \\rceil = 2 in the non-decreasing sorted\narray [2, 3, 8] . The median of the original array [2, 2, 8] is 2 , as it is\nthe number at index \\lceil \\frac{3}{2} \\rceil = 2 in the non-decreasing sorted\narray [2, 2, 8] . Thus, the median increased (3 > 2 ) in just one operation.\n\nIn the fourth test case, you can apply one operation to each of the numbers at\nindices 1, 2, 3 and obtain the array [6, 6, 6, 4, 5] , the median of this\narray is 6 , as it is the number at index \\lceil \\frac{5}{2} \\rceil = 3 in the\nnon-decreasing sorted array [4, 5, 6, 6, 6] . The median of the original array\n[5, 5, 5, 4, 5] is 5 , as it is the number at index \\lceil \\frac{5}{2} \\rceil\n= 2 in the non-decreasing sorted array [4, 5, 5, 5, 5] . Thus, the median\nincreased (6 > 5 ) in three operations. It can be shown that this is the\nminimum possible number of operations.\n\nIn the fifth test case, you can apply one operation to each of the numbers at\nindices 1, 3 and obtain the array [3, 1, 3, 3, 1, 4] , the median of this\narray is 3 , as it is the number at index \\lceil \\frac{6}{2} \\rceil = 3 in the\nnon-decreasing sorted array [1, 1, 3, 3, 3, 4] . The median of the original\narray [2, 1, 2, 3, 1, 4] is 2 , as it is the number at index \\lceil\n\\frac{6}{2} \\rceil = 3 in the non-decreasing sorted array [1, 1, 2, 2, 3, 4] .\nThus, the median increased (3 > 2 ) in two operations. It can be shown that\nthis is the minimum possible number of operations.", + "generated_code": [ + "t=int(input())\n \nwhile t>0:\n t-=1\n n=int(input())\n a=list(map(int,input().split()))\n a.sort()\n if n==1:\n print(1)\n else:\n res=0\n mdx=(n)//2 +n%2-1\n for i in range(mdx,n):\n if a[mdx]==a[i]:\n res+=1\n print(res)", + "def minimum_operations_to_increase_median(test_cases):\n results = []\n for case in test_cases:\n n, a = case\n a.sort()\n median_index = (n - 1) // 2\n median_value = a[median_index]\n \n operations = 0\n while median_index < n and a[median_index] == median_value:\n median_index += 1\n operations += 1\n \n results.append(operations)\n \n return results\n \n# Read input\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \n# Parse input\nindex = 0\nt = int(data[index])\nindex += 1\n \ntest_cases = []\nfor _ in range(t):\n n = int(data[index])\n index += 1\n a = list(map(int, data[index:index + n]))\n index += n\n test_cases.append((n, a))\n \n# Compute results\nresults = minimum_operations_to_increase_median(test_cases)\n \n# Print results\nfor result in results:\n print(result)", + "'''Median of Array'''\nt = int(input())\nfor _ in range(t):\n n = int(input().strip())\n a = list(map(int, input().strip().split()))\n \n a.sort()\n p = (n + 1) // 2 - 1\n res = a[p:].count(a[p])\n \n print(res)" + ] + }, + { + "task_name": "1946_B", + "description": "You have an array a of n integers.\n\nYou perform exactly k operations on it. In one operation, you select any\ncontiguous subarray of the array a (possibly empty) and insert the sum of this\nsubarray anywhere in the array.\n\nYour task is to find the maximum possible sum of the array after k such\noperations.\n\nAs this number can be very large, output the answer modulo 10^9 + 7 .\n\nReminder: the remainder of a number x modulo p is the smallest non-negative y\nsuch that there exists an integer q and x = p \\cdot q + y .\n\nInput\n\nEach test consists of several test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows the\ndescription of the test cases.\n\nThe first line of each test case contains two integers n and k (1 \\le n, k \\le\n2 \\cdot 10^5 ) — the length of the array a and the number of operations,\nrespectively.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n\n(-10^9 \\le a_i \\le 10^9 ) — the array a itself.\n\nIt is guaranteed that the sum of the values of n and k for all test cases does\nnot exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test, output a single integer — the maximum sum of the array that can\nbe obtained after k operations modulo 10^9 + 7 .\n\nExample\n\nInput\n\n 12\n \n 2 2\n \n -4 -7\n \n 3 3\n \n 2 2 8\n \n 1 7\n \n 7\n \n 5 1\n \n 4 -2 8 -12 9\n \n 7 4\n \n 8 14 -9 6 0 -1 3\n \n 7 100\n \n 5 3 -8 12 -5 -9 3\n \n 6 1000\n \n -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000\n \n 2 1\n \n 1000000000 8\n \n 5 4\n \n 0 0 0 0 0\n \n 6 10\n \n 48973 757292 58277 -38574 27475 999984\n \n 7 1\n \n -1000 1000 -1000 1000 -1000 1000 -1000\n \n 10 10050\n \n 408293874 -3498597 7374783 295774930 -48574034 26623784 498754833 -294875830 283045804 85938045\n\nOutput\n\n 999999996\n 96\n 896\n 17\n 351\n 716455332\n 42\n 2\n 0\n 897909241\n 0\n 416571966\n \nNote\n\nIn the first test case, it is advantageous to take an empty subarray of the\narray twice and insert the sum of the empty subarray (zero) anywhere, then the\nsum of the resulting array will be (-4) + (-7) + 0 + 0 = -11 , modulo 10^9 + 7\nthis is 999\\,999\\,996 .\n\nIn the second test case, it is advantageous to take the sum of the entire\narray three times and place it anywhere in the array, then one of the possible\nsequences of actions: [2, 2, 8 ] \\rightarrow [2, 2, 8, 12 ] \\rightarrow [2, 2,\n8, 12, 24 ] \\rightarrow [2, 2, 8, 12, 24, 48 ], the sum of the final array is\n2 + 2 + 8 + 12 + 24 + 48 = 96 .\n\nIn the fourth test case, it is advantageous to take a subarray of the array\nconsisting of the first three numbers (i.e. consisting of the numbers 4, -2\nand 8 ) and insert its sum at the beginning of the array, thereby obtaining\nthe array [10, 4, -2, 8, -12, 9 ], the sum of this array is 17 .\n\nIn the seventh test case, it will always be advantageous for us to take an\nempty subarray of the array. In this case, the sum of the resulting array will\nnot differ from the sum of the original. The answer will be the sum of the\noriginal array, taken modulo — 42 , because (-6 \\cdot (10^9 + 7) + 42 =\n-6\\,000\\,000\\,000) .", + "generated_code": [ + "import math\nfor i in range(int(input())):\n n,k=map(int,input().split())\n l=(list(map(int,input().split())))\n #print(l)\n c=0\n maxi=0\n for ele in l:\n if ele<0 and c<=abs(ele):\n maxi=max(c,maxi);c=0\n else:\n c+=ele\n maxi=max(c,maxi)\n maxi=max(c,maxi)\n print(((2**k)*maxi-maxi+sum(l))%1000000007)", + "import sys\n \nMOD = 1000000007\n \nT = int(sys.stdin.readline().strip())\nfor _ in range(T):\n n, k = map(int, sys.stdin.readline().strip().split())\n a = list(map(int, sys.stdin.readline().strip().split()))\n s = sum(a)\n t, tmp = 0, 0\n for x in a:\n tmp += x\n if tmp < 0:\n tmp = 0\n t = max(tmp ,t)\n ans = ((s + t) % MOD + MOD) % MOD\n for i in range(k - 1):\n t *= 2\n t %= MOD\n ans += t\n ans %= MOD\n print(ans)", + "from math import *\n \n \n \ndef mod(number):\n return number % 1000000007\n \ndef max_sum_segment(arr):\n new_segment = []\n max_segment = [0, 0]\n segments_variants = []\n max_sum = -1\n for i in range(len(arr)):\n #print(i)\n #print(new_segment)\n #print(max_segment)\n #print()\n if new_segment:\n if arr[i] < 0:\n if max_segment[0] > new_segment[0]:\n segments_variants.append(max_segment + [i - 1])\n else:\n segments_variants.append(new_segment + [i - 1])\n max_segment = new_segment\n new_segment = []\n max_segment[0] += arr[i]\n else:\n max_segment[0] += arr[i]\n new_segment[0] += arr[i]\n else:\n if arr[i] >= 0:\n new_segment = [arr[i], i]\n max_segment[0] += arr[i]\n segments_variants.append(max_segment + [len(arr) - 1])\n segments_variants.append(new_segment + [len(arr) - 1])\n total_max_segment = [-1]\n #print(segments_variants)\n for segment in segments_variants:\n if total_max_segment[0] < segment[0] and len(segment) != 1:\n total_max_segment = segment\n return total_max_segment\n \ndef repeat(number, quantity):\n answer = 0\n \n \n \nt = int(input())\n \nfor _ in range(t):\n n, k = map(int, input().split())\n a = list(map(int, input().split()))\n \n max_segment = max_sum_segment(a)\n #print(max_segment)\n if max_segment[0] == -1: max_segment[0] = 0\n \n answer = max_segment[0] * 2 ** k + sum(a) - max_segment[0]\n print(mod(answer))" + ] + }, + { + "task_name": "1946_C", + "description": "You are given a tree with n vertices.\n\nYour task is to find the maximum number x such that it is possible to remove\nexactly k edges from this tree in such a way that the size of each remaining\nconnected component^{\\dagger} is at least x .\n\n^{\\dagger} Two vertices v and u are in the same connected component if there\nexists a sequence of numbers t_1, t_2, \\ldots, t_k of arbitrary length k ,\nsuch that t_1 = v , t_k = u , and for each i from 1 to k - 1 , vertices t_i\nand t_{i+1} are connected by an edge.\n\nInput\n\nEach test consists of several sets of input data. The first line contains a\nsingle integer t (1 \\le t \\le 10^4 ) — the number of sets of input data. This\nis followed by a description of the sets of input data.\n\nThe first line of each set of input data contains two integers n and k (1 \\le\nk < n \\le 10^5 ) — the number of vertices in the tree and the number of edges\nto be removed.\n\nEach of the next n - 1 lines of each set of input data contains two integers v\nand u (1 \\le v, u \\le n ) — the next edge of the tree.\n\nIt is guaranteed that the sum of the values of n for all sets of input data\ndoes not exceed 10^5 .\n\nOutput\n\nFor each set of input data, output a single line containing the maximum number\nx such that it is possible to remove exactly k edges from the tree in such a\nway that the size of each remaining connected component is at least x .\n\nExample\n\nInput\n\n 6\n \n 5 1\n \n 1 2\n \n 1 3\n \n 3 4\n \n 3 5\n \n 2 1\n \n 1 2\n \n 6 1\n \n 1 2\n \n 2 3\n \n 3 4\n \n 4 5\n \n 5 6\n \n 3 1\n \n 1 2\n \n 1 3\n \n 8 2\n \n 1 2\n \n 1 3\n \n 2 4\n \n 2 5\n \n 3 6\n \n 3 7\n \n 3 8\n \n 6 2\n \n 1 2\n \n 2 3\n \n 1 4\n \n 4 5\n \n 5 6\n\nOutput\n\n 2\n 1\n 3\n 1\n 1\n 2\n \nNote\n\nThe tree in the first set of input data:\n\n![](https://espresso.codeforces.com/799bacd3be0dda357800fdfc3eadbf38ab259c51.png)\n\nAfter removing the edge 1 — 3 , the tree will look as follows:\n\n![](https://espresso.codeforces.com/a59ae10eeac1212e1e56fc7fe5f6a47764269104.png)\n\nThe tree has split into two connected components. The first component consists\nof two vertices: 1 and 2 . The second connected component consists of three\nvertices: 3, 4 and 5 . In both connected components, there are at least two\nvertices. It can be shown that the answer 3 is not achievable, so the answer\nis 2 .", + "generated_code": [ + "# import resource, sys\n# sys.setrecursionlimit(10**7)\n# resource.setrlimit(resource.RLIMIT_STACK, (10**7,-1))\n# import sys\n# sys.setrecursionlimit(999999999)\ndef solve(n,k,edges):\n g=[[] for _ in range(n+1)]\n for a,b in edges:\n g[a].append(b)\n g[b].append(a)\n c=0\n def check(A):\n stack=[(1,1)]\n visited=set()\n d={1:1}\n r=0\n while True:\n x,p=stack[-1]\n if x not in visited:\n visited.add(x)\n d[x]=1\n for node in g[x]:\n if node!=p:\n stack.append((node,x))\n else:\n if(x==1):\n break\n if(d[x]>=A):\n r+=1\n else:\n d[p]+=d[x]\n stack.pop()\n visited.remove(x)\n del d[x]\n # print(stack,d,r)\n if r>k or (d[1]>=A and r==k):\n return True\n return False\n \n # def dfs(x,y):\n # c=1\n # r=0\n # for node in g[x]:\n # if node==y:\n # continue\n # ans,rn=dfs(node,x)\n # r+=rn\n # if ans>=A:\n # r+=1\n # else:\n # c+=ans\n # # print(node,ans)\n # return c,r\n \n # ans,r=dfs(1,1)\n # print(ans,r,x)\n # if r>k or (ans>=A and r==k):\n # return True\n # return False\n # check(1)\n l=1\n r=(n//k)\n # print(l,r,n,k)\n while l<=r:\n mid=l+((r-l)//2)\n # print(mid,check(mid))\n if check(mid):\n l=mid+1\n else:\n r=mid-1\n # print(l,r)\n print(r)\n \nq=[]\nfor i in range(int(input())):\n n,k=map(int,input().split(' '))\n edges=[]\n for _ in range(n-1):\n a,b=map(int,input().split(' '))\n edges.append((a,b))\n # if(i==325):\n # print(n,k,edges)\n solve(n,k,edges)\n # q.append((n,k,edges))\n \n# print('ans:')\nfor n,k,edges in q:\n solve(n,k,edges)", + "import sys\nimport threading\n \nthreading.stack_size(1 << 26)\nsys.setrecursionlimit(1 << 30)\n \ndef boom():\n def solve():\n global numCuts\n n, k = list(map(int, sys.stdin.readline().split()))\n adj = [[] for i in range(n + 1)]\n for i in range(n - 1):\n a, b = list(map(int, sys.stdin.readline().split()))\n adj[a].append(b)\n adj[b].append(a)\n L = 1\n R = int(1e5 + 1)\n numCuts = 0\n \n def dfs(a, p):\n global numCuts\n vertices = 1\n for b in adj[a]:\n if b != p:\n vertices += dfs(b, a)\n if vertices >= x and a != p:\n numCuts += 1\n return 0\n return vertices\n \n while R - L > 1:\n x = (L + R) // 2\n numCuts = 0\n leftover = dfs(1, 1)\n if numCuts > k or (numCuts == k and leftover >= x):\n L = x\n else:\n R = x\n print(L)\n \n for _ in range(int(sys.stdin.readline())):\n solve()\n \nmain_thread = threading.Thread(target=boom)\nmain_thread.start()\nmain_thread.join()", + "import sys\n \nclass TreeNode:\n \n def __init__(self):\n self.edges = []\n self.children = []\n self.subtree_size = 1\n self.parent = None\n \n def __str__(self):\n return f\"(edges: {self.edges}, children: {self.children}, subtree_size: {self.subtree_size}, parent: {self.parent})\\n\"\n \n def __repr__(self):\n return self.__str__()\n \nclass Tree:\n \n def __init__(self, n):\n self.vertices = [TreeNode() for _ in range(n)]\n \n def add_edge(self, u: int, v: int) -> None:\n self.vertices[u].edges.append(v)\n self.vertices[v].edges.append(u)\n \n def root_tree(self, v: int, root: int) -> None:\n self.vertices[v].parent = root\n for u in self.vertices[v].edges:\n if u != root:\n self.vertices[v].children.append(u)\n self.root_tree(u, v)\n self.vertices[v].subtree_size += self.vertices[u].subtree_size\n \n def root_tree_non_recursive(self, v: int, root: int) -> None:\n stack = [(v, root)]\n while stack:\n (v, root) = stack.pop()\n self.vertices[v].parent = root\n for u in self.vertices[v].edges:\n if u != root:\n self.vertices[v].children.append(u)\n stack.append((u, v))\n self.vertices[v].subtree_size += self.vertices[u].subtree_size\n \n def __str__(self):\n return str(self.vertices)\n \ndef check_x_dfs(tree: Tree, s: int, x: int) -> (int, int):\n stack = [(s, False)]\n good_components = {}\n remaining_size = {}\n while stack:\n (v, postorder) = stack.pop()\n if not postorder:\n stack.append((v, True))\n good_components[v] = 0\n remaining_size[v] = 1\n for u in tree.vertices[v].children:\n stack.append((u, False))\n elif postorder: \n for u in tree.vertices[v].children:\n good_components[v] += good_components[u]\n if remaining_size[u] >= x:\n good_components[v] += 1\n else:\n remaining_size[v] += remaining_size[u]\n # print(v, tree.vertices[v].good_components, tree.vertices[v].remaining_size)\n return (good_components[s], remaining_size[s])\n \ndef check_x_dfs_recursive(tree: Tree, v: int, x: int) -> (int, int):\n good_components = 0\n remaining_size = 1\n \n for u in tree.vertices[v].children:\n (good_components_subtree, remaining_size_subtree) = check_x_dfs_recursive(tree, u, x)\n good_components += good_components_subtree\n if remaining_size_subtree >= x:\n good_components += 1\n else:\n remaining_size += remaining_size_subtree\n print(v, good_components, remaining_size)\n return (good_components, remaining_size)\n \n \ndef check_x(tree: Tree, n: int, k: int, x: int) -> bool:\n # print(\"checking \", x)\n (good_components, remaining_size) = check_x_dfs(tree, 0, x)\n if good_components > k:\n return True\n if good_components == k and remaining_size >= x:\n return True\n return False\n \ndef find_x(tree: Tree, n: int, k: int) -> int:\n beg = 1\n end = n\n while beg < end:\n mid = (beg + end + 1) // 2\n if check_x(tree, n, k, mid):\n beg = mid\n else:\n end = mid - 1\n return beg\n \ndef solve_case():\n [n, k] = map(int, input().split())\n tree = Tree(n)\n for i in range(1, n):\n [u, v] = map(int, input().split())\n tree.add_edge(u-1, v-1)\n tree.root_tree_non_recursive(0, -1)\n print(find_x(tree, n, k))\n \nif __name__ == '__main__':\n sys.setrecursionlimit(int(1e5)*2)\n t = int(input())\n while t > 0:\n t -= 1\n solve_case()" + ] + }, + { + "task_name": "1946_D", + "description": "Yarik's birthday is coming soon, and Mark decided to give him an array a of\nlength n .\n\nMark knows that Yarik loves bitwise operations very much, and he also has a\nfavorite number x , so Mark wants to find the maximum number k such that it is\npossible to select pairs of numbers [l_1, r_1 ], [l_2, r_2 ], \\ldots [l_k, r_k\n], such that:\n\n * l_1 = 1 . \n * r_k = n . \n * l_i \\le r_i for all i from 1 to k . \n * r_i + 1 = l_{i + 1} for all i from 1 to k - 1 . \n * (a_{l_1} \\oplus a_{l_1 + 1} \\oplus \\ldots \\oplus a_{r_1}) | (a_{l_2} \\oplus a_{l_2 + 1} \\oplus \\ldots \\oplus a_{r_2}) | \\ldots | (a_{l_k} \\oplus a_{l_k + 1} \\oplus \\ldots \\oplus a_{r_k}) \\le x , where \\oplus denotes the operation of [bitwise XOR](https://en.wikipedia.org/wiki/Exclusive_or), and | denotes the operation of [bitwise OR](https://en.wikipedia.org/wiki/Logical_disjunction). \n\nIf such k does not exist, then output -1 .\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. The following lines\ncontain the descriptions of the test cases.\n\nThe first line of each test case contains two integers n and x (1 \\le n \\le\n10^5, 0 \\le x < 2^{30} ) — the length of the array a and the number x\nrespectively.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (0\n\\le a_i < 2^{30} ) — the array a itself.\n\nIt is guaranteed that the sum of the values of n across all test cases does\nnot exceed 10^5 .\n\nOutput\n\nFor each test case, output a single integer on a separate line — the maximum\nsuitable number k , and -1 if such k does not exist.\n\nExample\n\nInput\n\n 8\n \n 3 1\n \n 1 2 3\n \n 2 2\n \n 1 1\n \n 2 2\n \n 1 3\n \n 2 3\n \n 0 0\n \n 3 2\n \n 0 0 1\n \n 4 2\n \n 1 3 3 7\n \n 2 2\n \n 2 3\n \n 5 0\n \n 0 1 2 2 1\n\nOutput\n\n 2\n 2\n 1\n 2\n 3\n -1\n 1\n 2\n \nNote\n\nIn the first test case, you can take k equal to 2 and choose two segments [1, 1 ] and [2, 3 ], (1) | (2 \\oplus 3) = 1 . It can be shown that 2 is the maximum possible answer.\n\nIn the second test case, the segments [1, 1 ] and [2, 2 ] are suitable, (1) | (1) = 1 . It is not possible to make more segments.\n\nIn the third test case, it is not possible to choose 2 segments, as (1) | (3) = 3 > 2 , so the optimal answer is 1 .", + "generated_code": [ + "import sys\ninput = sys.stdin.readline\n \ndef readList():\n return list(map(int, input().split()))\ndef readInt():\n return int(input())\ndef readInts():\n return map(int, input().split())\ndef readStr():\n return input().strip()\n \n# BF-OB5, EC, DB, CC, CL\ndef solve():\n n, x = readInts()\n a = readList()\n t, ans = [], -1\n for i in range(29, -1, -1):\n u, v = (x >> i) & 1, sum([(val >> i) & 1 for val in a])\n if u == v == 0:\n continue\n \n if u == 0:\n if v % 2:\n return ans\n else:\n op = ai = 0\n for val in a:\n op ^= (val >> i) & 1\n ai ^= val\n if not op:\n t.append(ai)\n ai = 0\n a, t = t, []\n \n else:\n if v % 2:\n continue\n elif v:\n op = cnt = 0\n for val in a:\n op ^= (val >> i) & 1\n if not op:\n cnt += 1\n ans = max(ans, cnt)\n else:\n break\n return max(ans, len(a))\n \n \nfor _ in range(int(input())):\n print(solve())", + "def thing(arr, x):\n \n\tdef find_new(cur_arr, bit):\n\t\t#if the current x bit is on then we have 2 options\n\t\t#1: turn it off (make all the ones with that bit even)\n\t\t#2: leave it on and continue\n \n\t\t#if the current x bit is off, we must \n \n\t\tif bit == -1:\n\t\t\treturn len(cur_arr)\n \n\t\tnew_arr = []\n\t\txor = 0\n \n\t\tfor i in cur_arr:\n\t\t\txor ^= i\n\t\t\tif not (xor >> bit) & 1:\n\t\t\t\tnew_arr.append(xor)\n\t\t\t\txor = 0\n \n\t\tif (xor >> bit) & 1:\n\t\t\tthing1 = -1\n\t\telse:\n\t\t\tthing1 = len(new_arr)\n \n\t\tif (x >> bit) & 1:\n\t\t\treturn max(thing1, find_new(cur_arr, bit - 1))\n\t\telif thing1 != -1:\n\t\t\treturn find_new(new_arr, bit - 1)\n\t\treturn -1\n \n\treturn find_new(arr, 30)\n \n \n \ntestcases = range(int(input()))\n \nfor case in testcases:\n\tn, k = [int(i) for i in input().split(\" \")]\n\tarr = [int(i) for i in input().split(\" \")]\n\tprint(thing(arr, k))" + ] + }, + { + "task_name": "1946_E", + "description": "Some permutation of length n is guessed.\n\nYou are given the indices of its prefix maximums and suffix maximums.\n\nRecall that a permutation of length k is an array of size k such that each\ninteger from 1 to k occurs exactly once.\n\nPrefix maximums are the elements that are the maximum on the prefix ending at\nthat element. More formally, the element a_i is a prefix maximum if a_i > a_j\nfor every j < i .\n\nSimilarly, suffix maximums are defined, the element a_i is a suffix maximum if\na_i > a_j for every j > i .\n\nYou need to output the number of different permutations that could have been\nguessed.\n\nAs this number can be very large, output the answer modulo 10^9 + 7 .\n\nInput\n\nEach test consists of several test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows the\ndescription of the test cases.\n\nThe first line of each test case contains three integers n, m_1 and m_2 (1 \\le\nm_1, m_2 \\le n \\le 2 \\cdot 10^5 ) — the length of the permutation, the number\nof prefix maximums, and the number of suffix maximums, respectively.\n\nThe second line of each test case contains m_1 integers p_1 < p_2 < \\ldots <\np_{m_1} (1 \\le p_i \\le n ) — the indices of the prefix maximums in increasing\norder.\n\nThe third line of each test case contains m_2 integers s_1 < s_2 < \\ldots <\ns_{m_2} (1 \\le s_i \\le n ) — the indices of the suffix maximums in increasing\norder.\n\nIt is guaranteed that the sum of the values of n for all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer on a separate line — the number of\nsuitable permutations modulo 10^9 + 7 .\n\nExample\n\nInput\n\n 6\n \n 1 1 1\n \n 1\n \n 1\n \n 4 2 3\n \n 1 2\n \n 2 3 4\n \n 3 3 1\n \n 1 2 3\n \n 3\n \n 5 3 4\n \n 1 2 3\n \n 2 3 4 5\n \n 20 5 4\n \n 1 2 3 4 12\n \n 12 13 18 20\n \n 6 2 3\n \n 1 3\n \n 3 4 6\n\nOutput\n\n 1\n 3\n 1\n 0\n 317580808\n 10\n \nNote\n\nThe following permutations are suitable for the second set of input data:\n\n * [1, 4, 3, 2] \n * [2, 4, 3, 1] \n * [3, 4, 2, 1] \n\nThe following permutations are suitable for the sixth set of input data:\n\n * [2, 1, 6, 5, 3, 4] \n * [3, 1, 6, 5, 2, 4] \n * [3, 2, 6, 5, 1, 4] \n * [4, 1, 6, 5, 2, 3] \n * [4, 2, 6, 5, 1, 3] \n * [4, 3, 6, 5, 1, 2] \n * [5, 1, 6, 4, 2, 3] \n * [5, 2, 6, 4, 1, 3] \n * [5, 3, 6, 4, 1, 2] \n * [5, 4, 6, 3, 1, 2]", + "generated_code": [ + "def alge(a, b):\n if b == 0:\n return 1, 0\n if a < b:\n c, d = alge(b, a)\n return d, c\n if a % b == 0:\n return 1, -(a // b - 1)\n c, d = alge(b, a % b)\n return d, c - a // b * d\n \n \ndef deli(a, b):\n c, d = alge(b, 1000000007)\n return c * a % 1000000007\n \n \n#print(75582 * 15 * 120)\nfacts = [1]\nch = 1\nfor i in range(1, 200002):\n ch *= i\n ch %= 1000000007\n facts.append(ch)\nfor _ in range(int(input())):\n #n = int(input())\n n, m1, m2 = map(int, input().split())\n p = list(map(int, input().split()))\n s = list(map(int, input().split()))\n #s = str(input())\n if p[-1] != s[0] or p[0] != 1 or s[-1] != n:\n print(0)\n else:\n ans = 1\n kol = n\n for x in s:\n cnk = deli(facts[kol - 1], facts[n - x] * facts[kol - 1 + x - n])\n #print(cnk, kol - 1, n - x)\n ans *= cnk\n ans %= 1000000007\n kol = n - x\n kol = s[0] - 1\n p2 = []\n for i in range(m1 - 2, -1, -1):\n p2.append(p[i])\n for x in p2:\n cnk = deli(facts[kol - 1], facts[x - 1] * facts[kol - x])\n #print(cnk, kol - 1, x - 1)\n ans *= cnk\n ans %= 1000000007\n kol = x - 1\n for i in range(m1 - 1):\n ans *= facts[p[i + 1] - p[i] - 1]\n ans %= 1000000007\n for i in range(m2 - 1):\n ans *= facts[s[i + 1] - s[i] - 1]\n ans %= 1000000007\n print(ans)\n \n# cnk = 1\n# for i in range(1, 20):\n# cnk *= i\n# print(cnk)", + "import sys\nimport math\ninput = sys.stdin.readline\nMOD = int(1e9+7)\n \ndef comb(n1, n2):\n if n1 == n2:\n return 1\n if n2 == 0:\n return 1\n f1 = 1\n f2 = 1\n f3 = 1\n for i in range(1, n1+1):\n if i == n2+1:\n f2 = f1\n if i == n1 - n2 + 1:\n f3 = f1\n f1 = (f1*i)%MOD\n a = pow((f2*f3)%MOD, -1, MOD)\n return (f1*a)%MOD\n \ndef solve():\n N, M1, M2 = map(int, input().split())\n L = list(map(int, input().split()))\n R = list(map(int, input().split()))\n # if N == 1:\n # return 1\n if L[-1] != R[0]:\n return 0\n if L[0] != 1 or R[-1] != N:\n return 0\n if M1 > 1 and M2 > 1 and L[-2] == R[1]:\n return 0\n ans = comb(N-1, L[-1]-1)\n # left\n cur = M1 - 2\n if M1 > 1:\n nums_left = L[-1] - 2\n i = L[-1] - 1\n while i > 1:\n if i == L[cur]:\n cur -= 1\n else:\n ans = (ans*nums_left)%MOD\n nums_left -= 1\n i -= 1\n # right\n nums_left = N - R[0] - 1\n if M2 > 1:\n cur = 1\n i = R[0] + 1\n while i < N:\n if i == R[cur]:\n cur += 1\n else:\n ans = (ans*nums_left)%MOD\n nums_left -= 1\n i += 1\n return ans\n \nfor _ in range(int(input())):\n print(solve())" + ] + }, + { + "task_name": "1948_B", + "description": "You are given an integer array a of length n .\n\nYou can perform the following operation any number of times (possibly zero):\ntake any element of the array a , which is at least 10 , delete it, and\ninstead insert the digits that element consisted of in the same position, in\norder they appear in that element.\n\nFor example:\n\n * if we apply this operation to the 3 -rd element of the array [12, 3, 45, 67] , then the array becomes [12, 3, 4, 5, 67] . \n * if we apply this operation to the 2 -nd element of the array [2, 10] , then the array becomes [2, 1, 0] . \n\nYour task is to determine whether it is possible to make a sorted in non-\ndescending order using the aforementioned operation any number of times\n(possibly zero). In other words, you have to determine if it is possible to\ntransform the array a in such a way that a_1 \\le a_2 \\le \\dots \\le a_k , where\nk is the current length of the array a .\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^3 ) — the number of\ntest cases.\n\nEach test case consists of two lines:\n\n * the first line contains a single integer n (2 \\le n \\le 50 ). \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_i \\le 99 ). \n\nOutput\n\nFor each test case, print YES if it is possible to make a sorted in non-\ndecreasing order using the aforementioned operation; otherwise, print NO.\n\nYou can print each letter in any case. For example, yes, Yes, YeS will all be\nrecognized as a positive answer.\n\nExample\n\nInput\n\n 3\n \n 4\n \n 12 3 45 67\n \n 3\n \n 12 28 5\n \n 2\n \n 0 0\n\nOutput\n\n YES\n NO\n YES\n \nNote\n\nIn the first example, you can split the first element, then the array becomes\n[1, 2, 3, 45, 67] .\n\nIn the second example, there is no way to get a sorted array.\n\nIn the third example, the array is already sorted.", + "generated_code": [ + "n = int(input())\n \nfor _ in range(n):\n m = int(input())\n arr = [int(i) for i in input().split()]\n ans = True\n for i in range(m-1, 0, -1):\n if arr[i] < arr[i-1]:\n nums = [int(i) for i in str(arr[i-1])] + [arr[i]]\n if nums != sorted(nums):\n ans = False;break;\n arr[i-1] = nums[0]\n print([\"NO\",\"YES\"][ans])\n#23MCA051", + "n = int(input())\n \nfor _ in range(n):\n m = int(input())\n arr = [int(i) for i in input().split()]\n ans = True\n for i in range(m-1, 0, -1):\n if arr[i] < arr[i-1]:\n nums = [int(i) for i in str(arr[i-1])] + [arr[i]]\n if nums != sorted(nums):\n ans = False;break;\n arr[i-1] = nums[0]\n print([\"NO\",\"YES\"][ans])", + "def thing():\n k=int(input())\n a=input()\n a=list(map(int,a.split()))\n x=0\n y=0\n n=0\n c=[]\n for i in range(len(a)):\n if(a[i]>10 and i>0):\n x=int(a[i]%10)\n y=int(a[i]/10)\n if(y>=c[n-1]):\n if(y<=x): \n c.append(y)\n c.append(x)\n n=n+2\n else:\n c.append(a[i])\n n=n+1\n else:\n c.append(a[i])\n n=n+1\n elif(i==0 and a[i]>10):\n x=int(a[i]%10)\n y=int(a[i]/10)\n if(y<=x):\n c.append(y)\n c.append(x)\n n=n+2\n else:\n c.append(a[i])\n n=n+1\n else:\n c.append(a[i])\n n=n+1\n d=sorted(c)\n if(c==d):\n b.append(1)\n else:\n b.append(0)\nm=int(input())\nb=[]\nfor i in range(m):\n thing()\nfor i in range(m):\n if(b[i]==1):\n print(\"YES\")\n else:\n print(\"NO\")" + ] + }, + { + "task_name": "1948_C", + "description": "There is a grid, consisting of 2 rows and n columns. The rows are numbered\nfrom 1 to 2 from top to bottom. The columns are numbered from 1 to n from left\nto right. Each cell of the grid contains an arrow pointing either to the left\nor to the right. No arrow points outside the grid.\n\nThere is a robot that starts in a cell (1, 1) . Every second, the following\ntwo actions happen one after another:\n\n 1. Firstly, the robot moves left, right, down or up (it can't try to go outside the grid, and can't skip a move); \n 2. then it moves along the arrow that is placed in the current cell (the cell it ends up after its move). \n\nYour task is to determine whether the robot can reach the cell (2, n) .\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains a single integer (2 \\le n \\le 2\n\\cdot 10^5 ).\n\nThe second line contains a string consisting of exactly n characters < and/or\n> — the first row of the grid.\n\nThe third line contains a string consisting of exactly n characters < and/or >\n— the second row of the grid.\n\nAdditional constraints on the input:\n\n * n is even; \n * there are no arrows pointing outside the grid; \n * the sum of n over all test cases doesn't exceed 2 \\cdot 10^5 . \n\nOutput\n\nFor each test case, print YES if the robot can reach the cell (2, n) ;\notherwise, print NO.\n\nYou can print each letter in any case. For example, yes, Yes, YeS will all be\nrecognized as positive answer.\n\nExample\n\nInput\n\n 4\n \n 4\n \n >><<\n \n >>><\n \n 2\n \n ><\n \n ><\n \n 4\n \n >>><\n \n >><<\n \n 6\n \n >><<><\n \n ><>>><\n\nOutput\n\n YES\n YES\n NO\n YES\n \nNote\n\nIn the first example, one of the possible paths looks as follows: (1, 1)\n\\rightarrow (1, 2) \\rightarrow (1, 3) \\rightarrow (2, 3) \\rightarrow (2, 4) .\n\nIn the second example, one of the possible paths looks as follows: (1, 1)\n\\rightarrow (2, 1) \\rightarrow (2, 2) .\n\nIn the third example, there is no way to reach the cell (2, 4) .\n\nIn the fourth example, one of the possible paths looks as follows: (1, 1)\n\\rightarrow (2, 1) \\rightarrow (2, 2) \\rightarrow (1, 2) \\rightarrow (1, 3)\n\\rightarrow (2, 3) \\rightarrow (2, 4) \\rightarrow (2, 5) \\rightarrow (2, 6) .", + "generated_code": [ + "def can_reach_end(n, row1, row2):\n \"\"\"\n 判断机器人是否能够从 (1,1) 到达 (2,n)。\n \"\"\"\n half_n = n // 2 # 列数的一半(n 是偶数)\n for i in range(half_n - 1):\n if row1[2 * i + 1] == '<' and (row2[2 * i] == '<' or row2[2 * i + 2] == '<'):\n return \"No\"\n if row1[n - 1] == '<' and row2[n - 2] == '<':\n return \"No\"\n return \"Yes\"\n \ndef process_test_cases():\n \"\"\"\n 读取输入并处理每个测试用例。\n \"\"\"\n t = int(input())\n results = []\n for _ in range(t):\n n = int(input())\n row1 = input()\n row2 = input()\n results.append(can_reach_end(n, row1, row2))\n print(\"\\n\".join(results))\n \nif __name__ == \"__main__\":\n process_test_cases()", + "t = int(input())\nfor _ in range(t):\n n = int(input())\n a = input()\n b = input()\n for i in range(1 ,n ,2):\n if (i+1c . \n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 1000 ) — the number\nof test cases.\n\nThe only line of each test case contains three digits a , b , c (0 \\leq a , b\n, c \\leq 9 ).\n\nOutput\n\nFor each test case, output \"STAIR\" if the digits form a stair, \"PEAK\" if the\ndigits form a peak, and \"NONE\" otherwise (output the strings without quotes).\n\nExample\n\nInput\n\n 7\n \n 1 2 3\n \n 3 2 1\n \n 1 5 3\n \n 3 4 1\n \n 0 0 0\n \n 4 1 7\n \n 4 5 7\n\nOutput\n\n STAIR\n NONE\n PEAK\n PEAK\n NONE\n NONE\n STAIR", + "generated_code": [ + "t = int(input())\nfor i in range(t):\n a,b,c = map(int,input().split())\n if ac:\n print(\"PEAK\")\n else:\n print(\"NONE\")", + "n = int(input())\nfor i in range(n):\n a, b, c = map(int, input().split())\n if ac:\n print(\"PEAK\")\n else:\n print( \"NONE\" )", + "q=int(input())\n \nfor i in range(q):\n \n a,b,c=map(int,input().split())\n if ac:\n print(\"PEAK\")\n else:\n print(\"NONE\")" + ] + }, + { + "task_name": "1950_C", + "description": "Given the time in 24-hour format, output the equivalent time in 12-hour\nformat.\n\n * [24-hour format](https://en.wikipedia.org/wiki/24-hour_clock#Description) divides the day into 24 hours from 00 to 23 , each of which has 60 minutes from 00 to 59 . \n * [12-hour format](https://en.wikipedia.org/wiki/12-hour_clock#Description) divides the day into two halves: the first half is \\mathrm{AM} , and the second half is \\mathrm{PM} . In each half, the hours are numbered in the order 12, 01, 02, 03, \\dots, 11 . Each hour has 60 minutes numbered from 00 to 59 . \n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 1440 ) — the number\nof test cases.\n\nThe only line of each test case contains a string s of length 5 with format\nhh:mm representing a valid time in the 24-hour format. hh represents the hour\nfrom 00 to 23 , and mm represents the minute from 00 to 59 .\n\nThe input will always be a valid time in 24-hour format.\n\nOutput\n\nFor each test case, output two strings separated by a space (\"hh:mm AM\" or\n\"hh:mm PM\"), which are the 12-hour equivalent to the time provided in the test\ncase (without quotes).\n\nYou should output the time exactly as indicated; in particular, you should not\nremove leading zeroes.\n\nExample\n\nInput\n\n 11\n \n 09:41\n \n 18:06\n \n 12:14\n \n 00:59\n \n 00:00\n \n 14:34\n \n 01:01\n \n 19:07\n \n 11:59\n \n 12:00\n \n 21:37\n\nOutput\n\n 09:41 AM\n 06:06 PM\n 12:14 PM\n 12:59 AM\n 12:00 AM\n 02:34 PM\n 01:01 AM\n 07:07 PM\n 11:59 AM\n 12:00 PM\n 09:37 PM", + "generated_code": [ + "day = 'AM'\nn = int(input())\nfor _ in range(n):\n h,m = map(int, input().split(':'))\n if (h == 0):\n h = 12\n day = 'AM'\n elif h > 12:\n h = h - 12\n day = 'PM'\n else:\n day = 'AM'\n if h == 12:\n day = 'PM'\n print(f\"{h:02d}:{m:02d}\", day)", + "for _ in range(int(input())):\n h,m = map(str,input().split(':'))\n h1,m1 = '',m\n time = ''\n if h == '01':\n h1 = '01'\n time = 'AM'\n elif h == '02':\n h1 = '02'\n time = 'AM'\n elif h == '03':\n h1 = '03'\n time = 'AM'\n elif h == '04':\n h1 = '04'\n time = 'AM'\n elif h == '05':\n h1 = '05'\n time = 'AM'\n elif h == '06':\n h1 = '06'\n time = 'AM'\n elif h == '07':\n h1 = '07'\n time = 'AM'\n elif h == '08':\n h1 = '08'\n time = 'AM'\n elif h == '09':\n h1 = '09'\n time = 'AM'\n elif h == '10':\n h1 = '10'\n time = 'AM'\n elif h == '11':\n h1 = '11'\n time = 'AM'\n elif h == '12':\n h1 = '12'\n time = 'PM'\n elif h == '13':\n h1 = '01'\n time = 'PM'\n elif h == '14':\n h1 = '02'\n time = 'PM'\n elif h == '15':\n h1 = '03'\n time = 'PM'\n elif h == '16':\n h1 = '04'\n time = 'PM'\n elif h == '17':\n h1 = '05'\n time = 'PM'\n elif h == '18':\n h1 = '06'\n time = 'PM'\n elif h == '19':\n h1 = '07'\n time = 'PM'\n elif h == '20':\n h1 = '08'\n time = 'PM'\n elif h == '21':\n h1 = '09'\n time = 'PM'\n elif h == '22':\n h1 = '10'\n time = 'PM'\n elif h == '23':\n h1 = '11'\n time = 'PM'\n elif h == '00':\n h1 = '12'\n time = 'AM'\n \n print(h1,':',m,' ',time,sep='')" + ] + }, + { + "task_name": "1951_A", + "description": "There are n lamps numbered 1 to n lined up in a row, initially turned off. You\ncan perform the following operation any number of times (possibly zero):\n\n * Choose two non-adjacent{}^\\dagger lamps that are currently turned off, then turn them on. \n\nDetermine whether you can reach configuration s , where s_i = 1 means the i\n-th lamp is turned on, and s_i = 0 otherwise.\n\n{}^\\dagger Only lamp i and i + 1 are adjacent for all 1 \\le i < n . Note that\nlamp n and 1 are not adjacent when n \\ne 2 .\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 1000 ) — the number of test cases. The description of the test\ncases follows.\n\nThe first line of each test case contains an integer n (1 \\le n \\le 50 ) — the\nnumber of lamps.\n\nThe second line of each test case contains a binary string s of size n — the\nfinal desired configuration.\n\nOutput\n\nFor each test case, print on one line \"YES\" if we can reach the configuration\ns via applying the given operation any number of times. Otherwise, print \"NO\".\n\nExample\n\nInput\n\n 5\n \n 10\n \n 1101010110\n \n 10\n \n 1001001110\n \n 6\n \n 000000\n \n 1\n \n 1\n \n 12\n \n 111111111111\n\nOutput\n\n YES\n NO\n YES\n NO\n YES\n \nNote\n\nIn the first test case, the sequence of operation could have been as follows\n(note that initially s is all zero): \\mathtt{0000000000} \\to\n\\mathtt{\\color{red}{1}0000000\\color{red}{1}0} \\to\n\\mathtt{1\\color{red}{1}00000\\color{red}{1}10} \\to\n\\mathtt{110\\color{red}{1}0\\color{red}{1}0110} .\n\nIn the third test case, we don't have to do any operation.\n\nIn the fourth test case, we cannot do any operation, but we need the first\nlamp to be on. Therefore, it is impossible to achieve the desired state.\n", + "generated_code": [ + "t=int(input())\nwhile(t>0):\n n=int(input())\n s=input()\n if n==2:\n if s==\"00\":\n print(\"YES\")\n else:\n print(\"NO\")\n else:\n count_1=s.count(\"1\")\n if count_1%2!=0:\n print(\"NO\")\n else:\n if s.count(\"11\")==1 and count_1==2:\n print(\"NO\")\n else:\n print(\"YES\")\n t-=1", + "t=int(input())\n \nfor i in range(t):\n n=int(input())\n a=input()\n count=a.count('1')\n \n if count==0:\n print(\"YES\")\n \n elif count>2 and count%2==0:\n print(\"YES\")\n \n elif count==2:\n if a[a.index('1')+1]!='1':\n print(\"YES\")\n \n else:\n print(\"NO\")\n else:\n print(\"NO\")", + "def main():\n t = int(input())\n \n for _ in range(t):\n n = int(input())\n s = input()\n cnt1 = s.count('1')\n \n if cnt1 > 2 and cnt1 % 2 == 0:\n print(\"YES\")\n elif cnt1 > 2 :\n print(\"NO\")\n else:\n if (cnt1 == 1 ):\n print(\"NO\")\n elif (\"11\" in s):\n print(\"NO\")\n else:\n print(\"YES\")\n \nif __name__ == \"__main__\":\n main()", + "t = int(input())\nresults = []\n \nfor _ in range(t):\n n = int(input())\n arr = input()\n \n count_ones = arr.count('1')\n \n if count_ones == 0:\n results.append('yes')\n elif count_ones % 2 != 0:\n results.append('no')\n elif count_ones == 2:\n if '11' in arr:\n results.append('no')\n else:\n results.append('yes')\n else:\n results.append('yes')\n \nfor r in results:\n print(r)" + ] + }, + { + "task_name": "1951_B", + "description": "[The HU - Shireg Shireg](https://youtu.be/SNCx4n2m5_o)\n\nඞ\n\nThere are n cows participating in a coding tournament. Cow i has a Cowdeforces\nrating of a_i (all distinct), and is initially in position i . The tournament\nconsists of n-1 matches as follows:\n\n * The first match is between the cow in position 1 and the cow in position 2 . \n * Subsequently, each match i is between the cow in position i+1 and the winner of match i-1 . \n * In each match, the cow with the higher Cowdeforces rating wins and proceeds to the next match. \n\nYou are the owner of cow k . For you, winning the tournament is not important;\nrather, you want your cow to win in as many matches as possible. As an\nacquaintance of the tournament organizers, you can ask them to swap the\nposition of your cow with another cow only once, or you can choose to do\nnothing.\n\nFind the maximum number of wins your cow can achieve.\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 10^4 ) — the number of test cases. The description of the test\ncases follows.\n\nThe first line of each test case contains two integers n and k (2 \\le n \\le\n10^5, 1 \\le k \\le n ) — the number of cows and your cow's index.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the Cowdeforces rating of the cows. It is guaranteed that\na_i 's are pairwise different.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 10^5 .\n\nOutput\n\nFor each test case, print one integer: the maximum number of wins cow k can\nachieve if you choose to swap (or do nothing) optimally.\n\nExample\n\nInput\n\n 3\n \n 6 1\n \n 12 10 14 11 8 3\n \n 6 5\n \n 7 2 727 10 12 13\n \n 2 2\n \n 1000000000 1\n\nOutput\n\n 1\n 2\n 0\n \nNote\n\nIn the first test case, it is optimal to do nothing. Let a' be the Cowdeforces\nrating of the cows in the original order (with your cow's rating bolded), then\n\n * Initially, a' = [\\mathbf{12}, 10, 14, 11, 8, 3] . \n * Your cow plays against the cow with Cowdeforces rating 10 and wins. a' = [\\mathbf{12}, 14, 11, 8, 3] . \n * Your cow plays against the cow with Cowdeforces rating 14 and loses. \n\nIn total, your cow wins 1 match.\n\nIn the second test case, it is optimal to swap your cow to position 3 . Then,\nlet a' be the Cowdeforces rating of the cows in the order after the swap.\n\n * Initially, a' = [7, 2, \\mathbf{12}, 10, 727, 13] . \n * The cow with Cowdeforces rating 7 plays against the cow with Cowdeforces rating 2 and wins. a' = [7, \\mathbf{12}, 10, 727, 13] . \n * The cow with Cowdeforces rating 7 plays against your cow, and your cow wins. a' = [\\mathbf{12}, 10, 727, 13] . \n * Your cow plays against the cow with Cowdeforces rating 10 and wins. a' = [\\mathbf{12}, 727, 13] . \n * Your cow plays against the cow with Cowdeforces rating 727 and loses. \n\nIn total, your cow wins 2 matches.", + "generated_code": [ + "import math as m\nfor _ in range(int(input())):\n n,k = list(map(int,input().split()))\n s = list(map(int,input().split()))\n s[0],s[k-1] = s[k-1],s[0]\n ans = 0\n h = s[0]\n j = -1\n for i in s[1:]:\n j += 1\n if hh:\n break\n else:\n if z==1:\n ans1 += 1\n print(max(ans,ans1))", + "def win():\n\tn,k=map(int,input().split())\n\ta=list(map(int,input().split()))\n\twins=0\n\tfor i in range(n):\n\t\tif(a[i]>a[k-1]):\n\t\t\tbreak\n\t\twins+=1\n\tif(wins>=k):\n\t\tprint(wins-1)\n\t\treturn\n\twin_with_swap=wins+1\n\tfor i in range(win_with_swap,k-1):\n\t\tif(a[i]>a[k-1]):\n\t\t\tbreak\n\t\twin_with_swap+=1\n\tprint(max(wins-1,win_with_swap-wins-1+(wins!=0)))\nif __name__ == \"__main__\":\n t = int(input())\nfor _ in range(t):\n\twin()", + "def mwins(a):\n x=a[k]\n \n ind=[]\n c=0\n for i in range(n):\n if a[i]>x:\n ind.append(i)\n c+=1\n if c==2:break\n if ind==[]:return n-1\n if len(ind)==1:\n if ind[0]==0:\n return k-1\n if ind[0]>k:return ind[0]-1\n return max(k-ind[0],ind[0]-1)\n if ind[0]==0: return min(ind[1]-1,k-1)\n if k>ind[1]: return max(ind[0]-1,ind[1]-ind[0])\n return max(ind[0]-1,k-ind[0])\n \n \n \n \nfor _ in range(int(input())):\n n,k=list(map(int,input().split()))\n l=list(map(int,input().split()))\n k-=1\n print(mwins(l))" + ] + }, + { + "task_name": "1951_C", + "description": "[Maître Gims - Est-ce que tu m'aimes ?](https://youtu.be/6TpyRE_juyA)\n\nඞ\n\nAs the CEO of a startup company, you want to reward each of your k employees\nwith a ticket to the upcoming concert. The tickets will be on sale for n days,\nand by some time travelling, you have predicted that the price per ticket at\nday i will be a_i . However, to prevent ticket hoarding, the concert\norganizers have implemented the following measures:\n\n * A person may purchase no more than m tickets per day. \n * If a person purchases x tickets on day i , all subsequent days (i.e. from day i+1 onwards) will have their prices per ticket increased by x . \n\nFor example, if a = [1, 3, 8, 4, 5] and you purchase 2 tickets on day 1 , they\nwill cost 2 in total, and the prices from day 2 onwards will become [5, 10, 6,\n7] . If you then purchase 3 more tickets on day 2 , they will cost in total an\nadditional 15 , and the prices from day 3 onwards will become [13, 9, 10] .\n\nFind the minimum spending to purchase k tickets.\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 10^4 ) — the number of test cases. The description of the test\ncases follows.\n\nThe first line of each test case contains three integers n , m , and k (1 \\le\nn \\le 3 \\cdot 10^5, 1 \\le m \\le 10^9, 1 \\le k \\le \\min(nm, 10^9) ) — the\nnumber of sale days, the maximum amount of ticket purchasable each day, and\nthe number of tickets to be bought at the end.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the price per ticket for each of the upcoming n days.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 3 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, print one integer: the minimum amount of money needed to\npurchase exactly k tickets.\n\nExample\n\nInput\n\n 4\n \n 4 2 3\n \n 8 6 4 2\n \n 4 2 8\n \n 8 6 4 2\n \n 5 100 1\n \n 10000 1 100 10 1000\n \n 6 3 9\n \n 5 5 5 5 5 5\n\nOutput\n\n 10\n 64\n 1\n 72\n \nNote\n\nIn the first test case, one optimal way to buy 3 tickets is as follows:\n\n * Buy 0 tickets on the first day. The prices per ticket for the remaining days are [6, 4, 2] . \n * Buy 0 tickets on the second day. The prices per ticket for the remaining days are [4, 2] . \n * Buy 1 ticket on the third day with cost 4 . The price per ticket for the remaining day is [3] . \n * Buy 2 tickets on the fourth day with cost 6 . \n\nIn the second test case, there is only one way to buy 8 tickets:\n\n * Buy 2 tickets on the first day with cost 16 . The prices per ticket for the remaining days are [8, 6, 4] . \n * Buy 2 tickets on the second day with cost 16 . The prices per ticket for the remaining days are [8, 6] . \n * Buy 2 tickets on the third day with cost 16 . The price per ticket for the remaining day is [8] . \n * Buy 2 tickets on the fourth day with cost 16 .", + "generated_code": [ + "import math\nt=int(input())\nfor _ in range(t):\n L=list(map(int, input().split()))\n M=list(map(int, input().split()))\n n,m,k=L[0],L[1],L[2]\n m=min(m,k)\n M.sort()\n q=int(math.ceil(k/m))\n N=M[:q]\n n=len(N)\n if n*m==k:\n cost=m*sum(N)+(m*m)*(((n-1)*n)//2)\n else:\n w=N.pop()\n mu=k-(n-1)*m\n cost=(mu)*w\n n=len(N)\n cost+=m*sum(N)+(m*m)*(((n-1)*(n))//2)+n*m*mu\n print(cost)\n continue", + "def min_cost_tickets(n, m, k, prices):\n # Create a priority queue to store the prices\n import heapq\n pq = [(price, i) for i, price in enumerate(prices)]\n heapq.heapify(pq)\n \n total_cost = 0\n tickets_bought = 0\n price_increase = 0\n \n while tickets_bought < k:\n # Get the cheapest ticket\n price, day = heapq.heappop(pq)\n price += price_increase\n \n # Calculate how many tickets we can buy on this day\n tickets_to_buy = min(m, k - tickets_bought)\n \n # Update total cost and tickets bought\n total_cost += price * tickets_to_buy\n tickets_bought += tickets_to_buy\n \n # Increase prices for subsequent days\n price_increase += tickets_to_buy\n \n return total_cost\n \n# Read number of test cases\nt = int(input())\n \nfor _ in range(t):\n # Read input for each test case\n n, m, k = map(int, input().split())\n prices = list(map(int, input().split()))\n \n # Calculate and print the result\n result = min_cost_tickets(n, m, k, prices)\n print(result)", + "for i in range(int(input())):\n n,m,k = map(int,input().split())\n l = list(map(int,input().split()))\n l.sort()\n t = 0\n s = 0\n c = 0\n \n for i in range(n):\n s = min(m,k)\n \n c += s*(l[i] + t)\n t += s\n k -= s\n print(int(c))" + ] + }, + { + "task_name": "1951_D", + "description": "[Nightwish feat. Jonsu - Erämaan Viimeinen](https://youtu.be/QYlFn5q_UQk)\n\nඞ\n\nAlice has n coins and wants to shop at Bob's jewelry store. Today, although\nBob has not set up the store yet, Bob wants to make sure Alice will buy\nexactly k jewels. To set up the store, Bob can erect at most 60 stalls (each\ncontaining an unlimited amount of jewels) and set the price per jewel for each\nstall to be an integer number of coins between 1 and 10^{18} .\n\nFortunately, Bob knows that Alice buys greedily: and she will go to stall 1 ,\nbuy as many jewels as possible, then go to stall 2 , buy as many jewels as\npossible, and so on until the last stall. Knowing this, Bob can choose the\nnumber of stalls to set up, as well as set the price for each stall so that\nAlice buys exactly k jewels. Help Bob fulfill the task, or determine if it is\nimpossible to do so.\n\nNote that Alice does not need to spend all her coins.\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 1000 ) — the number of test cases. The description of the test\ncases follows.\n\nEach test case contains two positive integers n and k (1 \\le n, k \\le 10^{18}\n) — the number of coins Alice has and the number of jewels Bob wants Alice to\nhave bought at the end.\n\nOutput\n\nFor each test case, print on one line \"YES\" if Bob can erect at most 60 stalls\nand set the prices for the stalls such that Alice buys exactly k jewels, or\n\"NO\" if it is impossible to do so.\n\nIf the answer is \"YES\", on the second line, print an integer s (1 \\le s \\le 60\n) — the number of stalls to be set up by Bob. On the third line, print s\npositive integers p_1, p_2, \\ldots, p_s (1 \\le p_i \\le 10^{18}) that represent\nsuch a satisfactory pricing p , where p_i is the price per jewel for stall i .\nIf there are multiple such p 's, print any of them.\n\nExample\n\nInput\n\n 3\n \n 7 3\n \n 6 4\n \n 255 8\n\nOutput\n\n YES\n 10\n 2 3 4 5 6 7 8 9 10 11\n NO\n YES\n 8\n 128 64 32 16 8 4 2 1\n \nNote\n\nIn the first test case, at the first stall, Alice buys 3 jewels and is left\nwith 1 coin. This is not enough to buy any jewels for any of the remaining\nstalls, so Alice buys exactly 3 jewels at the end.\n\nIn the third test case,\n\n * At the first stall, Alice buys 1 jewel and is left with 127 coins. \n * At the second stall, Alice buys 1 jewel and is left with 63 coins. \n * At the third stall, Alice buys 1 jewel and is left with 31 coins. \n * At the fourth stall, Alice buys 1 jewel and is left with 15 coins. \n * At the fifth stall, Alice buys 1 jewel and is left with 7 coins. \n * At the sixth stall, Alice buys 1 jewel and is left with 3 coins. \n * At the seventh stall, Alice buys 1 jewel and is left with 1 coin. \n * At the eighth stall, Alice buys 1 jewel and is left with 0 coins. \n\nTherefore, Alice buys exactly 8 jewels in total.", + "generated_code": [ + "from sys import stdin\nt=int(input())\nfor _ in range(t):\n n,k=map(int,stdin.readline().split())\n if n==k:\n print(\"YES\")\n print(1)\n print(1)\n else:\n if n+2>k*2:\n print(\"YES\")\n print(2)\n print(n-k+1,end=\" \")\n print(1)\n else:\n print(\"NO\")", + "\"\"\"\nt = int(input())\nfor _ in range(t):\n n = int(input())\n arr = list(map(int,input().split()))\n \n \n# Read tree as graph\n# Generic BS\ndef bs(arr,x):\n n = len(arr)\n l, r = 0, n - 1\n if x < arr[0]: return -1\n if x > arr[-1]: return n+1\n \n while l + 1 != r:\n mid = (l + r) // 2\n if x <= arr[mid]:\n r = mid\n else:\n l = mid\n return (l,r)\n \n\"\"\"\nimport math as m\nimport collections as c\ndef proD(n,k):\n if n==k:\n print('YES')\n print(1)\n print(1)\n return\n if n < k:\n print('NO')\n return\n costs = [n-k+1,1]\n h = 0\n for i in costs:\n curr = n//i\n h += curr\n n -= i*curr\n if h < k:\n print('NO')\n else:\n \n print('YES')\n print(2)\n print(*costs)\n \nt = int(input())\nfor _ in range(t):\n n,k = list(map(int,input().split()))\n #arr = list(map(int,input().split()))\n proD(n,k)", + "def jewels():\n n, k = map(int, input().split())\n if n= sum(nums):return n\n a , b = math.ceil(k/2) , k // 2\n ans = 0\n s_a = 0\n s_b = 0\n for i in range(n):\n s_a += nums[i]\n s_b += nums[n-i-1]\n if s_a <= a:\n ans += 1\n if s_b <= b:\n ans += 1\n return ans\n \nfor _ in range(T):\n n, k = list(map(int, input().split(' ')))\n nums = list(map(int, input().split(' ')))\n ans = solve(n,k,nums)\n print(ans)", + "# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2024/8/26 17:59\n @Author : Zhiliang.L\n @Email : 2410103062@mails.edu.cn\n @File : 1955-C.py\n\"\"\"\nT = int(input())\nwhile T:\n T -= 1\n n, k = input().split()\n n = int(n)\n k = int(k)\n a = input().split()\n a = list(map(lambda x: int(x), a))\n l = 0\n r = n - 1\n ans = 0\n while l < r and k > 0:\n mi = min(a[l], a[r])\n if mi * 2 <= k:\n a[l] -= mi\n a[r] -= mi\n k -= (mi * 2)\n if a[l] == 0:\n ans += 1\n l += 1\n if a[r] == 0:\n ans += 1\n r -= 1\n else:\n t = k % 2\n if a[l] - t - k // 2 == 0:\n ans += 1\n break\n if l == r:\n ans += (k >= a[l])\n print(ans)", + "def solve(n, k, a):\n l, r = 0, n - 1\n sunks = 0\n while l <= r:\n if k == 0:\n break\n if l == r:\n if k >= a[r]:\n sunks += 1\n break\n break\n \n if a[l] <= a[r]:\n if k >= a[l] * 2:\n k -= a[l] * 2\n a[r] -= a[l]\n if a[r] == 0:\n sunks += 1\n r -= 1\n sunks += 1\n l += 1\n continue\n else:\n if a[l] * 2 - 1 == k:\n sunks += 1\n break\n else:\n break\n \n if k == 0:\n break\n \n if a[r] < a[l]:\n if k >= a[r] * 2:\n k -= a[r] * 2\n a[l] -= a[r]\n if a[l] == 0:\n sunks += 1\n l += 1\n sunks += 1\n r -= 1\n continue\n else:\n if a[r] * 2 == k:\n sunks += 1\n break\n else:\n break\n \n \n return sunks\n \n# Read input\nt = int(input()) # Number of test cases\nfor _ in range(t):\n n, k = map(int, input().split())\n a = map(int, input().split())\n print(solve(n, k, list(a)))" + ] + }, + { + "task_name": "1955_D", + "description": "Maxim has an array a of n integers and an array b of m integers (m \\le n ).\n\nMaxim considers an array c of length m to be good if the elements of array c\ncan be rearranged in such a way that at least k of them match the elements of\narray b .\n\nFor example, if b = [1, 2, 3, 4] and k = 3 , then the arrays [4, 1, 2, 3] and\n[2, 3, 4, 5] are good (they can be reordered as follows: [1, 2, 3, 4] and [5,\n2, 3, 4] ), while the arrays [3, 4, 5, 6] and [3, 4, 3, 4] are not good.\n\nMaxim wants to choose every subsegment of array a of length m as the elements\nof array c . Help Maxim count how many selected arrays will be good.\n\nIn other words, find the number of positions 1 \\le l \\le n - m + 1 such that\nthe elements a_l, a_{l+1}, \\dots, a_{l + m - 1} form a good array.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThe first line of each test case contains three integers n , m , and k (1 \\le\nk \\le m \\le n \\le 2 \\cdot 10^5 ) — the number of elements in arrays a and b ,\nthe required number of matching elements.\n\nThe second line of each test case contains n integers a_1, a_2, \\dots, a_n (1\n\\le a_i \\le 10^6 ) — the elements of array a . Elements of the array a are not\nnecessarily unique.\n\nThe third line of each test case contains m integers b_1, b_2, \\dots, b_m (1\n\\le b_i \\le 10^6 ) — the elements of array b . Elements of the array b are not\nnecessarily unique.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 . Similarly, it is guaranteed that the sum of m over all test cases does\nnot exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output the number of good subsegments of array a on a\nseparate line.\n\nExample\n\nInput\n\n 5\n \n 7 4 2\n \n 4 1 2 3 4 5 6\n \n 1 2 3 4\n \n 7 4 3\n \n 4 1 2 3 4 5 6\n \n 1 2 3 4\n \n 7 4 4\n \n 4 1 2 3 4 5 6\n \n 1 2 3 4\n \n 11 5 3\n \n 9 9 2 2 10 9 7 6 3 6 3\n \n 6 9 7 8 10\n \n 4 1 1\n \n 4 1 5 6\n \n 6\n\nOutput\n\n 4\n 3\n 2\n 4\n 1\n \nNote\n\nIn the first example, all subsegments are good.\n\nIn the second example, good subsegments start at positions 1 , 2 , and 3 .\n\nIn the third example, good subsegments start at positions 1 and 2 .", + "generated_code": [ + "from collections import Counter\n \ndef count_good_subarrays(n, m, k, a, b):\n cb = Counter(sorted(b))\n ca = Counter(sorted(a[:m]))\n ans = 0\n sm = sum((ca & cb).values())\n if sm >= k:\n ans += 1\n for r in range(m, n):\n if ca[a[r]] < cb[a[r]]:\n sm += 1\n ca[a[r]] += 1\n if ca[a[r-m]] <= cb[a[r-m]]:\n sm -= 1\n ca[a[r-m]] -= 1\n if sm >= k:\n ans += 1\n return ans\n \n# Driver code\nfor _ in range(int(input())):\n n, m, k = map(int, input().split())\n a = list(map(int, input().split()))\n b = list(map(int, input().split()))\n print(count_good_subarrays(n, m, k, a,b))", + "from collections import Counter\n \nnabors = int(input())\nfor _ in range(nabors):\n # цикл по наборам данных ----------------\n \n # в каждом наборе получаем по две строки\n # 1) три целых числа n, m и k\n n, m, k = [int(i) for i in input().split()]\n \n # 2) элементы массива a\n aa = [str(i) for i in input().split()]\n \n # 3) элементы массива b\n bb = [str(i) for i in input().split()]\n \n cnt_aa = Counter(aa[:m]) \n cnt_bb = Counter(bb)\n D = cnt_aa & cnt_bb # D -найденные парные совпадения в cnt_aa и cnt_bb\n pairs_in_D = sum(D.values()) # сколько пар в D\n \n E = cnt_aa - D # E - несовпавшие элементы из cnt_aa\n C = cnt_bb - D # C - несовпавшие элементы из cnt_bb\n \n fnd = 1 if pairs_in_D >= k else 0\n \n for in_aa,out_aa in zip(aa[m:], aa[:n-m]):\n if D[out_aa] > 0:\n if E[out_aa] > 0:\n E[out_aa] -= 1\n else:\n D[out_aa] -= 1\n pairs_in_D -= 1 \n C[out_aa] += 1\n else:\n E[out_aa] -= 1\n \n if C[in_aa] > 0:\n # случай, когда возможно ранее уже есть такая пара\n D[in_aa] += 1\n pairs_in_D += 1 \n C[in_aa] -= 1\n else:\n E[in_aa] += 1\n \n fnd += 1 if pairs_in_D >= k else 0 \n \n print(fnd)", + "max_val = 1000000 # Update this with the actual known maximum value if needed\n \ncnt_b = [0] * (max_val + 1)\n \nfor _ in range(int(input())):\n n, m, k = map(int, input().split())\n \n a = list(map(int, input().split())) # n elements\n b = list(map(int, input().split())) # m elements\n \n for i in range(m):\n cnt_b[b[i]] += 1\n \n b_values = set(b)\n \n ans = 0\n curr = 0\n \n for i in range(m):\n if a[i] in b_values:\n cnt_b[a[i]] -= 1\n if cnt_b[a[i]] >= 0:\n curr += 1\n \n if curr >= k:\n ans += 1\n \n for i in range(n - m):\n if a[i] in b_values:\n cnt_b[a[i]] += 1\n if cnt_b[a[i]] > 0:\n curr -= 1\n \n if a[i + m] in b_values:\n cnt_b[a[i + m]] -= 1\n if cnt_b[a[i + m]] >= 0:\n curr += 1\n \n if curr >= k:\n ans += 1\n \n print(ans)\n \n for i in b_values:\n cnt_b[i] = 0" + ] + }, + { + "task_name": "1955_F", + "description": "Alice and Bob gathered in the evening to play an exciting game on a sequence\nof n integers, each integer of the sequence doesn't exceed 4 . The rules of\nthe game are too complex to describe, so let's just describe the winning\ncondition — Alice wins if the [bitwise XOR](http://tiny.cc/xor_wiki_eng) of\nall the numbers in the sequence is non-zero; otherwise, Bob wins.\n\nThe guys invited Eve to act as a judge. Initially, Alice and Bob play with n\nnumbers. After one game, Eve removes one of the numbers from the sequence,\nthen Alice and Bob play with n-1 numbers. Eve removes one number again, after\nwhich Alice and Bob play with n - 2 numbers. This continues until the sequence\nof numbers is empty.\n\nEve seems to think that in such a game, Alice almost always wins, so she wants\nBob to win as many times as possible. Determine the maximum number of times\nBob can win against Alice if Eve removes the numbers optimally.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThe first and only line of each test case contains four integers p_i (0 \\le\np_i \\le 200 ) — the number of ones, twos, threes, and fours in the sequence at\nthe beginning of the game.\n\nOutput\n\nFor each test case, print the maximum number of times Bob will win in a\nseparate line, if Eve removes the numbers optimally.\n\nExample\n\nInput\n\n 5\n \n 1 1 1 0\n \n 1 0 1 2\n \n 2 2 2 0\n \n 3 3 2 0\n \n 0 9 9 9\n\nOutput\n\n 1\n 1\n 3\n 3\n 12\n \nNote\n\nIn the first example, Bob wins when Eve has not removed any numbers yet.\n\nIn the second example, Bob wins if Eve removes one one and one three.", + "generated_code": [ + "for i in range(int(input())):\n a,b,c,d=map(int,input().split())\n print(a//2+b//2+c//2+d//2+int(a%2+b%2+c%2==3))", + "print('\\n'.join([str(sum(3*(x // 2) + (x % 2)*(i < 3) for (i, x) in enumerate(map(int, input().split()))) // 3) for _ in range(int(input()))]))", + "import math\nfor _ in range(int(input())):\n a = list(map(int,input().split()))\n cnt = 0\n if a[0]%2==a[1]%2==a[2]%2==1 :\n cnt+=1\n for x in a:\n cnt+=math.floor(x/2)\n print(cnt)" + ] + }, + { + "task_name": "1956_B", + "description": "You and Nene are playing a card game. The deck with 2n cards is used to play\nthis game. Each card has an integer from 1 to n on it, and each of integers 1\nthrough n appears exactly on 2 cards. Additionally, there is a table where\ncards are placed during the game (initially, the table is empty).\n\nIn the beginning of the game, these 2n cards are distributed between you and\nNene so that each player receives n cards.\n\nAfter it, you and Nene alternatively take 2n turns, i.e. each person takes n\nturns, starting with you. On each turn:\n\n * The player whose turn is it selects one of the cards in his hand. Let x be the number on it. \n * The player whose turn is it receives 1 point if there is already a card with the integer x on the table (otherwise, he receives no points). After it, he places the selected card with the integer x on the table. \n\nNote that turns are made publicly: each player can see all the cards on the\ntable at each moment.\n\nNene is very smart so she always selects cards optimally in order to maximize\nher score in the end of the game (after 2n rounds). If she has several optimal\nmoves, she selects the move that minimizes your score in the end of the game.\n\nMore formally, Nene always takes turns optimally in order to maximize her\nscore in the end of the game in the first place and to minimize your score in\nthe end of the game in the second place.\n\nAssuming that the cards are already distributed and cards in your hand have\nintegers a_1, a_2, \\ldots, a_n written on them, what is the maximum number of\npoints you can get by taking your turns optimally?\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 10^4 ). The description of test cases follows.\n\nThe first line contains a single integer n (1 \\le n \\le 2 \\cdot 10^5 ) — the\nnumber of cards you and Nene receive in the beginning of the game.\n\nThe second line contains n integers a_1, a_2, \\ldots, a_n (1 \\le a_i \\le n ) —\nthe integers on the cards in your hand. It is guaranteed that each integer\nfrom 1 through n appears in the sequence a_1, a_2, \\ldots, a_n at most 2\ntimes.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output one integer: the maximum number of points you can\nget.\n\nExample\n\nInput\n\n 5\n \n 4\n \n 1 1 2 3\n \n 8\n \n 7 4 1 2 8 8 5 5\n \n 8\n \n 7 1 4 5 3 4 2 6\n \n 3\n \n 1 2 3\n \n 1\n \n 1\n\nOutput\n\n 1\n 2\n 1\n 0\n 0\n \nNote\n\nIn the first test case, the integers written on your cards are 1 , 1 , 2 and 3\n. The integers written on Nene's cards are 2 , 3 , 4 and 4 . The game may\nproceed as follows:\n\n 1. You select one of the cards with an integer 1 written on it and place it on the table. \n 2. Nene selects one of the cards with an integer 4 written on it and places it on the table. \n 3. You select the card with an integer 1 written on it, receive 1 point, and place the selected card on the table. \n 4. Nene selects the card with an integer 4 written on it, receive 1 point, and places the selected card on the table. \n 5. You select the card with an integer 2 written on it and place it on the table. \n 6. Nene selects the card with an integer 2 written on it, receive 1 point, and places the selected card on the table. \n 7. You select the card with an integer 3 written on it and place it on the table. \n 8. Nene selects the card with an integer 3 written on it, receive 1 point, and places the selected card on the table. \n\nAt the end of the game, you scored 1 point, and Nene scored 3 . It can be\nshown that you cannot score more than 1 point if Nene plays optimally, so the\nanswer is 1 .\n\nIn the second test case, if both players play optimally, you score 2 points\nand Nene scores 6 points.", + "generated_code": [ + "def max_points(a, n):\n count_a = {}\n for num in a:\n if num in count_a:\n count_a[num] += 1\n else:\n count_a[num] = 1\n \n # Maximum points you can gain\n max_score = 0\n \n # Iterate over the card numbers to count how many \"safe\" points you can get\n for num in range(1, n + 1):\n if num in count_a:\n # If you have the number and it appears more than once, you can guarantee a point\n if count_a[num] == 2:\n max_score += 1\n \n return max_score\n \n# Process input cases\nt = int(input())\nresults = []\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n result = max_points(a, n)\n results.append(result)\n \n# Output all results\nfor res in results:\n print(res)", + "import sys\n \ninput = sys.stdin.readline\n \nfor _ in range(int(input())):\n n = int(input())\n a = list(map(int, input().split()))\n cnt = [0] * (n + 1)\n for x in a:\n cnt[x] += 1\n ans = 0\n for x in cnt:\n ans += max(0, x - 1)\n print(ans)", + "for line in [*open(0)][2::2]:\n print(len(tokens := line.split()) - len({*tokens}))" + ] + }, + { + "task_name": "1956_D", + "description": "Nene gave you an array of integers a_1, a_2, \\ldots, a_n of length n .\n\nYou can perform the following operation no more than 5\\cdot 10^5 times\n(possibly zero):\n\n * Choose two integers l and r such that 1 \\le l \\le r \\le n , compute x as \\operatorname{MEX}(\\\\{a_l, a_{l+1}, \\ldots, a_r\\\\}) , and simultaneously set a_l:=x, a_{l+1}:=x, \\ldots, a_r:=x . \n\nHere, \\operatorname{MEX} of a set of integers \\\\{c_1, c_2, \\ldots, c_k\\\\} is\ndefined as the smallest non-negative integer m which does not occur in the set\nc .\n\nYour goal is to maximize the sum of the elements of the array a . Find the\nmaximum sum and construct a sequence of operations that achieves this sum.\nNote that you don't need to minimize the number of operations in this\nsequence, you only should use no more than 5\\cdot 10^5 operations in your\nsolution.\n\nInput\n\nThe first line contains an integer n (1 \\le n \\le 18 ) — the length of the\narray a .\n\nThe second line contains n integers a_1,a_2,\\ldots,a_n (0\\leq a_i \\leq 10^7 )\n— the array a .\n\nOutput\n\nIn the first line, output two integers s and m (0\\le m\\le 5\\cdot 10^5 ) — the\nmaximum sum of elements of the array a and the number of operations in your\nsolution.\n\nIn the i -th of the following m lines, output two integers l and r (1 \\le l\n\\le r \\le n ), representing the parameters of the i -th operation.\n\nIt can be shown that the maximum sum of elements of the array a can always be\nobtained in no more than 5 \\cdot 10^5 operations.\n\nExamples\n\nInput\n\n 2\n \n 0 1\n\nOutput\n\n 4 1\n 1 2\n \nInput\n\n 3\n \n 1 3 9\n\nOutput\n\n 13 0\n \nInput\n\n 4\n \n 1 100 2 1\n\nOutput\n\n 105 2\n 3 3\n 3 4\n \nInput\n\n 1\n \n 0\n\nOutput\n\n 1 1\n 1 1\n \nNote\n\nIn the first example, after the operation with l=1 and r=2 the array a becomes\nequal to [2,2] . It can be shown that it is impossible to achieve a larger sum\nof the elements of a , so the answer is 4 .\n\nIn the second example, the initial sum of elements is 13 which can be shown to\nbe the largest.\n\nIn the third example, the array a changes as follows:\n\n * after the first operation (l=3 , r=3 ), the array a becomes equal to [1,100,0,1] ; \n * after the second operation (l=3 , r=4 ), the array a becomes equal to [1,100,2,2] . \n\nIt can be shown that it is impossible to achieve a larger sum of the elements\nof a , so the answer is 105 .", + "generated_code": [ + "#from functools import cache\nfrom typing import List, Tuple\n \nn = int(input())\narr = list(map(int, input().split()))\n \n \nres_dict = {}\ndef get_max_possible_value(start_index: int, end_index: int) -> int:\n key = (start_index, end_index)\n if key in res_dict:\n return res_dict[key]\n if start_index == end_index:\n res_dict[key] = max(1, arr[start_index])\n return max(1, arr[start_index])\n res = (end_index - start_index + 1) ** 2\n for i in range(start_index + 1, end_index):\n new_res = get_max_possible_value(start_index, i - 1) + get_max_possible_value(i + 1, end_index) + arr[i]\n res = max(res, new_res)\n res = max(res, arr[start_index] + get_max_possible_value(start_index + 1, end_index))\n res = max(res, arr[end_index] + get_max_possible_value(start_index, end_index - 1))\n res_dict[key] = res\n return res\n \n \ndef get_changes(start_index: int, end_index: int) -> List[Tuple[int, int]]:\n max_value = get_max_possible_value(start_index, end_index)\n length = end_index - start_index + 1\n if length == 1:\n if arr[start_index] > 0:\n return []\n return [(start_index, start_index)]\n if max_value == length ** 2:\n res = []\n \n def make_stairs(i:int) -> None:\n is_already_stairs = True\n for j in range(i + 1):\n if arr[start_index + j] != j:\n is_already_stairs = False\n if is_already_stairs:\n return\n if i == 0:\n res.append((start_index, start_index))\n arr[start_index] = 1\n return\n if arr[start_index + i] == i:\n make_stairs(i - 1)\n else:\n make_stairs(i - 1)\n res.append((start_index, start_index + i))\n for j in range(start_index, start_index + i + 1):\n arr[j] = i\n make_stairs(i - 1)\n make_stairs(length - 1)\n res.append((start_index, end_index))\n return res\n \n else:\n for i in range(start_index + 1, end_index):\n temp_res = get_max_possible_value(start_index, i - 1) + get_max_possible_value(i + 1, end_index) + arr[i]\n if temp_res == max_value:\n return get_changes(start_index, i - 1) + get_changes(i + 1, end_index)\n if arr[start_index] + get_max_possible_value(start_index + 1, end_index) == max_value:\n return get_changes(start_index + 1, end_index)\n elif arr[end_index] + get_max_possible_value(start_index, end_index - 1) == max_value:\n return get_changes(start_index, end_index - 1)\n \n \n \nres = get_max_possible_value(0, n - 1)\nchanges = get_changes(0, n - 1)\nprint(res, len(changes))\nfor a, b in changes:\n print(a + 1, b + 1)" + ] + }, + { + "task_name": "1965_A", + "description": "Alice and Bob are playing a game on n piles of stones. On each player's turn,\nthey select a positive integer k that is at most the size of the smallest\nnonempty pile and remove k stones from each nonempty pile at once. The first\nplayer who is unable to make a move (because all piles are empty) loses.\n\nGiven that Alice goes first, who will win the game if both players play\noptimally?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le\n2\\cdot 10^5 ) — the number of piles in the game.\n\nThe next line of each test case contains n integers a_1, a_2, \\ldots a_n (1\n\\le a_i \\le 10^9 ), where a_i is the initial number of stones in the i -th\npile.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2\\cdot\n10^5 .\n\nOutput\n\nFor each test case, print a single line with the name of the winner, assuming\nboth players play optimally. If Alice wins, print \"Alice\", otherwise print\n\"Bob\" (without quotes).\n\nExample\n\nInput\n\n 7\n \n 5\n \n 3 3 3 3 3\n \n 2\n \n 1 7\n \n 7\n \n 1 3 9 7 4 2 100\n \n 3\n \n 1 2 3\n \n 6\n \n 2 1 3 4 2 4\n \n 8\n \n 5 7 2 9 6 3 3 2\n \n 1\n \n 1000000000\n\nOutput\n\n Alice\n Bob\n Alice\n Alice\n Bob\n Alice\n Alice\n \nNote\n\nIn the first test case, Alice can win by choosing k=3 on her first turn, which\nwill empty all of the piles at once.\n\nIn the second test case, Alice must choose k=1 on her first turn since there\nis a pile of size 1 , so Bob can win on the next turn by choosing k=6 .", + "generated_code": [ + "from collections import *\nfrom math import *\nfrom heapq import *\nimport sys\nfrom bisect import *\nfrom random import randint\nrrr = randint(8888,88888)\n \n \ndef sol():\n N = int(input())\n \n nums = set(input().split())\n \n nums.add('0')\n nums = sorted(map(int,nums))\n \n ls = 0\n \n for i in range(len(nums)):\n nums[i] -= ls\n ls += nums[i]\n \n \n nw = True\n cw = True\n for i in range(len(nums)-2,0,-1):\n if nums[i] == 1:cw = not nw\n else:cw = True\n nw = cw\n \n if cw:print(\"Alice\")\n else:print(\"Bob\") \n \n \n \n \n \nfor _ in range(int(input())):\n sol()", + "import heapq\nimport sys\n \ninput = sys.stdin.readline\n \ndef solve(arr):\n A = False\n \n set_ = list(set(arr))\n set_.sort()\n if set_[0] != 1:\n return 'Alice'\n not_c = True\n for i in range(1, len(set_)):\n if set_[i] - set_[i-1] > 1:\n not_c = False\n break\n A = not A\n if not_c:\n A = not A\n \n return 'Alice' if A else 'Bob'\n \n \nt = int(input())\nc = 1\nwhile t > 0:\n n = list(map(int, input().rstrip().split()))\n \n arr = list(map(int, input().rstrip().split()))\n r = solve(arr)\n print(r)\n t -= 1", + "t=int(input())\nfor i in range(t):\n n=int(input())\n l=map(int,input().split())\n lis=sorted(set(l))\n if (1 not in lis) or (len(lis)==1) :\n print(\"Alice\")\n else:\n \n test=True\n for j in range(1,len(lis)):\n if lis[j]-lis[j-1]>1:\n if j%2==1:\n print(\"Bob\")\n else:\n print(\"Alice\")\n test=False\n break\n if test==True:\n if len(lis)%2==1:\n print(\"Alice\")\n else:\n print(\"Bob\")" + ] + }, + { + "task_name": "1966_B", + "description": "There is an n \\times m grid of white and black squares. In one operation, you\ncan select any two squares of the same color, and color all squares in the\nsubrectangle between them that color.\n\nFormally, if you select positions (x_1, y_1) and (x_2, y_2) , both of which\nare currently the same color c , set the color of all (x, y) where \\min(x_1,\nx_2) \\le x \\le \\max(x_1, x_2) and \\min(y_1, y_2) \\le y \\le \\max(y_1, y_2) to c\n.\n\nThis diagram shows a sequence of two possible operations on a grid:\n\n![](https://espresso.codeforces.com/efe0d6bfa2062b4821f73fb07120103af504fb62.png)\n\nIs it possible for all squares in the grid to be the same color, after\nperforming any number of operations (possibly zero)?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. The description of the test cases follows.\n\nThe first line of each test case contains two integers n and m (1 \\le n, m \\le\n500 ) — the number of rows and columns in the grid, respectively.\n\nEach of the next n lines contains m characters 'W' and 'B' — the initial\ncolors of the squares of the grid.\n\nIt is guaranteed that the sum of n\\cdot m over all test cases does not exceed\n3\\cdot 10^5 .\n\nOutput\n\nFor each test case, print \"YES\" if it is possible to make all squares in the\ngrid the same color, and \"NO\" otherwise.\n\nYou can output the answer in any case (upper or lower). For example, the\nstrings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 8\n \n 2 1\n \n W\n \n B\n \n 6 6\n \n WWWWBW\n \n WBWWWW\n \n BBBWWW\n \n BWWWBB\n \n WWBWBB\n \n BBBWBW\n \n 1 1\n \n W\n \n 2 2\n \n BB\n \n BB\n \n 3 4\n \n BWBW\n \n WBWB\n \n BWBW\n \n 4 2\n \n BB\n \n BB\n \n WW\n \n WW\n \n 4 4\n \n WWBW\n \n BBWB\n \n WWBB\n \n BBBB\n \n 1 5\n \n WBBWB\n\nOutput\n\n NO\n YES\n YES\n YES\n YES\n NO\n YES\n NO\n \nNote\n\nIn the first example, it is impossible to ever change the color of any square\nwith an operation, so we output NO.\n\nThe second example is the case pictured above. As shown in that diagram, it is\npossible for all squares to be white after two operations, so we output YES.\n\nIn the third and fourth examples, all squares are already the same color, so\nwe output YES.\n\nIn the fifth example we can do everything in two operations. First, select\npositions (2, 1) and (1, 4) and color all squares with 1 \\le x \\le 2 and 1 \\le\ny \\le 4 to white. Then, select positions (2, 1) and (3, 4) and color all\nsquares with 2 \\le x \\le 3 and 1 \\le y \\le 4 to white. After these two\noperations all squares are white.", + "generated_code": [ + "t = int(input())\n \nfor tc in range(t):\n n, m = map(int, input().split())\n gr = []\n \n for i in range(n):\n gr.append(input())\n \n ans = \"YES\"\n \n if gr[0][0] != gr[n - 1][m - 1]:\n \n impossible = True\n for j in range(m - 1):\n if gr[0][j] != gr[0][j + 1] or gr[n - 1][j] != gr[n - 1][j + 1]:\n impossible = False\n \n if impossible:\n ans = \"NO\"\n \n impossible = True\n for i in range(n - 1):\n if gr[i][0] != gr[i + 1][0] or gr[i][m - 1] != gr[i + 1][m - 1]:\n impossible = False\n \n if impossible:\n ans = \"NO\"\n \n print(ans)", + "for _ in range(int(input())):\n n, m = map(int, input().split())\n a = []\n \n first_row = ''\n last_row = ''\n \n for i in range(n):\n a.append(input())\n first_row += a[-1][0]\n last_row += a[-1][-1]\n \n if len(set(a[0])) == 1 and len(set(a[-1])) == 1 and a[0] != a[-1]:\n print('NO')\n elif len(set(first_row)) == 1 and len(set(last_row)) == 1 and first_row != last_row:\n print('NO')\n else:\n print('YES')" + ] + }, + { + "task_name": "1966_C", + "description": "Alice and Bob are playing a game on n piles of stones. On each player's turn,\nthey select a positive integer k that is at most the size of the smallest\nnonempty pile and remove k stones from each nonempty pile at once. The first\nplayer who is unable to make a move (because all piles are empty) loses.\n\nGiven that Alice goes first, who will win the game if both players play\noptimally?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le\n2\\cdot 10^5 ) — the number of piles in the game.\n\nThe next line of each test case contains n integers a_1, a_2, \\ldots a_n (1\n\\le a_i \\le 10^9 ), where a_i is the initial number of stones in the i -th\npile.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2\\cdot\n10^5 .\n\nOutput\n\nFor each test case, print a single line with the name of the winner, assuming\nboth players play optimally. If Alice wins, print \"Alice\", otherwise print\n\"Bob\" (without quotes).\n\nExample\n\nInput\n\n 7\n \n 5\n \n 3 3 3 3 3\n \n 2\n \n 1 7\n \n 7\n \n 1 3 9 7 4 2 100\n \n 3\n \n 1 2 3\n \n 6\n \n 2 1 3 4 2 4\n \n 8\n \n 5 7 2 9 6 3 3 2\n \n 1\n \n 1000000000\n\nOutput\n\n Alice\n Bob\n Alice\n Alice\n Bob\n Alice\n Alice\n \nNote\n\nIn the first test case, Alice can win by choosing k=3 on her first turn, which\nwill empty all of the piles at once.\n\nIn the second test case, Alice must choose k=1 on her first turn since there\nis a pile of size 1 , so Bob can win on the next turn by choosing k=6 .", + "generated_code": [ + "tc = int(input())\n \nwhile tc > 0:\n n = int(input())\n arr = sorted(list(set([int(x) for x in input().split(' ')])), reverse=True) + [0]\n dp = True\n n = len(arr) - 1\n for i in range(1, n):\n dp = (arr[i] - arr[i+1] > 1) or not dp\n print('Alice' if dp else 'Bob')\n tc -= 1", + "for _ in range(int(input())):\n n = int(input())\n arr = list(map(int, input().split()))\n s = set()\n for i in range(n):\n s.add(arr[i])\n s = list(s)\n s.sort()\n s = [0] + s\n ans = 1\n n = len(s)\n if n==2: print(\"Alice\")\n else:\n for i in range(1,n-1):\n if s[i]-s[i-1] > 1:\n break\n else:\n ans ^= 1\n if ans: print(\"Alice\")\n else: print(\"Bob\")", + "t = int(input())\n \nfor tc in range(t):\n \n n = int(input())\n a = list(map(int, input().split()))\n \n maxsize = max(a)\n \n a.sort()\n mexsize = 1\n for sz in a:\n if sz == mexsize:\n mexsize = mexsize + 1\n \n if mexsize > maxsize:\n print(\"Alice\" if mexsize % 2 == 0 else \"Bob\")\n else:\n print(\"Alice\" if mexsize % 2 == 1 else \"Bob\")" + ] + }, + { + "task_name": "1967_B1", + "description": "The two versions are different problems. You may want to read both versions.\nYou can make hacks only if both versions are solved.\n\nYou are given two positive integers n , m .\n\nCalculate the number of ordered pairs (a, b) satisfying the following\nconditions:\n\n * 1\\le a\\le n , 1\\le b\\le m ; \n * a+b is a multiple of b \\cdot \\gcd(a,b) . \n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\le t\\le 10^4 ). The description of the test cases follows.\n\nThe first line of each test case contains two integers n , m (1\\le n,m\\le 2\n\\cdot 10^6 ).\n\nIt is guaranteed that neither the sum of n nor the sum of m over all test\ncases exceeds 2 \\cdot 10^6 .\n\nOutput\n\nFor each test case, print a single integer: the number of valid pairs.\n\nExample\n\nInput\n\n 6\n \n 1 1\n \n 2 3\n \n 3 5\n \n 10 8\n \n 100 1233\n \n 1000000 1145141\n\nOutput\n\n 1\n 3\n 4\n 14\n 153\n 1643498\n \nNote\n\nIn the first test case, only (1,1) satisfies the conditions.\n\nIn the fourth test case,\n(1,1),(2,1),(2,2),(3,1),(4,1),(5,1),(6,1),(6,2),(6,3),(7,1),(8,1),(9,1),(10,1),(10,2)\nsatisfy the conditions.", + "generated_code": [ + "# LUOGU_RID: 157640359\nt=int(input())\nfor T in range(t):\n [n,m]=input().split()\n [n,m]=[int(n),int(m)]\n ans=n\n for b in range(2,min(n,m)+1):\n ans=ans+(n+b)//(b*b)\n print(ans)", + "t=int(input())\nfor i in range(t):\n n,m=map(int,input().split())\n count=2\n ans=n\n while count<=m:\n countmins=int(count -1)\n g=int(n/count)\n if g1 parts so that [bitwise XOR](http://tiny.cc/xor_wiki_eng) of\nvalues from each part are equal.\n\nMore formally, you must split array x into k consecutive segments, each\nelement of x must belong to exactly 1 segment. Let y_1,\\dots,y_k be the XOR of\nelements from each part respectively. Then y_1=y_2=\\dots=y_k must be\nfulfilled.\n\nFor example, if x = [1, 1, 2, 3, 0] , you can split it as follows:\n[\\color{blue}1], [\\color{green}1], [\\color{red}2, \\color{red}3, \\color{red}0]\n. Indeed \\color{blue}1=\\color{green}1=\\color{red}2 \\oplus \\color{red}3\\oplus\n\\color{red}0 .\n\nYou are given an array a_1,\\dots,a_n . Your task is to answer q queries:\n\n * For fixed l , r , determine whether the subarray a_l,a_{l+1},\\dots,a_r is interesting. \n\nInput\n\nThe first line contains a single integer t (1\\le t\\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains two integers n and q (2 \\le n \\le 2\n\\cdot 10^5 , 1 \\le q \\le 2 \\cdot 10^5 ) — the number of elements in the array\nand the number of queries respectively.\n\nThe next line contains n integers a_1,\\dots,a_n (0 \\le a_i < 2^{30} ) —\nelements of the array.\n\nEach of the next q lines contains two integers l and r (1 \\le l < r \\le n )\ndescribing the query.\n\nIt is guaranteed that the sum of n over all testcases does not exceed 2 \\cdot\n10^5 .\n\nIt is guaranteed that the sum of q over all testcases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each query, output \"YES\" if the subarray is interesting and \"NO\"\notherwise.\n\nYou can output \"Yes\" and \"No\" in any case (for example, the strings \"yES\",\n\"yes\", and \"Yes\" will be recognized as correct answers).\n\nExample\n\nInput\n\n 4\n \n 5 5\n \n 1 1 2 3 0\n \n 1 5\n \n 2 4\n \n 3 5\n \n 1 3\n \n 3 4\n \n 5 5\n \n 1 2 3 4 5\n \n 1 5\n \n 2 4\n \n 3 5\n \n 1 3\n \n 2 3\n \n 7 4\n \n 12 9 10 9 10 11 9\n \n 1 5\n \n 1 7\n \n 2 6\n \n 2 7\n \n 11 4\n \n 0 0 1 0 0 1 0 1 1 0 1\n \n 1 2\n \n 2 5\n \n 6 9\n \n 7 11\n\nOutput\n\n YES\n YES\n NO\n NO\n NO\n \n YES\n NO\n NO\n YES\n NO\n \n NO\n NO\n NO\n NO\n \n YES\n NO\n YES\n YES\n \nNote\n\nExplanation for the first test case:\n\nThe first query is described in the statement.\n\nIn the second query, we should divide [1,2,3] . A possible division is\n[1,2],[3] , since 1\\oplus 2=3 .\n\nIt can be shown that for queries 3,4,5 , the subarrays are not interesting.", + "generated_code": [ + "from collections import defaultdict\n \n \ndef read(cast):\n return map(cast, input().split())\n \n \ndef bin_search(arr, predicate):\n l, r = 0, len(arr)\n \n while l + 1 < r:\n mid = (l + r) // 2\n if predicate(arr[mid]):\n l = mid\n else:\n r = mid\n \n if predicate(arr[l]):\n return l\n return None\n \n \ndef upper_bound(arr, predicate):\n return bin_search(arr, predicate)\n \n \ndef lower_bound(arr, predicate):\n result = bin_search(arr, predicate)\n if result is not None:\n return result + 1\n return None\n \n \ndef main():\n n, q = read(int)\n \n a = list(read(int))\n x = [0]\n inds = defaultdict(list)\n inds[0].append(0)\n for i in a:\n x.append(x[-1] ^ i)\n inds[x[-1]].append(len(x) - 1)\n \n for i in range(q):\n l, r = read(int)\n \n if x[l - 1] == x[r]:\n print('Yes')\n continue\n \n lower = inds[x[r]][lower_bound(inds[x[r]], lambda arg: arg < l) or 0]\n upper = inds[x[l - 1]][upper_bound(inds[x[l - 1]], lambda arg: arg <= r)]\n \n if upper > lower:\n print('Yes')\n else:\n print('No')\n \n \nif __name__ == '__main__':\n # t = 1\n t, = read(int)\n for _ in range(t):\n main()", + "import sys\ninput = sys.stdin.read\nfrom collections import defaultdict\nfrom bisect import bisect_left\n \ndef solve():\n data = input().split()\n index = 0\n \n # Read number of test cases\n t = int(data[index])\n index += 1\n \n results = []\n \n for _ in range(t):\n # Read n and q\n n = int(data[index])\n q = int(data[index + 1])\n index += 2\n \n # Read the array\n a = [0] * (n + 1)\n pf = [0] * (n + 1)\n mp = defaultdict(list)\n \n mp[0].append(0)\n \n for i in range(1, n + 1):\n a[i] = int(data[index])\n index += 1\n pf[i] = pf[i - 1] ^ a[i]\n mp[pf[i]].append(i)\n \n for _ in range(q):\n l = int(data[index])\n r = int(data[index + 1])\n index += 2\n \n x = pf[r] ^ pf[l - 1]\n if x == 0:\n results.append(\"YES\")\n continue\n \n # Access lists v1 and v2 from map mp\n v1 = mp[pf[r]]\n v2 = mp[pf[l - 1]]\n \n # Find the range within v1 and v2\n it1 = bisect_left(v1, l)\n it2 = bisect_left(v2, r) - 1\n \n # Check if the found indices are valid and satisfy the condition\n if it1 < len(v1) and it2 >= 0 and v1[it1] < v2[it2]:\n results.append(\"YES\")\n else:\n results.append(\"NO\")\n \n # Print all results at the end\n print(\"\\n\".join(results))\n \n# Run the solve function\nsolve()" + ] + }, + { + "task_name": "1969_B", + "description": "Let's define a cyclic shift of some string s as a transformation from s_1 s_2\n\\dots s_{n-1} s_{n} into s_{n} s_1 s_2 \\dots s_{n-1} . In other words, you\ntake one last character s_n and place it before the first character while\nmoving all other characters to the right.\n\nYou are given a binary string s (a string consisting of only 0-s and/or 1-s).\n\nIn one operation, you can choose any substring s_l s_{l+1} \\dots s_r (1 \\le l\n< r \\le |s| ) and cyclically shift it. The cost of such operation is equal to\nr - l + 1 (or the length of the chosen substring).\n\nYou can perform the given operation any number of times. What is the minimum\ntotal cost to make s sorted in non-descending order?\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first and only line of each test case contains a binary string s (2 \\le\n|s| \\le 2 \\cdot 10^5 ; s_i \\in {0, 1}) — the string you need to sort.\n\nAdditional constraint on the input: the sum of lengths of strings over all\ntest cases doesn't exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print the single integer — the minimum total cost to make\nstring sorted using operation above any number of times.\n\nExample\n\nInput\n\n 5\n \n 10\n \n 0000\n \n 11000\n \n 101011\n \n 01101001\n\nOutput\n\n 2\n 0\n 9\n 5\n 11\n \nNote\n\nIn the first test case, you can choose the whole string and perform a cyclic\nshift: 10 \\rightarrow 01. The length of the substring is 2 , so the cost is 2\n.\n\nIn the second test case, the string is already sorted, so you don't need to\nperform any operations.\n\nIn the third test case, one of the optimal strategies is the next:\n\n 1. choose substring [1, 3] : 11000 \\rightarrow 01100; \n 2. choose substring [2, 4] : 01100 \\rightarrow 00110; \n 3. choose substring [3, 5] : 00110 \\rightarrow 00011. \n\nThe total cost is 3 + 3 + 3 = 9 .", + "generated_code": [ + "def solve(s):\n cost=0\n one=0\n for i in s:\n if i=='1':\n one+=1\n elif i=='0' and one>0:\n cost+=(one+1)\n \n return cost\nt=int(input())\nwhile t:\n s=input()\n print(solve(s))\n t=t-1", + "def solve():\n s = input()\n n = 0\n ans = 0\n \n for i in range(len(s)):\n if s[i] == '1':\n n+=1\n if s[i] == '0' and n!=0:\n ans += n+1\n \n print(ans)\n \ndef main():\n t = int(input())\n for _ in range(t):\n solve()\n \nif __name__ == \"__main__\":\n main()", + "# LUOGU_RID: 160731685\ndef main():\n n = int(input())\n for _ in range(n):\n s = list(map(int, input().strip()))\n zeroes = s.count(0)\n cnt = [0, 0]\n ans = 0\n for c in s:\n cnt[c] += 1\n if c == 0:\n ans += 1 if cnt[1] > 0 else 0\n else:\n ans += (zeroes - cnt[0])\n print(ans)\n \nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1969_D", + "description": "Alice and Bob are playing a game in the shop. There are n items in the shop;\neach item has two parameters: a_i (item price for Alice) and b_i (item price\nfor Bob).\n\nAlice wants to choose a subset (possibly empty) of items and buy them. After\nthat, Bob does the following:\n\n * if Alice bought less than k items, Bob can take all of them for free; \n * otherwise, he will take k items for free that Alice bought (Bob chooses which k items it will be), and for the rest of the chosen items, Bob will buy them from Alice and pay b_i for the i -th item. \n\nAlice's profit is equal to \\sum\\limits_{i \\in S} b_i - \\sum\\limits_{j \\in T}\na_j , where S is the set of items Bob buys from Alice, and T is the set of\nitems Alice buys from the shop. In other words, Alice's profit is the\ndifference between the amount Bob pays her and the amount she spends buying\nthe items.\n\nAlice wants to maximize her profit, Bob wants to minimize Alice's profit. Your\ntask is to calculate Alice's profit if both Alice and Bob act optimally.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains two integers n and k (1 \\le n \\le 2\n\\cdot 10^5 ; 0 \\le k \\le n ).\n\nThe second line contains n integers a_1, a_2, \\dots, a_n (1 \\le a_i \\le 10^9\n).\n\nThe third line contains n integers b_1, b_2, \\dots, b_n (1 \\le b_i \\le 10^9 ).\n\nAdditional constraint on the input: the sum of n over all test cases doesn't\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print a single integer — Alice's profit if both Alice and\nBob act optimally.\n\nExample\n\nInput\n\n 4\n \n 2 0\n \n 2 1\n \n 1 2\n \n 4 1\n \n 1 2 1 4\n \n 3 3 2 3\n \n 4 2\n \n 2 1 1 1\n \n 4 2 3 2\n \n 6 2\n \n 1 3 4 9 1 3\n \n 7 6 8 10 6 8\n\nOutput\n\n 1\n 1\n 0\n 7\n \nNote\n\nIn the first test case, Alice should buy the 2 -nd item and sell it to Bob, so\nher profit is 2 - 1 = 1 .\n\nIn the second test case, Alice should buy the 1 -st, the 2 -nd and the 3 -rd\nitem; then Bob takes the 1 -st item for free and pays for the 2 -nd and the 3\n-rd item. Alice's profit is (3+2) - (1+2+1) = 1 . Bob could take 2 -nd item\nfor free instead; this does not change Alice's profit. Bob won't take the 3\n-rd item for free, since this would lead to a profit of 2 .", + "generated_code": [ + "import heapq\nimport sys\n \nread_input = sys.stdin.readline\n \ndef get_single_integer():\n return int(read_input())\n \ndef get_integer_list():\n return map(int, read_input().split())\n \n \ndef calc_total(primary_items, secondary_heap):\n total = sum(item[0] for item in secondary_heap)\n for item in primary_items:\n if item[0] + item[1] >= 0:\n total += item[0] + item[1]\n return total\n \n \ndef main():\n test_cases = get_single_integer()\n \n for _ in range(test_cases):\n heap = []\n remaining_items = []\n n, k = get_integer_list()\n \n prices = list(get_integer_list())\n neg_prices = [-price for price in prices]\n \n bonuses = list(get_integer_list())\n \n max_profit = 0\n current_profit = 0\n \n combined = list(zip(neg_prices, bonuses))\n \n combined.sort(key=lambda item: item[1])\n \n for _ in range(k):\n if combined:\n heapq.heappush(heap, combined.pop())\n \n if combined:\n current_profit = calc_total(combined, heap)\n \n if current_profit > max_profit:\n max_profit = current_profit\n \n while combined:\n item = combined.pop()\n if item[0] + item[1] >= 0:\n current_profit -= item[1]\n else:\n current_profit += item[0]\n \n removed_item = heapq.heappushpop(heap, item)\n if removed_item:\n current_profit -= removed_item[0]\n \n if current_profit > max_profit:\n max_profit = current_profit\n print(max_profit)\n \n \nmain()" + ] + }, + { + "task_name": "1970_A1", + "description": "A parentheses sequence is a string consisting of characters \"(\" and \")\", for\nexample \"(()((\".\n\nA balanced parentheses sequence is a parentheses sequence which can become a\nvalid mathematical expression after inserting numbers and operations into it,\nfor example \"(()(()))\".\n\nThe balance of a parentheses sequence is defined as the number of opening\nparentheses \"(\" minus the number of closing parentheses \")\". For example, the\nbalance of the sequence \"(()((\" is 3.\n\nA balanced parentheses sequence can also be defined as a parentheses sequence\nwith balance 0 such that each of its prefixes has a non-negative balance.\n\nWe define the balanced shuffle operation that takes a parentheses sequence and\nreturns a parentheses sequence as follows: first, for every character of the\ninput sequence, we compute the balance of the prefix of the sequence before\nthat character and write those down in a table together with the positions of\nthe characters in the input sequence, for example:\n\nPrefix balance| 0| 1| 2| 1| 2| 3| 2| 1 \n---|---|---|---|---|---|---|---|--- \nPosition| 1| 2| 3| 4| 5| 6| 7| 8 \nCharacter| (| (| )| (| (| )| )| ) \n \nThen, we sort the columns of this table in increasing order of prefix balance,\nbreaking ties in decreasing order of position. In the above example, we get:\n\nPrefix balance| 0| 1| 1| 1| 2| 2| 2| 3 \n---|---|---|---|---|---|---|---|--- \nPosition| 1| 8| 4| 2| 7| 5| 3| 6 \nCharacter| (| )| (| (| )| (| )| ) \n \nThe last row of this table forms another parentheses sequence, in this case\n\"()(()())\". This sequence is called the result of applying the balanced\nshuffle operation to the input sequence, or in short just the balanced shuffle\nof the input sequence.\n\nYou are given a balanced parentheses sequence. Print its balanced shuffle.\n\nInput\n\nThe only line of input contains a string s consisting only of characters \"(\"\nand \")\". This string is guaranteed to be a non-empty balanced parentheses\nsequence with its length not exceeding 500\\,000 .\n\nOutput\n\nPrint the parentheses sequence t — the balanced shuffle of s .\n\nExample\n\nInput\n\n (()(()))\n \nOutput\n\n ()(()())", + "generated_code": [ + "class BalanceInfo:\n def __init__(self, balance, position, character):\n self.balance = balance\n self.position = position\n self.character = character\ndef compare(infoA, infoB):\n if infoA.balance != infoB.balance:\n return infoA.balance - infoB.balance\n return infoB.position - infoA.position\ndef balanced_shuffle(s):\n n = len(s)\n balance_info = []\n balance = 0\n for i in range(n):\n balance_info.append(BalanceInfo(balance, i, s[i]))\n if s[i] == '(':\n balance += 1\n else:\n balance -= 1\n balance_info.sort(key=lambda x: (x.balance, -x.position))\n result = ''.join(info.character for info in balance_info)\n print(result)\nif __name__ == \"__main__\":\n s = input().strip() \n balanced_shuffle(s)", + "def solve(s):\n n=len(s)\n ans=''\n d={}\n d[0]=0\n for i in range(len(s)):\n if s[i]=='(':\n d[i+1]=d[i]+1\n else:\n d[i+1]=d[i]-1\n d.pop(n)\n d=sorted(d.items(), key=lambda x:(x[1],-x[0]))\n for i , j in d:\n ans+=s[i]\n return ans\n \n \nn=input()\nprint(solve(n))", + "def balanced_shuffle(s):\n n = len(s)\n prefix_balance = []\n balance = 0\n \n for i in range(n):\n prefix_balance.append((balance, i, s[i]))\n if s[i] == '(':\n balance += 1\n else:\n balance -= 1\n \n prefix_balance.sort(key=lambda x: (x[0], -x[1]))\n \n result = ''.join([x[2] for x in prefix_balance])\n \n return result\n \ns = input().strip()\nprint(balanced_shuffle(s))" + ] + }, + { + "task_name": "1970_C2", + "description": "This is the medium version of the problem. The difference in this version is\nthat t=1 and we work on trees.\n\nRon and Hermione are playing a game on a tree of n nodes that are initially\ninactive. The game consists of t rounds, each of which starts with a stone on\nexactly one node, which is considered as activated. A move consists of picking\nan inactive neighbor of the node with a stone on it and moving the stone there\n(thus activating this neighbor). Ron makes the first move, after which he\nalternates with Hermione until no valid move is available. The player that\ncannot make a move loses the round. If both players play optimally, who wins\neach round of this game?\n\nNote that all the rounds are played with the same tree; only the starting node\nchanges. Moreover, after each round, all active nodes are considered inactive\nagain.\n\nInput\n\nThe first line contains integers n (2 \\leq n \\leq 2\\times 10^5 ), t (t=1 ),\nthe number of nodes in the tree and the number of rounds, respectively.\n\nThe next n-1 lines contain two integers 1 \\leq u, v \\leq n each, corresponding\nto an edge of the tree.\n\nThe next line contains t integers 1 \\leq u_1 , \\dots, u_t \\leq n ,\ncorresponding to the node where the stone is initially put.\n\nOutput\n\nThe output consists of t=1 line which is either \"Ron\" or \"Hermione\".\n\nExample\n\nInput\n\n 5 1\n \n 1 2\n \n 1 3\n \n 3 4\n \n 3 5\n \n 1\n\nOutput\n\n Ron", + "generated_code": [ + "from functools import reduce\nimport math\nfrom collections import deque, defaultdict\n \n \ndef dfs(nodes, start, parent=None):\n\tif len(nodes[start]) == 1 and nodes[start][0] == parent:\n\t\treturn False\n\tdistances = []\n\tfor node in nodes[start]:\n\t\tif node != parent:\n\t\t\tdistances.append(not dfs(nodes, node, start))\n\treturn any(distances)\n \n \ndef testcase():\n\tn, t = map(int, input().split())\n\tedges = []\n\tempty = True\n\tnodes = defaultdict(list)\n\tfor i in range(n - 1):\n\t\tu, v = map(int, input().split())\n\t\tnodes[u].append(v)\n\t\tnodes[v].append(u)\n\t\n\tleaves = deque()\n\tfor key in nodes:\n\t\tif len(nodes[key]) == 1:\n\t\t\tleaves.append(key)\n\t\n\tstart = int(input())\n\tmoves = dfs(nodes, start)\n\t\n\tif moves:\n\t\tprint(\"Ron\")\n\telse:\n\t\tprint(\"Hermione\")\n \n \nt = 1 # int(input())\n \nfor i in range(t):\n\ttestcase()" + ] + }, + { + "task_name": "1970_F1", + "description": "This afternoon, you decided to enjoy the first days of Spring by taking a walk\noutside. As you come near the Quidditch field, you hear screams. Once again,\nthere is a conflict about the score: the two teams are convinced that they won\nthe game! To prevent this problem from happening one more time, you decide to\nget involved in the refereeing of the matches.\n\nNow, you will stay in the stadium to watch the game and count the score. At\nthe end of the game, you will decide the winner.\n\nToday, two teams are competing: the red Gryffindor (R) and the blue Ravenclaw\n(B) team. Each team is composed of P players (1 \\leq P \\leq 10 ).\n\nThe field is a rectangle of N lines and M columns (3 \\leq N, M \\leq 99 , N and\nM are odd). All the positions are integers, and several entities are allowed\nto be at the same position in the field. At the beginning of the game, the\nfield contains goals for the two teams (each team can own between one and five\ngoals), the players, and exactly one Quaffle. Other types of balls will be\navailable in the harder versions of the problem.\n\nA game is composed of T steps (0 \\leq T \\leq 10000 ). At each step, one entity\non the field (a player or a ball) performs one action. All entities can move.\nA player can also catch a ball or throw the Quaffle that it is carrying. To\ncatch a ball, a player must be located on the same cell as it. The Quaffle\ndoes not perform any action while it is being carried; it only follows the\nmovements of the player. If a player carrying the Quaffle decides to throw it,\nthe Quaffle is simply put at the current position of the player.\n\nTo win a point, a player must leave the Quaffle at a goal of the other team.\nWhen it does, the team of the player wins one point, and the Quaffle instantly\nmoves to the middle of the field (the cell at the (M+1)/2 -th column of the\n(N+1)/2 -th line of the field, starting from 1). There is no goal in the\nmiddle of the field. If a player puts the ball in its own goal, the other team\nwins the point.\n\nInput\n\nOn the first line, the integers N and M .\n\nThe description of the field follows: N lines of M pairs of characters\nseparated by spaces. Each pair of characters represents a position on the\nfield. It can be either:\n\n * .. to represent an empty cell \n * R0, ..., R9, B0, ..., B9 to represent a player. The first character is the team of the player, and the second is the number of the player in the team. Each pair of characters is unique, but it is not guaranteed that all the pairs appear in the grid. \n * RG or BG to represent a goal. The blue team tries to put the ball in a red goal (RG) while the red team tries to put the ball in a blue goal (BG). \n * .Q to represent the Quaffle, which is the ball that the players use to score goals. \n\nThe next line contains T , the number of steps that compose the game. T lines\nfollow, each describing one action. It contains several pieces of information\nseparated by a space. First, a pair of characters representing the entity that\nmust perform the action. Second, the description of the action:\n\n * U, D, L, R indicate that the entity moves on the grid. It can move to the top of the grid (U), to the bottom (D), to the left (L), or to the right (R). Each entity moves by only one cell at a time. \n * C indicates that the player catches the ball (only a player can catch a ball). Then, there is a space followed by a pair of characters: the description of the ball caught by the player. This information is needed since in the next versions of the problem, several balls may be in the same cell. \n * T indicates that the player throws the Quaffle that it is carrying. \n\nAll the actions performed by the entities are guaranteed to be valid: the\nplayers stay in the field, don't catch a ball if they are not in the same\ncell, don't release the Quaffle if they are not carrying it, ...\n\nOutput\n\nYou must output the description of the main events of the game, one event per\nline. More precisely:\n\n * Each time a team scores, you must print t RED GOAL or t BLUE GOAL, depending on the team who scored, where t is the current time (the position of the action in the list of actions, starting from 0). In the case where a player scores in the wrong goal (a red player scores in the red goal, or a blue player scores in the blue goal), you must print the name of the team who wins one point, that is, the other team. \n\nThe events must be printed in ascending order of t.\n\nAt the end of the game, you must print the final score as: FINAL SCORE: r b,\nwhere r is the score of the red team and b is the score of the blue team.\n\nExamples\n\nInput\n\n 5 5\n \n .. R1 .. B1 ..\n \n RG .. .. .. BG\n \n RG R0 .Q B0 BG\n \n RG .. .. .. BG\n \n .. R2 .. B2 ..\n \n 13\n \n B2 U\n \n B2 U\n \n B2 L\n \n B2 C .Q\n \n B2 L\n \n B2 L\n \n B2 T\n \n R0 R\n \n R0 C .Q\n \n R0 D\n \n R0 R\n \n R0 R\n \n R0 T\n\nOutput\n\n 6 BLUE GOAL\n 12 RED GOAL\n FINAL SCORE: 1 1\n \nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 12\n \n R0 D\n \n R0 C .Q\n \n R0 R\n \n R0 T\n \n R0 D\n \n B0 R\n \n B0 U\n \n B0 C .Q\n \n B0 L\n \n B0 L\n \n B0 L\n \n B0 T\n\nOutput\n\n 11 BLUE GOAL\n FINAL SCORE: 0 1\n \nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 5\n \n R0 D\n \n R0 C .Q\n \n R0 L\n \n R0 L\n \n R0 T\n\nOutput\n\n 4 BLUE GOAL\n FINAL SCORE: 0 1\n \nNote\n\nIn the first example, a blue player goes to the middle of the grid, at the\nposition of the Quaffle. He takes it, goes to the goal of the red team, and\nlets the ball there. He scores! The ball gets back to the middle of the field,\na red player takes it and scores too.\n\nIn the second example, the red player takes the Quaffle, move it and throw it.\nThe blue player catches the ball, goes to the red goal and scores.\n\nIn the third example, the red player takes the ball and scores in the goal of\ntheir own team: the blue team wins a point.", + "generated_code": [ + "\"\"\"\nhttps://codeforces.com/problemset/problem/1970/F1\nF1. Playing Quidditch (Easy)\n\"\"\"\n \nn, m = [int(x) for x in input().split()]\nplayers = dict()\ngoals = {\"B\": [], \"R\": []}\nmouvements = {\"L\": (-1, 0), \"R\": (1, 0), \"U\": (0, -1), \"D\": (0, 1)}\npointsb, pointsr = 0, 0\n \nfor y in range(n):\n s = input().split()\n for x in range(m):\n if s[x] == \"..\" or s[x] == \".Q\":\n continue\n elif s[x] == \"RG\":\n goals[\"R\"].append((x, y))\n elif s[x] == \"BG\":\n goals[\"B\"].append((x, y))\n else:\n players[s[x]] = (x, y)\n \n \ndef add(a, b):\n x, y = a\n dx, dy = b\n return x + dx, y + dy\n \n \nmoves = int(input())\nfor i in range(moves):\n mo = input().split()\n if mo[1] in \"ULDR\":\n players[mo[0]] = add(players[mo[0]], mouvements[mo[1]])\n elif mo[1] == \"T\":\n if players[mo[0]] in goals[\"R\"]:\n pointsb += 1\n print(i, \"BLUE GOAL\")\n if players[mo[0]] in goals[\"B\"]:\n pointsr += 1\n print(i, \"RED GOAL\")\n \n \nprint(\"FINAL SCORE:\", pointsr, pointsb)", + "from sys import stdin\n \nmov = {'U':(-1,0),'D':(1,0),'L':(0,-1),'R':(0,1),'T':(0,0)};\nGoalName = [\"RED\", \"BLUE\"]\n \ndef main():\n n,m = map(int,stdin.readline().strip().split());\n grid = [];\n elements = {\".B\":(-1,-1)};\n allPlayers = {};\n goal = [[],[]]\n points= [0,0];\n \n def goalIn( pos ):\n res = 0 if ( pos in goal[0] ) else ( 1 if ( pos in goal[1] ) else -1 );\n return res;\n def isPlayer( el ):\n res = (el[0] == 'B' or el[0] == 'R')and(el[1]!='G');\n return res;\n \n for i in range(n):\n line = stdin.readline().strip().split();\n grid.append( line );\n for ind in range(len(line)):\n if ( line[ind] != \"..\" ):\n elements[line[ind]] = (i,ind);\n if ( isPlayer( line[ind] ) ):\n allPlayers[line[ind]] = False;\n elif ( line[ind][1]=='G' ):\n tmp = 0 if line[ind][0] =='B' else 1;\n goal[tmp].append( (i,ind) );\n \n t = int(stdin.readline().strip());\n for time in range( t ):\n comand = stdin.readline().strip().split();\n if ( len(comand) == 3 ):\n obj, com, el = comand;\n if ( el == \".Q\" ):\n # print(\"lo agarra en (%d, %d)\" % ( elements[obj][0], elements[obj][1] ) );\n allPlayers[obj] = True;\n elif ( el == \".S\" ):\n team = 1 if obj[0] =='B' else 0;\n points[team] += 10;\n print( \"%d %s CATCH GOLDEN SNITCH\" % ( time, GoalName[team] ) );\n else:\n obj, com = comand;\n pos = elements[obj];\n nxt = (pos[0]+mov[com][0], pos[1]+mov[com][1] );\n if ( ( obj == \".B\" and isPlayer(grid[nxt[0]][nxt[1]])) or ( isPlayer(obj) and elements[\".B\"]==nxt ) ):\n player = obj if isPlayer(obj) else grid[nxt[0]][nxt[1]];\n print( \"%d %s ELIMINATED\" % (time, player ) );\n elif ( com=='T' ):\n allPlayers[obj] = False;\n if ( goalIn(pos)!=-1 ):\n team=goalIn(pos);\n print( \"%d %s GOAL\" %( time, GoalName[team] ) );\n points[team] += 1;\n elif( isPlayer(obj) ):\n elements[obj] = nxt;\n \n if ( obj == \".B\" ):\n elements[obj] = nxt;\n \n print(\"FINAL SCORE: %d %d\"%( points[0], points[1] ));\n \n \n \n \nmain();" + ] + }, + { + "task_name": "1970_F2", + "description": "This afternoon, you decided to enjoy the first days of Spring by taking a walk\noutside. As you come near the Quidditch field, you hear screams. Once again,\nthere is a conflict about the score: the two teams are convinced that they won\nthe game! To prevent this problem from happening one more time, you decide to\nget involved in the refereeing of the matches.\n\nNow, you will stay in the stadium to watch the game and count the score. At\nthe end of the game, you will decide the winner.\n\nToday, two teams are competing: the red Gryffindor (R) and the blue Ravenclaw\n(B) team. Each team is composed of P players (1 \\leq P \\leq 10 ).\n\nThe field is a rectangle of N lines and M columns (3 \\leq N, M \\leq 99 , N and\nM are odd). All the positions are integers, and several entities are allowed\nto be at the same position in the field. At the beginning of the game, the\nfield contains goals for the two teams (each team can own between one and five\ngoals), the players, and exactly one Quaffle. In this version of the problem,\none Bludger can be present. An other type of ball will be available in the\nharder version of the problem.\n\nA game is composed of T steps (0 \\leq T \\leq 10000 ). At each step, one entity\non the field (a player or a ball) performs one action. All entities can move.\nA player can also catch a ball or throw the Quaffle that it is carrying. To\ncatch a ball, a player must be located on the same cell as it. The Quaffle\ndoes not perform any action while it is being carried; it only follows the\nmovements of the player. If a player carrying the Quaffle decides to throw it,\nthe Quaffle is simply put at the current position of the player. If a player\nis on the same cell as a Bludger (either after a movement from the player or\nthe Bludger), the player is eliminated. If the player is eliminated while it\nis carrying the Quaffle, the Quaffle remains on the cell containing both the\nplayer and the Bludger after the move. It is guaranteed that this never occurs\nwhile the player is in a cell containing a goal.\n\nTo win a point, a player must leave the Quaffle at a goal of the other team.\nWhen it does, the team of the player wins one point, and the Quaffle instantly\nmoves to the middle of the field (the cell at the (M+1)/2 -th column of the\n(N+1)/2 -th line of the field, starting from 1). There is no goal in the\nmiddle of the field. If a player puts the ball in its own goal, the other team\nwins the point.\n\nInput\n\nOn the first line, the integers N and M .\n\nThe description of the field follows: N lines of M pairs of characters\nseparated by spaces. Each pair of characters represents a position on the\nfield. It can be either:\n\n * .. to represent an empty cell \n * R0, ..., R9, B0, ..., B9 to represent a player. The first character is the team of the player, and the second is the number of the player in the team. Each pair of characters is unique, but it is not guaranteed that all the pairs appear in the grid. \n * RG or BG to represent a goal. The blue team tries to put the ball in a red goal (RG) while the red team tries to put the ball in a blue goal (BG). \n * .Q to represent the Quaffle, which is the ball that the players use to score goals. \n * .B to represent a Bludger.\n\nThe next line contains T , the number of steps that compose the game. T lines\nfollow, each describing one action. It contains several pieces of information\nseparated by a space. First, a pair of characters representing the entity that\nmust perform the action. Second, the description of the action:\n\n * U, D, L, R indicate that the entity moves on the grid. It can move to the top of the grid (U), to the bottom (D), to the left (L), or to the right (R). Each entity moves by only one cell at a time. \n * C indicates that the player catches the ball (only a player can catch a ball). Then, there is a space followed by a pair of characters: the description of the ball caught by the player. This information is needed since several balls can be in the same cell. \n * T indicates that the player throws the Quaffle that it is carrying. \n\nAll the actions performed by the entities are guaranteed to be valid: the\nplayers stay in the field, don't catch a ball if they are not in the same\ncell, don't release the Quaffle if they are not carrying it, ...\n\nOutput\n\nYou must output the description of the main events of the game, one event per\nline. More precisely:\n\n * Each time a team scores, you must print t RED GOAL or t BLUE GOAL, depending on the team who scored, where t is the current time (the position of the action in the list of actions, starting from 0). In the case where a player scores in the wrong goal (a red player scores in the red goal, or a blue player scores in the blue goal), you must print the name of the team who wins one point, that is, the other team. \n * Each time a player is eliminated, you must print t p ELIMINATED, where t is the current time and p is the player who is eliminated. The format to print the player is the same as in the input.\n\nThe events must be printed in ascending order of t. If several players are\neliminated at the same time, the events must be written in alphabetical order:\nB0, ..., B9, R0, ... R9.\n\nAt the end of the game, you must print the final score as: FINAL SCORE: r b,\nwhere r is the score of the red team and b is the score of the blue team.\n\nExamples\n\nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 12\n \n R0 D\n \n R0 C .Q\n \n R0 R\n \n R0 T\n \n R0 D\n \n B0 R\n \n B0 U\n \n B0 C .Q\n \n B0 L\n \n B0 L\n \n B0 L\n \n B0 T\n\nOutput\n\n 11 BLUE GOAL\n FINAL SCORE: 0 1\n \nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 5\n \n R0 D\n \n R0 C .Q\n \n R0 L\n \n R0 L\n \n R0 T\n\nOutput\n\n 4 BLUE GOAL\n FINAL SCORE: 0 1\n \nInput\n\n 5 5\n \n .. .. .. .. ..\n \n .. .. .. .. ..\n \n RG R0 .Q B0 BG\n \n .. .. .. .. ..\n \n .. .. .B .. ..\n \n 5\n \n .B L\n \n .B U\n \n .B U\n \n B0 L\n \n B0 L\n\nOutput\n\n 2 R0 ELIMINATED\n 4 B0 ELIMINATED\n FINAL SCORE: 0 0\n \nNote\n\nIn the first example, the red player takes the Quaffle, move it and throw it.\nThe blue player catches the ball, goes to the red goal and scores.\n\nIn the second example, the red player takes the ball and scores in the goal of\ntheir own team: the blue team wins a point.\n\nIn the third example, the Bludger goes at the position of R0: R0 is\neliminated. Then, B0 moves to the position of the Bludger: B0 is eliminated\ntoo.\n\nYou can find one more example in the easy version of the problem", + "generated_code": [ + "# /**\n# * author: brownfox2k6\n# * created: 05/08/2024 21:39:39 Hanoi, Vietnam\n# **/\n \ndef move(obj, d):\n if d == 'U':\n obj[0] -= 1\n elif d == 'D':\n obj[0] += 1\n elif d == 'L':\n obj[1] -= 1\n elif d == 'R':\n obj[1] += 1\n \ndef check_eliminate(t):\n out = []\n for p in player:\n if player[p] == blud:\n out.append(p)\n player[p] = [-1, -1]\n for p in sorted(out):\n print(t, p, \"ELIMINATED\")\n \nn, m = map(int, input().split())\nrg = []\nbg = []\nblud = [-1, -1]\nplayer = dict()\nfor i in range(n):\n s = input().split()\n for j in range(m):\n if s[j] == 'RG':\n rg.append([i, j])\n elif s[j] == 'BG':\n bg.append([i, j])\n elif s[j] == '.Q':\n ball = [i, j]\n elif s[j] == '.B':\n blud = [i, j]\n else:\n player[s[j]] = [i, j]\n \ncarry = None\nbs = rs = 0\nfor t in range(int(input())):\n p, d = input().split()[:2]\n if d == 'C':\n carry = p\n elif d == 'T':\n carry = None\n if ball in bg:\n rs += 1\n print(t, \"RED GOAL\")\n ball = [n // 2, m // 2]\n elif ball in rg:\n bs += 1\n print(t, \"BLUE GOAL\")\n ball = [n // 2, m // 2]\n elif p == '.Q':\n move(ball, d)\n elif p == '.B':\n move(blud, d)\n check_eliminate(t)\n else:\n move(player[p], d)\n check_eliminate(t)\n if carry == p:\n ball = player[p]\nprint(\"FINAL SCORE:\", rs, bs)", + "\"\"\"\nhttps://codeforces.com/problemset/problem/1970/F2\nF2. Playing Quidditch (Medium)\n\"\"\"\n \nn, m = [int(x) for x in input().split()]\nplayers = dict()\ngoals = {\"B\": [], \"R\": []}\nmouvements = {\"L\": (-1, 0), \"R\": (1, 0), \"U\": (0, -1), \"D\": (0, 1)}\nmiddle = ((m + 1) // 2, (n + 1) // 2)\nquidditch = [middle, \"\"]\npointsb, pointsr = 0, 0\n \nfor y in range(n):\n s = input().split()\n for x in range(m):\n if s[x] == \"..\":\n continue\n elif s[x] == \".Q\":\n quidditch[0] = (x, y)\n elif s[x] == \"RG\":\n goals[\"R\"].append((x, y))\n elif s[x] == \"BG\":\n goals[\"B\"].append((x, y))\n else:\n players[s[x]] = (x, y)\n \n \ndef add(a, b):\n x, y = a\n dx, dy = b\n return x + dx, y + dy\n \n \nmoves = int(input())\nfor i in range(moves):\n mo = input().split()\n if mo[0] == \".Q\":\n quidditch[0] = add(quidditch[0], mouvements[mo[1]])\n elif mo[1] in \"ULDR\":\n players[mo[0]] = add(players[mo[0]], mouvements[mo[1]])\n if \".B\" in players:\n elimines = []\n for k, v in players.items():\n if k != \".B\" and v == players[\".B\"]:\n elimines.append(k)\n elimines.sort()\n for c in elimines:\n print(i, c, \"ELIMINATED\")\n if quidditch[1] == c:\n quidditch = [players[c], \"\"]\n del players[c]\n elif mo[1] == \"C\":\n quidditch[1] == mo[0]\n elif mo[1] == \"T\":\n quidditch[1] = \"\"\n if players[mo[0]] in goals[\"R\"]:\n pointsb += 1\n print(i, \"BLUE GOAL\")\n if mo[0][0] == \"R\":\n quidditch[0] = middle\n else:\n quidditch[0] = players[mo[0]]\n if players[mo[0]] in goals[\"B\"]:\n pointsr += 1\n print(i, \"RED GOAL\")\n if mo[0][0] == \"B\":\n quidditch[0] = middle\n else:\n quidditch[0] = players[mo[0]]\nprint(\"FINAL SCORE:\", pointsr, pointsb)" + ] + }, + { + "task_name": "1971_D", + "description": "You are given a binary string^{\\dagger} . Please find the minimum number of\npieces you need to cut it into, so that the resulting pieces can be rearranged\ninto a sorted binary string.\n\n![](https://espresso.codeforces.com/76039f9769ba94c1817dbbc5e1fb1b5e4f60950f.png)\n\nNote that:\n\n * each character must lie in exactly one of the pieces; \n * the pieces must be contiguous substrings of the original string; \n * you must use all the pieces in the rearrangement. \n\n^{\\dagger} A binary string is a string consisting of characters \\texttt{0} and\n\\texttt{1} . A sorted binary string is a binary string such that all\ncharacters \\texttt{0} come before all characters \\texttt{1} .\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 500 ) — the number\nof test cases.\n\nThe only line of each test case contains a single string s (1 \\leq |s| \\leq\n500 ) consisting of characters \\texttt{0} and \\texttt{1} , where |s| denotes\nthe length of the string s .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of pieces\nneeded to be able to rearrange the string into a sorted binary string.\n\nExample\n\nInput\n\n 6\n \n 11010\n \n 00000000\n \n 1\n \n 10\n \n 0001111\n \n 0110\n\nOutput\n\n 3\n 1\n 1\n 2\n 1\n 2\n \nNote\n\nThe first test case is pictured in the statement. It can be proven that you\ncan't use fewer than 3 pieces.\n\nIn the second and third test cases, the binary string is already sorted, so\nonly 1 piece is needed.\n\nIn the fourth test case, you need to make a single cut between the two\ncharacters and rearrange them to make the string \\texttt{01} .", + "generated_code": [ + "t = int(input())\n \nfor _ in range(t):\n a = input()\n cut0 = 0\n cut1 = 0\n for i in range(len(a)-1):\n if a[i] == '1' and a[i+1] == '0':\n cut1 += 1\n if a[i] == '0' and a[i+1] == '1':\n cut0 += 1\n if cut0 == 0:\n print(cut1+1)\n else:\n print(cut0+cut1)\n \n# 011 0 111 0 11\n# 1 011", + "t=int(input())\nfor i in range(t):\n s=input()\n count=1\n flag=False\n j=0\n while j=p1+p2:\n print(p1+p2)\n else:\n x=0\n y=p3\n while y>=x:\n if p1-x<=p2-(y):\n print(p1-x+p3)\n break\n else:\n x+=1\n y-=1\n else:\n print(p3)", + "t = int(input()) # Lecture du nombre de cas de test\nfor _ in range(t):\n a, b, c = map(int, input().split()) # Lecture des trois entiers\n if (a + b + c) % 2 != 0:\n print(-1)\n continue\n x = (a + b + c) // 2\n y = a + b\n print(min(x, y))" + ] + }, + { + "task_name": "1974_A", + "description": "Little Rosie has a phone with a desktop (or launcher, as it is also called).\nThe desktop can consist of several screens. Each screen is represented as a\ngrid of size 5 \\times 3 , i.e., five rows and three columns.\n\nThere are x applications with an icon size of 1 \\times 1 cells; such an icon\noccupies only one cell of the screen. There are also y applications with an\nicon size of 2 \\times 2 cells; such an icon occupies a square of 4 cells on\nthe screen. Each cell of each screen can be occupied by no more than one icon.\n\nRosie wants to place the application icons on the minimum number of screens.\nHelp her find the minimum number of screens needed.\n\nInput\n\nThe first line of the input contains t (1 \\leq t \\leq 10^4 ) — the number of\ntest cases.\n\nThe first and only line of each test case contains two integers x and y (0\n\\leq x, y \\leq 99 ) — the number of applications with a 1 \\times 1 icon and\nthe number of applications with a 2 \\times 2 icon, respectively.\n\nOutput\n\nFor each test case, output the minimal number of required screens on a\nseparate line.\n\nExample\n\nInput\n\n 11\n \n 1 1\n \n 7 2\n \n 12 4\n \n 0 3\n \n 1 0\n \n 8 1\n \n 0 0\n \n 2 0\n \n 15 0\n \n 8 2\n \n 0 9\n\nOutput\n\n 1\n 1\n 2\n 2\n 1\n 1\n 0\n 1\n 1\n 2\n 5\n \nNote\n\nThe solution for the first test case can look as follows:\n\n![](https://espresso.codeforces.com/f9882979f0d9b5c31c5260fd626217227c2f05de.png)\nBlue squares represent empty spaces for icons, green squares represent 1\n\\times 1 icons, red squares represent 2 \\times 2 icons\n\nThe solution for the third test case can look as follows:\n\n![](https://espresso.codeforces.com/0e737a290e056a29f38918bf06c13be790307a8d.png)", + "generated_code": [ + "n = int(input())\n \nresult = []\n \nfor _ in range(n):\n \n x , y = list(map(int , input().split()))\n \n space_x = x*1\n space_y = y*4\n total_space = space_y + space_x\n \n if (y % 2 == 0):\n screen_require_for_y = y // 2\n else:\n screen_require_for_y = (y // 2) + 1\n \n # print(screen_require_for_y)\n \n \n remaining_cells =( 15*screen_require_for_y) - space_y\n \n if (space_x <= remaining_cells):\n result.append(screen_require_for_y)\n else :\n extra_space = space_x - remaining_cells\n # if extra_space <= 15 :\n # extra_screen = 1\n if extra_space % 15 == 0:\n extra_screen = extra_space // 15\n else :\n extra_screen = ( extra_space // 15 ) + 1\n \n result.append(extra_screen + screen_require_for_y)\n \n \nprint(\"\\n\".join(map(str,result)))", + "import math\n \ndef sol():\n ap = int(input())\n for k in range(ap):\n x, y = map(int, input().split())\n if x > 0 and y > 0:\n bxsfory = math.ceil(y / 2)\n x = x - bxsfory * 15 + y * 4\n bxsfory1 = 0 if x <= 0 else math.ceil(x / 15)\n print(bxsfory1 + bxsfory)\n elif x == 0 and y > 0:\n print(math.ceil(y / 2))\n elif x > 0 and y == 0:\n print(math.ceil(x / 15))\n else:\n print(0)\nsol()", + "n=int(input())\nfor i in range(n):\n a,b=input().split()\n a=int(a)\n b=int(b)\n t=b\n if t%2==0:\n t=t//2\n else:\n t=t//2+1\n t1=t*15-b*4\n if t1>=a:\n t=t\n else:\n t2=a-t1\n if t2%15==0:\n t=t+t2//15\n else:\n t=t+t2//15+1\n print(t)" + ] + }, + { + "task_name": "1974_B", + "description": "Polycarp has a string s , which consists of lowercase Latin letters. He\nencodes this string using the following algorithm:\n\n * first, he constructs a new auxiliary string r , which consists of all distinct letters of the string s , written in alphabetical order; \n * then the encoding happens as follows: each character in the string s is replaced by its symmetric character from the string r (the first character of the string r will be replaced by the last, the second by the second from the end, and so on). \n\nFor example, encoding the string s =\"codeforces\" happens as follows:\n\n * the string r is obtained as \"cdefors\"; \n * the first character s_1 ='c' is replaced by 's'; \n * the second character s_2 ='o' is replaced by 'e'; \n * the third character s_3 ='d' is replaced by 'r'; \n * ... \n * the last character s_{10} ='s' is replaced by 'c'. \n\n![](https://espresso.codeforces.com/b6f889887677396af4d296900b8ca492324e83ef.png)\nThe string r and replacements for s =\"codeforces\".\n\nThus, the result of encoding the string s =\"codeforces\" is the string\n\"serofedsoc\".\n\nWrite a program that performs decoding — that is, restores the original string\ns from the encoding result.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 2\n\\cdot 10^5 ) — the length of the string b .\n\nThe second line of each test case contains a string b of length n , consisting\nof lowercase Latin letters — the result of encoding the original string s .\n\nIt is guaranteed that the sum of the values of n over all test cases in the\ntest does not exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output the string s from which the encoding result b was\nobtained.\n\nExample\n\nInput\n\n 5\n \n 10\n \n serofedsoc\n \n 3\n \n ttf\n \n 9\n \n tlrhgmaoi\n \n 1\n \n w\n \n 15\n \n hnndledmnhlttin\n\nOutput\n\n codeforces\n fft\n algorithm\n w\n meetinthemiddle", + "generated_code": [ + "def decode_string(encoded):\n # Get unique characters and sort them to form 'r'\n r = ''.join(sorted(set(encoded)))\n # Create the mapping dictionary\n mapping = {r[i]: r[-(i+1)] for i in range(len(r))}\n # Decode the string using the mapping\n return ''.join(mapping[char] for char in encoded)\n \n# Reading input\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \nindex = 0\nt = int(data[index])\nindex += 1\nresults = []\n \nfor _ in range(t):\n n = int(data[index])\n index += 1\n b = data[index]\n index += 1\n results.append(decode_string(b))\n \n# Output the results\nprint('\\n'.join(results))", + "def decode_string(encoded):\n # Step 1: Extract unique characters from the encoded string and sort them to form r\n unique_chars = sorted(set(encoded))\n \n # Step 2: Create a mapping from each character in r to its symmetric counterpart\n char_map = {}\n len_unique = len(unique_chars)\n for i in range(len_unique):\n char_map[unique_chars[i]] = unique_chars[len_unique - 1 - i]\n \n # Step 3: Decode the encoded string b using the mapping\n decoded = ''.join(char_map[ch] for ch in encoded)\n \n return decoded\n \n# Reading input\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \nindex = 0\nt = int(data[index])\nindex += 1\nresults = []\n \nfor _ in range(t):\n n = int(data[index])\n index += 1\n b = data[index]\n index += 1\n results.append(decode_string(b))\n \n# Printing output\nfor result in results:\n print(result)", + "def decode_string(encoded):\n # Determine the auxiliary string r\n unique_chars = sorted(set(encoded))\n r = ''.join(unique_chars)\n \n # Create the mapping from encoded characters to original characters\n char_map = {char: r[-i-1] for i, char in enumerate(r)}\n \n # Decode the string using the mapping\n decoded = ''.join(char_map[char] for char in encoded)\n return decoded\n \n# Read input\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \nt = int(data[0])\nindex = 1\nresults = []\n \nfor _ in range(t):\n n = int(data[index])\n index += 1\n encoded = data[index]\n index += 1\n results.append(decode_string(encoded))\n \n# Output the results\nprint(\"\\n\".join(results))" + ] + }, + { + "task_name": "1975_A", + "description": "Mocha likes arrays, so before her departure, Bazoka gave her an array a\nconsisting of n positive integers as a gift.\n\nNow Mocha wants to know whether array a could become sorted in non-decreasing\norder after performing the following operation some (possibly, zero) times:\n\n * Split the array into two parts — a prefix and a suffix, then swap these two parts. In other words, let a=x+y . Then, we can set a:= y+x . Here + denotes the array concatenation operation. \n\nFor example, if a=[3,1,4,1,5] , we can choose x=[3,1] and y=[4,1,5] ,\nsatisfying a=x+y . Then, we can set a:= y + x = [4,1,5,3,1] . We can also\nchoose x=[3,1,4,1,5] and y=[\\,] , satisfying a=x+y . Then, we can set a := y+x\n= [3,1,4,1,5] . Note that we are not allowed to choose x=[3,1,1] and y=[4,5] ,\nneither are we allowed to choose x=[1,3] and y=[5,1,4] , as both these choices\ndo not satisfy a=x+y .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\leq t\\leq 1000 ). The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (2\\leq n\\leq 50 )\n— the length of the array a .\n\nThe second line of each test case contains n integers a_1,a_2,\\ldots,a_n\n(1\\leq a_i \\leq 10^6 ) — the elements of array a .\n\nOutput\n\nFor each test case, output \"Yes\" if a could become non-decreasing after\nperforming the operation any number of times, and output \"No\" if not.\n\nYou can output \"Yes\" and \"No\" in any case (for example, strings \"yEs\", \"yes\",\n\"Yes\" and \"YES\" will be recognized as a positive response).\n\nExample\n\nInput\n\n 3\n \n 6\n \n 1 1 4 5 1 4\n \n 5\n \n 7 9 2 2 3\n \n 3\n \n 1 2 3\n\nOutput\n\n No\n Yes\n Yes\n \nNote\n\nIn the first test case, it can be proven that a cannot become non-decreasing\nafter performing the operation any number of times.\n\nIn the second test case, we can perform the following operations to make a\nsorted in non-decreasing order:\n\n * Split the array into two parts: x=[7] and y=[9,2,2,3] , then swap these two parts. The array will become y+x = [9,2,2,3,7] . \n * Split the array into two parts: x=[9] and y=[2,2,3,7] , then swap these two parts. The array will become y+x=[2,2,3,7,9] , which is non-decreasing.", + "generated_code": [ + "t = int(input())\n \n \nfor _ in range(t):\n\tn = int(input())\n\t\n\ta = list(map(int, input().split()))\n\t\n\tcheck_all = all([ a[i-1]<= a[i] for i in range(1 , n)])\n\t\n\tif check_all:\n\t\tprint(\"YES\")\n\telse:\n\t\tfor i in range(1, n):\n\t\t\tif a[i-1] > a[i]:\n\t\t\t\tnew = a[i:]\n\t\t\t\tcheck_all_new = all([ a[0]>= new[i] for i in range(len(new))])\n\t\t\t\tnew_all = all([ new[i-1]<= new[i] for i in range(1, len(new))])\n\t\t\t\t\n\t\t\t\tif check_all_new and new_all:\n\t\t\t\t\tprint(\"YES\")\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint(\"NO\")\n\t\t\t\t\tbreak", + "def can_sort_by_swapping(a):\n n = len(a)\n sorted_a = sorted(a)\n concatenated_a = a + a\n \n # Check if sorted_a is a subarray of concatenated_a\n for i in range(n):\n if concatenated_a[i:i+len(sorted_a)] == sorted_a:\n return \"Yes\"\n return \"No\"\n \ndef main():\n import sys\n input = sys.stdin.read\n data = input().split()\n idx = 0\n t = int(data[idx])\n idx += 1\n results = []\n for _ in range(t):\n n = int(data[idx])\n idx += 1\n a = list(map(int, data[idx:idx+n]))\n idx += n\n result = can_sort_by_swapping(a)\n results.append(result)\n print(\"\\n\".join(results))\n \nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1975_C", + "description": "Mocha likes arrays, so before her departure, Chamo gave her an array a\nconsisting of n positive integers as a gift.\n\nMocha doesn't like arrays containing different numbers, so Mocha decides to\nuse magic to change the array. Mocha can perform the following three-step\noperation some (possibly, zero) times:\n\n 1. Choose indices l and r (1 \\leq l < r \\leq n ) \n 2. Let x be the median^\\dagger of the subarray [a_l, a_{l+1},\\ldots, a_r] \n 3. Set all values a_l, a_{l+1},\\ldots, a_r to x \n\nSuppose a=[1,2,3,4,5] initially:\n\n * If Mocha chooses (l,r)=(3,4) in the first operation, then x=3 , the array will be changed into a=[1,2,3,3,5] . \n * If Mocha chooses (l,r)=(1,3) in the first operation, then x=2 , the array will be changed into a=[2,2,2,4,5] . \n\nMocha will perform the operation until the array contains only the same\nnumber. Mocha wants to know what is the maximum possible value of this number.\n\n^\\dagger The median in an array b of length m is an element that occupies\nposition number \\lfloor \\frac{m+1}{2} \\rfloor after we sort the elements in\nnon-decreasing order. For example, the median of [3,1,4,1,5] is 3 and the\nmedian of [5,25,20,24] is 20 .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\leq t\\leq 500 ). The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (2\\leq n\\leq 10^5\n) — the length of the array a .\n\nThe second line of each test case contains n integers a_1,a_2,\\ldots,a_n\n(1\\leq a_i \\leq 10^9 ) — the elements of the array a .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 10^5 .\n\nOutput\n\nFor each test case, output the maximum value of the number.\n\nExample\n\nInput\n\n 2\n \n 2\n \n 1 2\n \n 5\n \n 1 2 3 4 5\n\nOutput\n\n 1\n 4\n \nNote\n\nIn the first test case, a=[1,2] . Mocha can only choose the interval\n(l,r)=(1,2) . The array will be changed to a=[1,1] . Therefore, the answer is\n1 .\n\nIn the second test case, Mocha can perform the following operations:\n\n * Choose the interval (l,r)=(4,5) , then a=[1,2,3,4,4] . \n * Choose the interval (l,r)=(3,5) , then a=[1,2,4,4,4] . \n * Choose the interval (l,r)=(1,5) , then a=[4,4,4,4,4] . \n\nThe array contains only the same number, which is 4 . It can be proven that\nthe maximum value of the final number cannot be greater than 4 .", + "generated_code": [ + "t = int(input())\nfor _ in range(t):\n n=int(input())\n a=list(map(int, input().split()))\n if n==2:\n print(min(a))\n continue\n max=0\n for i in range(n-2):\n temp=a[i:i+3]\n temp.sort()\n if temp[1]>max:\n max=temp[1]\n print(max)" + ] + }, + { + "task_name": "1976_A", + "description": "Monocarp is working on his new site, and the current challenge is to make the\nusers pick strong passwords.\n\nMonocarp decided that strong passwords should satisfy the following\nconditions:\n\n * password should consist only of lowercase Latin letters and digits; \n * there should be no digit that comes after a letter (so, after each letter, there is either another letter or the string ends); \n * all digits should be sorted in the non-decreasing order; \n * all letters should be sorted in the non-decreasing order. \n\nNote that it's allowed for the password to have only letters or only digits.\n\nMonocarp managed to implement the first condition, but he struggles with the\nremaining ones. Can you help him to verify the passwords?\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 1000 ) — the number of\ntestcases.\n\nThe first line of each testcase contains a single integer n (1 \\le n \\le 20 )\n— the length of the password.\n\nThe second line contains a string, consisting of exactly n characters. Each\ncharacter is either a lowercase Latin letter or a digit.\n\nOutput\n\nFor each testcase, print \"YES\" if the given password is strong and \"NO\"\notherwise.\n\nExample\n\nInput\n\n 5\n \n 4\n \n 12ac\n \n 5\n \n 123wa\n \n 9\n \n allllmost\n \n 5\n \n ac123\n \n 6\n \n 011679\n\nOutput\n\n YES\n NO\n YES\n NO\n YES\n \nNote\n\nIn the second testcase, the letters are not sorted in the non-decreasing\norder.\n\nIn the fourth testcase, there is a digit that comes after a letter — digit '1'\nafter a letter 'c'.", + "generated_code": [ + "def check_password(n, password):\n # Separate letters and digits\n letters = []\n digits = []\n \n # Split the password into letters and digits\n for ch in password:\n if ch.isdigit():\n digits.append(ch)\n else:\n letters.append(ch)\n \n # Check if letters are sorted in non-decreasing order\n if letters != sorted(letters):\n return \"NO\"\n \n # Check if digits are sorted in non-decreasing order\n if digits != sorted(digits):\n return \"NO\"\n \n # Check if there is any digit after a letter\n for i in range(len(password) - 1):\n if password[i].isalpha() and password[i + 1].isdigit():\n return \"NO\"\n \n return \"YES\"\n \n# Input handling\nt = int(input()) # number of test cases\nfor _ in range(t):\n n = int(input()) # length of the password\n password = input().strip() # password string\n print(check_password(n, password))", + "def isValid(password):\n digits = []\n letters = []\n for char in password:\n if char.isdigit():\n digits.append(char)\n else:\n letters.append(char)\n \n # Sorting the digits and letters\n digits.sort()\n letters.sort()\n \n # Checking if there is any digit coming after a letter\n for i in range(len(digits)):\n if i < len(digits)-1 and digits[i] > digits[i+1]:\n return False\n if i < len(letters) and digits[-1] > letters[i]:\n return False\n \n # Concatenating the sorted digits and letters\n sortedPassword = ''.join(digits + letters)\n \n # Comparing the sorted password with the original password\n if sortedPassword == password:\n return True\n else:\n return False\n \ntestCases = int(input())\nwhile testCases:\n length = int(input())\n password = input()\n print('YES') if isValid(password) else print('NO')\n testCases -= 1" + ] + }, + { + "task_name": "1977_A", + "description": "The little boy Nikita was given some cubes as a present. He decided to build a\ntower out of them.\n\nInitially, the tower doesn't have any cubes. In one move, Nikita either puts\nexactly 1 cube on top of the tower or removes exactly 1 cube from the top of\nthe tower. Is it possible that after n moves, the resulting tower has exactly\nm cubes?\n\nInput\n\nEach test contains multiple test cases. The first line of input contains a\nsingle integer t (1 \\le t \\le 100 ) — the number of test cases. The\ndescription of the test cases follows.\n\nThe only line of each test case contains two integers n and m (1 \\le n, m \\le\n100 ).\n\nOutput\n\nFor each test case, output \"Yes\" (without quotes) if Nikita can obtain a tower\nwith m cubes, and \"No\" (without quotes) otherwise.\n\nYou can output each letter in any case (lowercase or uppercase). For example,\nthe strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be accepted as a positive\nanswer.\n\nExample\n\nInput\n\n 3\n \n 3 3\n \n 2 4\n \n 5 3\n\nOutput\n\n Yes\n No\n Yes\n \nNote\n\nIn the first test case, Nikita can put 1 cube on top of the tower 3 times in a\nrow, so the answer is \"Yes\".\n\nIn the second test case, Nikita can only end up with either a tower with no\nblocks or a tower with 2 blocks, so the answer is \"No\".", + "generated_code": [ + "for _ in range(int(input())):\n n,m=map(int,input().split())\n if n>=m and (n-m)%2==0:print('YES')\n else:print('NO')", + "a=int(input())\nfor i in range(a):\n b,c=map(int,input().split())\n q=(b,c)\n if b==c:\n print('YES')\n elif b=0:\n print('Yes')\n else:\n print('No')\nkreker=int(input())\nfor i in range(kreker):\n makaroni()" + ] + }, + { + "task_name": "1977_B", + "description": "You are given a positive integer x . Find any array of integers a_0, a_1,\n\\ldots, a_{n-1} for which the following holds:\n\n * 1 \\le n \\le 32 , \n * a_i is 1 , 0 , or -1 for all 0 \\le i \\le n - 1 , \n * x = \\displaystyle{\\sum_{i=0}^{n - 1}{a_i \\cdot 2^i}} , \n * There does not exist an index 0 \\le i \\le n - 2 such that both a_{i} \\neq 0 and a_{i + 1} \\neq 0 . \n\nIt can be proven that under the constraints of the problem, a valid array\nalways exists.\n\nInput\n\nEach test contains multiple test cases. The first line of input contains a\nsingle integer t (1 \\le t \\le 10^4 ) — the number of test cases. The\ndescription of the test cases follows.\n\nThe only line of each test case contains a single positive integer x (1 \\le x\n< 2^{30} ).\n\nOutput\n\nFor each test case, output two lines.\n\nOn the first line, output an integer n (1 \\le n \\le 32 ) — the length of the\narray a_0, a_1, \\ldots, a_{n-1} .\n\nOn the second line, output the array a_0, a_1, \\ldots, a_{n-1} .\n\nIf there are multiple valid arrays, you can output any of them.\n\nExample\n\nInput\n\n 7\n \n 1\n \n 14\n \n 24\n \n 15\n \n 27\n \n 11\n \n 19\n\nOutput\n\n 1\n 1\n 5\n 0 -1 0 0 1\n 6\n 0 0 0 -1 0 1\n 5\n -1 0 0 0 1\n 6\n -1 0 -1 0 0 1\n 5\n -1 0 -1 0 1\n 5\n -1 0 1 0 1\n\nNote\n\nIn the first test case, one valid array is [1] , since (1) \\cdot 2^0 = 1 .\n\nIn the second test case, one possible valid array is [0,-1,0,0,1] , since (0)\n\\cdot 2^0 + (-1) \\cdot 2^1 + (0) \\cdot 2^2 + (0) \\cdot 2^3 + (1) \\cdot 2^4 =\n-2 + 16 = 14 .", + "generated_code": [ + "t=int(input())\nfor nalla in range(t):\n x=int(input())\n s=[]\n length=30\n for i in range(30):\n if(x & pow(2,i)):\n s.append('1')\n else:\n s.append('0')\n flag=0\n for i in range(0,29):\n if(flag and s[i]=='0'):\n s[i]='1'\n flag=0\n if(flag==0 and s[i]==s[i+1] and s[i]=='1'):\n s[i]='-1'\n flag=1\n elif(flag==1):\n s[i]='0'\n else:\n pass\n if(flag and s[29]=='0'):\n s[29]='1'\n elif(flag):\n s[29]='0'\n s.append('1')\n length+=1\n for i in range(1, length):\n if (s[i] == '-1') & (s[i-1] == '1'):\n s[i] = '0'\n s[i-1]= '-1'\n print(length)\n print(*s)\n # print(*ans)" + ] + }, + { + "task_name": "1978_A", + "description": "Alice has n books. The 1 -st book contains a_1 pages, the 2 -nd book contains\na_2 pages, \\ldots , the n -th book contains a_n pages. Alice does the\nfollowing:\n\n * She divides all the books into two non-empty piles. Thus, each book ends up in exactly one of the two piles.\n * Alice reads one book with the highest number in each pile.\n\nAlice loves reading very much. Help her find the maximum total number of pages\nshe can read by dividing the books into two piles.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 500 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (2 \\le n \\le 100\n) — the number of books Alice has.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the number of pages in each book.\n\nOutput\n\nFor each test case, output a single integer — the maximum number of pages\nAlice can read.\n\nExample\n\nInput\n\n 5\n \n 2\n \n 1 1\n \n 4\n \n 2 3 3 1\n \n 5\n \n 2 2 3 2 2\n \n 2\n \n 10 3\n \n 3\n \n 1 2 3\n\nOutput\n\n 2\n 4\n 5\n 13\n 5\n \nNote\n\nIn the first test case, Alice can put book number 1 in the first pile, and\nbook number 2 in the second pile. Then she will read a_1 + a_2 = 1 + 1 = 2\npages.\n\nIn the second test case, Alice can put books with numbers 2 and 3 in the first\npile, and books with numbers 1 and 4 in the second pile. Then she will read\nthe book with the highest number 3 from the first pile, and the book with the\nhighest number 4 from the second pile. Then she will read a_3 + a_4 = 3 + 1 =\n4 pages.", + "generated_code": [ + "t= int(input())\nfor _ in range(t):\n n = int(input())\n nums = list(map(int,input().split()))\n print(max(nums[:-1])+nums[-1])" + ] + }, + { + "task_name": "1978_B", + "description": "Bob decided to open a bakery. On the opening day, he baked n buns that he can\nsell. The usual price of a bun is a coins, but to attract customers, Bob\norganized the following promotion:\n\n * Bob chooses some integer k (0 \\le k \\le \\min(n, b) ).\n * Bob sells the first k buns at a modified price. In this case, the price of the i -th (1 \\le i \\le k ) sold bun is (b - i + 1) coins.\n * The remaining (n - k) buns are sold at a coins each.\n\nNote that k can be equal to 0 . In this case, Bob will sell all the buns at a\ncoins each.\n\nHelp Bob determine the maximum profit he can obtain by selling all n buns.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe only line of each test case contains three integers n , a , and b (1 \\le\nn, a, b \\le 10^9 ) — the number of buns, the usual price of a bun, and the\nprice of the first bun to be sold at a modified price.\n\nOutput\n\nFor each test case, output a single integer — the maximum profit that Bob can\nobtain.\n\nExample\n\nInput\n\n 7\n \n 4 4 5\n \n 5 5 9\n \n 10 10 5\n \n 5 5 11\n \n 1000000000 1000000000 1000000000\n \n 1000000000 1000000000 1\n \n 1000 1 1000\n\nOutput\n\n 17\n 35\n 100\n 45\n 1000000000000000000\n 1000000000000000000\n 500500\n \nNote\n\nIn the first test case, it is optimal for Bob to choose k = 1 . Then he will\nsell one bun for 5 coins, and three buns at the usual price for 4 coins each.\nThen the profit will be 5 + 4 + 4 + 4 = 17 coins.\n\nIn the second test case, it is optimal for Bob to choose k = 5 . Then he will\nsell all the buns at the modified price and obtain a profit of 9 + 8 + 7 + 6 +\n5 = 35 coins.\n\nIn the third test case, it is optimal for Bob to choose k = 0 . Then he will\nsell all the buns at the usual price and obtain a profit of 10 \\cdot 10 = 100\ncoins.", + "generated_code": [ + "t=int(input())\nfor _ in range(t):\n n,a,b=map(int,input().split())\n if b<=a:\n print(n*a)\n else:\n if (b-a)>=n:\n print(int((2*b-n+1)*n//2))\n else:\n print(int((b-a)*(b-a+1)//2+a*n))", + "for _ in range(int(input())):\n n,a,b=map(int,input().split())\n k=min(n,b-a)\n if(b<=a):\n print(a*n)\n else:\n print(b*k-k*(k-1)//2+(n-k)*a)", + "def calculate_profit(k, n, a, b):\n return k * b - (k * (k - 1)) // 2 + (n - k) * a\n \ndef max_profit(n, a, b):\n low, high = 0, min(n, b)\n max_profit = 0\n \n while low <= high:\n mid = (low + high) // 2\n profit_mid = calculate_profit(mid, n, a, b)\n profit_next = calculate_profit(mid + 1, n, a, b)\n \n max_profit = max(max_profit, profit_mid)\n \n if profit_next > profit_mid:\n low = mid + 1\n else:\n high = mid - 1\n \n return max_profit\n \nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n n, a, b = map(int, input().split())\n print(max_profit(n, a, b))" + ] + }, + { + "task_name": "1978_C", + "description": "Let's call the Manhattan value of a permutation^{\\dagger} p the value of the\nexpression |p_1 - 1| + |p_2 - 2| + \\ldots + |p_n - n| .\n\nFor example, for the permutation [1, 2, 3] , the Manhattan value is |1 - 1| +\n|2 - 2| + |3 - 3| = 0 , and for the permutation [3, 1, 2] , the Manhattan\nvalue is |3 - 1| + |1 - 2| + |2 - 3| = 2 + 1 + 1 = 4 .\n\nYou are given integers n and k . Find a permutation p of length n such that\nits Manhattan value is equal to k , or determine that no such permutation\nexists.\n\n^{\\dagger} A permutation of length n is an array consisting of n distinct\nintegers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a\npermutation, but [1,2,2] is not a permutation (2 appears twice in the array),\nand [1,3,4] is also not a permutation (n=3 but there is 4 in the array).\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^{4} ) — the number of test cases. The description\nof the test cases follows.\n\nThe only line of each test case contains two integers n and k (1 \\le n \\le 2\n\\cdot 10^{5}, 0 \\le k \\le 10^{12} ) — the length of the permutation and the\nrequired Manhattan value.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^{5} .\n\nOutput\n\nFor each test case, if there is no suitable permutation, output \"No\".\nOtherwise, in the first line, output \"Yes\", and in the second line, output n\ndistinct integers p_1, p_2, \\ldots, p_n (1 \\le p_i \\le n ) — a suitable\npermutation.\n\nIf there are multiple solutions, output any of them.\n\nYou can output the answer in any case (for example, the strings \"yEs\", \"yes\",\n\"Yes\", and \"YES\" will be recognized as a positive answer).\n\nExample\n\nInput\n\n 8\n \n 3 4\n \n 4 5\n \n 7 0\n \n 1 1000000000000\n \n 8 14\n \n 112 777\n \n 5 12\n \n 5 2\n\nOutput\n\n Yes\n 3 1 2\n No\n Yes\n 1 2 3 4 5 6 7\n No\n Yes\n 8 2 3 4 5 6 1 7\n No\n Yes\n 5 4 3 1 2\n Yes\n 2 1 3 4 5\n \nNote\n\nIn the first test case, the permutation [3, 1, 2] is suitable, its Manhattan\nvalue is |3 - 1| + |1 - 2| + |2 - 3| = 2 + 1 + 1 = 4 .\n\nIn the second test case, it can be proven that there is no permutation of\nlength 4 with a Manhattan value of 5 .\n\nIn the third test case, the permutation [1,2,3,4,5,6,7] is suitable, its\nManhattan value is |1-1|+|2-2|+|3-3|+|4-4|+|5-5|+|6-6|+|7-7|=0 .", + "generated_code": [ + "def list_p(n,k):\n k=k//2\n l=list(range(1,n+1))\n c=0\n for i in range(n,-1,-2):\n c+=1\n if k==0:\n return l\n if k=prod:\n\t print(-1)\n\telse:\n\t ans=\"\"\n\t for i in range(bets):\n\t ans+=str(a[i])+\" \"\n\t print(ans)", + "from math import gcd\n \ndef lcm(a, b):\n return abs(a * b) // gcd(a, b)\n \ndef calculate_lcm(numbers):\n result = numbers[0]\n for num in numbers[1:]:\n result = lcm(result, num)\n return result\n \nt = int(input())\nfor _ in range(t):\n n=int(input())\n k=list(map(int, input().split()))\n m=calculate_lcm(k)\n c=[]\n for i in range(n):\n c.append(m//k[i])\n if sum(c)>=m:\n print(-1)\n continue\n for i in range(n):\n print(c[i], end=' ')\n print('\\n', end='')", + "from math import gcd\ndef lcm(a, b):\n return a * b // gcd(a, b)\n \ndef solve():\n N = int(input().strip())\n vals = [int(r) for r in input().strip().split()]\n den = vals[0]\n for x in vals:\n den = lcm(den, x)\n # prod = 1\n # for r in vals:\n # prod *= r\n vprod = [den//r for r in vals]\n den = den - sum(vprod)\n if den <= 0:\n print(-1)\n return\n \n print(\" \".join([str(x) for x in vprod]))\n \ncases = int(input())\nfor n in range(cases):\n solve()" + ] + }, + { + "task_name": "1980_A", + "description": "Vlad is planning to hold m rounds next month. Each round should contain one\nproblem of difficulty levels 'A', 'B', 'C', 'D', 'E', 'F', and 'G'.\n\nVlad already has a bank of n problems, where the i -th problem has a\ndifficulty level of a_i . There may not be enough of these problems, so he may\nhave to come up with a few more problems.\n\nVlad wants to come up with as few problems as possible, so he asks you to find\nthe minimum number of problems he needs to come up with in order to hold m\nrounds.\n\nFor example, if m=1 , n = 10 , a= 'BGECDCBDED', then he needs to come up with\ntwo problems: one of difficulty level 'A' and one of difficulty level 'F'.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 1000 ) — the number of\ntest cases.\n\nThe first line of each test case contains two integers n and m (1 \\le n \\le 50\n, 1 \\le m \\le 5 ) — the number of problems in the bank and the number of\nupcoming rounds, respectively.\n\nThe second line of each test case contains a string a of n characters from 'A'\nto 'G' — the difficulties of the problems in the bank.\n\nOutput\n\nFor each test case, output a single integer — the minimum number of problems\nthat need to come up with to hold m rounds.\n\nExample\n\nInput\n\n 3\n \n 10 1\n \n BGECDCBDED\n \n 10 2\n \n BGECDCBDED\n \n 9 1\n \n BBCDEFFGG\n\nOutput\n\n 2\n 5\n 1", + "generated_code": [ + "from collections import Counter\nt=int(input())\nfor _ in range(t):\n n,m=map(int,input().split())\n s=input()\n ans=0\n p=\"ABCDEFG\"\n hmp=Counter(s)\n for i in p:\n if i not in hmp:\n ans+=m\n for i in hmp:\n if hmp[i]0):\n t-=1 \n d=defaultdict(default_value)\n n,m=list(map(int,input().split())) \n s=input() \n d['A']=0\n d['B']=0\n d['C']=0\n d['D']=0\n d['E']=0\n d['F']=0\n d['G']=0\n for i in range(n):\n d[s[i]]=d[s[i]]+1 \n ans=0\n \n for val in d.keys():\n if(d[val]<=m):\n ans=ans+m-d[val]\n print(ans)", + "def min_problems_to_create(n, m, a):\n # Step 2: Initialize the count list\n count = [0] * 7\n \n # Step 3: Count the occurrences of each difficulty level\n for char in a:\n count[ord(char) - ord('A')] += 1\n \n # Step 4: Check which counters are less than m\n needed_problems = 0\n for i in range(7):\n if count[i] < m:\n needed_problems += m - count[i]\n \n return needed_problems\n \n# Reading the number of test cases\nt = int(input())\nfor _ in range(t):\n # Reading n and m for each test case\n n, m = map(int, input().split())\n # Reading the string a for each test case\n a = input()\n # Outputting the result for each test case\n print(min_problems_to_create(n, m, a))" + ] + }, + { + "task_name": "1971_E", + "description": "Timur is in a car traveling on the number line from point 0 to point n . The\ncar starts moving from point 0 at minute 0 .\n\nThere are k+1 signs on the line at points 0, a_1, a_2, \\dots, a_k , and Timur\nknows that the car will arrive there at minutes 0, b_1, b_2, \\dots, b_k ,\nrespectively. The sequences a and b are strictly increasing with a_k = n .\n\n![](https://espresso.codeforces.com/eaf3bfb8e7a8fa4f5e8673f9a02116761cb86c93.png)\n\nBetween any two adjacent signs, the car travels with a constant speed. Timur\nhas q queries: each query will be an integer d , and Timur wants you to output\nhow many minutes it takes the car to reach point d , rounded down to the\nnearest integer.\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 10^4 ) — the number\nof test cases.\n\nThe first line of each test case contains three integers n , k , and q , (k\n\\leq n \\leq 10^9 ; 1 \\leq k, q \\leq 10^5 ) — the final destination, the number\nof points Timur knows the time for, and the number of queries respectively.\n\nThe second line of each test case contains k integers a_i (1 \\leq a_i \\leq n ;\na_i < a_{i+1} for every 1 \\leq i \\leq k-1 ; a_k = n ).\n\nThe third line of each test case contains k integers b_i (1 \\leq b_i \\leq 10^9\n; b_i < b_{i+1} for every 1 \\leq i \\leq k-1 ).\n\nEach of the following q lines contains a single integer d (0 \\leq d \\leq n ) —\nthe distance that Timur asks the minutes passed for.\n\nThe sum of k over all test cases doesn't exceed 10^5 , and the sum of q over\nall test cases doesn't exceed 10^5 .\n\nOutput\n\nFor each query, output a single integer — the number of minutes passed until\nthe car reaches the point d , rounded down.\n\nExample\n\nInput\n\n 4\n \n 10 1 3\n \n 10\n \n 10\n \n 0\n \n 6\n \n 7\n \n 10 2 4\n \n 4 10\n \n 4 7\n \n 6\n \n 4\n \n 2\n \n 7\n \n 1000000000 1 1\n \n 1000000000\n \n 1000000000\n \n 99999999\n \n 6 1 3\n \n 6\n \n 5\n \n 2\n \n 6\n \n 5\n\nOutput\n\n 0 6 7 \n 5 4 2 5 \n 99999999 \n 1 5 4 \n \nNote\n\nFor the first test case, the car goes from point 0 to point 10 in 10 minutes,\nso the speed is 1 unit per minute and:\n\n * At point 0 , the time will be 0 minutes. \n * At point 6 , the time will be 6 minutes. \n * At point 7 , the time will be 7 minutes. \n\nFor the second test case, between points 0 and 4 , the car travels at a speed\nof 1 unit per minute and between 4 and 10 with a speed of 2 units per minute\nand:\n\n * At point 6 , the time will be 5 minutes. \n * At point 4 , the time will be 4 minutes. \n * At point 2 , the time will be 2 minutes. \n * At point 7 , the time will be 5.5 minutes, so the answer is 5 . \n\nFor the fourth test case, the car travels with 1.2 units per minute, so the\nanswers to the queries are:\n\n * At point 2 , the time will be 1.66\\dots minutes, so the answer is 1 . \n * At point 6 , the time will be 5 minutes. \n * At point 5 , the time will be 4.16\\dots minutes, so the answer is 4 .", + "generated_code": [ + "from bisect import bisect_left\nt = int(input())\n \nfor _ in range(t):\n n, k, q = map(int, input().split())\n a = [0] + list(map(int, input().split()))\n b = [0] + list(map(int, input().split()))\n ad = [0]\n bd = [0]\n for i in range(1, len(a)):\n ad.append(a[i]-a[i-1])\n for i in range(1, len(b)):\n bd.append(b[i]-b[i-1])\n v = [0]\n for i in range(1,len(a)):\n v.append(ad[i]/bd[i]) \n for l in range(q):\n m = 0\n i = 1\n ql = int(input())\n s = bisect_left(a, ql)\n if a[s] == ql:\n print(b[s], end=' ')\n continue\n ql -= a[s-1]\n m += b[s-1]\n m += bd[s] * ql//ad[s]\n print(m, end=' ')\n print()" + ] + } +] \ No newline at end of file diff --git a/new_data/filtered_merged_incor.json b/new_data/filtered_merged_incor.json new file mode 100644 index 0000000..104f2d3 --- /dev/null +++ b/new_data/filtered_merged_incor.json @@ -0,0 +1,855 @@ +[ + { + "task_name": "1919_A", + "description": "Alice and Bob are bored, so they decide to play a game with their wallets.\nAlice has a coins in her wallet, while Bob has b coins in his wallet.\n\nBoth players take turns playing, with Alice making the first move. In each\nturn, the player will perform the following steps in order:\n\n 1. Choose to exchange wallets with their opponent, or to keep their current wallets. \n 2. Remove 1 coin from the player's current wallet. The current wallet cannot have 0 coins before performing this step. \n\nThe player who cannot make a valid move on their turn loses. If both Alice and\nBob play optimally, determine who will win the game.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 1000 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first and only line of each test case contains two integers a and b (1 \\le\na, b \\le 10^9 ) — the number of coins in Alice's and Bob's wallets,\nrespectively.\n\nOutput\n\nFor each test case, output \"Alice\" if Alice will win the game, and \"Bob\" if\nBob will win the game.\n\nExample\n\nInput\n\n 10\n \n 1 1\n \n 1 4\n \n 5 3\n \n 4 5\n \n 11 9\n \n 83 91\n \n 1032 9307\n \n 839204 7281\n \n 1000000000 1000000000\n \n 53110 2024\n\nOutput\n\n Bob\n Alice\n Bob\n Alice\n Bob\n Bob\n Alice\n Alice\n Bob\n Bob\n \nNote\n\nIn the first test case, an example of the game is shown below:\n\n * Alice chooses to not swap wallets with Bob in step 1 of her move. Now, a=0 and b=1 . \n * Since Alice's wallet is empty, Bob must choose to not swap their wallets in step 1 of his move. Now, a=0 and b=0 . \n * Since both Alice's and Bob's wallets are empty, Alice is unable to make a move. Hence, Bob wins. \n\nIn the second test case, an example of the game is shown below:\n\n * Alice chooses to swap wallets with Bob in step 1 of her move. Now, a=3 and b=1 . \n * Bob chooses to swap wallets with Alice in step 1 of his move. Now, a=1 and b=2 . \n * Alice chooses to not swap wallets with Bob in step 1 of her move. Now, a=0 and b=2 . \n * Since Alice's wallet is empty, Bob can only choose to not swap wallets with Alice in step 1 of his move. Now, a=0 and b=1 . \n * Since Alice's wallet is empty, Alice can only choose to swap wallets with Bob in step 1 of her move. Now, a=0 and b=0 . \n * Since both Alice's wallet and Bob's wallet are empty, Bob is unable to make a move. Hence, Alice wins.", + "generated_code": [ + "T=int(input())\nfor i in range(T):\n a,b = map(int, input().split())\n if a==b:\n print(\"Bob\")\n else:\n if a==1:\n print(\"Alice\")\n elif b==1:\n print(\"Bob\")\n else:\n if a%2==1:\n print(\"Bob\")\n elif a%2==0 and b%2==1:\n print(\"Alice\")\n else:\n if a>b:\n print(\"Bob\")\n else:\n print(\"Alice\")", + "def determine_winner(a, b):\n # If the sum of coins is odd, Alice wins, because she can always force Bob\n # to face an empty wallet scenario first due to having the first move advantage.\n # For an even sum, Bob wins, by following Alice's strategy and ensuring\n # that Alice faces the empty wallet scenario first.\n if (a + b) % 2 == 0:\n return \"Bob\"\n else:\n return \"Alice\"\n \ndef main():\n t = int(input(\"Enter the number of test cases: \")) # Read the number of test cases\n \n results = []\n \n for _ in range(t):\n a, b = map(int, input().strip().split()) # Read the number of coins in Alice's and Bob's wallets\n winner = determine_winner(a, b)\n results.append(winner)\n \n for result in results:\n print(result)\n \nif __name__ == \"__main__\":\n main()", + "for i in range(int(input())):\n\ts = input()\n\ta=int(list(s.split())[0])\n\tb=int(list(s.split())[1])\n\t\nif (a+b)%2 == 0:\n\tprint(\"bob \") \nelse :\n\tprint(\"alice\")", + "t = int(input())\n \nfor _rep in range(t):\n n, k = list(map(int, input().split()))\n \n if n > k:\n print(\"Bob\")\n elif n < k:\n print(\"Alice\")\n else:\n print(\"Bob\")" + ] + }, + { + "task_name": "1919_B", + "description": "You are given a string s of length n consisting of characters \"+\" and \"-\". s\nrepresents an array a of length n defined by a_i=1 if s_i= \"+\" and a_i=-1 if\ns_i= \"-\".\n\nYou will do the following process to calculate your penalty:\n\n 1. Split a into non-empty arrays b_1,b_2,\\ldots,b_k such that b_1+b_2+\\ldots+b_k=a^\\dagger , where + denotes array concatenation. \n 2. The penalty of a single array is the absolute value of its sum multiplied by its length. In other words, for some array c of length m , its penalty is calculated as p(c)=|c_1+c_2+\\ldots+c_m| \\cdot m . \n 3. The total penalty that you will receive is p(b_1)+p(b_2)+\\ldots+p(b_k) . \n\nIf you perform the above process optimally, find the minimum possible penalty\nyou will receive.\n\n^\\dagger Some valid ways to split a=[3,1,4,1,5] into (b_1,b_2,\\ldots,b_k) are\n([3],[1],[4],[1],[5]) , ([3,1],[4,1,5]) and ([3,1,4,1,5]) while some invalid\nways to split a are ([3,1],[1,5]) , ([3],[\\,],[1,4],[1,5]) and ([3,4],[5,1,1])\n.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 1000 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 5000\n) — the length of string s .\n\nThe second line of each test case contains string s (s_i \\in \\\\{ \\mathtt{+},\n\\mathtt{-} \\\\} , |s| = n ).\n\nNote that there are no constraints on the sum of n over all test cases.\n\nOutput\n\nFor each test case, output a single integer representing the minimum possible\npenalty you will receive.\n\nExample\n\nInput\n\n 5\n \n 1\n \n +\n \n 5\n \n -----\n \n 6\n \n +-+-+-\n \n 10\n \n --+++++++-\n \n 20\n \n +---++++-+++++---++-\n\nOutput\n\n 1\n 5\n 0\n 4\n 4\n \nNote\n\nIn the first test case, we have a=[1] . We can split array a into ([1]) .\nThen, the sum of penalties of the subarrays is p([1]) = 1 .\n\nIn the second test case, we have a=[-1,-1,-1,-1,-1] . We can split array a\ninto ([-1],[-1],[-1],[-1],[-1]) . Then, the sum of penalties of the subarrays\nis p([-1]) + p([-1]) + p([-1]) + p([-1]) + p([-1]) = 1 + 1 + 1 + 1 + 1 = 5 .\n\nIn the third test case, we have a=[1,-1,1,-1,1,-1] . We can split array a into\n([1,-1,1,-1],[1,-1]) . Then, the sum of penalties of the subarrays is\np([1,-1,1,-1]) + p([1,-1]) = 0 + 0 = 0 .", + "generated_code": [ + "for i in range(int(input())):\n s = int(input())\n e = input()\n P = 0\n M = 0\n for q in e:\n if q == '+':\n P += 1\n else:\n M += 1\n print(P-M)", + "def solve(expression, length):\n count = 0\n balance = 0\n \n for char in expression:\n if char == '+':\n balance += 1\n elif char == '-':\n balance -= 1\n \n if balance < 0:\n count += 1\n balance = 0\n \n return count + (balance > 0)\n \n# Read the number of test cases\nt = int(input())\n \n# Process each test case\nfor _ in range(t):\n length = int(input())\n expression = input().strip()\n \n # Split expression by '-' to get the length of the final result\n parts = expression.split('-')\n result_length = sum(len(part) for part in parts)\n \n print(solve(expression, result_length))", + "def solve():\n\tn = int(input())\n\ts = input()\n\tneg = 0\n\tfor i in s:\n\t\tif i=='-':neg+=1\n\tprint(n-2*neg if n!=neg else n)\nt = int(input())\nwhile t:\n\tsolve()\n\tt-=1" + ] + }, + { + "task_name": "1919_C", + "description": "You are given an array a of size n . You will do the following process to\ncalculate your penalty:\n\n 1. Split array a into two (possibly empty) subsequences^\\dagger s and t such that every element of a is either in s or t^\\ddagger . \n 2. For an array b of size m , define the penalty p(b) of an array b as the number of indices i between 1 and m - 1 where b_i < b_{i + 1} . \n 3. The total penalty you will receive is p(s) + p(t) . \n\nIf you perform the above process optimally, find the minimum possible penalty\nyou will receive.\n\n^\\dagger A sequence x is a subsequence of a sequence y if x can be obtained\nfrom y by the deletion of several (possibly, zero or all) elements.\n\n^\\ddagger Some valid ways to split array a=[3,1,4,1,5] into (s,t) are\n([3,4,1,5],[1]) , ([1,1],[3,4,5]) and ([\\,],[3,1,4,1,5]) while some invalid\nways to split a are ([3,4,5],[1]) , ([3,1,4,1],[1,5]) and ([1,3,4],[5,1]) .\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^4 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1\\le n\\le 2\\cdot\n10^5 ) — the size of the array a .\n\nThe second line contains n integers a_1, a_2, \\ldots, a_n (1 \\le a_i \\le n ) —\nthe elements of the array a .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2\\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single integer representing the minimum possible\npenalty you will receive.\n\nExample\n\nInput\n\n 5\n \n 5\n \n 1 2 3 4 5\n \n 8\n \n 8 2 3 1 1 7 4 3\n \n 5\n \n 3 3 3 3 3\n \n 1\n \n 1\n \n 2\n \n 2 1\n\nOutput\n\n 3\n 1\n 0\n 0\n 0\n \nNote\n\nIn the first test case, a possible way to split a is s=[2,4,5] and t=[1,3] .\nThe penalty is p(s)+p(t)=2 + 1 =3 .\n\nIn the second test case, a possible way to split a is s=[8,3,1] and\nt=[2,1,7,4,3] . The penalty is p(s)+p(t)=0 + 1 =1 .\n\nIn the third test case, a possible way to split a is s=[\\,] and t=[3,3,3,3,3]\n. The penalty is p(s)+p(t)=0 + 0 =0 .", + "generated_code": [ + "for _ in range(int(input())):\n\tn = int(input())\n\t*inp, = map(int, input().split())\n\tx=y=n+1\n\tans=0\n\tfor a in inp:\n\t\tif a<=x:x=a\n\t\telif a<=y:y=a\n\t\telse: x==y;y=a;ans+=1\n\tprint(ans)", + "for _ in range(int(input())):\n n=int(input())\n l=list(map(int,input().split()))\n a=l[0]\n b=0\n c=0\n y=0\n for y in range(1,n):\n if l[y]>l[y-1]:\n b=l[y]\n break\n \n for x in range(y+1,n):\n #print(a,b)\n if l[x]>a and l[x]>b:\n if l[x]-a>=l[x]-b:\n a=l[x]\n else:\n b=l[x]\n c+=1\n elif l[x]=l[x]:\n a=l[x]\n else:\n b=l[x]\n \n print(c)", + "for _ in range (int(input())):\n n = int(input());\n lit = list(map(int, input().split()));\n a, b = [lit[0]], [];\n cp = 0;\n for i in range (1, n):\n if a[-1] < lit[i]:\n b.append(lit[i]);\n else:\n a.append(lit[i]);\n s = 0;\n for i in range (1, len(a)):\n if a[i] > a[i-1]: s += 1;\n for i in range (1, len(b)):\n if b[i] > b[i-1]: s += 1;\n print (s);" + ] + }, + { + "task_name": "1920_A", + "description": "Alex is solving a problem. He has n constraints on what the integer k can be.\nThere are three types of constraints:\n\n 1. k must be greater than or equal to some integer x ; \n 2. k must be less than or equal to some integer x ; \n 3. k must be not equal to some integer x . \n\nHelp Alex find the number of integers k that satisfy all n constraints. It is\nguaranteed that the answer is finite (there exists at least one constraint of\ntype 1 and at least one constraint of type 2 ). Also, it is guaranteed that no\ntwo constraints are the exact same.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 500 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (2 \\leq n \\leq\n100 ) — the number of constraints.\n\nThe following n lines describe the constraints. Each line contains two\nintegers a and x (a \\in \\\\{1,2,3\\\\}, \\, 1 \\leq x \\leq 10^9 ). a denotes the\ntype of constraint. If a=1 , k must be greater than or equal to x . If a=2 , k\nmust be less than or equal to x . If a=3 , k must be not equal to x .\n\nIt is guaranteed that there is a finite amount of integers satisfying all n\nconstraints (there exists at least one constraint of type 1 and at least one\nconstraint of type 2 ). It is also guaranteed that no two constraints are the\nexact same (in other words, all pairs (a, x) are distinct).\n\nOutput\n\nFor each test case, output a single integer — the number of integers k that\nsatisfy all n constraints.\n\nExample\n\nInput\n\n 6\n \n 4\n \n 1 3\n \n 2 10\n \n 3 1\n \n 3 5\n \n 2\n \n 1 5\n \n 2 4\n \n 10\n \n 3 6\n \n 3 7\n \n 1 2\n \n 1 7\n \n 3 100\n \n 3 44\n \n 2 100\n \n 2 98\n \n 1 3\n \n 3 99\n \n 6\n \n 1 5\n \n 2 10\n \n 1 9\n \n 2 2\n \n 3 2\n \n 3 9\n \n 5\n \n 1 1\n \n 2 2\n \n 3 1\n \n 3 2\n \n 3 3\n \n 6\n \n 1 10000\n \n 2 900000000\n \n 3 500000000\n \n 1 100000000\n \n 3 10000\n \n 3 900000001\n\nOutput\n\n 7\n 0\n 90\n 0\n 0\n 800000000\n \nNote\n\nIn the first test case, k \\geq 3 and k \\leq 10 . Furthermore, k \\neq 1 and k\n\\neq 5 . The possible integers k that satisfy the constraints are\n3,4,6,7,8,9,10 . So the answer is 7 .\n\nIn the second test case, k \\ge 5 and k \\le 4 , which is impossible. So the\nanswer is 0 .", + "generated_code": [ + "import math\nimport re\n \ndef input_n(isOne=False):\n if not isOne: return int(input())\n else: return 1\ndef input_list(space=True, to_int = True):\n line = input()\n if space:\n items = line.split()\n else:\n items = list(line)\n \n if to_int:\n return [int(i) for i in items]\n else:\n return items\n \ndef list_to_string(arr, sym):\n string = \"\"\n for i in arr:\n string += str(i) + sym\n return string\n \n \ndef find_all_indices_string(string, substring):\n indices = []\n index = string.find(substring)\n while index != -1:\n indices.append(index)\n index = string.find(substring, index + 1)\n return indices\n \ndef find_all_indices_arr(arr, element):\n return [index for index, value in enumerate(arr) if value == element]\n \ndef find_arr_in_arr(arr, index, value):\n for subArray in arr:\n if subArray[index]==value:\n return subArray\n return None\n \n \ndef solve():\n n = int(input())\n start = -1\n end = 1e9\n num = []\n for i in range(n):\n t,v = tuple(map(int, input().split()))\n if t ==1:\n if start < v: start = v\n if t == 2:\n if end > v: end =v\n if t ==3: num.append(v)\n count_num = 0\n for i in num:\n if i < start or i > end: continue\n else: count_num+=1\n if start > end: return 0\n return end - start + 1 - count_num if end - start + 1 >= count_num else 0\n \n \n \nn = input_n()\nans = []\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\n \nfor i in range(n):\n ans.append(solve())\nfor i in ans:\n print(i)", + "t = int(input())\nr = []\nfor _ in range(t):\n n = int(input())\n \n cx = set()\n ax = int(1e9 + 7)\n bx = -1\n for _ in range(n):\n a, x = map(int, input().split())\n if a == 1:\n bx = max(x, bx)\n elif a == 2:\n ax = min(x, ax)\n else:\n cx.add(x)\n \n if bx >= ax:\n r.append(0)\n else:\n tmp = 0\n for i in cx:\n if i >= bx and i <= ax:\n tmp += 1\n r.append(ax - bx + 1 - tmp)\n \nprint(*r, sep=\"\\n\")", + "loop = int(input())\nfor iterable in range(loop):\n less = []\n big = []\n no = []\n num = 0\n innerLoop = int(input())\n for iterable2 in range(innerLoop):\n x , a = map(int ,input().split())\n if(x == 1):big.append(a)\n elif(x == 2):less.append(a)\n else:no.append(a)\n for i in range(max(big) , min(less)):\n if(i not in no):\n num = i\n break\n print(num)" + ] + }, + { + "task_name": "1920_B", + "description": "Alice and Bob are playing a game. They have an array a_1, a_2,\\ldots,a_n . The\ngame consists of two steps:\n\n * First, Alice will remove at most k elements from the array. \n * Second, Bob will multiply at most x elements of the array by -1 . \n\nAlice wants to maximize the sum of elements of the array while Bob wants to\nminimize it. Find the sum of elements of the array after the game if both\nplayers play optimally.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^4 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains three integers n , k , and x (1 \\leq\nn \\leq 2 \\cdot 10^5 , 1 \\leq x,k \\leq n ) — the number of elements in the\narray, the limit on the number of elements of the array that Alice can remove,\nand the limit on the number of elements of the array that Bob can multiply -1\nto.\n\nThe second line of each test case contains n integers a_1, a_2,\\ldots, a_n (1\n\\leq a_i \\leq 1000 ) — the elements of the array.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single integer — the sum of elements of the array\nafter the game if both players play optimally.\n\nExample\n\nInput\n\n 8\n \n 1 1 1\n \n 1\n \n 4 1 1\n \n 3 1 2 4\n \n 6 6 3\n \n 1 4 3 2 5 6\n \n 6 6 1\n \n 3 7 3 3 32 15\n \n 8 5 3\n \n 5 5 3 3 3 2 9 9\n \n 10 6 4\n \n 1 8 2 9 3 3 4 5 3 200\n \n 2 2 1\n \n 4 3\n \n 2 1 2\n \n 1 3\n\nOutput\n\n 0\n 2\n 0\n 3\n -5\n -9\n 0\n -1\n \nNote\n\nIn the first test case, it is optimal for Alice to remove the only element of\nthe array. Then, the sum of elements of the array is 0 after the game is over.\n\nIn the second test case, it is optimal for Alice to not remove any elements.\nBob will then multiply 4 by -1 . So the final sum of elements of the array is\n3+1+2-4=2 .\n\nIn the fifth test case, it is optimal for Alice to remove 9, 9 . Bob will then\nmultiply 5, 5, 3 by -1 . So the final sum of elements of the array is\n-5-5-3+3+3+2=-5 .", + "generated_code": [ + "def main():\n t = int(input())\n for i in range(t):\n n,k,x = map(int, input().split())\n a = list(map(int, input().split()))\n a.sort()\n product = alice(k, x, a)\n print(product)\n \ndef alice(removals, negatives, elements):\n if removals == 6 and negatives == 3:\n return 0\n pos = []\n s = sum(elements)\n n = sum(elements[-negatives:])\n pos.append(s - 2 * n)\n for i in range(1, removals+1):\n s -= elements[-i]\n try:\n n += elements[-(negatives+i)] - elements[-i]\n except IndexError:\n n = 0\n pos.append(s - 2 * n)\n return max(pos)\n \nmain()", + "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 6 21:42:15 2024\n \n@author: dehon\n\"\"\"\n \nt = int(input())\nfor _ in range(t):\n n,k,x = map(int, input().split())\n a = sorted(list(map(int, input().split())), reverse = True)\n ans1 = sum(a)\n for i in range(x):\n ans1 -= a[i] * 2\n ans2 = ans1\n for i in range(k):\n ans1 += a[i]\n if i + x < n:\n ans1 -= a[i+x] * 2\n ans = max(ans1, ans2)\n print(ans)", + "for _ in range(int(input())):\n n,k,x = map(int,input().split())\n a = list(map(int,input().split()))\n a.sort()\n a.reverse()\n sum1 = sum(a)\n ans = []\n for i in range(k+1):\n if i==0:\n sums = sum1- 2*sum(a[:x+1])\n ans.append(sums)\n else:\n if i+x-1 int:\n counter = 0\n i = 0\n while i < n:\n if s1[i] != s2[i]:\n if i < n - 1 and s1[i + 1] != s2[i + 1] and s1[i] != s1[i + 1]:\n counter += 1\n i += 2\n else:\n counter += 1\n i += 1\n else:\n i += 1\n return counter\n \n# Input and output handling\nt = int(input())\nfor _ in range(t):\n n = int(input())\n s1 = input()\n s2 = input()\n print(solution(n, s1, s2))", + "t = int(input())\n \nfor _ in range(t):\n n = int(input())\n s1 = input()\n s2 = input()\n \n a1 = s1.count(\"1\")\n a2 = s2.count(\"1\")\n hd = a1 - a2\n res = abs(a1 - a2)\n for i in range(n):\n if hd > 0:\n hd -= 1\n continue\n if s1[i] == \"1\" and s2[i] == \"0\": res += 1\n print(res)" + ] + }, + { + "task_name": "1921_C", + "description": "Stepan is a very busy person. Today he needs to send n messages at moments\nm_1, m_2, \\dots m_n (m_i < m_{i + 1} ). Unfortunately, by the moment 0 , his\nphone only has f units of charge left. At the moment 0 , the phone is turned\non.\n\nThe phone loses a units of charge for each unit of time it is on. Also, at any\nmoment, Stepan can turn off the phone and turn it on later. This action\nconsumes b units of energy each time. Consider turning on and off to be\ninstantaneous, so you can turn it on at moment x and send a message at the\nsame moment, and vice versa, send a message at moment x and turn off the phone\nat the same moment.\n\nIf at any point the charge level drops to 0 (becomes \\le 0 ), it is impossible\nto send a message at that moment.\n\nSince all messages are very important to Stepan, he wants to know if he can\nsend all the messages without the possibility of charging the phone.\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. This is followed by the descriptions of the test\ncases.\n\nThe first line of each test case contains four integers n , f , a , and b (1\n\\le n \\le 2 \\cdot 10^5 , 1 \\le f, a, b \\le 10^9 ) — the number of messages,\nthe initial phone's charge, the charge consumption per unit of time, and the\nconsumption when turned off and on sequentially.\n\nThe second line of each test case contains n integers m_1, m_2, \\dots, m_n (1\n\\le m_i \\le 10^9 , m_i < m_{i + 1} ) — the moments at which messages need to\nbe sent.\n\nIt is guaranteed that in a test the sum of n over all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output \"YES\" if Stepan can send all the messages, and \"NO\"\notherwise.\n\nYou can output each letter in any case (lowercase or uppercase). For example,\nthe strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be accepted as a positive\nanswer.\n\nExample\n\nInput\n\n 6\n \n 1 3 1 5\n \n 3\n \n 7 21 1 3\n \n 4 6 10 13 17 20 26\n \n 5 10 1 2\n \n 1 2 3 4 5\n \n 1 1000000000 1000000000 1000000000\n \n 1000000000\n \n 3 11 9 6\n \n 6 8 10\n \n 12 621526648 2585904 3566299\n \n 51789 61859 71998 73401 247675 298086 606959 663464 735972 806043 806459 919683\n\nOutput\n\n NO\n YES\n YES\n NO\n NO\n YES\n \nNote\n\nIn the first test case of the example, at moment 0 , the phone's charge is 3 .\nWhen sending a message at moment 3 without turning it off, (3 - 0) \\cdot 1 = 3\nunits of charge will be spent. In this case, the charge will drop to 0 and\nStepan will not be able to send the message. When turning off and on, the\nphone's charge will decrease by 5 , so it will not be possible to send the\nmessage in this way.\n\nIn the third test case of the example, at moment 0 , the phone's charge is 10\n. The phone loses 1 unit of charge per unit of time, and when turned off and\non, it loses 2 units of charge. To send all messages, the following actions\ncan be taken:\n\n * Turn off the phone at moment 0 and turn it on at moment 1 , after which 10 - 2 = 8 units of charge will remain; \n * send a message at moment 1 ; \n * send a message at moment 2 , after which 8 - (2 - 1) \\cdot 1 = 7 units of charge will remain; \n * Turn off the phone at moment 2 and turn it on at moment 3 , after which 7 - 2 = 5 units of charge will remain; \n * send a message at moment 3 ; \n * Turn off the phone at moment 3 and turn it on at moment 4 , after which 5 - 2 = 3 units of charge will remain; \n * send a message at moment 4 ; \n * Turn off the phone at moment 4 and turn it on at moment 5 , after which 3 - 2 = 1 unit of charge will remain; \n * send a message at moment 5 . \n\nThe last (sixth) test set of the example may fail if there is an integer\noverflow in your solution.", + "generated_code": [ + "t=int(input(\"\"))\nwhile(t>0):\n n,f,a,b=map(int,input(\"\").split(\" \"))\n ls=list(map(int,input(\"\").split(\" \")))\n for i in range(1,len(ls)):\n f=f-min(a*(ls[i]-ls[i-1]),b)\n if(f>0):\n print(\"YES\")\n else:\n print(\"NO\")\n t-=1" + ] + }, + { + "task_name": "1921_E", + "description": "Alice and Bob are playing a game on a checkered board. The board has h rows,\nnumbered from top to bottom, and w columns, numbered from left to right. Both\nplayers have a chip each. Initially, Alice's chip is located at the cell with\ncoordinates (x_a, y_a) (row x_a , column y_a ), and Bob's chip is located at\n(x_b, y_b) . It is guaranteed that the initial positions of the chips do not\ncoincide. Players take turns making moves, with Alice starting.\n\nOn her turn, Alice can move her chip one cell down or one cell down-right or\ndown-left (diagonally). Bob, on the other hand, moves his chip one cell up,\nup-right, or up-left. It is not allowed to make moves that go beyond the board\nboundaries.\n\nMore formally, if at the beginning of Alice's turn she is in the cell with\ncoordinates (x_a, y_a) , then she can move her chip to one of the cells (x_a +\n1, y_a) , (x_a + 1, y_a - 1) , or (x_a + 1, y_a + 1) . Bob, on his turn, from\nthe cell (x_b, y_b) can move to (x_b - 1, y_b) , (x_b - 1, y_b - 1) , or (x_b\n- 1, y_b + 1) . The new chip coordinates (x', y') must satisfy the conditions\n1 \\le x' \\le h and 1 \\le y' \\le w .\n\n![](https://espresso.codeforces.com/d2faa6ca73d70e765c2cc6ef0834e24c2e4a5528.png)\nExample game state. Alice plays with the white chip, Bob with the black one.\nArrows indicate possible moves.\n\nA player immediately wins if they place their chip in a cell occupied by the\nother player's chip. If either player cannot make a move (Alice—if she is in\nthe last row, i.e. x_a = h , Bob—if he is in the first row, i.e. x_b = 1 ),\nthe game immediately ends in a draw.\n\nWhat will be the outcome of the game if both opponents play optimally?\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. This is followed by\nthe description of the test cases.\n\nEach test case consists of a single line containing six integers h , w , x_a ,\ny_a , x_b , y_b (1 \\le x_a, x_b \\le h \\le 10^6 , 1 \\le y_a, y_b \\le w \\le 10^9\n) — the dimensions of the board and the initial positions of Alice's and Bob's\nchips. It is guaranteed that either x_a \\ne x_b or y_a \\ne y_b .\n\nIt is guaranteed that the sum of h over all test cases does not exceed 10^6 .\n\nOutput\n\nFor each test case, output \"Alice\" if Alice wins, \"Bob\" if Bob wins, and\n\"Draw\" if neither player can secure a victory. You can output each letter in\nany case (lowercase or uppercase). For example, the strings \"bOb\", \"bob\",\n\"Bob\", and \"BOB\" will be accepted as Bob's victory.\n\nExample\n\nInput\n\n 12\n \n 6 5 2 2 5 3\n \n 4 1 2 1 4 1\n \n 1 4 1 3 1 1\n \n 5 5 1 4 5 2\n \n 4 4 1 1 4 4\n \n 10 10 1 6 10 8\n \n 10 10 2 6 10 7\n \n 10 10 9 1 8 1\n \n 10 10 8 1 10 2\n \n 10 10 1 1 2 1\n \n 10 10 1 3 4 1\n \n 10 10 3 1 1 1\n\nOutput\n\n Alice\n Bob\n Draw\n Draw\n Draw\n Alice\n Draw\n Draw\n Bob\n Alice\n Alice\n Draw", + "generated_code": [ + "for i in range(int(input())):\n h,w,xa,ya,xb,yb= map(int,input().split())\n \n if xa>xb: print('Draw')\n else:\n x=abs(xa-xb)//2\n if abs(xa-xb)%2:\n l=max(1,yb-x)\n r=min(w,yb+x)\n # print('###',l,r,x,abs(xa-xb),abs(l-ya),abs(r-ya))\n print(*(['Draw'],['Alice'])[abs(l-ya)<=x+1 and abs(r-ya)<=x+1])\n else:\n l=max(1,ya-x)\n r=min(w,yb+x)\n # print('@@@',l,r,x,abs(xa-xb),abs(l-yb),abs(r-yb))\n print(*(['Draw'],['Bob'])[abs(l-yb)<=x and abs(r-yb)<=x])", + "test_cases = int(input())\nanswers = []\nfor i in range(test_cases):\n clues = list(map(int,input().split(\" \")))\n if clues[2] > clues[4] or clues[0]==1:\n answers.append(\"Draw\")\n elif(clues[2]%2==0 and clues[4]%2==0) or (clues[2]%2!=0 and clues[4]%2!=0):\n if clues[3] == clues[5]:\n answers.append(\"Bob\")\n elif clues[3]1:\n if clues[3]-1 >= abs((clues[2]-clues[4])//2) or clues[5]-clues[3] >= abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Bob\")\n else:\n if clues[3]-1 > abs((clues[2]-clues[4])//2) or clues[5]-clues[3] > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Bob\")\n elif clues[3]>clues[5]:\n if abs(clues[3]-clues[5])>1:\n if clues[1]-clues[3]>= abs((clues[2]-clues[4])//2) or clues[3]-clues[5] >= abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Bob\")\n else:\n if clues[1]-clues[3]> abs((clues[2]-clues[4])//2) or clues[3]-clues[5] > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Bob\")\n else:\n if clues[3] == clues[5]:\n answers.append(\"Alice\")\n elif clues[3]1:\n if clues[1]-clues[5] > abs((clues[2]-clues[4])//2) or clues[5]-clues[3] > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Alice\")\n else:\n if clues[1]-clues[5]-1 > abs((clues[2]-clues[4])//2) or clues[5]-clues[3]-1 > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Alice\")\n elif clues[3]>clues[5]:\n if abs(clues[3]-clues[5])>1:\n if clues[5]-1 > abs((clues[2]-clues[4])//2) or clues[3]-clues[5] > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Alice\")\n else:\n if clues[5]-1-1 > abs((clues[2]-clues[4])//2) or clues[3]-clues[5]-1 > abs((clues[2]-clues[4])//2):\n answers.append(\"Draw\")\n else:\n answers.append(\"Alice\")\nfor j in answers:\n print(j)", + "def pushp_():\n r = list(map(int, input().split()))\n n, m, x1, y1, x2, y2 = r[0], r[1], r[2], r[3], r[4], r[5]\n \n if x2 <= x1:\n print(\"draw\")\n return\n \n if (x2 - x1) % 2 != 0:\n if y1 == y2:\n print(\"Alice\")\n return\n \n if y2 > y1:\n y1 += 1\n x1 += 1\n else:\n y1 -= 1\n x1 += 1\n \n if y1 == y2:\n print(\"Alice\")\n return\n \n if y1 >= y2:\n a = y2 - 1\n else:\n a = m - y2\n \n b = x2 - x1\n t = abs(y2 - y1)\n x1 += a\n x2 -= a\n \n if x2 <= x1 or x1 < 1 or x2 > n:\n print(\"draw\")\n return\n \n if abs(y2 - 1) < abs(y2 - m):\n y2 = 1\n y1 -= a\n c = y1 - 1\n else:\n y2 = m\n y1 += a\n c = m - y1\n \n if (b // 2) > a and abs(x2 - c) >= (x1 + c) and 1 <= y1 <= m and 1 <= x1 <= n:\n print(\"Alice\")\n return\n else:\n print(\"draw\")\n return\n \n else:\n if y1 == y2:\n print(\"bob\")\n return\n \n if y2 >= y1:\n a = y1 - 1\n else:\n a = m - y1\n \n b = x2 - x1\n t = abs(y2 - y1)\n x1 += a\n x2 -= a\n \n if x2 <= x1 or x1 < 1 or x2 > n:\n print(\"draw\")\n return\n \n if abs(y1 - 1) < abs(y1 - m):\n y1 = 1\n y2 -= a\n c = y2 - 1\n else:\n y1 = m\n y2 += a\n c = m - y2\n \n if (b // 2) > a and abs(x2 - c) >= (x1 + c) and 1 <= y1 <= m and 1 <= x1 <= n:\n print(\"bob\")\n return\n else:\n print(\"draw\")\n return\n \n \ntt = int(input())\nfor _ in range(tt):\n pushp_()" + ] + }, + { + "task_name": "1922_A", + "description": "You are given an integer n and three strings a, b, c , each consisting of n\nlowercase Latin letters.\n\nLet a template be a string t consisting of n lowercase and/or uppercase Latin\nletters. The string s matches the template t if the following conditions hold\nfor all i from 1 to n :\n\n * if the i -th letter of the template is lowercase, then s_i must be the same as t_i ; \n * if the i -th letter of the template is uppercase, then s_i must be different from the lowercase version of t_i . For example, if there is a letter 'A' in the template, you cannot use the letter 'a' in the corresponding position of the string. \n\nAccordingly, the string doesn't match the template if the condition doesn't\nhold for at least one i .\n\nDetermine whether there exists a template t such that the strings a and b\nmatch it, while the string c does not.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 1000 ) — the number of test\ncases.\n\nThe first line of each test case contains an integer n (1 \\le n \\le 20 ) — the\nlength of the given strings.\n\nThe next three lines contain the strings a, b and c . Each string consists of\nexactly n lowercase Latin letters.\n\nOutput\n\nFor each testcase, print \"YES\" if there exists a template t such that the\nstrings a and b match it, while the string c does not. Otherwise, print \"NO\".\n\nExample\n\nInput\n\n 4\n \n 1\n \n a\n \n b\n \n c\n \n 2\n \n aa\n \n bb\n \n aa\n \n 10\n \n mathforces\n \n luckforces\n \n adhoccoder\n \n 3\n \n acc\n \n abd\n \n abc\n\nOutput\n\n YES\n NO\n YES\n NO\n \nNote\n\nIn the first test case, you can use the template \"C\". The first letter of\nstrings a and b differ from 'c', so they match the template. The first letter\nof string c equals 'c', so it doesn't match.\n\nIn the third test case, you can use the template \"CODEforces\".", + "generated_code": [ + "t = int(input())\n \nl = \"YES\"\n \nfor i in range(t):\n n = int(input())\n a = input()\n b = input()\n c = input()\n \n for i in range(n):\n if a[i] != c[i] and b[i] != c[i]:\n l = \"YES\"\n else: l = \"NO\"\n \n print(l)", + "tests = int(input())\nfor i in range(tests):\n slength = int(input())\n a = input()\n b = input()\n c = input()\n no = True\n if c == a or c == b:\n no=False\n print(\"NO\")\n else:\n for x in c:\n if x not in a and x not in b:\n print(\"YES\")\n no = False\n break\n if no:\n print(\"NO\")", + "def solve():\n t = int(input())\n \n for _ in range(t):\n n = int(input())\n a = input().strip()\n b = input().strip()\n c = input().strip()\n \n template = []\n for i in range(n):\n if a[i] == b[i]:\n template.append(a[i])\n else:\n template.append(a[i].upper())\n \n match_a_b = True\n for i in range(n):\n if template[i].islower():\n if a[i] != template[i] or b[i] != template[i]:\n match_a_b = False\n break\n else:\n if (a[i].lower() == template[i].lower()) or (b[i].lower() == template[i].lower()):\n match_a_b = False\n break\n \n match_c = True\n for i in range(n):\n if template[i].islower():\n if c[i] != template[i]:\n match_c = False\n break\n else:\n if c[i].lower() == template[i].lower():\n match_c = False\n break\n \n if match_a_b and not match_c:\n print(\"YES\")\n else:\n print(\"NO\")" + ] + }, + { + "task_name": "1922_B", + "description": "You have n sticks, numbered from 1 to n . The length of the i -th stick is\n2^{a_i} .\n\nYou want to choose exactly 3 sticks out of the given n sticks, and form a non-\ndegenerate triangle out of them, using the sticks as the sides of the\ntriangle. A triangle is called non-degenerate if its area is strictly greater\nthan 0 .\n\nYou have to calculate the number of ways to choose exactly 3 sticks so that a\ntriangle can be formed out of them. Note that the order of choosing sticks\ndoes not matter (for example, choosing the 1 -st, 2 -nd and 4 -th stick is the\nsame as choosing the 2 -nd, 4 -th and 1 -st stick).\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nEach test case consists of two lines:\n\n * the first line contains one integer n (1 \\le n \\le 3 \\cdot 10^5 ); \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_i \\le n ). \n\nAdditional constraint on the input: the sum of n over all test cases does not\nexceed 3 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print one integer — the number of ways to choose exactly 3\nsticks so that a triangle can be formed out of them.\n\nExample\n\nInput\n\n 4\n \n 7\n \n 1 1 1 1 1 1 1\n \n 4\n \n 3 2 1 3\n \n 3\n \n 1 2 3\n \n 1\n \n 1\n\nOutput\n\n 35\n 2\n 0\n 0\n \nNote\n\nIn the first test case of the example, any three sticks out of the given 7 can\nbe chosen.\n\nIn the second test case of the example, you can choose the 1 -st, 2 -nd and 4\n-th stick, or the 1 -st, 3 -rd and 4 -th stick.\n\nIn the third test case of the example, you cannot form a triangle out of the\ngiven sticks with lengths 2 , 4 and 8 .", + "generated_code": [ + "import math\n \nt = int(input())\nfor _ in range(t):\n n = int(input())\n num_of_lens = {}\n nums = list(map(int, input().split()))\n for x in nums:\n num_of_lens[x] = num_of_lens.get(x, 0) + 1\n \n res = 0\n for cnt in num_of_lens.values():\n if cnt >= 3:\n res += math.comb(cnt, 3)\n if cnt >= 2:\n total_sum = sum(i for i in num_of_lens.values() if i!= cnt)\n res += math.comb(cnt, 2) * total_sum\n \n print(res)", + "t=int(input())\nbuffer=[]\nfor i in range(t):\n n=int(input())\n w=[int(k) for k in input().split()]\n if n>=3:\n q={}\n # zeta=[0 for j in range(n+1)]\n # #print(type(q))\n # for j in range(n):\n # if zeta[w[j]]==1:\n # q[w[j]]+=1\n # else:\n # q[w[j]]=1\n # zeta[w[j]]=1\n # if w[0]==262144 and j==150901:\n # print(len(q.keys()))\n # break\n # if w[0]==262144:\n # print(n) #(eta_ln)\n # break\n q=[0 for j in range(n+1)]\n for j in range(n):\n q[w[j]]+=1\n eta=[]\n for j in range(n+1):\n if q[j]>0:\n eta.append(j)\n # epsilon=set()\n # q=[0 for j in range(300000)]\n # for j in range(n):\n # q[w[j]]+=1\n # epsilon.add(w[j])\n eta_ln=len(eta)\n rho=q[eta[0]]\n if eta_ln==1:\n print(n*(n-1)*(n-2)//6)\n else:\n res=q[eta[0]]*(q[eta[0]]-1)*(q[eta[0]]-2)//6\n for j in range(1, eta_ln):\n res+=q[eta[j]]*(q[eta[j]]-1)*(q[eta[j]]-2)//6\n res+=q[eta[j]]*(q[eta[j]]-1)//2*rho\n rho+=q[eta[j]]\n if j>1000:\n break\n print(res)\n else:\n print(0)", + "def cnt_cmbnts(test_cases):\n results = []\n \n for _ in range(test_cases):\n n = int(input())\n num_list = list(map(int, input().split()))\n \n num_of_lens = {}\n for x in num_list:\n if x in num_of_lens:\n num_of_lens[x] += 1\n else:\n num_of_lens[x] = 1\n \n res = 0\n total_count = 0\n for cnt in num_of_lens.values():\n if cnt >= 3:\n res += cnt * (cnt - 1) * (cnt - 2) // 6\n if cnt >= 2:\n res += cnt * (cnt - 1) // 2 * total_count\n total_count += cnt\n \n results.append(res)\n \n for result in results:\n print(result)\n \n \nt = int(input())\ncnt_cmbnts(t)" + ] + }, + { + "task_name": "1922_C", + "description": "There are n cities located on the number line, the i -th city is in the point\na_i . The coordinates of the cities are given in ascending order, so a_1 < a_2\n< \\dots < a_n .\n\nThe distance between two cities x and y is equal to |a_x - a_y| .\n\nFor each city i , let's define the closest city j as the city such that the\ndistance between i and j is not greater than the distance between i and each\nother city k . For example, if the cities are located in points [0, 8, 12, 15,\n20] , then:\n\n * the closest city to the city 1 is the city 2 ; \n * the closest city to the city 2 is the city 3 ; \n * the closest city to the city 3 is the city 4 ; \n * the closest city to the city 4 is the city 3 ; \n * the closest city to the city 5 is the city 4 . \n\nThe cities are located in such a way that for every city, the closest city is\nunique. For example, it is impossible for the cities to be situated in points\n[1, 2, 3] , since this would mean that the city 2 has two closest cities (1\nand 3 , both having distance 1 ).\n\nYou can travel between cities. Suppose you are currently in the city x . Then\nyou can perform one of the following actions:\n\n * travel to any other city y , paying |a_x - a_y| coins; \n * travel to the city which is the closest to x , paying 1 coin. \n\nYou are given m queries. In each query, you will be given two cities, and you\nhave to calculate the minimum number of coins you have to spend to travel from\none city to the other city.\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nEach test case is given in the following format:\n\n * the first line contains one integer n (2 \\le n \\le 10^5 ); \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_1 < a_2 < \\dots < a_n \\le 10^9 ); \n * the third line contains one integer m (1 \\le m \\le 10^5 ); \n * then m lines follow; the i -th of them contains two integers x_i and y_i (1 \\le x_i, y_i \\le n ; x_i \\ne y_i ), denoting that in the i -th query, you have to calculate the minimum number of coins you have to spend to travel from the city x_i to the city y_i . \n\nAdditional constraints on the input:\n\n * in every test case, for each city, the closest city is determined uniquely; \n * the sum of n over all test cases does not exceed 10^5 ; \n * the sum of m over all test cases does not exceed 10^5 . \n\nOutput\n\nFor each query, print one integer — the minimum number of coins you have to\nspend.\n\nExample\n\nInput\n\n 1\n \n 5\n \n 0 8 12 15 20\n \n 5\n \n 1 4\n \n 1 5\n \n 3 4\n \n 3 2\n \n 5 1\n\nOutput\n\n 3\n 8\n 1\n 4\n 14\n \nNote\n\nLet's consider the first two queries in the example from the statement:\n\n * in the first query, you are initially in the city 1 . You can travel to the closest city (which is the city 2 ), paying 1 coin. Then you travel to the closest city (which is the city 3 ) again, paying 1 coin. Then you travel to the closest city (which is the city 4 ) again, paying 1 coin. In total, you spend 3 coins to get from the city 1 to the city 4 ; \n * in the second query, you can use the same way to get from the city 1 to the city 4 , and then spend 5 coins to travel from the city 4 to the city 5 .", + "generated_code": [ + "r=lambda : map(int,input().split())\nt,=r()\nwhile t:\n t-=1\n r()\n a=-1e9,*r(),2e9\n b=[0,0]\n # print(a)\n for w,x,y,z in zip(a,a[1:],a[2:],a[3:]):\n v=y-x\n b+=b[-2]+v**(v>(x-w)),b[-1]+v**(v>(z-y))\n print(b,\"B\")\n u,=r()\n while u:\n u-=1\n c,d=r()\n # print(c,d)\n if c-1:\n mini=min(abs(lst[start]-lst[start-1]),mini)\n if mini==abs(lst[start]-lst[start+inc]):\n s+=1\n else:\n s+=abs(lst[start]-lst[start+inc])\n start+=inc\n d1[start]=s\n start=len(lst)-1;end=0;inc=-1;s=0\n while start!=end:\n mini=11111111\n if (start+1)-1:\n mini=min(abs(lst[start]-lst[start-1]),mini)\n if mini==abs(lst[start]-lst[start+inc]):\n s+=1\n else:\n s+=abs(lst[start]-lst[start+inc])\n start+=inc\n d2[start]=s\n m=int(input())\n for i in range(m):\n start,end=map(int,input().split())\n start-=1;\n end-=1\n s=0\n if start 0:\n\t\t\tback = cities[i-1]\n\t\tif i < n-1:\n\t\t\tforward = cities[i+1]\n\t\t\n\t\tif abs(forward - cities[i]) < abs(cities[i] - back):\n\t\t\tprog_cities[i] = 1\n\t\telse:\n\t\t\tprog_cities[i] = abs(forward - cities[i])\n\treturn prog_cities\n \nfor _ in range(t):\n\tn = int(input())\n\tcities = input().split()\n\tfor i in range(n):\n\t\tcities[i] = int(cities[i])\n\t\n\tforward_cities = go_through(cities, n)\n\tcities.reverse()\n\tbackward_cities = go_through(cities, n)\n \n\tpref_sum_f = [0]\n\tpref_sum_b = [0]\n \n\tfor i in range(n-1):\n\t\tpref_sum_f.append(pref_sum_f[i]+forward_cities[i])\n\t\tpref_sum_b.append(pref_sum_b[i]+backward_cities[i])\n \n \n\tpref_sum_b.reverse()\n \n\tm = int(input())\n \n\tfor i in range(m):\n\t\ta, b = input().split()\n\t\ta, b = int(a), int(b)\n \n\t\tif a < b:\n\t\t\tprint(pref_sum_f[b-1] - pref_sum_f[a-1])\n\t\t\n\t\telse:\n\t\t\tprint(pref_sum_b[b-1] - pref_sum_b[a-1])" + ] + }, + { + "task_name": "1923_A", + "description": "There is a ribbon divided into n cells, numbered from 1 to n from left to\nright. Each cell either contains a chip or is free.\n\nYou can perform the following operation any number of times (possibly zero):\nchoose a chip and move it to the closest free cell to the left. You can choose\nany chip that you want, provided that there is at least one free cell to the\nleft of it. When you move the chip, the cell where it was before the operation\nbecomes free.\n\nYour goal is to move the chips in such a way that they form a single block,\nwithout any free cells between them. What is the minimum number of operations\nyou have to perform?\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 1000 ) — the number of test\ncases.\n\nEach test case consists of two lines:\n\n * the first line contains one integer n (2 \\le n \\le 50 ) — the number of cells; \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_i \\le 1 ); a_i = 0 means that the i -th cell is free; a_i = 1 means that the i -th cell contains a chip. \n\nAdditional constraint on the input: in each test case, at least one cell\ncontains a chip.\n\nOutput\n\nFor each test case, print one integer — the minimum number of operations you\nhave to perform so that all chips form a single block without any free cells\nbetween them.\n\nExample\n\nInput\n\n 5\n \n 8\n \n 0 1 1 1 0 1 1 0\n \n 6\n \n 0 1 0 0 0 0\n \n 6\n \n 1 1 1 1 1 1\n \n 5\n \n 1 0 1 0 1\n \n 9\n \n 0 1 1 0 0 0 1 1 0\n\nOutput\n\n 1\n 0\n 0\n 2\n 3\n \nNote\n\nIn the first example, you can perform the operation on the chip in the 7 -th\ncell. The closest free cell to the left is the 5 -th cell, so it moves there.\nAfter that, all chips form a single block.\n\nIn the second example, all chips are already in a single block. Same for the\nthird example.", + "generated_code": [ + "t=int(input(\"\"))\nfor _ in range(t):\n n=int(input(\"\"))\n arr=str(input(\"\"))\n x=arr.find(\"1\")\n y=(arr[::-1]).find(\"1\")\n z=arr[x:n-y]\n print(z.count(\"0\"))", + "t=int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int,input().split()))\n res = 0\n \n while a and a[0]== 0:\n a.pop(0)\n \n while a and a[-1] == 0:\n a.pop()\n \n print(a)\n \n for i in range(len(a)):\n if a[i]==0:\n res += 1 \n print(res)", + "'''\n \n0 과 1로 이루어진 배열을 받고 난 후 \n0으로만 연속되고 1으로만 연속된 하나의 블록으로 만드는 것이 목표임\n오른쪽에 있는 1을 가장 가까운 왼쪽으로 옮겨서 독립된 0, 1 블록으로 만들어야 함\n \n그냥 중간에 비어있는 0의 갯수가 정답일 듯\n \n'''\n \nt = int(input())\n \nfor _ in range(t):\n length = int(input())\n arrs = list(map(int, input().split()))\n \n cnt0 = 0\n \n for idx in range(len(arrs)):\n if arrs[0] == 0 and idx != 0: #0이면 0으로 이루어지다가 1로 이루어져야함\n if arrs[idx] == 0:\n cnt0 += 1\n elif arrs[0] == 1: #처음이 1이면 무조건 0\n if arrs[idx] == 0:\n cnt0 += 1\n \n cnt1 = 0\n \n for idx in range(len(arrs)):\n if arrs[idx] == 1:\n cnt1 +=1\n \n if arrs[0] == 0:\n if arrs[len(arrs)-1] == 0:\n cnt0 -= 1\n \n ans = 0\n \n if cnt1 == 1 or cnt1 == 0:\n ans = 0\n else:\n ans = cnt0\n \n print(ans)" + ] + }, + { + "task_name": "1923_B", + "description": "You are playing a computer game. The current level of this game can be modeled\nas a straight line. Your character is in point 0 of this line. There are n\nmonsters trying to kill your character; the i -th monster has health equal to\na_i and is initially in the point x_i .\n\nEvery second, the following happens:\n\n * first, you fire up to k bullets at monsters. Each bullet targets exactly one monster and decreases its health by 1 . For each bullet, you choose its target arbitrary (for example, you can fire all bullets at one monster, fire all bullets at different monsters, or choose any other combination). Any monster can be targeted by a bullet, regardless of its position and any other factors; \n * then, all alive monsters with health 0 or less die; \n * then, all alive monsters move 1 point closer to you (monsters to the left of you increase their coordinates by 1 , monsters to the right of you decrease their coordinates by 1 ). If any monster reaches your character (moves to the point 0 ), you lose. \n\nCan you survive and kill all n monsters without letting any of them reach your\ncharacter?\n\nInput\n\nThe first line of the input contains one integer t (1 \\le t \\le 3 \\cdot 10^4 )\n— the number of test cases.\n\nEach test case consists of three lines:\n\n * the first line contains two integers n and k (1 \\le n \\le 3 \\cdot 10^5 ; 1 \\le k \\le 2 \\cdot 10^9 ); \n * the second line contains n integers a_1, a_2, \\dots, a_n (1 \\le a_i \\le 10^9 ); \n * the third line contains n integers x_1, x_2, \\dots, x_n (-n \\le x_1 < x_2 < x_3 < \\dots < x_n \\le n ; x_i \\ne 0 ). \n\nAdditional constraint on the input: the sum of n over all test cases does not\nexceed 3 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print YES if you can kill all n monsters before they reach\nyour character, or NO otherwise.\n\nYou can output each letter of the answer in any case (upper or lower). For\nexample, the strings yEs, yes, Yes, and YES will all be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 5\n \n 3 2\n \n 1 2 3\n \n -1 2 3\n \n 2 1\n \n 1 1\n \n -1 1\n \n 4 10\n \n 3 4 2 5\n \n -3 -2 1 3\n \n 5 3\n \n 2 1 3 2 5\n \n -3 -2 3 4 5\n \n 2 1\n \n 1 2\n \n 1 2\n\nOutput\n\n YES\n NO\n YES\n YES\n NO\n \nNote\n\nIn the first example, you can act as follows:\n\n * during the 1 -st second, fire 1 bullet at the 1 -st monster and 1 bullet at the 3 -rd monster. Then the 1 -st monster dies, the 2 -nd and the 3 -rd monster move closer; \n * during the 2 -nd second, fire 2 bullets at the 2 -nd monster. Then the 2 -nd monster dies, the 3 -rd monster moves closer; \n * during the 3 -rd second, fire 2 bullets at the 3 -rd monster. Then the 3 -rd monster dies. \n\nIn the second example, you can fire only 1 bullet, so you can kill only one of\nthe two monsters during the 1 -st second. Then, the remaining monster moves\ncloser and kills your character.", + "generated_code": [ + "def solve():\n t = int(input())\n for _ in range(t):\n n, k = map(int, input().split())\n healths = list(map(int, input().split()))\n positions = list(map(int, input().split()))\n \n # Sort the monsters by their distance from point 0.\n monsters = sorted(zip(positions, healths), key=lambda x: abs(x[0]))\n \n # Can we kill all monsters before any of them reaches 0?\n total_bullets_used = 0\n success = True\n for i in range(n):\n position, health = monsters[i]\n distance = abs(position)\n # Calculate the number of seconds available before the monster reaches 0.\n time_available = distance\n # Calculate the number of bullets needed for this monster.\n bullets_needed = health\n \n # If the total bullets we have used + the bullets needed for this monster exceed the time available, we lose.\n if total_bullets_used + bullets_needed > time_available:\n success = False\n break\n # Otherwise, add the bullets used for this monster.\n total_bullets_used += bullets_needed\n \n print(\"YES\" if success else \"NO\")\n \nif __name__ == \"__main__\":\n solve()", + "def monster_attack():\n try:\n n, k = map(int, input().split())\n a = list(map(int, input().split()))\n b = [0] * (n + 1)\n \n for i in range(n):\n x = int(input())\n b[abs(x)] += a[i]\n \n r = 0\n for i in range(1, n + 1):\n r += k\n if r < b[i]:\n print(\"NO\")\n return\n r -= b[i]\n \n print(\"YES\")\n except ValueError:\n print(\"Invalid input format\")\n \ndef main():\n try:\n t = int(input())\n for _ in range(t):\n monster_attack()\n except ValueError:\n print(\"Invalid input format\")\n \nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1923_C", + "description": "An array a of length m is considered good if there exists an integer array b\nof length m such that the following conditions hold:\n\n 1. \\sum\\limits_{i=1}^{m} a_i = \\sum\\limits_{i=1}^{m} b_i ; \n 2. a_i \\neq b_i for every index i from 1 to m ; \n 3. b_i > 0 for every index i from 1 to m . \n\nYou are given an array c of length n . Each element of this array is greater\nthan 0 .\n\nYou have to answer q queries. During the i -th query, you have to determine\nwhether the subarray c_{l_{i}}, c_{l_{i}+1}, \\dots, c_{r_{i}} is good.\n\nInput\n\nThe first line contains one integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThe first line of each test case contains two integers n and q (1 \\le n, q \\le\n3 \\cdot 10^5 ) — the length of the array c and the number of queries.\n\nThe second line of each test case contains n integers c_1, c_2, \\dots, c_n (1\n\\le c_i \\le 10^9 ).\n\nThen q lines follow. The i -th of them contains two integers l_i and r_i (1\n\\le l_i \\le r_i \\le n ) — the borders of the i -th subarray.\n\nAdditional constraints on the input: the sum of n over all test cases does not\nexceed 3 \\cdot 10^5 ; the sum of q over all test cases does not exceed 3 \\cdot\n10^5 .\n\nOutput\n\nFor each query, print YES if the subarray is good. Otherwise, print NO.\n\nYou can output each letter of the answer in any case (upper or lower). For\nexample, the strings yEs, yes, Yes, and YES will all be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 1\n \n 5 4\n \n 1 2 1 4 5\n \n 1 5\n \n 4 4\n \n 3 4\n \n 1 3\n\nOutput\n\n YES\n NO\n YES\n NO", + "generated_code": [ + "# https://codeforces.com/contest/1923/problem/C\nimport math\n \ndef solve():\n n, q = map(int,input().split(' '))\n nums = list(map(int,input().split(' ')))\n \n ones = [0 for i in range(n+1)]\n sum = [0 for i in range(n+1)]\n for i in range(1, n+1):\n ones[i] = ones[i-1] + (1 if nums[i-1] == 1 else 0)\n sum[i] = sum[i-1] + nums[i-1]-1\n \n for _ in range(q):\n l,r = map(int,input().split(' '))\n if l == r:\n print(\"NO\")\n continue\n \n onesInRange = ones[r] - ones[l-1]\n sumInRange = sum[r] - sum[l-1]\n \n if (2*onesInRange + (r-l+1) - onesInRange) <= sumInRange:\n print(\"YES\")\n else:\n print(\"NO\")\n \ntestCases = int(input())\nfor i in range(testCases):\n solve()", + "for _ in range(int(input())):\n n,m=map(int,input().split())\n l=list(map(int,input().split()))\n p=[]\n c=0\n \n for x in l:\n c+=x\n p.append(c)\n \n for _ in range(m):\n a,b=map(int,input().split())\n s=p[b-1]\n \n if a-2>=0:\n s-=p[a-2]\n \n if b-a+1>1 and s>=2*(b-a+1):\n print('YES')\n else:\n print('NO')", + "from itertools import accumulate\ndef solve():\n n,q=map(int,input().split())\n a=[0]+[int(x) for x in input().split()]\n b=[0]*(n+1)\n for i in range(1,n+1):\n x = 1 if a[i]>1 else 2\n b[i]=b[i-1] + x\n a=list(accumulate(a))\n print(*a)\n for _ in range(q):\n x,y=map(int,input().split())\n print(\"NO\") if a[y]-a[x-1]= n:\n print('YES')\n else:\n print('NO')\n tmp = ''\n ans = chr(ord('a')+k-1) * cnt\n for i in range(k):\n if cur & (1 << i) == 0:\n tmp = chr(ord('a')+i)\n ans += tmp\n ans += 'a'*(n-cnt-1)\n print(ans)", + "from collections import *\nfrom math import *\nfrom heapq import *\nimport sys\nfrom bisect import *\nfrom random import randint\nrrr = randint(8888,88888)\n \n \ndef sol():\n n,k,m = tuple(map(int,input().split()))\n \n s = input()\n us = set(chr(i+97) for i in range(k))\n win = set()\n ans = []\n ps = 0\n for i in s:\n if i in us:\n win.add(i)\n if len(win) == k:\n ans.append(i)\n ps += 1\n win.clear()\n \n # print(ps)\n if ps >= n:return print(\"YES\")\n \n print(\"NO\")\n \n for i in us:\n if i not in win:\n print(\"\".join(ans)+i + (\"a\" * (n - len(ans) - 1)))\n \n \n \nfor _ in range(int(input())):\n sol()" + ] + }, + { + "task_name": "1925_A", + "description": "You are given two positive integers n and k .\n\nYour task is to find a string s such that all possible strings of length n\nthat can be formed using the first k lowercase English alphabets occur as a\nsubsequence of s .\n\nIf there are multiple answers, print the one with the smallest length. If\nthere are still multiple answers, you may print any of them.\n\nNote: A string a is called a subsequence of another string b if a can be\nobtained by deleting some (possibly zero) characters from b without changing\nthe order of the remaining characters.\n\nInput\n\nThe first line of input contains a single integer t (1\\leq t\\leq 676 )\ndenoting the number of test cases.\n\nEach test case consists of a single line of input containing two integers n\n(1\\leq n\\leq 26 ) and k (1\\leq k\\leq 26 ).\n\nOutput\n\nFor each test case, print a single line containing a single string s which\nsatisfies the above property. If there are multiple answers, print the one\nwith the smallest length. If there are still multiple answers, you may print\nany of them.\n\nExample\n\nInput\n\n 4\n \n 1 2\n \n 2 1\n \n 2 2\n \n 2 3\n\nOutput\n\n ab\n aa\n baab\n abcbac\n \nNote\n\nFor the first test case, there are two strings of length 1 which can be formed\nusing the first 2 lowercase English alphabets, and they are present in s as a\nsubsequence as follows:\n\n * \\texttt{a}: {\\color{red}{\\texttt{a}}}\\texttt{b} \n * \\texttt{b}: \\texttt{a}{\\color{red}{\\texttt{b}}} \n\nFor the second test case, there is only one string of length 2 which can be\nformed using the first lowercase English alphabet, and it is present in s as a\nsubsequence as follows:\n\n * \\texttt{aa}: {\\color{red}{\\texttt{aa}}} \n\nFor the third test case, there are 4 strings of length 2 which can be formed\nusing the first 2 lowercase English alphabets, and they are present in s as a\nsubsequence as follows:\n\n * \\texttt{aa}: \\texttt{b}{\\color{red}{\\texttt{aa}}}\\texttt{b} \n * \\texttt{ab}: \\texttt{ba}{\\color{red}{\\texttt{ab}}} \n * \\texttt{ba}: {\\color{red}{\\texttt{ba}}}\\texttt{ab} \n * \\texttt{bb}: {\\color{red}{\\texttt{b}}}\\texttt{aa}{\\color{red}{\\texttt{b}}} \n\nFor the fourth test case, there are 9 strings of length 2 which can be formed\nusing the first 3 lowercase English alphabets, and they are present in s as a\nsubsequence as follows:\n\n * \\texttt{aa}: {\\color{red}{\\texttt{a}}}\\texttt{bcb}{\\color{red}{\\texttt{a}}}\\texttt{c} \n * \\texttt{ab}: {\\color{red}{\\texttt{ab}}}\\texttt{cbac} \n * \\texttt{ac}: \\texttt{abcb}{\\color{red}{\\texttt{ac}}} \n * \\texttt{ba}: \\texttt{abc}{\\color{red}{\\texttt{ba}}}\\texttt{c} \n * \\texttt{bb}: \\texttt{a}{\\color{red}{\\texttt{b}}}\\texttt{c}{\\color{red}{\\texttt{b}}}\\texttt{ac} \n * \\texttt{bc}: \\texttt{a}{\\color{red}{\\texttt{bc}}}\\texttt{bac} \n * \\texttt{ca}: \\texttt{ab}{\\color{red}{\\texttt{c}}}\\texttt{b}{\\color{red}{\\texttt{a}}}\\texttt{c} \n * \\texttt{cb}: \\texttt{ab}{\\color{red}{\\texttt{cb}}}\\texttt{ac} \n * \\texttt{cc}: \\texttt{ab}{\\color{red}{\\texttt{c}}}\\texttt{ba}{\\color{red}{\\texttt{c}}}", + "generated_code": [ + "import collections\nfrom collections import Counter\nfrom collections import defaultdict\nimport math\nfrom math import log\n \ndef solve(): \n n,k=map(int, input().split())\n s='abcdefghijklmnopqrstuvw'\n return s[:k]*(n)\nt = int(input())\nfor i in range(t):\n res = solve()\n print(res)", + "t=int(input())\nfor i in range(t):\n n,k=map(int,input().split())\n s=''\n for j in range(97,k+97):\n s+=chr(j)\n if k==1:\n print(n*s)\n else:\n print((2-(n==1))*s)" + ] + }, + { + "task_name": "1925_D", + "description": "There are n children in a class, m pairs among them are friends. The i -th\npair who are friends have a friendship value of f_i .\n\nThe teacher has to go for k excursions, and for each of the excursions she\nchooses a pair of children randomly, equiprobably and independently. If a pair\nof children who are friends is chosen, their friendship value increases by 1\nfor all subsequent excursions (the teacher can choose a pair of children more\nthan once). The friendship value of a pair who are not friends is considered 0\n, and it does not change for subsequent excursions.\n\nFind the expected value of the sum of friendship values of all k pairs chosen\nfor the excursions (at the time of being chosen). It can be shown that this\nanswer can always be expressed as a fraction \\dfrac{p}{q} where p and q are\ncoprime integers. Calculate p\\cdot q^{-1} \\bmod (10^9+7) .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 5 \\cdot 10^4 ). Description of the test cases\nfollows.\n\nThe first line of each test case contains 3 integers n , m and k (2 \\le n \\le\n10^5 , 0 \\le m \\le \\min \\Big(10^5 , \\frac{n(n-1)}{2} \\Big) , 1 \\le k \\le 2\n\\cdot 10^5 ) — the number of children, pairs of friends and excursions\nrespectively.\n\nThe next m lines contain three integers each — a_i , b_i , f_i — the indices\nof the pair of children who are friends and their friendship value. (a_i \\neq\nb_i , 1 \\le a_i,b_i \\le n , 1 \\le f_i \\le 10^9 ). It is guaranteed that all\npairs of friends are distinct.\n\nIt is guaranteed that the sum of n and sum m over all test cases does not\nexceed 10^5 and the sum of k over all test cases does not exceed 2 \\cdot 10^5\n.\n\nOutput\n\nFor each test case, print one integer — the answer to the problem.\n\nExample\n\nInput\n\n 4\n \n 100 0 24\n \n 2 1 10\n \n 1 2 1\n \n 3 1 2\n \n 2 1 1\n \n 5 2 4\n \n 1 2 25\n \n 3 2 24\n\nOutput\n\n 0\n 55\n 777777784\n 40000020\n \nNote\n\nFor the first test case, there are no pairs of friends, so the friendship\nvalue of all pairs is 0 and stays 0 for subsequent rounds, hence the\nfriendship value for all excursions is 0 .\n\nFor the second test case, there is only one pair possible (1, 2) and its\nfriendship value is initially 1 , so each turn they are picked and their\nfriendship value increases by 1 . Therefore, the total sum is 1+2+3+\\ldots+10\n= 55 .\n\nFor the third test case, the final answer is \\frac{7}{9} = 777\\,777\\,784\\bmod\n(10^9+7) .", + "generated_code": [ + "for i in range(int(input())):\n n,m,k=map(int,input().split())\n M=10**9+7\n c=pow(n*(n-1)//1,-1,M)\n s=0\n a=0\n for i in range(m):\n u,v,f=map(int,input().split())\n a+=f\n for i in range(k):\n s=s+c*i*c*m+c*a\n print(s%M)", + "MOD = 10**9 + 7\n \ndef calculate_expected_value(n, m, k, friendships):\n result = 0\n \n for i in range(m):\n a, b, f = friendships[i]\n result += f * (k * (k + 1) // 2) % MOD\n \n return result % MOD\n \ndef main():\n t = int(input())\n \n for _ in range(t):\n n, m, k = map(int, input().split())\n friendships = [list(map(int, input().split())) for _ in range(m)]\n \n result = calculate_expected_value(n, m, k, friendships)\n print(result)\n \nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1926_A", + "description": "Vladislav has a string of length 5 , whose characters are each either\n\\texttt{A} or \\texttt{B} .\n\nWhich letter appears most frequently: \\texttt{A} or \\texttt{B} ?\n\nInput\n\nThe first line of the input contains an integer t (1 \\leq t \\leq 32 ) — the\nnumber of test cases.\n\nThe only line of each test case contains a string of length 5 consisting of\nletters \\texttt{A} and \\texttt{B} .\n\nAll t strings in a test are different (distinct).\n\nOutput\n\nFor each test case, output one letter (\\texttt{A} or \\texttt{B} ) denoting the\ncharacter that appears most frequently in the string.\n\nExample\n\nInput\n\n 8\n \n ABABB\n \n ABABA\n \n BBBAB\n \n AAAAA\n \n BBBBB\n \n BABAA\n \n AAAAB\n \n BAAAA\n\nOutput\n\n B\n A\n B\n A\n B\n A\n A\n A", + "generated_code": [ + "import math\nt = int(input())\nfor q in range(t) :\n ac = 0\n bc = 0\n s = input()\n for i in s :\n if i=='A':\n ac+=1\n else : bc+=1\nif ac>bc :\n print(\"A\")\nelse : print(\"B\")", + "t=int(input())\nl=0\nh=0\nfor i in range(t):\n a=str(input())\n for j in a :\n if j in 'A' :\n l+=1\n else:\n h+=1\n if(l>h):\n print('A')\n elif(l countB:\n print(\"A\")\n elif countB > countA:\n print(\"B\")\n else:\n pass\n \nuserStrings = [\"8\", \"ABABB\", \"ABABA\", \"BBBAB\", \"AAAAA\", \"BBBBB\", \"BABAA\", \"AAAAB\", \"BAAAA\"]\n \nfor userString in userStrings:\n charCount(userString)" + ] + }, + { + "task_name": "1926_B", + "description": "Vladislav has a binary square grid of n \\times n cells. A triangle or a square\nis drawn on the grid with symbols \\texttt{1} . As he is too busy being cool,\nhe asks you to tell him which shape is drawn on the grid.\n\n * A triangle is a shape consisting of k (k>1 ) consecutive rows, where the i -th row has 2 \\cdot i-1 consecutive characters \\texttt{1} , and the central 1s are located in one column. An upside down triangle is also considered a valid triangle (but not rotated by 90 degrees).\n\n![](https://espresso.codeforces.com/6528b67bef9e7966366c8ff95b57ba96a1f44217.png)\nTwo left pictures contain examples of triangles: k=4 , k=3 . The two right\npictures don't contain triangles.\n\n * A square is a shape consisting of k (k>1 ) consecutive rows, where the i -th row has k consecutive characters \\texttt{1} , which are positioned at an equal distance from the left edge of the grid.\n\n![](https://espresso.codeforces.com/4b06bb9ff8f408edc96077ace0d5e299065a3c50.png)\nExamples of two squares: k=2 , k=4 .\n\nFor the given grid, determine the type of shape that is drawn on it.\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 100 ) — the number\nof test cases.\n\nThe first line of each test case contains a single integer n (2 \\leq n \\leq 10\n) — the size of the grid.\n\nThe next n lines each contain n characters \\texttt{0} or \\texttt{1} .\n\nThe grid contains exactly one triangle or exactly one square that contains all\nthe \\texttt{1} s in the grid. It is guaranteed that the size of the triangle\nor square is greater than 1 (i.e., the shape cannot consist of exactly one 1).\n\nOutput\n\nFor each test case, output \"SQUARE\" if all the \\texttt{1} s in the grid form a\nsquare, and \"TRIANGLE\" otherwise (without quotes).\n\nExample\n\nInput\n\n 6\n \n 3\n \n 000\n \n 011\n \n 011\n \n 4\n \n 0000\n \n 0000\n \n 0100\n \n 1110\n \n 2\n \n 11\n \n 11\n \n 5\n \n 00111\n \n 00010\n \n 00000\n \n 00000\n \n 00000\n \n 10\n \n 0000000000\n \n 0000000000\n \n 0000000000\n \n 0000000000\n \n 0000000000\n \n 1111111110\n \n 0111111100\n \n 0011111000\n \n 0001110000\n \n 0000100000\n \n 3\n \n 111\n \n 111\n \n 111\n\nOutput\n\n SQUARE\n TRIANGLE\n SQUARE\n TRIANGLE\n TRIANGLE\n SQUARE", + "generated_code": [ + "a=int(input())\nfor i in range(a):\n k=[]\n for _ in range(int(input())):\n b=input()\n if '1' in b:\n k.append(b.count('1'))\n if k[0]==k[1]:\n print(k)", + "t=int(input())\nfor i in range(t):\n n=int(input())\n a=0\n b=''\n for j in range(n):\n s=input()\n if s.count(\"1\")==1:\n a='Triangle'\n elif s.count(\"1\")>1:\n b='Square'\n if a!=0:\n print(a)\n else:\n print(b)" + ] + }, + { + "task_name": "1926_C", + "description": "Please note that the time limit for this problem is only 0.5 seconds per test.\n\nVladislav wrote the integers from 1 to n , inclusive, on the board. Then he\nreplaced each integer with the sum of its digits.\n\nWhat is the sum of the numbers on the board now?\n\nFor example, if n=12 then initially the numbers on the board are:\n\nThen after the replacement, the numbers become:\n\nThe sum of these numbers is 1+2+3+4+5+6+7+8+9+1+2+3=51 . Thus, for n=12 the\nanswer is 51 .\n\nInput\n\nThe first line contains an integer t (1 \\leq t \\leq 10^4 ) — the number of\ntest cases.\n\nThe only line of each test case contains a single integer n (1 \\leq n \\leq 2\n\\cdot 10^5 ) — the largest number Vladislav writes.\n\nOutput\n\nFor each test case, output a single integer — the sum of the numbers at the\nend of the process.\n\nExample\n\nInput\n\n 7\n \n 12\n \n 1\n \n 2\n \n 3\n \n 1434\n \n 2024\n \n 200000\n\nOutput\n\n 51\n 1\n 3\n 6\n 18465\n 28170\n 4600002", + "generated_code": [ + "def problem():\n t = int(input())\n numbers = []\n for _ in range(t):\n n = int(input())\n numbers.append(n)\n \n values = [0 for _ in range(max(numbers) + 1)]\n sum_values = [0 for _ in range(max(numbers) + 1)]\n \n total = 0\n for i in range(10):\n values[i] = i\n total += i\n sum_values[i] = total\n \n for i in range(10, n + 1):\n word = str(i)\n last = int(word[len(word) - 1])\n remainder = int(word[:-1])\n values[i] = values[last] + values[remainder]\n sum_total = values[i] + sum_values[i - 1]\n sum_values[i] = sum_total\n \n for n in numbers:\n print(sum_values[n])\n \nproblem()", + "def sum_of_digits(n):\n return sum(int(d) for d in str(n))\nsoma = 0\nN = int(input())\n \nfor _ in range(N):\n n = int(input())\n for i in range(n):\n soma += sum_of_digits(i)\n \nprint(soma)", + "def sum_of_digits(n):\n return sum(int(d) for d in str(n))\nsoma = 0\nfor i in range(13):\n soma += sum_of_digits(i)\n \nprint(soma)" + ] + }, + { + "task_name": "1926_D", + "description": "Vladislav has n non-negative integers, and he wants to divide all of them into\nseveral groups so that in any group, any pair of numbers does not have\nmatching bit values among bits from 1 -st to 31 -st bit (i.e., considering the\n31 least significant bits of the binary representation).\n\nFor an integer k , let k_2(i) denote the i -th bit in its binary\nrepresentation (from right to left, indexing from 1). For example, if k=43 ,\nsince 43=101011_2 , then 43_2(1)=1 , 43_2(2)=1 , 43_2(3)=0 , 43_2(4)=1 ,\n43_2(5)=0 , 43_2(6)=1 , 43_2(7)=0 , 43_2(8)=0, \\dots, 43_2(31)=0 .\n\nFormally, for any two numbers x and y in the same group, the condition x_2(i)\n\\neq y_2(i) must hold for all 1 \\leq i < 32 .\n\nWhat is the minimum number of groups Vlad needs to achieve his goal? Each\nnumber must fall into exactly one group.\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 10^4 ) — the number\nof test cases.\n\nThe first line of each test case contains a single integer n (1 \\leq n \\leq 2\n\\cdot 10^5 ) — the total number of integers.\n\nThe second line of each test case contains n given integers a_1, \\ldots, a_n\n(0 \\leq a_j < 2^{31} ).\n\nThe sum of n over all test cases in a test does not exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of groups\nrequired to satisfy the condition.\n\nExample\n\nInput\n\n 9\n \n 4\n \n 1 4 3 4\n \n 2\n \n 0 2147483647\n \n 5\n \n 476319172 261956880 2136179468 1671164475 1885526767\n \n 3\n \n 1335890506 811593141 1128223362\n \n 4\n \n 688873446 627404104 1520079543 1458610201\n \n 4\n \n 61545621 2085938026 1269342732 1430258575\n \n 4\n \n 0 0 2147483647 2147483647\n \n 3\n \n 0 0 2147483647\n \n 8\n \n 1858058912 289424735 1858058912 2024818580 1858058912 289424735 122665067 289424735\n\nOutput\n\n 4\n 1\n 3\n 2\n 2\n 3\n 2\n 2\n 4\n \nNote\n\nIn the first test case, any two numbers have the same last 31 bits, so we need\nto place each number in its own group.\n\nIn the second test case, a_1=0000000000000000000000000000000_2 ,\na_2=1111111111111111111111111111111_2 so they can be placed in the same group\nbecause a_1(i) \\ne a_2(i) for each i between 1 and 31 , inclusive.", + "generated_code": [ + "times = int(input())\ncheck = 2**31 -1\nfor _ in range(times):\n n = int(input())\n data = list(map(int,input().split()))\n dic = dict()\n ans = n\n check = 2**31-1\n for i in data:\n s=i^check\n if s in dic:\n dic[s] -= 1\n ans -= 1\n if dic[s] == 0:\n del(dic[s])\n else:\n if i in dic:\n dic[i] += 1\n else:\n dic[i] = 1\n print(ans)", + "def solve(n,a):\n res =0\n count={}\n for num in a:\n if num not in count:\n count[num^((1<<31)-1)] = count.get(num^((1<<31)-1),0)+1\n res+=1\n else:\n count[num]-=1\n return res\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a= list(map(int,input().split()))\n print(solve(n,a))" + ] + }, + { + "task_name": "1926_E", + "description": "Vladislav has n cards numbered 1, 2, \\dots, n . He wants to lay them down in a\nrow as follows:\n\n * First, he lays down all the odd-numbered cards from smallest to largest. \n * Next, he lays down all cards that are twice an odd number from smallest to largest (i.e. 2 multiplied by an odd number). \n * Next, he lays down all cards that are 3 times an odd number from smallest to largest (i.e. 3 multiplied by an odd number). \n * Next, he lays down all cards that are 4 times an odd number from smallest to largest (i.e. 4 multiplied by an odd number). \n * And so on, until all cards are laid down. \n\nWhat is the k -th card he lays down in this process? Once Vladislav puts a\ncard down, he cannot use that card again.\n\nInput\n\nThe first line contains an integer t (1 \\leq t \\leq 5 \\cdot 10^4 ) — the\nnumber of test cases.\n\nThe only line of each test case contains two integers n and k (1 \\leq k \\leq n\n\\leq 10^9 ) — the number of cards Vlad has, and the position of the card you\nneed to output.\n\nOutput\n\nFor each test case, output a single integer — the k -th card Vladislav lays\ndown.\n\nExample\n\nInput\n\n 11\n \n 7 1\n \n 7 2\n \n 7 3\n \n 7 4\n \n 7 5\n \n 7 6\n \n 7 7\n \n 1 1\n \n 34 14\n \n 84 19\n \n 1000000000 1000000000\n\nOutput\n\n 1\n 3\n 5\n 7\n 2\n 6\n 4\n 1\n 27\n 37\n 536870912\n \nNote\n\nIn the first seven test cases, n=7 . Vladislav lays down the cards as follows:\n\n * First — all the odd-numbered cards in the order 1 , 3 , 5 , 7 . \n * Next — all cards that are twice an odd number in the order 2 , 6 . \n * Next, there are no remaining cards that are 3 times an odd number. (Vladislav has only one of each card.) \n * Next — all cards that are 4 times an odd number, and there is only one such card: 4 . \n * There are no more cards left, so Vladislav stops. \n\nThus the order of cards is 1 , 3 , 5 , 7 , 2 , 6 , 4 .", + "generated_code": [ + "t=int(input())\nfor _ in range(t):\n n,k=map(int,input().split())\n L=[]\n while n:\n m=(n+1)//2\n n-=m\n tot=0;pow=1\n for a in L:\n if tot (n + 1) // 2:\n while s < k and d > 0:\n s += (d + 1) // 2\n d -= (d + 1) // 2\n i += 1\n \n while p <= (i - 1):\n g += (h + 1) // 2\n h -= (h + 1) // 2\n p += 1\n \n f = k - g\n y = (2**(i - 1)) * f\n print(y)\n else:\n print(2*k - 1)" + ] + }, + { + "task_name": "1927_B", + "description": "Polycarp lost the string s of length n consisting of lowercase Latin letters,\nbut he still has its trace.\n\nThe trace of the string s is an array a of n integers, where a_i is the number\nof such indices j (j < i ) that s_i=s_j . For example, the trace of the string\nabracadabra is the array [0, 0, 0, 1, 0, 2, 0, 3, 1, 1, 4 ].\n\nGiven a trace of a string, find any string s from which it could have been\nobtained. The string s should consist only of lowercase Latin letters a-z.\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. Then the descriptions of the test cases follow.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 2\n\\cdot 10^5 ) — the length of the lost string.\n\nThe second line of each test case contains n integers a_1, a_2, \\dots, a_n (0\n\\le a_i < n ) — the trace of the string. It is guaranteed that for the given\ntrace, there exists a suitable string s .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a string s that corresponds to the given trace. If\nthere are multiple such strings s , then output any of them.\n\nThe string s should consist of lowercase Latin letters a-z.\n\nIt is guaranteed that for each test case, a valid answer exists.\n\nExample\n\nInput\n\n 5\n \n 11\n \n 0 0 0 1 0 2 0 3 1 1 4\n \n 10\n \n 0 0 0 0 0 1 0 1 1 0\n \n 1\n \n 0\n \n 8\n \n 0 1 2 3 4 5 6 7\n \n 8\n \n 0 0 0 0 0 0 0 0\n\nOutput\n\n abracadabra\n codeforces\n a\n aaaaaaaa\n dijkstra", + "generated_code": [ + "a='abcdefghijklmnopqrstuvwxyz'\nb=[0]*26\nfor t in range(int(input())):\n n=int(input())\n s=list(map(int,input().split()))\n r=''\n for i in s:\n \n x=b.index(i)\n \n r+=a[x]\n b[x]+=1\n print(r)", + "for i in range(int(input())):\n l=int(input())\n array=list(map(int,input().split()))\n alp=[\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n rev_array=array[::-1]\n ans=[]\n for j in range(l):\n ans.append(alp[rev_array[j::].count(rev_array[j])-1])\n print(\"\".join(map(str,ans)))", + "def solve(n,a):\n sam = 'abcdefghijklmnopqrstuvqwxyz'\n a_map = { x:0 for x in range(n)}\n res = \"\"\n for i in range(n):\n beg = a_map[a[i]]\n #print(\"beg = \",beg)\n res += sam[a_map[a[i]]%27]\n a_map[a[i]]+=1\n #print(a_map)\n #print(\"res = \",res)\n return res\n \n \nt = int(input())\nfor i in range(t):\n n = int(input())\n #s = input()\n #a,b,r = map(int,input().split())\n a = list(map(int,input().split()))\n #b = list(map(int,input().split()))\n ans = solve(n,a)\n print(ans)\n #print(\"Yes\") if ans else print(\"No\")" + ] + }, + { + "task_name": "1927_C", + "description": "Given an array a of n integers, an array b of m integers, and an even number k\n.\n\nYour task is to determine whether it is possible to choose exactly \\frac{k}{2}\nelements from both arrays in such a way that among the chosen elements, every\ninteger from 1 to k is included.\n\nFor example:\n\n * If a=[2, 3, 8, 5, 6, 5] , b=[1, 3, 4, 10, 5] , k=6 , then it is possible to choose elements with values 2, 3, 6 from array a and elements with values 1, 4, 5 from array b . In this case, all numbers from 1 to k=6 will be included among the chosen elements.\n * If a=[2, 3, 4, 5, 6, 5] , b=[1, 3, 8, 10, 3] , k=6 , then it is not possible to choose elements in the required way. \n\nNote that you are not required to find a way to choose the elements — your\nprogram should only check whether it is possible to choose the elements in the\nrequired way.\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. The descriptions of the test cases follow.\n\nThe first line of each test case contains three integers n , m , and k (1 \\le\nn, m \\le 2\\cdot10^5 , 2 \\le k \\le 2 \\cdot \\min(n, m) , k is even) — the length\nof array a , the length of array b , and the number of elements to be chosen,\nrespectively.\n\nThe second line of each test case contains n integers a_1, a_2, \\dots, a_n (1\n\\le a_i \\le 10^6 ) — the elements of array a .\n\nThe third line of each test case contains m integers b_1, b_2, \\dots, b_m (1\n\\le b_j \\le 10^6 ) — the elements of array b .\n\nIt is guaranteed that the sum of values n and m over all test cases in a test\ndoes not exceed 4 \\cdot 10^5 .\n\nOutput\n\nOutput t lines, each of which is the answer to the corresponding test case. As\nthe answer, output \"YES\" if it is possible to choose \\frac{k}{2} numbers from\neach array in such a way that among the chosen elements, every integer from 1\nto k is included. Otherwise, output \"NO\".\n\nYou can output each letter in any case (lowercase or uppercase). For example,\nthe strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be accepted as a positive\nanswer.\n\nExample\n\nInput\n\n 6\n \n 6 5 6\n \n 2 3 8 5 6 5\n \n 1 3 4 10 5\n \n 6 5 6\n \n 2 3 4 5 6 5\n \n 1 3 8 10 3\n \n 3 3 4\n \n 1 3 5\n \n 2 4 6\n \n 2 5 4\n \n 1 4\n \n 7 3 4 4 2\n \n 1 4 2\n \n 2\n \n 6 4 4 2\n \n 1 5 2\n \n 3\n \n 2 2 1 4 3\n\nOutput\n\n YES\n NO\n YES\n YES\n NO\n NO\n \nNote\n\nIn the first test case of the example, it is possible to choose elements equal\nto 2 , 3 , and 6 from array a and elements equal to 1 , 4 , and 5 from array b\n. Thus, all numbers from 1 to k=6 are included among the chosen elements.\n\nIn the second test case of the example, it can be shown that it is not\npossible to choose exactly three elements from each array in the required way.\n\nIn the third test case of the example, it is possible to choose elements equal\nto 1 and 3 from array a and elements equal to 2 and 4 from array b . Thus, all\nnumbers from 1 to k=4 are included among the chosen elements.", + "generated_code": [ + "for t in range(int(input())):\n n,m,k=map(int,input().split())\n a=list(map(int,input().split()))\n b=list(map(int,input().split()))\n \n aOnes=0\n bOnes=0\n newk=k//2\n i=1\n \n while i<=k:\n if i in a and i in b:\n if aOnes i + 1:\n if a[i] <= k:\n count_a += 1\n if len_b > i + 1:\n if b[i] <= k:\n count_b += 1\n print(\"YES\" if count_a >= d and count_b >= d else \"NO\")" + ] + }, + { + "task_name": "1928_A", + "description": "Bob has a rectangle of size a \\times b . He tries to cut this rectangle into\ntwo rectangles with integer sides by making a cut parallel to one of the sides\nof the original rectangle. Then Bob tries to form some other rectangle from\nthe two resulting rectangles, and he can rotate and move these two rectangles\nas he wishes.\n\nNote that if two rectangles differ only by a 90^{\\circ} rotation, they are\nconsidered the same. For example, the rectangles 6 \\times 4 and 4 \\times 6 are\nconsidered the same.\n\nThus, from the 2 \\times 6 rectangle, another rectangle can be formed, because\nit can be cut into two 2 \\times 3 rectangles, and then these two rectangles\ncan be used to form the 4 \\times 3 rectangle, which is different from the 2\n\\times 6 rectangle.\n\n![](https://espresso.codeforces.com/670958570876245598e151e6877e3b0231a7c60e.png)\n\nHowever, from the 2 \\times 1 rectangle, another rectangle cannot be formed,\nbecause it can only be cut into two rectangles of 1 \\times 1 , and from these,\nonly the 1 \\times 2 and 2 \\times 1 rectangles can be formed, which are\nconsidered the same.\n\n![](https://espresso.codeforces.com/1463aaa4fa7eb1e7432c1d8b5813e7ae91147066.png)\n\nHelp Bob determine if he can obtain some other rectangle, or if he is just\nwasting his time.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^4 ) — the number of test cases. This is followed\nby the description of the test cases.\n\nThe single line of each test case contains two integers a and b (1 \\le a, b\n\\le 10^9 ) — the size of Bob's rectangle.\n\nOutput\n\nFor each test case, output \"Yes\" if Bob can obtain another rectangle from the\na \\times b rectangle. Otherwise, output \"No\".\n\nYou can output the answer in any case (upper or lower). For example, the\nstrings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be recognized as positive answers.\n\nExample\n\nInput\n\n 7\n \n 1 1\n \n 2 1\n \n 2 6\n \n 3 2\n \n 2 2\n \n 2 4\n \n 6 3\n\nOutput\n\n No\n No\n Yes\n Yes\n Yes\n Yes\n No\n \nNote\n\nIn the first test case, the 1 \\times 1 rectangle cannot be cut into two\nrectangles, so another rectangle cannot be obtained from it.\n\nIn the fourth test case, the 3 \\times 2 rectangle can be cut into two 3 \\times\n1 rectangles, and from these, the 1 \\times 6 rectangle can be formed.\n\nIn the fifth test case, the 2 \\times 2 rectangle can be cut into two 1 \\times\n2 rectangles, and from these, the 1 \\times 4 rectangle can be formed.", + "generated_code": [ + "def solve(a, b):\n return \"yes\" if b % 2 == 0 else \"no\"\n \nfor _ in range(int(input())):\n a, b = map(int, input().split())\n print(solve(a, b))", + "# Number of test cases\nt = int(input())\n \n# Loop over all test cases\nfor _ in range(t):\n # Read the dimensions a and b\n a, b = map(int, input().split())\n \n # If either dimension is even, we can form a different rectangle\n if a % 2 == 0 or b % 2 == 0:\n print(\"Yes\")\n else:\n print(\"No\")", + "for i in range(int(input())):\n a, b, = [int(i) for i in input().split()]\n if(a%2==0 and b%2==0):\n print('yes')\n elif(a-b==-a,a) or (b-a==-b,b):\n print('no') \n elif((a-b)%2>0 or (a-b)%2<0):\n print('yes')\n else:\n print('no')", + "n = int(input())\nfor i in range(n):\n a, b = [int(i) for i in input().split()]\n if(a%2!=0 and b%2!=0):\n print(\"NO\")\n elif(a/2==b or b/2==a):\n print(\"NO\")\n else:\n print(\"YES\")" + ] + }, + { + "task_name": "1928_B", + "description": "Vasya has two hobbies — adding permutations^{\\dagger} to arrays and finding\nthe most frequently occurring element. Recently, he found an array a and\ndecided to find out the maximum number of elements equal to the same number in\nthe array a that he can obtain after adding some permutation to the array a .\n\nMore formally, Vasya must choose exactly one permutation p_1, p_2, p_3,\n\\ldots, p_n of length n , and then change the elements of the array a\naccording to the rule a_i := a_i + p_i . After that, Vasya counts how many\ntimes each number occurs in the array a and takes the maximum of these values.\nYou need to determine the maximum value he can obtain.\n\n^{\\dagger} A permutation of length n is an array consisting of n distinct\nintegers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a\npermutation, but [1,2,2] is not a permutation (2 appears twice in the array),\nand [1,3,4] is also not a permutation (n=3 but there is 4 in the array).\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 2 \\cdot 10^4 ) — the number of test cases. Then\nfollows the description of the test cases.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 2\n\\cdot 10^5 ) — the length of the array a .\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the elements of the array a .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single number — the maximum number of elements\nequal to the same number after the operation of adding a permutation.\n\nExample\n\nInput\n\n 7\n \n 2\n \n 1 2\n \n 4\n \n 7 1 4 1\n \n 3\n \n 103 102 104\n \n 5\n \n 1 101 1 100 1\n \n 5\n \n 1 10 100 1000 1\n \n 2\n \n 3 1\n \n 3\n \n 1000000000 999999997 999999999\n\nOutput\n\n 2\n 2\n 3\n 2\n 1\n 1\n 2\n \nNote\n\nIn the first test case, it is optimal to choose p = [2, 1] . Then after\napplying the operation, the array a will be [3, 3] , in which the number 3\noccurs twice, so the answer is 2 .\n\nIn the second test case, one of the optimal options is p = [2, 3, 1, 4] .\nAfter applying the operation, the array a will be [9, 4, 5, 5] . Since the\nnumber 5 occurs twice, the answer is 2 .", + "generated_code": [ + "def ii(): return int(input())\n \ndef mii(): return map(int, input().split())\n \ndef lii(): return list(map(int, input().split()))\n \ndef slii(): return sorted(list(map(int, input().split())))\n \ndef mis(): return map(str, input().split())\n \ndef lis(): return list(input())\n \ndef slis(): return sorted(list(map(str, input().split())))\n \ndef pre(arr):\n ans = []\n tem = 1\n for i in range(len(arr)):\n tem *= arr[i]\n ans.append(tem)\n \n return ans\n \ndef suf(arr):\n ans = []\n tem = 1\n for i in range(len(arr)-1,-1,-1):\n tem *= arr[i]\n ans.append(tem)\n \n return ans\n \n \n \nfor _ in range(ii()):\n n = ii()\n arr = lii()\n \n m = max(arr)\n new= []\n for i in range(n):\n new.append(m - arr[i]+1)\n \n new.sort()\n ans = set()\n for i in new:\n if i <= n and i >0:\n ans.add(i)\n \n print(len(ans))" + ] + }, + { + "task_name": "1928_C", + "description": "In a well-known school, a physical education lesson took place. As usual,\neveryone was lined up and asked to settle in \"the first–k -th\" position.\n\nAs is known, settling in \"the first–k -th\" position occurs as follows: the\nfirst k people have numbers 1, 2, 3, \\ldots, k , the next k - 2 people have\nnumbers k - 1, k - 2, \\ldots, 2 , the next k people have numbers 1, 2, 3,\n\\ldots, k , and so on. Thus, the settling repeats every 2k - 2 positions.\nExamples of settling are given in the \"Note\" section.\n\nThe boy Vasya constantly forgets everything. For example, he forgot the number\nk described above. But he remembers the position he occupied in the line, as\nwell as the number he received during the settling. Help Vasya understand how\nmany natural numbers k fit under the given constraints.\n\nNote that the settling exists if and only if k > 1 . In particular, this means\nthat the settling does not exist for k = 1 .\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 100 ) — the number of test cases. This is followed by\nthe description of the test cases.\n\nThe only line of each test case contains two integers n and x (1 \\le x < n \\le\n10^9 ) — Vasya's position in the line and the number Vasya received during the\nsettling.\n\nOutput\n\nFor each test case, output a single integer — the number of different k that\nfit under the given constraints.\n\nIt can be proven that under the given constraints, the answer is finite.\n\nExample\n\nInput\n\n 5\n \n 10 2\n \n 3 1\n \n 76 4\n \n 100 99\n \n 1000000000 500000000\n\nOutput\n\n 4\n 1\n 9\n 0\n 1\n \nNote\n\nIn the first test case, k equals 2, 3, 5, 6 are suitable.\n\nAn example of settling for these k :\n\nk / №| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 \n---|---|---|---|---|---|---|---|---|---|--- \n2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 \n3 | 1 | 2 | 3 | 2 | 1 | 2 | 3 | 2 | 1 | 2 \n5 | 1 | 2 | 3 | 4 | 5 | 4 | 3 | 2 | 1 | 2 \n6 | 1 | 2 | 3 | 4 | 5 | 6 | 5 | 4 | 3 | 2 \n \nIn the second test case, k = 2 is suitable.", + "generated_code": [ + "def sep_num(x):\n output1 = []\n output2 = []\n for i in range(1, int(x ** 0.5) + 1):\n if x % i == 0:\n output1.append(i)\n output2.append(int(x / i))\n output1.reverse()\n return output2 + output1\n \nt = int(input())\n \nfor i in range(t):\n n, x = map(int, input().split())\n output = []\n if (n + x - 2) % 2 == 0:\n sep = sep_num(n + x - 2)\n for s in sep:\n if (s + 2) % 2 == 0 and (s + 2) / 2 >= x:\n output.append((s + 2) / 2)\n if (n - x) % 2 == 0:\n sep = sep_num(n - x)\n for s in sep:\n if (s + 2) % 2 == 0 and (s + 2) / 2 >= x:\n output.append((s + 2) / 2)\n output = list(set(output))\n # print(output, len(output))", + "import math\ndef factors(q,x):\n M=[]\n w=math.sqrt(q)\n if w==w//1 and w>=x-1:\n M+=[w]\n for i in range(1,int(w//1)):\n if q%i==0:\n if i>=x-1:\n M+=[i]\n if (q//i)>=x-1:\n M+=[q//i]\n return M\n \nt=int(input())\nfor _ in range(t):\n L=list(map(int, input().split()))\n n=L[0]\n x=L[1]\n ans=0\n y=(n+x)\n if y%2!=0:\n print(0)\n continue\n else:\n L1=factors((y-2)//2,x)\n if n>=3*x-2:\n L1+=factors((n-x)//2,x)\n L1=list(set(L1))\n print(len(L1))\n continue" + ] + }, + { + "task_name": "1929_A", + "description": "Sasha decided to give his girlfriend an array a_1, a_2, \\ldots, a_n . He found\nout that his girlfriend evaluates the beauty of the array as the sum of the\nvalues (a_i - a_{i - 1}) for all integers i from 2 to n .\n\nHelp Sasha and tell him the maximum beauty of the array a that he can obtain,\nif he can rearrange its elements in any way.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 500 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (2 \\leq n \\leq\n100 ) — the length of the array a .\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\leq a_i \\leq 10^9 ) — the elements of the array a .\n\nOutput\n\nFor each test case, output a single integer — the maximum beauty of the array\na that can be obtained.\n\nExample\n\nInput\n\n 5\n \n 3\n \n 2 1 3\n \n 3\n \n 69 69 69\n \n 5\n \n 100 54 80 43 90\n \n 4\n \n 3 4 3 3\n \n 2\n \n 2 1\n\nOutput\n\n 2\n 0\n 57\n 1\n 1\n \nNote\n\nIn the first test case, the elements of the array a can be rearranged to make\na = [1, 2, 3] . Then its beauty will be equal to (a_2 - a_1) + (a_3 - a_2) =\n(2 - 1) + (3 - 2) = 2 .\n\nIn the second test case, there is no need to rearrange the elements of the\narray a . Then its beauty will be equal to 0 .", + "generated_code": [ + "num = int(input())\n \n \ndef check_order(a, num2):\n order = 0\n for i in range(1, num2):\n if a[i - 1] >= a[i]:\n order += 1\n if order == 0:\n return True\n else:\n return False\n \n \nfor i in range(0, num):\n num2 = int(input())\n case = input()\n a = [int(i) for i in case.split() if i.isdigit()]\n if check_order(a, num2):\n print(0)\n else:\n beauty = 0\n b = sorted(a)\n for x in range(1, num2):\n beauty += b[x] - b[x - 1]\n print(beauty)", + "t = int(input())\nfor e in range(t):\n l = int(input())\n nums = [int(x) for x in input().split()]\n x=0\n y=100000000\n for i in range(l):\n if nums[i]>x:\n x = nums[i]\n if nums[i] 0:\n adv = min(a[i-1]-a[i]-1, cnt, counter[a[i-1]])\n for j in range(adv):\n ans.append(a[i-1]-j-1)\n cnt -= adv\n counter[a[i-1]] -= adv\n ans.append(a[i])\n counter[a[i]] -= 1\n \n for _ in range(cnt):\n ans.append(ans[-1]-1)\n \n print(*ans)\n \n \nt = int(input())\nfor _ in range(t):\n solve()", + "def solve() -> None:\n n = int(input())\n arr = list(map(int, input().split()))\n st = set()\n for i in range(n):\n st.add(arr[i] + i + 1)\n print(*sorted(st, reverse=True))\n \n \nfor _ in range(int(input())):\n solve()" + ] + }, + { + "task_name": "1931_A", + "description": "Nikita had a word consisting of exactly 3 lowercase Latin letters. The letters\nin the Latin alphabet are numbered from 1 to 26 , where the letter \"a\" has the\nindex 1 , and the letter \"z\" has the index 26 .\n\nHe encoded this word as the sum of the positions of all the characters in the\nalphabet. For example, the word \"cat\" he would encode as the integer 3 + 1 +\n20 = 24 , because the letter \"c\" has the index 3 in the alphabet, the letter\n\"a\" has the index 1 , and the letter \"t\" has the index 20 .\n\nHowever, this encoding turned out to be ambiguous! For example, when encoding\nthe word \"ava\", the integer 1 + 22 + 1 = 24 is also obtained.\n\nDetermine the lexicographically smallest word of 3 letters that could have\nbeen encoded.\n\nA string a is lexicographically smaller than a string b if and only if one of\nthe following holds:\n\n * a is a prefix of b , but a \\ne b ;\n * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b .\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 100 ) —\nthe number of test cases in the test.\n\nThis is followed by the descriptions of the test cases.\n\nThe first and only line of each test case contains an integer n (3 \\le n \\le\n78 ) — the encoded word.\n\nOutput\n\nFor each test case, output the lexicographically smallest three-letter word\nthat could have been encoded on a separate line.\n\nExample\n\nInput\n\n 5\n \n 24\n \n 70\n \n 3\n \n 55\n \n 48\n\nOutput\n\n aav\n rzz\n aaa\n czz\n auz", + "generated_code": [ + "import string\n \nalphabet = string.ascii_lowercase\n \nfor i in range(int(input())):\n n = int(input())\n word = \"\"\n if n > 52:\n word += alphabet[n - 53] + \"zz\"\n elif n > 26:\n word += \"a\" + alphabet[n - 28] + \"z\"\n else:\n word += \"aa\" + alphabet[n - 3]\n print(word)", + "cases=int(input())\nfor i in range(cases):\n arr=[]\n lex=int(input())\n for j in range(2):\n if(lex<=26):\n arr.append(1)\n lex=lex-1\n elif(lex<52):\n arr.append(26)\n lex=lex-26\n else:\n arr.append(26)\n lex=lex-26 \n arr.append(lex)\n arr.sort()\n for k in range(3):\n print(chr(arr[k]+96), end='')", + "def number_to_lowercase_alphabet(num):\n if 1 <= num <= 26:\n return chr(num + 96)\n \n \nt = int(input())\nfor _ in range(t):\n n = int(input())\n a = ''\n b = ''\n c = ''\n if n // 26 == 0:\n a = chr(96 + 1) \n b = chr(96 + 1) \n c = chr(96 + (n - 2)) \n elif n // 26 == 1:\n a = chr(96 + 1) \n b = chr(96 + (n - 27)) \n c = chr(96 + 26) \n elif n // 26 == 2:\n a = chr(96 + (n - 52)) \n b = chr(96 + 26) \n c = chr(96 + 26) \n \n print(a + '' + b + '' + c)" + ] + }, + { + "task_name": "1931_D", + "description": "Polycarp has two favorite integers x and y (they can be equal), and he has\nfound an array a of length n .\n\nPolycarp considers a pair of indices \\langle i, j \\rangle (1 \\le i < j \\le n )\nbeautiful if:\n\n * a_i + a_j is divisible by x ; \n * a_i - a_j is divisible by y . \n\nFor example, if x=5 , y=2 , n=6 , a= [1, 2, 7, 4, 9, 6 ], then the only\nbeautiful pairs are:\n\n * \\langle 1, 5 \\rangle : a_1 + a_5 = 1 + 9 = 10 (10 is divisible by 5 ) and a_1 - a_5 = 1 - 9 = -8 (-8 is divisible by 2 ); \n * \\langle 4, 6 \\rangle : a_4 + a_6 = 4 + 6 = 10 (10 is divisible by 5 ) and a_4 - a_6 = 4 - 6 = -2 (-2 is divisible by 2 ). \n\nFind the number of beautiful pairs in the array a .\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. Then the descriptions of the test cases follow.\n\nThe first line of each test case contains three integers n , x , and y (2 \\le\nn \\le 2 \\cdot 10^5 , 1 \\le x, y \\le 10^9 ) — the size of the array and\nPolycarp's favorite integers.\n\nThe second line of each test case contains n integers a_1, a_2, \\dots, a_n (1\n\\le a_i \\le 10^9 ) — the elements of the array.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single integer — the number of beautiful pairs in\nthe array a .\n\nExample\n\nInput\n\n 7\n \n 6 5 2\n \n 1 2 7 4 9 6\n \n 7 9 5\n \n 1 10 15 3 8 12 15\n \n 9 4 10\n \n 14 10 2 2 11 11 13 5 6\n \n 9 5 6\n \n 10 7 6 7 9 7 7 10 10\n \n 9 6 2\n \n 4 9 7 1 2 2 13 3 15\n \n 9 2 3\n \n 14 6 1 15 12 15 8 2 15\n \n 10 5 7\n \n 13 3 3 2 12 11 3 7 13 14\n\nOutput\n\n 2\n 0\n 1\n 3\n 5\n 7\n 0", + "generated_code": [ + "def count_beautiful_pairs(t, test_cases):\n results = []\n \n # Process each test case\n for case in test_cases:\n n, x, y = case[\"params\"]\n a = case[\"array\"]\n \n freq = {}\n beautiful_count = 0\n \n # Debug: Printing the input for the test case\n print(f\"Processing Test Case: n = {n}, x = {x}, y = {y}, array = {a}\")\n \n for num in a:\n # Calculate modular values\n mod_x = num % x\n mod_y = num % y\n \n # Calculate the required modular values for valid pairs\n required_mod_x = (x - mod_x) % x\n required_mod_y = mod_y\n \n # Debug: Check the current mod values\n print(f\"Number: {num}, mod_x: {mod_x}, mod_y: {mod_y}, required_mod_x: {required_mod_x}, required_mod_y: {required_mod_y}\")\n \n # Count pairs that satisfy the conditions\n if (required_mod_x, required_mod_y) in freq:\n beautiful_count += freq[(required_mod_x, required_mod_y)]\n \n # Update the frequency dictionary\n if (mod_x, mod_y) not in freq:\n freq[(mod_x, mod_y)] = 0\n freq[(mod_x, mod_y)] += 1\n \n # Debug: Output the final beautiful count for this test case\n print(f\"Beautiful pairs count: {beautiful_count}\")\n \n # Store the result for the current test case\n results.append(beautiful_count)\n \n return results", + "def count_beautiful_pairs(test_cases):\n results = []\n \n for n, x, y, arr in test_cases:\n count = 0\n mod_x_map = {}\n mod_y_map = {}\n \n for num in arr:\n # Calculate residues for current number\n mod_x = (-num) % x\n mod_y = num % y\n \n # Count pairs where conditions are satisfied\n count += mod_x_map.get(mod_x, 0) + mod_y_map.get(mod_y, 0)\n \n # Update hash maps with current number's residues\n mod_x_key = num % x\n mod_y_key = num % y\n \n mod_x_map[mod_x_key] = mod_x_map.get(mod_x_key, 0) + 1\n mod_y_map[mod_y_key] = mod_y_map.get(mod_y_key, 0) + 1\n \n results.append(count)\n \n return results\n \n \n# Input Reading\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \n# Parse input\nt = int(data[0])\nindex = 1\ntest_cases = []\n \nfor _ in range(t):\n n, x, y = map(int, data[index:index+3])\n index += 3\n arr = list(map(int, data[index:index+n]))\n index += n\n test_cases.append((n, x, y, arr))\n \n# Solve and output results\nresults = count_beautiful_pairs(test_cases)\nprint(\"\\n\".join(map(str, results)))", + "def count_beautiful_pairs(test_cases):\n results = []\n \n for n, x, y, arr in test_cases:\n count = 0\n mod_x = {}\n mod_y = {}\n \n for num in arr:\n # Remainders needed for conditions\n rem_x = (-num) % x\n rem_y = (num % y)\n \n # Count valid pairs based on previously seen elements\n count += mod_x.get(rem_x, 0) and mod_y.get(rem_y, 0)\n \n # Update the dictionaries\n mod_x[num % x] = mod_x.get(num % x, 0) + 1\n mod_y[num % y] = mod_y.get(num % y, 0) + 1\n \n results.append(count)\n \n return results\n \n \n# Input and output handling\ndef main():\n import sys\n input = sys.stdin.read\n data = input().splitlines()\n \n t = int(data[0])\n test_cases = []\n idx = 1\n \n for _ in range(t):\n n, x, y = map(int, data[idx].split())\n arr = list(map(int, data[idx + 1].split()))\n test_cases.append((n, x, y, arr))\n idx += 2\n \n results = count_beautiful_pairs(test_cases)\n \n for result in results:\n print(result)\n \n \nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1931_E", + "description": "Sasha gave Anna a list a of n integers for Valentine's Day. Anna doesn't need\nthis list, so she suggests destroying it by playing a game.\n\nPlayers take turns. Sasha is a gentleman, so he gives Anna the right to make\nthe first move.\n\n * On her turn, Anna must choose an element a_i from the list and reverse the sequence of its digits. For example, if Anna chose the element with a value of 42 , it would become 24 ; if Anna chose the element with a value of 1580 , it would become 851 . Note that leading zeros are removed. After such a turn, the number of elements in the list does not change.\n * On his turn, Sasha must extract two elements a_i and a_j (i \\ne j ) from the list, concatenate them in any order and insert the result back into the list. For example, if Sasha chose the elements equal to 2007 and 19 , he would remove these two elements from the list and add the integer 200719 or 192007 . After such a turn, the number of elements in the list decreases by 1 .\n\nPlayers can't skip turns. The game ends when Sasha can't make a move, i.e.\nafter Anna's move there is exactly one number left in the list. If this\ninteger is not less than 10^m (i.e., \\ge 10^m ), Sasha wins. Otherwise, Anna\nwins.\n\nIt can be shown that the game will always end. Determine who will win if both\nplayers play optimally.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThen follows the description of the test cases.\n\nThe first line of each test case contains integers n , m (1 \\le n \\le 2 \\cdot\n10^5 , 0 \\le m \\le 2 \\cdot 10^6 ) — the number of integers in the list and the\nparameter determining when Sasha wins.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the list that Sasha gave to Anna.\n\nIt is guaranteed that the sum of n for all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output:\n\n * \"Sasha\", if Sasha wins with optimal play; \n * \"Anna\", if Anna wins with optimal play. \n\nExample\n\nInput\n\n 9\n \n 2 2\n \n 14 2\n \n 3 5\n \n 9 56 1\n \n 4 10\n \n 1 2007 800 1580\n \n 4 5\n \n 5000 123 30 4\n \n 10 10\n \n 6 4 6 2 3 1 10 9 10 7\n \n 1 1\n \n 6\n \n 1 1\n \n 10\n \n 8 9\n \n 1 2 9 10 10 2 10 2\n \n 4 5\n \n 10 10 10 10\n\nOutput\n\n Sasha\n Anna\n Anna\n Sasha\n Sasha\n Anna\n Anna\n Anna\n Sasha\n \nNote\n\nConsider the first test case.\n\nAnna can reverse the integer 2 , then Sasha can concatenate the integers 2 and\n14 , obtaining the integer 214 , which is greater than 10^2 = 100 . If Anna\nhad reversed the integer 14 , Sasha would have concatenated the integers 41\nand 2 , obtaining the integer 412 , which is greater than 10^2 = 100 . Anna\nhas no other possible moves, so she loses.", + "generated_code": [ + "n_test = int(input())\n \nanswers = [None] * n_test\ndef count_zero(num):\n counter = 0\n for i in range(len(num)-1,-1,-1):\n if num[i] == \"0\":\n counter+=1\n else:\n break\n return counter\n \n \nfor test in range(n_test):\n \n n,m = tuple(map(int,input().split()))\n array = input().split()\n total_digits = 0\n zeros = []\n for item in array:\n total_digits += len(item)\n if count_zero(item)>0:\n zeros.append(count_zero(item))\n zeros = sorted(zeros,reverse=True)\n subtract_zero = 0\n for i in range(0,len(zeros),2):\n subtract_zero += zeros[i]\n if abs(total_digits-subtract_zero) >= m+1:\n answers[test] = \"Sashah\"\n else:\n answers[test] = \"Anna\"\n \n \nfor answer in answers:\n print(answer)", + "for y in range(int(input())):\n rev_val = []\n rev_res = ''\n list_len, max_power = input().split()\n operational_list = input().split()\n \n for x in operational_list:\n x_rev = int(x[::-1])\n if len(str(x_rev)) == len(x):\n rev_res = rev_res + x\n else:\n rev_val.append(x[::-1])\n \n rev_val.sort()\n \n \n # print(operational_list)\n # print(rev_res,'/',rev_val)\n \n for x in range(len(rev_val)):\n if (x % 2) == 0:\n # print('X:',rev_val[x])\n val_in = int(rev_val[x])\n # print('X:',val_in)\n rev_res += str(val_in)\n else:\n val_in = rev_val[x]\n rev_res += val_in[::-1]\n # print(rev_res)\n \n \n if 10**int(max_power) < int(rev_res):\n print('Sasha')\n else:\n print('Anna')" + ] + }, + { + "task_name": "1931_F", + "description": "There are n people in the programming contest chat. Chat participants are\nordered by activity, but each person sees himself at the top of the list.\n\nFor example, there are 4 participants in the chat, and their order is [2, 3,\n1, 4] . Then\n\n * 1 -st user sees the order [1, 2, 3, 4] . \n * 2 -nd user sees the order [2, 3, 1, 4] . \n * 3 -rd user sees the order [3, 2, 1, 4] . \n * 4 -th user sees the order [4, 2, 3, 1] . \n\nk people posted screenshots in the chat, which show the order of participants\nshown to this user. The screenshots were taken within a short period of time,\nand the order of participants has not changed.\n\nYour task is to determine whether there is a certain order that all\nscreenshots correspond to.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ninput test cases. The descriptions of test cases follow.\n\nThe first line of the description of each test case contains two integers n\nand k (1 \\le k \\le n \\le 2 \\cdot 10^5, n \\cdot k \\le 2 \\cdot 10^5 ) — the\nnumber of chat participants and the number of participants who posted\nscreenshots.\n\nThe following k lines contain descriptions of screenshots posted by the\nparticipants.\n\nThe i -th row contains n integers a_{ij} each (1 \\le a_{ij} \\le n , all a_{ij}\nare different) — the order of participants shown to the participant a_{i0} ,\nwhere a_{i0} — the author of the screenshot. You can show that in the\nscreenshot description it will always be at the top of the list.\n\nIt is guaranteed that the sum of n \\cdot k for all test cases does not exceed\n2 \\cdot 10^5 . It is also guaranteed that all the authors of the screenshots\nare different.\n\nOutput\n\nOutput t lines, each of which is the answer to the corresponding test case. As\nan answer, output \"YES\" if there exists at least one order of participants,\nunder which all k screenshots could have been obtained. Otherwise, output\n\"NO\".\n\nYou can output the answer in any case (upper or lower). For example, the\nstrings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 10\n \n 5 1\n \n 1 2 3 4 5\n \n 4 4\n \n 1 2 3 4\n \n 2 3 1 4\n \n 3 2 1 4\n \n 4 2 3 1\n \n 6 2\n \n 1 3 5 2 4 6\n \n 6 3 5 2 1 4\n \n 3 3\n \n 1 2 3\n \n 2 3 1\n \n 3 2 1\n \n 10 2\n \n 1 2 3 4 5 6 7 8 9 10\n \n 10 9 8 7 6 5 4 3 2 1\n \n 1 1\n \n 1\n \n 5 2\n \n 1 2 3 5 4\n \n 2 1 3 5 4\n \n 3 3\n \n 3 1 2\n \n 2 3 1\n \n 1 3 2\n \n 5 4\n \n 3 5 1 4 2\n \n 2 5 1 4 3\n \n 1 5 4 3 2\n \n 5 1 4 3 2\n \n 3 3\n \n 1 3 2\n \n 2 1 3\n \n 3 2 1\n\nOutput\n\n YES\n YES\n YES\n YES\n NO\n YES\n YES\n YES\n YES\n NO", + "generated_code": [ + "from heapq import *\n \nt = int(input())\n \n \nfor _ in range(t):\n n, m = map(int, input().split())\n if m == 1:\n input()\n print(\"yes\")\n continue\n a1, *l1 = map(int, input().split())\n a2, *l2 = map(int, input().split())\n l11 = [i for i in l1 if i != a2]\n l22 = [i for i in l2 if i != a1]\n if l11 != l22:\n for _ in range(m - 2):\n input()\n print(\"no\")\n continue\n idx1 = idx2 = -1\n p1 = p2 = 0\n for i in range(n - 1):\n if i + max(p1, p2) == n - 1:\n break\n if l1[i + p1] != l2[i + p2]:\n if l1[i + p1] == a2 and l2[i + p2] == a1:\n idx1 = idx2 = i\n break\n else:\n if l1[i + p1] == a2:\n idx1 = i\n p1 = 1\n else:\n idx2 = i\n p2 = 1\n if idx1 >= 0 and idx2 >= 0:\n break\n val = []\n if idx1 < idx2:\n l2.insert(idx1, a2)\n l = l2\n elif idx1 > idx2:\n l1.insert(idx2, a1)\n l = l1\n else:\n if m == 2:\n print(\"yes\")\n continue\n a3, *l3 = map(int, input().split())\n if l3.index(a1) < l3.index(a2):\n l1.insert(idx2, a1)\n l = l1\n else:\n l2.insert(idx1, a2)\n l = l2\n val.append((a3, l3))\n m -= 1\n for _ in range(m - 2):\n a3, *l3 = map(int, input().split())\n val.append((a3, l3))\n for a3, l3 in val:\n if l3 != [i for i in l if i != a3]:\n print(\"no\")\n break\n else:\n print(\"yes\")" + ] + }, + { + "task_name": "1932_A", + "description": "During your journey through computer universes, you stumbled upon a very\ninteresting world. It is a path with n consecutive cells, each of which can\neither be empty, contain thorns, or a coin. In one move, you can move one or\ntwo cells along the path, provided that the destination cell does not contain\nthorns (and belongs to the path). If you move to the cell with a coin, you\npick it up.\n\n![](https://espresso.codeforces.com/34bd88a4aba4a1ae98e5681455c4a47900b7b9a8.png)\nHere, green arrows correspond to legal moves, and the red arrow corresponds to\nan illegal move.\n\nYou want to collect as many coins as possible. Find the maximum number of\ncoins you can collect in the discovered world if you start in the leftmost\ncell of the path.\n\nInput\n\nThe first line of input contains a single integer t (1 \\le t \\le 1000 ) — the\nnumber of test cases. Then the descriptions of the test cases follow.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 50 )\n— the length of the path.\n\nThe second line of each test case contains a string of n characters, the\ndescription of the path. The character '.' denotes an empty cell, '@' denotes\na cell with a coin, and '*' denotes a cell with thorns. It is guaranteed that\nthe first cell is empty.\n\nOutput\n\nFor each test case, output a single integer, the maximum number of coins you\ncan collect.\n\nExample\n\nInput\n\n 3\n \n 10\n \n .@@*@.**@@\n \n 5\n \n .@@@@\n \n 15\n \n .@@..@***..@@@*\n\nOutput\n\n 3\n 4\n 3\n \nNote\n\nThe picture for the first example is in the problem statement.\n\nHere is the picture for the second example:\n\n![](https://espresso.codeforces.com/68fd7116585f37e79535fbc164a552cc8e148b75.png)\n\nAnd here is the picture for the third example:\n\n![](https://espresso.codeforces.com/1695fc45669a1bf1d6e1b3d4901cdd3cda38273c.png)", + "generated_code": [ + "class Solution:\n def Coins(self, n: int, s: str) -> int:\n if n == 0:\n return 0\n \n dp = [0] * n\n \n if s[0] == '@':\n dp[0] = 1\n \n if n > 1 and s[1] != '*':\n dp[1] = dp[0] + (1 if s[1] == '@' else 0)\n \n for i in range(2, n):\n if s[i] != '*':\n dp[i] = max(dp[i-1], dp[i-2])\n if s[i] == '@':\n dp[i] += 1\n \n return dp[-1]\n \nsolution = Solution()\n \nt = int(input())\n \nfor _ in range(t):\n n = int(input())\n a = input()\n print(solution.Coins(n, a))", + "for _ in range(int(input())):\n len = int(input())\n s = list(input())\n ret = 0\n thorn =0\n for i in s:\n if(i=='@'):\n thorn=0\n ret+=1\n elif(i=='*'):\n thorn+=1\n if(thorn==2):\n break\n else:\n thorn==0\n print(ret)", + "a = int(input())\ns = 0\n \nfor i in range(a):\n d = int(input()) \n b = input()\n for j in range(len(b)):\n if b[j] == '@':\n s = s+1\n elif b[j] == '*':\n if b[::]:\n break\n elif b[j+1] == '*':\n break\n \n print(s)\n s = 0" + ] + }, + { + "task_name": "1932_B", + "description": "The Chaya tribe believes that there are n signs of the apocalypse. Over time,\nit has been found out that the i -th sign occurs every a_i years (in years a_i\n, 2 \\cdot a_i , 3 \\cdot a_i , \\dots ).\n\nAccording to the legends, for the apocalypse to happen, the signs must occur\nsequentially. That is, first they wait for the first sign to occur, then\nstrictly after it, the second sign will occur, and so on. That is, if the i\n-th sign occurred in the year x , the tribe starts waiting for the occurrence\nof the (i+1) -th sign, starting from the year x+1 .\n\nIn which year will the n -th sign occur and the apocalypse will happen?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 1000 ) —\nthe number of test cases. Then follow the descriptions of the test cases.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 100\n) — the number of signs.\n\nThe second line of each test case contains n integers a_1, a_2, a_3, \\dots,\na_n (1 \\le a_i \\le 10^6 ) — the periodicities of the signs.\n\nOutput\n\nFor each test case, output a single integer — the year in which all n signs\nwill occur.\n\nExample\n\nInput\n\n 4\n \n 6\n \n 3 2 4 5 9 18\n \n 5\n \n 1 2 3 4 5\n \n 5\n \n 1 1 1 1 1\n \n 6\n \n 50 30 711 200 503 1006\n\nOutput\n\n 36\n 5\n 5\n 2012\n \nNote\n\nIn the first set of input data of the example:\n\n * The tribe will wait for the first sign in the 3 -rd year; \n * the tribe will wait for the second sign in the 4 -th year (since year 2 have already passed); \n * the tribe will wait for the third sign in the 8 -th year (since the second sign has already occurred in the 4 -th year); \n * the tribe will wait for the fourth sign in the 10 -th year (since year 5 have already passed); \n * the tribe will wait for the fifth sign in the 18 -th year (since year 9 have already passed); \n * the tribe will wait for the sixth sign in the 36 -th year (since the fifth sign has already occurred in the 18 -th year).", + "generated_code": [ + "def max_coins_collected(path):\n n = len(path)\n if n == 0:\n return 0\n \n # dp[i] will store the maximum coins collected to reach cell i\n dp = [0] * n\n \n # Initialize dp array\n if path[0] == '@':\n dp[0] = 1\n elif path[0] == '*':\n dp[0] = -float('inf') # Impossible to start on a thorn\n \n if n > 1:\n if path[1] == '*':\n dp[1] = -float('inf')\n else:\n dp[1] = dp[0] + (1 if path[1] == '@' else 0)\n \n # Fill dp array\n for i in range(2, n):\n if path[i] == '*':\n dp[i] = -float('inf')\n else:\n dp[i] = max(dp[i-1], dp[i-2]) + (1 if path[i] == '@' else 0)\n \n # The result is the maximum value in dp array that isn't -inf\n return max(x for x in dp if x > -float('inf'))\n \ndef solve():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n t = int(data[0])\n index = 1\n results = []\n \n for _ in range(t):\n n = int(data[index])\n index += 1\n path = data[index]\n index += 1\n \n results.append(max_coins_collected(path))\n \n for result in results:\n print(result)", + "t = int(input())\n \nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n year = 0\n for ai in a:\n year += (year % ai) or ai\n print(year)", + "num_tests = int(input())\n \nwhile num_tests > 0:\n num_tests -= 1\n \n n = int(input())\n nums = [int(x) for x in input().split(\" \")] \n \n start_year = 0\n for x in range(0, len(nums)):\n start_year = ((start_year+1)//nums[x] + 1)*(nums[x])\n print(start_year)" + ] + }, + { + "task_name": "1937_A", + "description": "You are given an array a_1, a_2, \\ldots, a_n . Initially, a_i=i for each 1 \\le\ni \\le n .\n\nThe operation \\texttt{swap}(k) for an integer k \\ge 2 is defined as follows:\n\n * Let d be the largest divisor^\\dagger of k which is not equal to k itself. Then swap the elements a_d and a_k . \n\nSuppose you perform \\texttt{swap}(i) for each i=2,3,\\ldots, n in this exact\norder. Find the position of 1 in the resulting array. In other words, find\nsuch j that a_j = 1 after performing these operations.\n\n^\\dagger An integer x is a divisor of y if there exists an integer z such that\ny = x \\cdot z .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 10^4 ). The description of the test cases follows.\n\nThe only line of each test case contains one integer n (1 \\le n \\le 10^9 ) —\nthe length of the array a .\n\nOutput\n\nFor each test case, output the position of 1 in the resulting array.\n\nExample\n\nInput\n\n 4\n \n 1\n \n 4\n \n 5\n \n 120240229\n\nOutput\n\n 1\n 4\n 4\n 67108864\n \nNote\n\nIn the first test case, the array is [1] and there are no operations\nperformed.\n\nIn the second test case, a changes as follows:\n\n * Initially, a is [1,2,3,4] . \n * After performing \\texttt{swap}(2) , a changes to [\\underline{2},\\underline{1},3,4] (the elements being swapped are underlined). \n * After performing \\texttt{swap}(3) , a changes to [\\underline{3},1,\\underline{2},4] . \n * After performing \\texttt{swap}(4) , a changes to [3,\\underline{4},2,\\underline{1}] . \n\nFinally, the element 1 lies on index 4 (that is, a_4 = 1 ). Thus, the answer\nis 4 .", + "generated_code": [ + "from math import log2\nn_cases = int(input())\n \nfor i in range(n_cases):\n n = int(input())\n if n == 1:\n print(1)\n else:\n power = 1\n while power < log2(n):\n power += 1\n if power == n:\n print(2 ** power)\n else:\n power -= 1\n print(2 ** power)" + ] + }, + { + "task_name": "1937_D", + "description": "There is a one-dimensional grid of length n . The i -th cell of the grid\ncontains a character s_i , which is either '<' or '>'.\n\nWhen a pinball is placed on one of the cells, it moves according to the\nfollowing rules:\n\n * If the pinball is on the i -th cell and s_i is '<', the pinball moves one cell to the left in the next second. If s_i is '>', it moves one cell to the right. \n * After the pinball has moved, the character s_i is inverted (i. e. if s_i used to be '<', it becomes '>', and vice versa). \n * The pinball stops moving when it leaves the grid: either from the left border or from the right one. \n\nYou need to answer n independent queries. In the i -th query, a pinball will\nbe placed on the i -th cell. Note that we always place a pinball on the\ninitial grid.\n\nFor each query, calculate how many seconds it takes the pinball to leave the\ngrid. It can be shown that the pinball will always leave the grid within a\nfinite number of steps.\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 10^5 ). The description of the test cases follows.\n\nThe first line of each test case contains an integer n (1 \\le n \\le 5 \\cdot\n10^5 ).\n\nThe second line of each test case contains a string s_1s_2 \\ldots s_{n} of\nlength n consisting of characters '<' and '>'.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 5 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, for each i (1 \\le i \\le n ) output the answer if a pinball\nis initially placed on the i -th cell.\n\nExample\n\nInput\n\n 3\n \n 3\n \n ><<\n \n 4\n \n <<<<\n \n 6\n \n <><<<>\n\nOutput\n\n 3 6 5 \n 1 2 3 4 \n 1 4 7 10 8 1 \n \nNote\n\nIn the first test case, the movement of the pinball for i=1 is shown in the\nfollowing pictures. It takes the pinball 3 seconds to leave the grid.\n\n![](https://espresso.codeforces.com/775b656d27e63ce8901e1ef80487972d536b4a54.png)\n\nThe movement of the pinball for i=2 is shown in the following pictures. It\ntakes the pinball 6 seconds to leave the grid.\n\n![](https://espresso.codeforces.com/515bd5576868cf33d4190893928faa21e69dd5c7.png)", + "generated_code": [ + "from itertools import accumulate\n \ndef last(arr, times):\n l = len(arr)\n return arr[-1] - arr[max(-n, -1-times)]\n \ndef solve(s1, n):\n pre = [i+1 for i,el in enumerate(s1) if el==\">\"]\n totalOne = len(pre)\n preOne = list(accumulate(pre, initial=0))\n suffZero = [0]\n \n ans = [0]*n\n for i in range(n-1, -1, -1):\n el = s1[i]\n if el == \">\":\n ## this is a one\n ol, zr = totalOne, len(suffZero) - 1\n if ol <= zr:\n ## exit on the left\n zeroInd = 2*last(suffZero, ol)\n oneInd = 2*preOne[-1] - last(preOne, 1)\n ans[i] = zeroInd - oneInd\n else:\n ## exit on the right\n zeroInd = 2*suffZero[-1]\n oneInd = last(preOne, zr) + last(preOne, zr+1)\n oneInd -= last(preOne, 1)\n fi = last(preOne, zr+1) - last(preOne, zr)\n ans[i] = zeroInd - oneInd + n+1 - fi\n preOne.pop()\n totalOne -= 1\n else:\n ## this is a zero\n suffZero.append(suffZero[-1] + i+1)\n ol, zr = totalOne, len(suffZero) - 1\n if zr <= ol:\n ## zr is atleast 1\n ## exit on the right\n zeroInd = suffZero[-1] + suffZero[-2]\n oneInd = 2*last(preOne, zr)\n ans[i] = zeroInd - oneInd + n+1\n else:\n ## exit on the left\n ## ol can be zero\n zeroInd = 2*last(suffZero, ol+1) - last(suffZero, 1)\n oneInd = 2*preOne[-1]\n ans[i] = zeroInd - oneInd\n \n print(*ans)\nfor case in range(int(input())):\n n = int(input())\n s1 = input()\n solve(s1, n)", + "t = int(input())\n \n \n \ndef solve(s):\n n = len(s)\n A = [] \n idx_A = []\n for i in range(0, n):\n if s[i] == '>':\n if (len(idx_A) == 0):\n A.append(0)\n else:\n x = A[len(A) - 1] + (i - idx_A[len(idx_A) - 1]) * len(idx_A)\n A.append(x)\n idx_A.append(i)\n B = []\n idx_B = []\n for j in range(0, n):\n i = n - 1 - j\n if s[i] == '<':\n if (len(idx_B) == 0):\n B.append(0)\n else:\n x = B[len(B) - 1] + (idx_B[len(B) - 1] - i) * len(idx_B)\n B.append(x)\n idx_B.append(i)\n l = 0\n r = len(B)\n \n for i in range(0, n):\n if (s[i] == '>'):\n if l < r:\n a = A[l]\n x = r - (l + 2)\n b = B[r - 1]\n if x >= 0:\n b = b - B[x]\n b = b - (idx_B[x] - idx_B[r - 1]) * (x + 1)\n b = (idx_B[r - 1] - i) * (l + 1)\n print(a * 2 + b * 2 + i + 1, end = \" \")\n else:\n if (r == 0):\n print(n - i, end = \" \")\n else:\n a = B[r - 1] + (idx_B[r - 1] - i) * r\n b = A[l - 1]\n if l - r > 0:\n b = b - A[l - r - 1]\n b = b - (idx_A[l - 1] - idx_A[l - r - 1]) * (l - r)\n b = b + (i - idx_A[l - 1]) * r\n print(a * 2 + b * 2 + (n - i), end = \" \")\n l += 1\n else:\n r -= 1\n if (l <= r):\n if (l == 0):\n print(i + 1, end = \" \")\n else:\n a = A[l - 1]\n a = a + (i - idx_A[l - 1]) * l\n b = B[r]\n if r - l >= 0:\n b = b - B[r - l]\n b = b - (idx_B[r - l] - i) * (r - l)\n b = b + (idx_B[r] - i) * l\n print(a * 2 + b * 2 + i + 1, end = \" \")\n else:\n if (r == 0):\n print((n - i) + (i - idx_A[l - 1]) * 2, end = \" \")\n else:\n a = B[r]\n b = A[l - 1]\n if l - r - 1 > 0:\n b = b - A[l - r - 2]\n b = b - (idx_A[l - 1] - idx_A[l - r - 2]) * (l - r - 1)\n b = b + (i - idx_A[l - 1]) * (r + 1)\n print(a * 2 + b * 2 + (n - i), end = \" \")\n \n \nfor i in range(0, t):\n n = int(input())\n s = input()\n solve(s)\n print()" + ] + }, + { + "task_name": "1941_B", + "description": "Rudolf has an array a of n integers, the elements are numbered from 1 to n .\n\nIn one operation, he can choose an index i (2 \\le i \\le n - 1 ) and assign:\n\n * a_{i - 1} = a_{i - 1} - 1 \n * a_i = a_i - 2 \n * a_{i + 1} = a_{i + 1} - 1 \n\nRudolf can apply this operation any number of times. Any index i can be used\nzero or more times.\n\nCan he make all the elements of the array equal to zero using this operation?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases in the test.\n\nThe first line of each case contains a single integer n (3 \\le n \\le 2 \\cdot\n10^5 ) — the number of elements in the array.\n\nThe second line of each case contains n integers a_1, a_2, \\dots, a_n (0 \\le\na_j \\le 10^9 ) — the elements of the array.\n\nIt is guaranteed that the sum of the values of n over all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output \"YES\" if it is possible to make all the elements of\nthe array zero using the described operations. Otherwise, output \"NO\".\n\nYou can output each letter in any case (lowercase or uppercase). For example,\nthe strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be accepted as a positive\nanswer.\n\nExample\n\nInput\n\n 7\n \n 5\n \n 1 3 5 5 2\n \n 5\n \n 2 4 4 5 1\n \n 5\n \n 0 1 3 3 1\n \n 6\n \n 5 6 0 2 3 0\n \n 4\n \n 1 2 7 2\n \n 3\n \n 7 1 0\n \n 4\n \n 1 1 1 1\n\nOutput\n\n YES\n NO\n YES\n NO\n NO\n NO\n NO\n \nNote\n\nIn the first example, the original array is [1, 3, 5, 5, 2] , to make all its\nelements zero, Rudolf can act as follows:\n\n * apply the operation at i=4 and get the array [1, 3, 4, 3, 1] ; \n * apply the operation at i=3 and get the array [1, 2, 2, 2, 1] ; \n * apply the operation at i=2 and get the array [0, 0, 1, 2, 1] ; \n * apply the operation at i=4 and get the array [0, 0, 0, 0, 0] .", + "generated_code": [ + "for _ in range(int(input())):\n a = int(input())\n b = list(map(int, input().split()))\n if b[0] % 2 == 1 and b[1] != b[0] + 2 or b[-1] % 2 == 1 and b[-2] != b[-1] + 2:\n print(\"NO\")\n else:\n print(\"YES\")", + "def isempty(list,n): \n for i in range(n):\n if list[i]!=0:\n return False\n return True\n \ndef rudolf(list,n):\n for i in range(1,n-1):\n while list[i]>1 and list[i-1]>0 and list[i+1]>0:\n list[i-1]-=1*list[i-1]\n list[i]-=2*list[i-1]\n list[i+1]-=1*list[i-1]\n if isempty(list,n):\n print(\"YES\")\n else :\n print(\"NO\")\n \n \n \nt = int(input())\nfor i in range(t):\n n = int(input())\n l = input()\n lst = list(map(int,l.split()))\n rudolf(lst,n)", + "answers = []\n \ndef processArray(array, index):\n array[index-1]=array[index-1]-1\n array[index]=array[index]-2\n array[index+1]=array[index+1]-1\n return array\n \n \n \n #check for success\ndef CheckForSuccess(arrayForSuccess):\n #print(f\"Checking this array for success: {arrayForSuccess}\")\n for x in arrayForSuccess:\n if x !=0:\n return False\n \n return True\n \n \n \n \n \n \ndef mainAlgorithm(inputarray):\n if CheckForSuccess(inputarray):\n answers.append(\"YES\")\n return\n \n loop_counter = 1\n while (loop_counter!=100):\n length = len(inputarray)\n #print(f\"Array length {length}\")\n \n #find index to highest element that is not 0 and not n-1\n highestNumber=-1\n highestIndex=-1\n for elementIndex in range(1,length-1):\n if inputarray[elementIndex] >= highestNumber:\n highestIndex = elementIndex\n highestNumber=inputarray[elementIndex]\n \n #print(f\"Highest Index of {inputarray} is {highestIndex}\")\n \n if (highestNumber <0):\n #Bail out time\n answers.append(\"NO\")\n return\n \n \n \n newArray = processArray(inputarray, highestIndex)\n #print (f\"New Array: {newArray}\")\n \n \n \n if (CheckForSuccess(newArray)):\n answers.append(\"YES\")\n return\n \n loop_counter+=1\n \n \n answers.append(\"NO\")\n \n \n \n \n# my algorithm is find highest number and always start wit hthat one.\n \n \nnumberOfArrays = int(input())\nfor arrayCounter in range (0,numberOfArrays):\n elementSize = int(input()) \n array = list(map(int, input().split()))\n \n mainAlgorithm(array)\n \nfor ans in answers:\n print(f\"{ans}\")" + ] + }, + { + "task_name": "1941_C", + "description": "Rudolf has a string s of length n . Rudolf considers the string s to be ugly\nif it contains the substring^\\dagger \"pie\" or the substring \"map\", otherwise\nthe string s will be considered beautiful.\n\nFor example, \"ppiee\", \"mmap\", \"dfpiefghmap\" are ugly strings, while \"mathp\",\n\"ppiiee\" are beautiful strings.\n\nRudolf wants to shorten the string s by removing some characters to make it\nbeautiful.\n\nThe main character doesn't like to strain, so he asks you to make the string\nbeautiful by removing the minimum number of characters. He can remove\ncharacters from any positions in the string (not just from the beginning or\nend of the string).\n\n^\\dagger String a is a substring of b if there exists a consecutive segment of\ncharacters in string b equal to a .\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases. The descriptions of the test cases follow.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 10^6\n) — the length of the string s .\n\nThe next line of each test case contains the string s of length n . The string\ns consists of lowercase Latin letters.\n\nThe sum of n over all test cases does not exceed 10^6 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of characters\nthat need to be deleted to make the string s beautiful. If the string is\ninitially beautiful, then output 0 .\n\nExample\n\nInput\n\n 6\n \n 9\n \n mmapnapie\n \n 9\n \n azabazapi\n \n 8\n \n mappppie\n \n 18\n \n mapmapmapmapmapmap\n \n 1\n \n p\n \n 11\n \n pppiepieeee\n\nOutput\n\n 2\n 0\n 2\n 6\n 0\n 2\n \nNote\n\nIn the first test case, for example, you can delete the 4 th and 9 th\ncharacters to make the string beautiful.\n\nIn the second test case, the string is already beautiful.", + "generated_code": [ + "t=int(input())\nfor i in range(t):\n n=int(input())\n s=input()\n m=s.count(\"map\")\n s=s.replace(\"map\",\"\")\n \n p=s.count(\"pie\")\n print(m+p)", + "for _ in range(int(input())):\n a=int(input()) \n s=input() \n x=s.count(\"map\") \n y=s.count(\"pie\") \n print(x+y)", + "def solve(s):\n if s=='mapie':\n return 1\n ans=0\n while s.find('map')!=-1:\n s=s[:s.find('map')]+s[s.find('map')+2:]\n ans+=1\n while s.find('pie')!=-1:\n s=s[:s.find('pie')]+s[s.find('pie')+2:]\n ans+=1\n return ans\n \nt=int(input())\nfor i in range(t):\n n=int(input())\n s=input()\n print(solve(s))", + "for _ in range(int(input())):\n a = input()\n ans = 0\n i = 0\n while i 0 else 0) + row[i] + 1\n return row[-1]\n \n \ndef solve():\n n, m, k, d = (int(e) for e in input().split(\" \"))\n rows = [[int(e) for e in input().split(\" \")] for _ in range(n)]\n costs = [best_solution(row, d) for row in rows]\n total_costs = []\n for i in range(len(costs) - (k - 1)):\n total_costs.append(sum(costs[i : i + k]))\n print(min(total_costs))\n \n \nif __name__ == \"__main__\":\n for _ in range(int(input())):\n solve()" + ] + }, + { + "task_name": "1942_C1", + "description": "[Proof Geometric Construction Can Solve All Love Affairs -\nmanbo-p](https://soundcloud.com/alice-law-314125270/manbo-p-proof-geometric-\nconstruction-can-solve-all-love-affairs)\n\n⠀\n\nThis is the easy version of the problem. The only difference between the two\nversions is the constraint on y . In this version y = 0 . You can make hacks\nonly if both versions are solved.\n\nBessie has received a birthday cake from her best friend Elsie, and it came in\nthe form of a regular polygon with n sides. The vertices of the cake are\nnumbered from 1 to n clockwise. You and Bessie are going to choose some of\nthose vertices to cut non-intersecting diagonals into the cake. In other\nwords, the endpoints of the diagonals must be part of the chosen vertices.\n\nBessie would only like to give out pieces of cake which result in a triangle\nto keep consistency. The size of the pieces doesn't matter, and the whole cake\ndoes not have to be separated into all triangles (other shapes are allowed in\nthe cake, but those will not be counted).\n\nBessie has already chosen x of those vertices that can be used to form\ndiagonals. She wants you to choose no more than y other vertices such that the\nnumber of triangular pieces of cake she can give out is maximized.\n\nWhat is the maximum number of triangular pieces of cake Bessie can give out?\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 10^4 ) — the number\nof test cases.\n\nThe first line of each test case consists of three integers, n , x , and y (4\n\\leq n \\leq 10^9 , 2 \\leq x \\leq \\min(n, 2 \\cdot 10^5) , y = 0 ) — the number\nof sides of the polygon, number of vertices Bessie has chosen, and the maximum\nnumber of other vertices you can choose.\n\nThe second line consists of x distinct integers from 1 to n , representing the\nvertices Bessie has chosen.\n\nIt is guaranteed the sum of x over all test cases does not exceed 2 \\cdot 10^5\n.\n\nOutput\n\nFor each test case, output a single integer: the maximum number of non-\nintersecting triangular pieces of cake she can give out.\n\nExample\n\nInput\n\n 3\n \n 8 4 0\n \n 1 6 2 5\n \n 8 8 0\n \n 1 3 2 5 4 6 7 8\n \n 4 2 0\n \n 1 3\n\nOutput\n\n 2\n 6\n 2\n \nNote\n\nIn test cases 1 , 2 and 3 , you can get 2 , 6 and 2 non-intersecting\ntriangular pieces of cake, respectively. A possible construction is shown in\nthe following pictures:\n\nThe green dots represent vertices that can be used, the blue lines represent\ndiagonals that are drawn, and the red numbers represent triangles that are\ncounted.\n\n![](https://espresso.codeforces.com/80282d636b83d4002ec89755d465b4adb37b9cfb.png)", + "generated_code": [ + "T=int(input())\nfor _ in range(T):\n n,x,y=map(int,input().split())\n list0=list(map(int,input().split()))\n list0=sorted(list0)\n count=0\n for i in range(x-1):\n num=list0[i+1]-list0[i]-1\n if num==1:\n count+=1\n num=n-list0[-1]\n if num==1:\n count+=1\n print(count+x-2)", + "if __name__ == \"__main__\":\n t=int(input())\n while(t>0):\n t-=1\n [n,x,y]=map(int,input().split())\n arr=input().split()\n arr=[int(arr[i]) for i in range(x)]\n print(x-2)" + ] + }, + { + "task_name": "1943_C", + "description": "You are given a tree with n vertices numbered 1, 2, \\ldots, n . Initially, all\nvertices are colored white.\n\nYou can perform the following two-step operation:\n\n 1. Choose a vertex v (1 \\leq v \\leq n ) and a distance d (0 \\leq d \\leq n-1 ). \n 2. For all vertices u (1 \\leq u \\leq n ) such that \\text{dist}^\\dagger(u,v)=d , color u black. \n\nConstruct a sequence of operations to color all the nodes in the tree black\nusing the minimum possible number of operations. It can be proven that it is\nalways possible to do so using at most n operations.\n\n^\\dagger \\text{dist}(x, y) denotes the number of edges on the (unique) simple\npath between vertices x and y on the tree.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 200 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 2\n\\cdot 10^3 ) — the number of vertices of the tree.\n\nThe following n - 1 lines of each test case describe the edges of the tree.\nThe i -th of these lines contains two integers u_i and v_i (1 \\le u_i, v_i \\le\nn , u_i \\neq v_i ), the indices of the vertices connected by the i -th edge.\n\nIt is guaranteed that the given edges form a tree.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^3 .\n\nOutput\n\nFor each test case, first output a single integer op (1 \\le op \\le n) , the\nminimum number of operations needed to color all vertices of the tree black.\n\nThen, output op lines, each containing 2 integers. The i -th line should\ncontain the values of v and d chosen for the i -th operation (1 \\le v \\le n ,\n0 \\le d \\le n - 1 )\n\nYou must guarantee that at the end of op operations, all vertices are colored\nblack.\n\nIf there are multiple solutions, you may output any one of them.\n\nExample\n\nInput\n\n 4\n \n 1\n \n 2\n \n 1 2\n \n 4\n \n 1 2\n \n 1 3\n \n 1 4\n \n 7\n \n 2 7\n \n 3 2\n \n 6 4\n \n 5 7\n \n 1 6\n \n 6 7\n\nOutput\n\n 1\n 1 0\n 2\n 1 1\n 2 1\n 2\n 1 1\n 2 1\n 3\n 6 1\n 7 1\n 2 1\n\nNote\n\nIn the first test case, there is only one possible operation, and performing\nit gives us a valid answer.\n\nIn the second test case, the first operation colors vertex 2 black, and the\nsecond operation colors vertex 1 black. It can be shown that it is impossible\nto color both vertices black in one operation, so the minimum number of\noperations needed is 2 . Another possible solution is to use the 2 operations:\n(u, r) = (1, 0) and (u, r) = (2, 0) .\n\nIn the third test case, the first operation colors vertices 2 , 3 and 4 black,\nand the second operation colors vertex 1 black. Again, it can be shown that it\nis impossible to color all vertices black in 1 operation, so the minimum\nnumber of operations needed is 2 .\n\nIn the fourth test case, the first operation colors vertices 4 , 1 and 7\nblack, the second operation colors vertices 2 , 5 and 6 black while the third\noperation colors vertices 3 and 7 black. Notice that it is allowed to color\nvertex 7 black twice.\n\nThus, each node was marked at least once, with node 7 marked twice. It can be\nshown that it is impossible to color all vertices black in fewer than 3 moves.", + "generated_code": [ + "def argmax(l):\n return max(range(len(l)), key=lambda x: l[x])\n \ndef alg():\n n = int(input())\n u2vs = [[] for _ in range(n)]\n for _ in range(n - 1):\n u, v = tuple(map(int, input().split()))\n u-=1; v-=1\n u2vs[u].append(v)\n u2vs[v].append(u)\n \n \n # find diameter of tree\n def bfs(s):\n nonlocal n\n d = [-1 for _ in range(n)]\n prev = [ -1 for _ in range(n)]\n q = [s]\n d[s] = 0\n \n \n while len(q) > 0:\n u = q.pop(0)\n du = d[u]\n for v in u2vs[u]:\n if d[v] == -1:\n d[v] = du + 1\n prev[v] = u\n q.append(v)\n return d, prev\n \n d, _ = bfs(0); a = argmax(d)\n d, previous = bfs(a); b = argmax(d)\n path_ba = [b]\n while True:\n n = previous[path_ba[-1]]\n if n == -1:\n break\n path_ba.append(n)\n \n # print(path_ba)\n # end of find diameter, path_ab - diameter\n \n # generate commands\n \n # if len(path_ba) - odd => find centre and propagate commands from it\n ops = []\n if len(path_ba) % 2 == 1:\n ci = len(path_ba) // 2\n c = path_ba[ci]\n for i in range(ci+1):\n ops.append((c, i))\n \n # if len(path_ba) - even => find 2 centres and ?????\n else:\n c2 = len(path_ba) // 2\n c1 = c2 - 1\n \n for i in range(1, len(path_ba) - c1, 2): \n ops.append((c1, i))\n ops.append((c2, i))\n \n # end of generate commands \n \n \n # print\n \n print(len(ops))\n \n print(*map(lambda x: f\"{x[0]+1} {x[1]}\" , ops), sep=\"\\n\")\n \n \n return None\n \n \n \nif __name__ == \"__main__\":\n for _ in range(int(input())):\n alg()" + ] + }, + { + "task_name": "1944_A", + "description": "There are n islands, numbered 1, 2, \\ldots, n . Initially, every pair of\nislands is connected by a bridge. Hence, there are a total of \\frac{n (n -\n1)}{2} bridges.\n\nEverule lives on island 1 and enjoys visiting the other islands using bridges.\nDominater has the power to destroy at most k bridges to minimize the number of\nislands that Everule can reach using (possibly multiple) bridges.\n\nFind the minimum number of islands (including island 1 ) that Everule can\nvisit if Dominater destroys bridges optimally.\n\nInput\n\nEach test contains multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^3 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first and only line of each test case contains two integers n and k (1 \\le\nn \\le 100 , 0 \\le k \\le \\frac{n \\cdot (n - 1)}{2} ).\n\nOutput\n\nFor each test case, output the minimum number of islands that Everule can\nvisit if Dominater destroys bridges optimally.\n\nExample\n\nInput\n\n 6\n \n 2 0\n \n 2 1\n \n 4 1\n \n 5 10\n \n 5 3\n \n 4 4\n\nOutput\n\n 2\n 1\n 4\n 1\n 5\n 1\n \nNote\n\nIn the first test case, since no bridges can be destroyed, all the islands\nwill be reachable.\n\nIn the second test case, you can destroy the bridge between islands 1 and 2 .\nEverule will not be able to visit island 2 but can still visit island 1 .\nTherefore, the total number of islands that Everule can visit is 1 .\n\nIn the third test case, Everule always has a way of reaching all islands\ndespite what Dominater does. For example, if Dominater destroyed the bridge\nbetween islands 1 and 2 , Everule can still visit island 2 by traveling by 1\n\\to 3 \\to 2 as the bridges between 1 and 3 , and between 3 and 2 are not\ndestroyed.\n\nIn the fourth test case, you can destroy all bridges since k = \\frac{n \\cdot\n(n - 1)}{2} . Everule will be only able to visit 1 island (island 1 ).", + "generated_code": [ + "t=int(input())\nimport math\nfor i in range(0,t,1):\n n,k=map(int,input().split())\n if k>=n-1:\n print(1)\n else:\n print(n-1)", + "for _ in range(int(input())):\n n, k = map(int, input().split())\n print(n if n-k<=1 else 1)", + "qs = int(input())\n \nfor _ in range(qs):\n n, k = [int(num) for num in input().split()]\n \n reachable_count = n\n \n while (k >= (reachable_count - 1)) and (k > 0):\n k -= (reachable_count - 1)\n reachable_count -= 1\n \n print(reachable_count)" + ] + }, + { + "task_name": "1945_A", + "description": "The organizing committee plans to take the participants of the Olympiad on a\nhike after the tour. Currently, the number of tents needed to be taken is\nbeing calculated. It is known that each tent can accommodate up to 3 people.\n\nAmong the participants, there are a introverts, b extroverts, and c\nuniversals:\n\n * Each introvert wants to live in a tent alone. Thus, a tent with an introvert must contain exactly one person — only the introvert himself. \n * Each extrovert wants to live in a tent with two others. Thus, the tent with an extrovert must contain exactly three people. \n * Each universal is fine with any option (living alone, with one other person, or with two others). \n\nThe organizing committee respects the wishes of each participant very much, so\nthey want to fulfill all of them.\n\nTell us the minimum number of tents needed to be taken so that all\nparticipants can be accommodated according to their preferences. If it is\nimpossible to accommodate the participants in a way that fulfills all the\nwishes, output -1 .\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. This is followed by\nthe descriptions of the test cases.\n\nEach test case is described by a single line containing three integers a , b ,\nc (0 \\le a, b, c \\le 10^9 ) — the number of introverts, extroverts, and\nuniversals, respectively.\n\nOutput\n\nFor each test case, output a single integer — the minimum number of tents, or\n-1 if it is impossible to accommodate the participants.\n\nExample\n\nInput\n\n 10\n \n 1 2 3\n \n 1 4 1\n \n 1 4 2\n \n 1 1 1\n \n 1 3 2\n \n 19 7 18\n \n 0 0 0\n \n 7 0 0\n \n 0 24 0\n \n 1000000000 1000000000 1000000000\n\nOutput\n\n 3\n -1\n 3\n -1\n 3\n 28\n 0\n 7\n 8\n 1666666667\n \nNote\n\nIn the first test case, 1 tent will be given to the introverts, 1 tent will be\nshared by two extroverts and one universal, and the last tent will be shared\nby two universals. In total, 3 tents are needed.\n\nIn the second test case, three extroverts will take 1 tent, and 1 tent will be\ntaken by an introvert. Then, one extrovert and one universal will be left.\nThis extrovert will not be able to live with two others.", + "generated_code": [ + "from math import ceil\nfrom typing import Optional\n \n \n \n \n# Each introvert wants to live in a tent alone. Thus, a tent with an introvert must contain exactly one person — only the introvert himself.\n# Each extrovert wants to live in a tent with two others. Thus, the tent with an extrovert must contain exactly three people.\n# Each universal is fine with any option(living alone, with one other person, or with two others).\n \n \ndef f(extroverts: int, universals: int) -> Optional[int]:\n if extroverts % 3 != 0:\n if extroverts % 3 + universals < 3:\n return None\n return ceil((extroverts + universals)/3)\n \ndef g(introverts: int, extroverts: int, universals: int) -> int:\n ret = f(extroverts, universals)\n return -1 if ret is None else introverts+ret\n \n# test_case_n = int(input())\n# for _ in range(test_case_n):\n# (introverts, extroverts, universals) = map(int, input().split(' '))\n# # return min area\n# print(g(introverts, extroverts, universals))\n \nfor line in '''1 2 3\n1 4 1\n1 4 2\n1 1 1\n1 3 2\n19 7 18\n0 0 0\n7 0 0\n0 24 0\n1000000000 1000000000 1000000000'''.splitlines():\n (introverts, extroverts, universals) = map(int, line.split(' '))\n print('line:', line)\n print('ret:', g(introverts, extroverts, universals))", + "n=int(input())\nfor i in range(n):\n a, b, c = map(int, input().split())\n k=0\n if (b%3!=0 and c<3) and (b+c)%3!=0: print(-1)\n else:\n k+=a+(b+c)//3\n if (b+c)%3!=0: k+=1\n print(k)", + "for line in [*open(0)][1:]:\n p, q, r = map(int, line.split())\n q += r\n print((p - q // 3, -1)[r < q % 3])" + ] + }, + { + "task_name": "1945_B", + "description": "One of the days of the hike coincided with a holiday, so in the evening at the\ncamp, it was decided to arrange a festive fireworks display. For this purpose,\nthe organizers of the hike bought two installations for launching fireworks\nand a huge number of shells for launching.\n\nBoth installations are turned on simultaneously. The first installation\nlaunches fireworks every a minutes (i.e., after a, 2 \\cdot a, 3 \\cdot a, \\dots\nminutes after launch). The second installation launches fireworks every b\nminutes (i.e., after b, 2 \\cdot b, 3 \\cdot b, \\dots minutes after launch).\n\nEach firework is visible in the sky for m + 1 minutes after launch, i.e., if a\nfirework was launched after x minutes after the installations were turned on,\nit will be visible every minute from x to x + m , inclusive. If one firework\nwas launched m minutes after another, both fireworks will be visible for one\nminute.\n\nWhat is the maximum number of fireworks that could be seen in the sky at the\nsame time?\n\nInput\n\nEach test consists of several test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. Then follow the\ndescriptions of the test cases.\n\nThe first and only line of each test case contains integers a , b , m (1 \\le\na, b, m \\le 10^{18} ) — the frequency of launching for the first installation,\nthe second installation, and the time the firework is visible in the sky.\n\nOutput\n\nFor each set of input data, output a single number — the maximum number of\nfireworks that can be seen simultaneously.\n\nExample\n\nInput\n\n 6\n \n 6 7 4\n \n 3 4 10\n \n 7 8 56\n \n 5 6 78123459896\n \n 1 1 1\n \n 1 1 1000000000000000000\n\nOutput\n\n 2\n 7\n 17\n 28645268630\n 4\n 2000000000000000002\n \nNote\n\nIn the first set of input data, the fireworks are visible in the sky for 5\nminutes. Since the first installation launches fireworks every 6 minutes, and\nthe second one every 7 minutes, two fireworks launched from the same\ninstallation will not be visible in the sky at the same time. At the same\ntime, after 7 minutes from the start of the holiday, one firework from the\nfirst and one from the second camp will be visible. Thus, it is possible to\nsee no more than 2 fireworks simultaneously.\n\nIn the third set of input data, 17 fireworks will be visible after 112\nminutes:\n\n * 9 fireworks launched from the first installation at times [56, 63, 70, 77, 84, 91, 98, 105, 112 ]; \n * 8 fireworks launched from the second installation at times [56, 64, 72, 80, 88, 96, 104, 112 ].", + "generated_code": [ + "t=int(input())\nfor _ in range(t):\n a,b,m=map(int,input().split())\n A=int(m/a)+1\n B=int(m/b)+1\n print(A+B)", + "t = int(input())\n \nfor i in range(t):\n a, b, m = map(int, input().split())\n \n if m < a or m < b:\n print(2)\n \n else:\n print(m//a + m//b + 2)", + "t=int(input())\nfor i in range(t):\n a,b,m=map(int,input().split())\n mn=min(a,b)+m\n if m%a==0 and m%b==0 and a!=1 and b!=1:\n print((mn)//a+(mn)//b+1)\n else:\n print((mn)//a+(mn)//b)" + ] + }, + { + "task_name": "1945_C", + "description": "In the village of Letovo, there are n houses. The villagers decided to build a\nbig road that will divide the village into left and right sides. Each resident\nwants to live on either the right or the left side of the street, which is\ndescribed as a sequence a_1, a_2, \\dots, a_n , where a_j = 0 if the resident\nof the j -th house wants to live on the left side of the street; otherwise,\na_j = 1 .\n\nThe road will pass between two houses. The houses to the left of it will be\ndeclared the left-side, and the houses to the right will be declared the\nright-side. More formally, let the road pass between houses i and i+1 . Then\nthe houses at positions between 1 and i will be on the left side of the\nstreet, and at positions between i+1 and n will be on the right side. The road\nalso may pass before the first and after the last house; in this case, the\nentire village is declared to be either the right or left side, respectively.\n\nTo make the design fair, it was decided to lay the road so that at least half\nof the residents on each side of the village are satisfied with the choice.\nThat is, among x residents on one side, at least \\lceil\\frac{x}{2}\\rceil\nshould want to live on that side, where \\lceil x \\rceil denotes rounding up a\nreal number x .\n\n![](https://espresso.codeforces.com/75baa17903d65a630fb0d3334683e857d5fdc345.png)\nTo the left of the road, there will be i houses, among the corresponding a_j\nthere must be at least \\lceil\\frac{i}{2}\\rceil zeros. To the right of the\nroad, there will be n-i houses, among the corresponding a_j there must be at\nleast \\lceil\\frac{n-i}{2}\\rceil ones.\n\nDetermine after which house i the road should be laid in order to satisfy the\ndescribed condition and be as close to the middle of the village as possible.\nFormally, among all suitable positions i , minimize \\left|\\frac{n}{2} -\ni\\right| .\n\nIf there are multiple suitable positions i with the minimum \\left|\\frac{n}{2}\n- i\\right| , output the smaller one.\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 2\\cdot 10^4 ). The description of the test cases\nfollows.\n\nThe first line of each test case contains a single integer n (3 \\le n \\le\n3\\cdot 10^5 ). The next line of each test case contains a string a of length n\n, consisting only of 0 and 1 .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 3\\cdot\n10^5 .\n\nOutput\n\nFor each test case, output a single number i — the position of the house after\nwhich the road should be laid (if it should be laid before the first house,\noutput 0 ). We can show that the answer always exists.\n\nExample\n\nInput\n\n 7\n \n 3\n \n 101\n \n 6\n \n 010111\n \n 6\n \n 011001\n \n 3\n \n 000\n \n 3\n \n 110\n \n 3\n \n 001\n \n 4\n \n 1100\n\nOutput\n\n 2\n 3\n 2\n 3\n 0\n 1\n 0\n \nNote\n\nLet's consider the first example of input data.\n\nIf we lay the road after the first house, there will be one house a_1 = 1 on\nthe left side of the street, the resident of which would like to live on the\nright side of the street. Then 0 out of 1 residents on the even side will be\nsatisfied with the choice, which means that the road cannot be laid after\nhouse 1 .\n\nIf we lay the road after the second house, 1 out of 2 residents on the left\nside (with preferences a_1 = 1 , a_2 = 0 ) and 1 out of 1 resident on the\nright side (with preference a_3 = 1 ) will be satisfied with the choice. More\nthan half of the residents on each side are satisfied with the choice, which\nmeans that the road can be laid after house 2 . We can show that this is the\noptimal answer.", + "generated_code": [ + "import math\nfrom decimal import Decimal\n \nt = int(input()) \nwhile t:\n n=int(input())\n input_string = input()\n arr = [int(ch) for ch in input_string]\n z = arr.count(0)\n o = arr.count(1)\n z_r = z\n o_r = o\n z_l=0\n o_l=0\n dist,ans,pos=abs(n/2),0,0\n if o_r>=(z_r+o_r)/2:\n b_d=dist\n else:\n b_d=30001\n for i in arr:\n pos+=1\n if i==0:\n z_l+=1\n z_r-=1\n else:\n o_l+=1\n o_r-=1\n if o_r>=((z_r+o_r)/2) and z_l>=((z_l+o_l)/2) and b_d > abs(n/2-pos):\n ans=pos\n b_d = abs(n/2-pos)\n print(ans)\n t -= 1", + "from heapq import heappush, heappop, heapify\nfrom collections import defaultdict, deque,Counter\nfrom math import ceil, floor, sqrt, factorial,gcd,cos,sin,pi\nfrom itertools import permutations, combinations,product\nfrom bisect import bisect_left, bisect_right\nfrom copy import deepcopy\nfrom fractions import Fraction\nimport sys\n#from functools import cache,lru_cache #@lru_cache(maxsize=None)\n# sys.setrecursionlimit(10**6)\n# input = sys.stdin.readline\nvector1 = [[0, -1], [1, 0], [0, 1], [-1, 0]]\nvector2 = [[0, 1], [1, 0], [-1, 0], [0, -1],\n [1,-1], [-1, 1], [1, 1], [-1, -1]]\n \n \n \ndef solve():\n \n n = int(input())\n a = input()\n S = [[0,0]]\n for s in a:\n x, y = S[-1]\n if s == \"0\":\n x += 1\n else:\n y += 1\n S.append([x,y])\n ans = 0\n satisfy = 0\n for i in range(n):\n left = S[i][0]\n lsum = S[i][0] + S[i][1]\n right = S[-1][1] - S[i][1]\n rsum = n - lsum\n \n if left*2 < lsum or right*2 < rsum:\n continue\n elif abs(n/2 - i) <= abs(n/2 - ans):\n ans = i\n \n print(ans)\n #print(S)\n \n \ndef main():\n for _ in range(int(input())):\n solve()\n \n \n \n \n \nif __name__ == '__main__':\n main()", + "t = int(input())\nfor _ in range(t):\n n = int(input())\n s = input()\n \n mid = n // 2\n leftZero = 0\n rightZero = 0\n leftOne = 0\n rightOne = 0\n tleftZero = 0\n trightZero = 0\n tleftOne = 0\n trightOne = 0\n \n for i in range(mid):\n if s[i] == '0':\n leftZero += 1\n tleftZero += 1\n else:\n leftOne += 1\n tleftOne += 1\n \n for i in range(mid, n):\n if s[i] == '0':\n rightZero += 1\n trightZero += 1\n else:\n rightOne += 1\n trightOne += 1\n \n left = mid\n leftMove = 0\n while left > 0 and (leftZero < (left+1)//2 or rightOne < (n-left+1)//2):\n if s[left-1] == '0':\n leftZero -= 1\n rightZero += 1\n else:\n leftOne -= 1\n rightOne += 1\n left -= 1\n \n right = mid\n while right < n and (tleftZero < (right+1)//2 or trightOne < (n-right+1)//2):\n if s[right] == '0':\n tleftZero += 1\n trightZero -= 1\n else:\n tleftOne += 1\n trightOne -= 1\n right += 1\n \n if left == 0:\n if right != n:\n print(right)\n else:\n if rightOne >= (n+1)//2:\n print(left)\n else:\n print(right)\n elif right == n:\n if tleftZero >= (n+1)//2:\n print(right)\n else:\n print(left)\n else:\n if abs((n+1)//2-left) <= abs((n+1)//2-right):\n print(left)\n else:\n print(right)", + "import math\nt=int(input())\nfor _ in range(t):\n n=int(input())\n s=input()\n \n if n%2==0:\n pk=n//2\n else:\n pk=(n//2) \n \n sl=list(s)\n o=sl.count(\"1\")\n z=sl.count(\"0\")\n \n zero,one=0,0\n lst=[]\n mini=pow(10,8)\n for i in range(n-1):\n if s[i]==\"0\":\n zero+=1\n else:\n one+=1\n \n zero_perc = math.ceil((zero * 100) / (i + 1))\n one_perc = math.ceil(((o - one) * 100) / (n - i - 1))\n #print(zero_perc,one_perc,\"hulu\",i)\n if zero_perc>=50 and one_perc>=50:\n lst.append(i+1)\n #print(lst)\n \n #print(mini,\"le\")\n #print(lst)\n #print(pk)\n for ele in lst:\n mini=min(mini,abs(pk-ele))\n final=[]\n #print(mini,\"88\")\n for elem in lst:\n if abs(pk-elem)==mini:\n final.append(elem)\n \n final.sort()\n if len(final)==0:\n c1=(o*100)//n\n if c1>=50:\n final.append(0)\n else:\n final.append(n)\n \n print(final[0])" + ] + }, + { + "task_name": "1945_D", + "description": "The guys lined up in a queue of n people, starting with person number i = 1 ,\nto ask Serafim the Owl about the meaning of life. Unfortunately, Kirill was\nvery busy writing the legend for this problem, so he arrived a little later\nand stood at the end of the line after the n -th person. Kirill is completely\ndissatisfied with this situation, so he decided to bribe some people ahead of\nhim.\n\nFor the i -th person in the queue, Kirill knows two values: a_i and b_i . If\nat the moment Kirill is standing at position i , then he can choose any\nposition j such that j < i and exchange places with the person at position j .\nIn this case, Kirill will have to pay him a_j coins. And for each k such that\nj < k < i , Kirill will have to pay b_k coins to the person at position k .\nKirill can perform this action any number of times.\n\nKirill is thrifty, so he wants to spend as few coins as possible, but he\ndoesn't want to wait too long, so Kirill believes he should be among the first\nm people in line.\n\nHelp Kirill determine the minimum number of coins he will have to spend in\norder to not wait too long.\n\nInput\n\nEach test consists of several sets of input data. The first line contains a\nsingle integer t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows\nthe description of the test case.\n\nThe first line of each test case contains two integers n and m (1 \\le m \\le n\n\\le 200\\,000 ) — the number of people in the queue besides Kirill and the\nmaximum allowable final position of Kirill, respectively.\n\nThe second line contains n integers a_1, a_2, \\dots, a_n separated by spaces\n(1 \\le a_i \\le 10^9 ).\n\nThe third line contains n integers b_1, b_2, \\dots, b_n separated by spaces (1\n\\le b_i \\le 10^9 ).\n\nIt is guaranteed that the sum of the values of n over all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of coins\nKirill needs to spend.\n\nExample\n\nInput\n\n 4\n \n 4 2\n \n 7 3 6 9\n \n 4 3 8 5\n \n 6 2\n \n 6 9 7 1 8 3\n \n 5 8 8 1 4 1\n \n 7 7\n \n 7 2 9 2 6 5 9\n \n 9 1 10 7 1 4 9\n \n 2 1\n \n 2 3\n \n 1 1\n\nOutput\n\n 14\n 22\n 9\n 3", + "generated_code": [ + "def moedasMinimas():\n n, k = map(int, input().split())\n lista_A = list(map(int, input().split()))\n lista_A.reverse()\n \n lista_B = list(map(int, input().split()))\n lista_B.reverse()\n \n soma_b = 0\n pref = 0\n \n for i in range(n - k):\n if lista_A[i] < lista_B[i]:\n pref += soma_b\n pref += lista_A[i]\n soma_b = 0\n else:\n soma_b += lista_B[i]\n \n resultado = float('inf')\n \n for i in range(n - k, n):\n resultado = min(resultado, pref + soma_b + lista_A[i])\n soma_b += lista_B[i]\n \n print(resultado)\n \ndef main():\n numero_testes = int(input())\n for _ in range(numero_testes):\n moedasMinimas()", + "cases = int(input())\n \nfor c in range(cases):\n na_frente, pos_final = map(int, input().split())\n custo_pra_trocar_a = list(map(int, input().split()))\n custo_pra_passar_b = list(map(int, input().split()))\n \n na_frente -= 1\n pos_final -= 1\n \n total = 0\n best = 10**12\n for v in range(na_frente, -1, -1):\n if(v <= pos_final):\n if(best > total + custo_pra_trocar_a[v]):\n best = total + custo_pra_trocar_a[v]\n \n if(custo_pra_trocar_a[v] < custo_pra_passar_b[v]):\n total += custo_pra_trocar_a[v]\n else:\n total += custo_pra_passar_b[v]\n else:\n if(custo_pra_trocar_a[v] < custo_pra_passar_b[v]):\n total += custo_pra_trocar_a[v]\n else:\n total += custo_pra_passar_b[v]\n \n print(best)", + "x = int(input())\ncustos = []\n \nfor i in range(x):\n custo = 0\n num_fila = 0\n max_p = 0\n a_values = []\n b_values = []\n nf = input().split()\n num_fila = int(nf[0])\n max_p = int(nf[1])\n a = input().split()\n b = input().split()\n for y in a:\n a_values.append(int(y))\n for y in b:\n b_values.append(int(y))\n for y in range(num_fila - 1, max_p - 1, -1):\n if a_values[y] < b_values[y]:\n custo += a_values[y]\n else:\n custo += b_values[y]\n for y in range(max_p - 1, 0, -1):\n if (a_values[y - 1] + b_values[y]) <= a_values[y]:\n custo += b_values[y]\n if y == 1:\n custo += a_values[0]\n break\n else:\n custo += a_values[y]\n break\n custos.append(custo)\n \nfor c in custos:\n print(c)" + ] + }, + { + "task_name": "1945_F", + "description": "As soon as everyone in the camp fell asleep, Kirill sneaked out of the tent\nand went to the Wise Oak to gather mushrooms.\n\nIt is known that there are n mushrooms growing under the Oak, each of which\nhas magic power v_i . Kirill really wants to make a magical elixir of maximum\nstrength from the mushrooms.\n\nThe strength of the elixir is equal to the product of the number of mushrooms\nin it and the minimum magic power among these mushrooms. To prepare the\nelixir, Kirill will sequentially pick one mushroom growing under the Oak.\nKirill can gather mushrooms in any order.\n\nHowever, it's not that simple. The Wise Oak informed Kirill of a permutation\nof numbers p from 1 to n . If Kirill picks only k mushrooms, then the magic\npower of all mushrooms with indices p_1, p_2, \\dots, p_{k - 1} will become 0 .\nKirill will not use mushrooms with zero magic power to prepare the elixir.\n\nYour task is to help Kirill gather mushrooms in such a way that he can brew\nthe elixir of maximum possible strength. However, Kirill is a little scared to\nstay near the oak for too long, so out of all the suitable options for\ngathering mushrooms, he asks you to find the one with the minimum number of\nmushrooms.\n\nA permutation of length n is an array consisting of n different integers from\n1 to n in any order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is\nnot a permutation (2 appears in the array twice) and [1,3,4] is also not a\npermutation (n=3 , but 4 appears in the array).\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. The description of\nthe test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le\n200\\,000 ) — the number of mushrooms.\n\nThe second line contains an array v of size n (1\\le v_i \\le 10^9 ) — the magic\npowers of the mushrooms.\n\nThe third line contains a permutation p of numbers from 1 to n .\n\nIt is guaranteed that the sum of the values of n over all test cases does not\nexceed 2\\cdot 10^5 .\n\nOutput\n\nFor each test case, output two integers separated by a space — the maximum\nstrength of the elixir that can be brewed and the minimum number of mushrooms\nthat Kirill needs to use for this.\n\nExample\n\nInput\n\n 6\n \n 3\n \n 9 8 14\n \n 3 2 1\n \n 5\n \n 1 2 3 4 5\n \n 1 2 3 4 5\n \n 6\n \n 1 2 3 4 5 6\n \n 6 5 4 3 2 1\n \n 5\n \n 1 4 6 10 10\n \n 2 1 4 5 3\n \n 4\n \n 2 2 5 5\n \n 4 2 3 1\n \n 5\n \n 1 2 9 10 10\n \n 1 4 2 3 5\n\nOutput\n\n 16 2\n 9 3\n 8 2\n 20 2\n 5 1\n 20 2\n \nNote\n\nIn the first example, you need to take the mushrooms with indices 1 and 2 , so\nthe strength of the elixir is equal to 2 \\cdot \\min(a_1, a_2) = 2 \\cdot\n\\min(9, 8) = 2 \\cdot 8 = 16 . Note that the magic power of the mushroom with\nindex 3 after picking two mushrooms will become 0 .", + "generated_code": [ + "import math\nfrom bisect import bisect_left, bisect_right\nfrom typing import Generic, Iterable, Iterator, List, Tuple, TypeVar, Optional\nT = TypeVar('T')\n \nclass SortedMultiset(Generic[T]):\n BUCKET_RATIO = 16\n SPLIT_RATIO = 24\n \n def __init__(self, a: Iterable[T] = []) -> None:\n \"Make a new SortedMultiset from iterable. / O(N) if sorted / O(N log N)\"\n a = list(a)\n n = self.size = len(a)\n if any(a[i] > a[i + 1] for i in range(n - 1)):\n a.sort()\n num_bucket = int(math.ceil(math.sqrt(n / self.BUCKET_RATIO)))\n self.a = [a[n * i // num_bucket : n * (i + 1) // num_bucket] for i in range(num_bucket)]\n \n def __iter__(self) -> Iterator[T]:\n for i in self.a:\n for j in i: yield j\n \n def __reversed__(self) -> Iterator[T]:\n for i in reversed(self.a):\n for j in reversed(i): yield j\n \n def __eq__(self, other) -> bool:\n return list(self) == list(other)\n \n def __len__(self) -> int:\n return self.size\n \n def __repr__(self) -> str:\n return \"SortedMultiset\" + str(self.a)\n \n def __str__(self) -> str:\n s = str(list(self))\n return \"{\" + s[1 : len(s) - 1] + \"}\"\n \n def _position(self, x: T) -> Tuple[List[T], int, int]:\n \"return the bucket, index of the bucket and position in which x should be. self must not be empty.\"\n for i, a in enumerate(self.a):\n if x <= a[-1]: break\n return (a, i, bisect_left(a, x))\n \n def __contains__(self, x: T) -> bool:\n if self.size == 0: return False\n a, _, i = self._position(x)\n return i != len(a) and a[i] == x\n \n def count(self, x: T) -> int:\n \"Count the number of x.\"\n return self.index_right(x) - self.index(x)\n \n def add(self, x: T) -> None:\n \"Add an element. / O(√N)\"\n if self.size == 0:\n self.a = [[x]]\n self.size = 1\n return\n a, b, i = self._position(x)\n a.insert(i, x)\n self.size += 1\n if len(a) > len(self.a) * self.SPLIT_RATIO:\n mid = len(a) >> 1\n self.a[b:b+1] = [a[:mid], a[mid:]]\n \n def _pop(self, a: List[T], b: int, i: int) -> T:\n ans = a.pop(i)\n self.size -= 1\n if not a: del self.a[b]\n return ans\n \n def discard(self, x: T) -> bool:\n \"Remove an element and return True if removed. / O(√N)\"\n if self.size == 0: return False\n a, b, i = self._position(x)\n if i == len(a) or a[i] != x: return False\n self._pop(a, b, i)\n return True\n \n def lt(self, x: T) -> Optional[T]:\n \"Find the largest element < x, or None if it doesn't exist.\"\n for a in reversed(self.a):\n if a[0] < x:\n return a[bisect_left(a, x) - 1]\n \n def le(self, x: T) -> Optional[T]:\n \"Find the largest element <= x, or None if it doesn't exist.\"\n for a in reversed(self.a):\n if a[0] <= x:\n return a[bisect_right(a, x) - 1]\n \n def gt(self, x: T) -> Optional[T]:\n \"Find the smallest element > x, or None if it doesn't exist.\"\n for a in self.a:\n if a[-1] > x:\n return a[bisect_right(a, x)]\n \n def ge(self, x: T) -> Optional[T]:\n \"Find the smallest element >= x, or None if it doesn't exist.\"\n for a in self.a:\n if a[-1] >= x:\n return a[bisect_left(a, x)]\n \n def __getitem__(self, i: int) -> T:\n \"Return the i-th element.\"\n if i < 0:\n for a in reversed(self.a):\n i += len(a)\n if i >= 0: return a[i]\n else:\n for a in self.a:\n if i < len(a): return a[i]\n i -= len(a)\n raise IndexError\n \n def pop(self, i: int = -1) -> T:\n \"Pop and return the i-th element.\"\n if i < 0:\n for b, a in enumerate(reversed(self.a)):\n i += len(a)\n if i >= 0: return self._pop(a, ~b, i)\n else:\n for b, a in enumerate(self.a):\n if i < len(a): return self._pop(a, b, i)\n i -= len(a)\n raise IndexError\n \n def index(self, x: T) -> int:\n \"Count the number of elements < x.\"\n ans = 0\n for a in self.a:\n if a[-1] >= x:\n return ans + bisect_left(a, x)\n ans += len(a)\n return ans\n \n def index_right(self, x: T) -> int:\n \"Count the number of elements <= x.\"\n ans = 0\n for a in self.a:\n if a[-1] > x:\n return ans + bisect_right(a, x)\n ans += len(a)\n return ans\n \n \n \nt = int(input())\nfor _ in range(t):\n n = int(input())\n v = list(map(int,input().split()))\n p = list(map(int,input().split()))\n a = []\n for i in range(n):\n a.append(v[p[i]-1])\n r = SortedMultiset(a)\n ans = -1\n idx = 1\n for i in range(1,n):\n if r.__len__()ans:\n ans = x\n idx = i \n r.discard(a[i-1]) \n print(ans,idx)" + ] + }, + { + "task_name": "1946_A", + "description": "You are given an array a of n integers.\n\nThe median of an array q_1, q_2, \\ldots, q_k is the number p_{\\lceil\n\\frac{k}{2} \\rceil} , where p is the array q sorted in non-decreasing order.\nFor example, the median of the array [9, 5, 1, 2, 6] is 5 , as in the sorted\narray [1, 2, 5, 6, 9] , the number at index \\lceil \\frac{5}{2} \\rceil = 3 is 5\n, and the median of the array [9, 2, 8, 3] is 3 , as in the sorted array [2,\n3, 8, 9] , the number at index \\lceil \\frac{4}{2} \\rceil = 2 is 3 .\n\nYou are allowed to choose an integer i (1 \\le i \\le n ) and increase a_i by 1\nin one operation.\n\nYour task is to find the minimum number of operations required to increase the\nmedian of the array.\n\nNote that the array a may not necessarily contain distinct numbers.\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows the\ndescription of the test cases.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 10^5\n) — the length of the array a .\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the array a .\n\nIt is guaranteed that the sum of the values of n over all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of operations\nrequired to increase the median of the array.\n\nExample\n\nInput\n\n 8\n \n 3\n \n 2 2 8\n \n 4\n \n 7 3 3 1\n \n 1\n \n 1000000000\n \n 5\n \n 5 5 5 4 5\n \n 6\n \n 2 1 2 3 1 4\n \n 2\n \n 1 2\n \n 2\n \n 1 1\n \n 4\n \n 5 5 5 5\n\nOutput\n\n 1\n 2\n 1\n 3\n 2\n 1\n 2\n 3\n \nNote\n\nIn the first test case, you can apply one operation to the first number and\nobtain the array [3, 2, 8] , the median of this array is 3 , as it is the\nnumber at index \\lceil \\frac{3}{2} \\rceil = 2 in the non-decreasing sorted\narray [2, 3, 8] . The median of the original array [2, 2, 8] is 2 , as it is\nthe number at index \\lceil \\frac{3}{2} \\rceil = 2 in the non-decreasing sorted\narray [2, 2, 8] . Thus, the median increased (3 > 2 ) in just one operation.\n\nIn the fourth test case, you can apply one operation to each of the numbers at\nindices 1, 2, 3 and obtain the array [6, 6, 6, 4, 5] , the median of this\narray is 6 , as it is the number at index \\lceil \\frac{5}{2} \\rceil = 3 in the\nnon-decreasing sorted array [4, 5, 6, 6, 6] . The median of the original array\n[5, 5, 5, 4, 5] is 5 , as it is the number at index \\lceil \\frac{5}{2} \\rceil\n= 2 in the non-decreasing sorted array [4, 5, 5, 5, 5] . Thus, the median\nincreased (6 > 5 ) in three operations. It can be shown that this is the\nminimum possible number of operations.\n\nIn the fifth test case, you can apply one operation to each of the numbers at\nindices 1, 3 and obtain the array [3, 1, 3, 3, 1, 4] , the median of this\narray is 3 , as it is the number at index \\lceil \\frac{6}{2} \\rceil = 3 in the\nnon-decreasing sorted array [1, 1, 3, 3, 3, 4] . The median of the original\narray [2, 1, 2, 3, 1, 4] is 2 , as it is the number at index \\lceil\n\\frac{6}{2} \\rceil = 3 in the non-decreasing sorted array [1, 1, 2, 2, 3, 4] .\nThus, the median increased (3 > 2 ) in two operations. It can be shown that\nthis is the minimum possible number of operations.", + "generated_code": [ + "num = int(input())\n \nfor i in range(0, num):\n num2 = int(input())\n case = input()\n op = 0\n if num2 > 10000:\n print(1)\n print(16668)\n break\n else:\n \n a = [int(i) for i in case.split() if i.isdigit()]\n b = sorted(a)\n if num2 % 2 == 0:\n ma = int(num2 / 2) - 1\n else:\n ma = int(num2 / 2)\n median = b[ma]\n new_median = median\n \n while new_median <= median:\n b[ma] += 1\n op += 1\n b = sorted(b)\n new_median = b[ma]\n print(op)", + "'''Median of Array'''\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n a.sort()\n p = (n + 1) // 2 - 1\n res = a.count(a[p])\n print(res)", + "import heapq\n \ndef icecreamParlor(t, test_cases):\n results = []\n \n for i in range(t):\n n, arr = test_cases[i]\n arr.sort()\n median_index = n // 2\n current_median = arr[median_index]\n \n # Use a min-heap to keep track of elements from median_index to end\n heap = arr[median_index:]\n heapq.heapify(heap)\n \n operations = 0\n while heap[0] <= current_median:\n # Increase the smallest element in the heap\n smallest = heapq.heappop(heap)\n heapq.heappush(heap, smallest + 1)\n operations += 1\n \n results.append(operations)\n \n return results\n \nif __name__ == '__main__':\n import sys\n input = sys.stdin.read\n data = input().split()\n \n t = int(data[0])\n index = 1\n test_cases = []\n \n for _ in range(t):\n n = int(data[index])\n arr = list(map(int, data[index + 1: index + 1 + n]))\n test_cases.append((n, arr))\n index += 1 + n\n \n results = icecreamParlor(t, test_cases)\n for result in results:\n print(result)", + "t = int(input())\n \nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n a.sort()\n median_index = n // 2\n median = a[median_index]\n operations = 0\n for i in range(n):\n if a[i] < median:\n operations += median - a[i]\n print(operations)" + ] + }, + { + "task_name": "1946_B", + "description": "You have an array a of n integers.\n\nYou perform exactly k operations on it. In one operation, you select any\ncontiguous subarray of the array a (possibly empty) and insert the sum of this\nsubarray anywhere in the array.\n\nYour task is to find the maximum possible sum of the array after k such\noperations.\n\nAs this number can be very large, output the answer modulo 10^9 + 7 .\n\nReminder: the remainder of a number x modulo p is the smallest non-negative y\nsuch that there exists an integer q and x = p \\cdot q + y .\n\nInput\n\nEach test consists of several test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows the\ndescription of the test cases.\n\nThe first line of each test case contains two integers n and k (1 \\le n, k \\le\n2 \\cdot 10^5 ) — the length of the array a and the number of operations,\nrespectively.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n\n(-10^9 \\le a_i \\le 10^9 ) — the array a itself.\n\nIt is guaranteed that the sum of the values of n and k for all test cases does\nnot exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test, output a single integer — the maximum sum of the array that can\nbe obtained after k operations modulo 10^9 + 7 .\n\nExample\n\nInput\n\n 12\n \n 2 2\n \n -4 -7\n \n 3 3\n \n 2 2 8\n \n 1 7\n \n 7\n \n 5 1\n \n 4 -2 8 -12 9\n \n 7 4\n \n 8 14 -9 6 0 -1 3\n \n 7 100\n \n 5 3 -8 12 -5 -9 3\n \n 6 1000\n \n -1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000\n \n 2 1\n \n 1000000000 8\n \n 5 4\n \n 0 0 0 0 0\n \n 6 10\n \n 48973 757292 58277 -38574 27475 999984\n \n 7 1\n \n -1000 1000 -1000 1000 -1000 1000 -1000\n \n 10 10050\n \n 408293874 -3498597 7374783 295774930 -48574034 26623784 498754833 -294875830 283045804 85938045\n\nOutput\n\n 999999996\n 96\n 896\n 17\n 351\n 716455332\n 42\n 2\n 0\n 897909241\n 0\n 416571966\n \nNote\n\nIn the first test case, it is advantageous to take an empty subarray of the\narray twice and insert the sum of the empty subarray (zero) anywhere, then the\nsum of the resulting array will be (-4) + (-7) + 0 + 0 = -11 , modulo 10^9 + 7\nthis is 999\\,999\\,996 .\n\nIn the second test case, it is advantageous to take the sum of the entire\narray three times and place it anywhere in the array, then one of the possible\nsequences of actions: [2, 2, 8 ] \\rightarrow [2, 2, 8, 12 ] \\rightarrow [2, 2,\n8, 12, 24 ] \\rightarrow [2, 2, 8, 12, 24, 48 ], the sum of the final array is\n2 + 2 + 8 + 12 + 24 + 48 = 96 .\n\nIn the fourth test case, it is advantageous to take a subarray of the array\nconsisting of the first three numbers (i.e. consisting of the numbers 4, -2\nand 8 ) and insert its sum at the beginning of the array, thereby obtaining\nthe array [10, 4, -2, 8, -12, 9 ], the sum of this array is 17 .\n\nIn the seventh test case, it will always be advantageous for us to take an\nempty subarray of the array. In this case, the sum of the resulting array will\nnot differ from the sum of the original. The answer will be the sum of the\noriginal array, taken modulo — 42 , because (-6 \\cdot (10^9 + 7) + 42 =\n-6\\,000\\,000\\,000) .", + "generated_code": [ + "from math import *\n \n \n \ndef mod(number):\n return number % 1000000007\n \ndef max_sum_segment(arr):\n new_segment = []\n max_segment = [0, 0]\n segments_variants = []\n max_sum = -1\n for i in range(len(arr)):\n #print(i)\n #print(new_segment)\n #print(max_segment)\n #print()\n if new_segment:\n if arr[i] < 0:\n if max_segment[0] > new_segment[0]:\n segments_variants.append(max_segment + [i - 1])\n else:\n segments_variants.append(new_segment + [i - 1])\n max_segment = new_segment\n new_segment = []\n max_segment[0] += arr[i]\n else:\n max_segment[0] += arr[i]\n new_segment[0] += arr[i]\n else:\n if arr[i] >= 0:\n new_segment = [arr[i], i]\n max_segment[0] += arr[i]\n segments_variants.append(max_segment + [len(arr) - 1])\n segments_variants.append(new_segment + [len(arr) - 1])\n total_max_segment = [-1]\n for segment in segments_variants:\n if total_max_segment[0] < segment[0]:\n total_max_segment = segment\n if len(total_max_segment) == 1: total_max_segment = [-1]\n return total_max_segment\n \ndef repeat(number, quantity):\n answer = 0\n \n \n \nt = int(input())\n \nfor _ in range(t):\n n, k = map(int, input().split())\n a = list(map(int, input().split()))\n \n max_segment = max_sum_segment(a)\n #print(max_segment)\n if max_segment[0] == -1: max_segment[0] = 0\n \n answer = max_segment[0] * 2 ** k + sum(a) - max_segment[0]\n print(mod(answer))", + "import math\nfor i in range(int(input())):\n n,k=map(int,input().split())\n l=(list(map(int,input().split())))\n #print(l)\n c=0\n maxi=0\n for ele in l:\n if ele<0 and c<=abs(ele):\n maxi=max(c,maxi);c=0\n else:\n c+=ele\n maxi=max(c,maxi)\n print(((2**k)*maxi-maxi+sum(l))%1000000007)" + ] + }, + { + "task_name": "1946_C", + "description": "You are given a tree with n vertices.\n\nYour task is to find the maximum number x such that it is possible to remove\nexactly k edges from this tree in such a way that the size of each remaining\nconnected component^{\\dagger} is at least x .\n\n^{\\dagger} Two vertices v and u are in the same connected component if there\nexists a sequence of numbers t_1, t_2, \\ldots, t_k of arbitrary length k ,\nsuch that t_1 = v , t_k = u , and for each i from 1 to k - 1 , vertices t_i\nand t_{i+1} are connected by an edge.\n\nInput\n\nEach test consists of several sets of input data. The first line contains a\nsingle integer t (1 \\le t \\le 10^4 ) — the number of sets of input data. This\nis followed by a description of the sets of input data.\n\nThe first line of each set of input data contains two integers n and k (1 \\le\nk < n \\le 10^5 ) — the number of vertices in the tree and the number of edges\nto be removed.\n\nEach of the next n - 1 lines of each set of input data contains two integers v\nand u (1 \\le v, u \\le n ) — the next edge of the tree.\n\nIt is guaranteed that the sum of the values of n for all sets of input data\ndoes not exceed 10^5 .\n\nOutput\n\nFor each set of input data, output a single line containing the maximum number\nx such that it is possible to remove exactly k edges from the tree in such a\nway that the size of each remaining connected component is at least x .\n\nExample\n\nInput\n\n 6\n \n 5 1\n \n 1 2\n \n 1 3\n \n 3 4\n \n 3 5\n \n 2 1\n \n 1 2\n \n 6 1\n \n 1 2\n \n 2 3\n \n 3 4\n \n 4 5\n \n 5 6\n \n 3 1\n \n 1 2\n \n 1 3\n \n 8 2\n \n 1 2\n \n 1 3\n \n 2 4\n \n 2 5\n \n 3 6\n \n 3 7\n \n 3 8\n \n 6 2\n \n 1 2\n \n 2 3\n \n 1 4\n \n 4 5\n \n 5 6\n\nOutput\n\n 2\n 1\n 3\n 1\n 1\n 2\n \nNote\n\nThe tree in the first set of input data:\n\n![](https://espresso.codeforces.com/799bacd3be0dda357800fdfc3eadbf38ab259c51.png)\n\nAfter removing the edge 1 — 3 , the tree will look as follows:\n\n![](https://espresso.codeforces.com/a59ae10eeac1212e1e56fc7fe5f6a47764269104.png)\n\nThe tree has split into two connected components. The first component consists\nof two vertices: 1 and 2 . The second connected component consists of three\nvertices: 3, 4 and 5 . In both connected components, there are at least two\nvertices. It can be shown that the answer 3 is not achievable, so the answer\nis 2 .", + "generated_code": [ + "import sys\nimport threading\nthreading.stack_size(1 << 26)\nsys.setrecursionlimit(1 << 30)\n \ndef boom():\n\tt = int(sys.stdin.readline())\n\t\n\t\n\tfor z in range(t):\n\t n, k = list(map(int, sys.stdin.readline().split()))\n\t adj = [[] for i in range(n+1)]\n\t for i in range(n-1):\n\t a, b = list(map(int, sys.stdin.readline().split()))\n\t adj[a].append(b)\n\t adj[b].append(a)\n\t L = 1\n\t R = int(1e5+1)\n\t numCuts = 0\n\t\n\t def dfs(a, p):\n\t global numCuts\n\t vertices = 1\n\t for b in adj[a]:\n\t if b != p:\n\t vertices += dfs(b, a)\n\t if vertices >= x and a != p:\n\t numCuts += 1\n\t return 0\n\t return vertices\n\t \n\t while R - L > 1:\n\t x = (L+R) // 2\n\t numCuts = 0\n\t leftover = dfs(1, 1)\n\t if numCuts > k or (numCuts == k and leftover >= x):\n\t L = x\n\t else:\n\t R = x\n\t print(L)\nmain_thread = threading.Thread(target=boom)\nmain_thread.start()\nmain_thread.join()", + "import sys\n \nclass TreeNode:\n \n def __init__(self):\n self.edges = []\n self.children = []\n self.subtree_size = 1\n self.parent = None\n self.good_components = 0\n self.remaining_size = 1\n \n def __str__(self):\n return f\"(edges: {self.edges}, children: {self.children}, subtree_size: {self.subtree_size}, parent: {self.parent})\\n\"\n \n def __repr__(self):\n return self.__str__()\n \nclass Tree:\n \n def __init__(self, n):\n self.vertices = [TreeNode() for _ in range(n)]\n \n def add_edge(self, u: int, v: int) -> None:\n self.vertices[u].edges.append(v)\n self.vertices[v].edges.append(u)\n \n def root_tree(self, v: int, root: int) -> None:\n self.vertices[v].parent = root\n for u in self.vertices[v].edges:\n if u != root:\n self.vertices[v].children.append(u)\n self.root_tree(u, v)\n self.vertices[v].subtree_size += self.vertices[u].subtree_size\n \n def root_tree_non_recursive(self, v: int, root: int) -> None:\n stack = [(v, root)]\n while stack:\n (v, root) = stack.pop()\n self.vertices[v].parent = root\n for u in self.vertices[v].edges:\n if u != root:\n self.vertices[v].children.append(u)\n stack.append((u, v))\n self.vertices[v].subtree_size += self.vertices[u].subtree_size\n \n def __str__(self):\n return str(self.vertices)\n \ndef check_x_dfs(tree: Tree, s: int, x: int) -> (int, int):\n stack = [(s, False)]\n while stack:\n (v, postorder) = stack.pop()\n if not postorder:\n stack.append((v, True))\n for u in tree.vertices[v].children:\n stack.append((u, False))\n if postorder: \n for u in tree.vertices[v].children:\n tree.vertices[v].good_components += tree.vertices[u].good_components\n if tree.vertices[u].remaining_size >= x:\n tree.vertices[v].good_components += 1\n else:\n tree.vertices[v].remaining_size += tree.vertices[u].remaining_size\n \n return (tree.vertices[s].good_components, tree.vertices[s].remaining_size)\n \ndef check_x_dfs_recursive(tree: Tree, v: int, x: int) -> (int, int):\n good_components = 0\n remaining_size = 1\n \n for u in tree.vertices[v].children:\n (good_components_subtree, remaining_size_subtree) = check_x_dfs_recursive(tree, u, x)\n good_components += good_components_subtree\n if remaining_size_subtree >= x:\n good_components += 1\n else:\n remaining_size += remaining_size_subtree\n \n return (good_components, remaining_size)\n \n \ndef check_x(tree: Tree, n: int, k: int, x: int) -> bool:\n (good_components, remaining_size) = check_x_dfs(tree, 0, x)\n if good_components > k:\n return True\n if good_components == k and remaining_size >= x:\n return True\n return False\n \ndef find_x(tree: Tree, n: int, k: int) -> int:\n beg = 1\n end = n\n while beg < end:\n mid = (beg + end + 1) // 2\n if check_x(tree, n, k, mid):\n beg = mid\n else:\n end = mid - 1\n return beg\n \ndef solve_case():\n [n, k] = map(int, input().split())\n tree = Tree(n)\n for i in range(1, n):\n [u, v] = map(int, input().split())\n tree.add_edge(u-1, v-1)\n tree.root_tree_non_recursive(0, -1)\n print(find_x(tree, n, k))\n \nif __name__ == '__main__':\n sys.setrecursionlimit(int(1e5)*2)\n t = int(input())\n while t > 0:\n t -= 1\n solve_case()", + "def solve(n,k,edges):\n g=[[] for _ in range(n+1)]\n for a,b in edges:\n g[a].append(b)\n g[b].append(a)\n c=0\n visited=set()\n def dfs(x,y):\n c=1\n r=0\n visited.add(x)\n for node in g[x]:\n if node not in visited:\n ans,rn=dfs(node,y)\n r+=rn\n if ans>=y:\n r+=1\n else:\n c+=ans\n # print(node,ans)\n return c,r\n def check(x):\n visited.clear()\n ans,r=dfs(1,x)\n # print(ans,r,x)\n if ans>=x and r>=k:\n return True\n return False\n l=1\n r=(n//k)+1\n # print(l,r,n,k)\n while l<=r:\n mid=l+((r-l)//2)\n # print(mid,check(mid))\n if check(mid):\n l=mid+1\n else:\n r=mid-1\n # print(l,r)\n print(r)\n \nq=[]\nfor i in range(int(input())):\n n,k=map(int,input().split(' '))\n edges=[]\n for _ in range(n-1):\n a,b=map(int,input().split(' '))\n edges.append((a,b))\n if(i==325):\n print(n,k,edges)\n solve(n,k,edges)\n # q.append((n,k,edges))\n \n# print('ans:')\nfor n,k,edges in q:\n solve(n,k,edges)" + ] + }, + { + "task_name": "1946_D", + "description": "Yarik's birthday is coming soon, and Mark decided to give him an array a of\nlength n .\n\nMark knows that Yarik loves bitwise operations very much, and he also has a\nfavorite number x , so Mark wants to find the maximum number k such that it is\npossible to select pairs of numbers [l_1, r_1 ], [l_2, r_2 ], \\ldots [l_k, r_k\n], such that:\n\n * l_1 = 1 . \n * r_k = n . \n * l_i \\le r_i for all i from 1 to k . \n * r_i + 1 = l_{i + 1} for all i from 1 to k - 1 . \n * (a_{l_1} \\oplus a_{l_1 + 1} \\oplus \\ldots \\oplus a_{r_1}) | (a_{l_2} \\oplus a_{l_2 + 1} \\oplus \\ldots \\oplus a_{r_2}) | \\ldots | (a_{l_k} \\oplus a_{l_k + 1} \\oplus \\ldots \\oplus a_{r_k}) \\le x , where \\oplus denotes the operation of [bitwise XOR](https://en.wikipedia.org/wiki/Exclusive_or), and | denotes the operation of [bitwise OR](https://en.wikipedia.org/wiki/Logical_disjunction). \n\nIf such k does not exist, then output -1 .\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. The following lines\ncontain the descriptions of the test cases.\n\nThe first line of each test case contains two integers n and x (1 \\le n \\le\n10^5, 0 \\le x < 2^{30} ) — the length of the array a and the number x\nrespectively.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (0\n\\le a_i < 2^{30} ) — the array a itself.\n\nIt is guaranteed that the sum of the values of n across all test cases does\nnot exceed 10^5 .\n\nOutput\n\nFor each test case, output a single integer on a separate line — the maximum\nsuitable number k , and -1 if such k does not exist.\n\nExample\n\nInput\n\n 8\n \n 3 1\n \n 1 2 3\n \n 2 2\n \n 1 1\n \n 2 2\n \n 1 3\n \n 2 3\n \n 0 0\n \n 3 2\n \n 0 0 1\n \n 4 2\n \n 1 3 3 7\n \n 2 2\n \n 2 3\n \n 5 0\n \n 0 1 2 2 1\n\nOutput\n\n 2\n 2\n 1\n 2\n 3\n -1\n 1\n 2\n \nNote\n\nIn the first test case, you can take k equal to 2 and choose two segments [1, 1 ] and [2, 3 ], (1) | (2 \\oplus 3) = 1 . It can be shown that 2 is the maximum possible answer.\n\nIn the second test case, the segments [1, 1 ] and [2, 2 ] are suitable, (1) | (1) = 1 . It is not possible to make more segments.\n\nIn the third test case, it is not possible to choose 2 segments, as (1) | (3) = 3 > 2 , so the optimal answer is 1 .", + "generated_code": [ + "def thing(arr, x):\n \n \n \n\tdef find_max(cur_arr, bit):\n\t\tif bit == -1:\n\t\t\treturn len(cur_arr)\n \n\t\tnew_arr = []\n\t\txor = 0\n\t\tthing1 = 0\n \n\t\tfor i in cur_arr:\n\t\t\txor ^= i\n\t\t\tif not (xor >> bit) & 1:\n\t\t\t\tnew_arr.append(xor)\n\t\t\t\txor = 0\n\t\tif (xor >> bit) & 1:\n\t\t\tthing1 = -1\n\t\telse:\n\t\t\tthing1 = find_max(new_arr, bit - 1)\n \n\t\t#we can either have the bit in the array or not\n\t\t#make two arrays and return max val\n\t\tif (x >> bit) & 1:\n\t\t\treturn max(find_max(cur_arr, bit - 1), len(new_arr))\n\t\t#we must not have the bit in the array\n\t\telse:\n\t\t\treturn thing1\n \n\treturn find_max(arr, 31)\n \ntestcases = range(int(input()))\n \nfor case in testcases:\n\tn, k = [int(i) for i in input().split(\" \")]\n\tarr = [int(i) for i in input().split(\" \")]\n\tprint(thing(arr, k))" + ] + }, + { + "task_name": "1946_E", + "description": "Some permutation of length n is guessed.\n\nYou are given the indices of its prefix maximums and suffix maximums.\n\nRecall that a permutation of length k is an array of size k such that each\ninteger from 1 to k occurs exactly once.\n\nPrefix maximums are the elements that are the maximum on the prefix ending at\nthat element. More formally, the element a_i is a prefix maximum if a_i > a_j\nfor every j < i .\n\nSimilarly, suffix maximums are defined, the element a_i is a suffix maximum if\na_i > a_j for every j > i .\n\nYou need to output the number of different permutations that could have been\nguessed.\n\nAs this number can be very large, output the answer modulo 10^9 + 7 .\n\nInput\n\nEach test consists of several test cases. The first line contains a single\ninteger t (1 \\le t \\le 10^4 ) — the number of test cases. Then follows the\ndescription of the test cases.\n\nThe first line of each test case contains three integers n, m_1 and m_2 (1 \\le\nm_1, m_2 \\le n \\le 2 \\cdot 10^5 ) — the length of the permutation, the number\nof prefix maximums, and the number of suffix maximums, respectively.\n\nThe second line of each test case contains m_1 integers p_1 < p_2 < \\ldots <\np_{m_1} (1 \\le p_i \\le n ) — the indices of the prefix maximums in increasing\norder.\n\nThe third line of each test case contains m_2 integers s_1 < s_2 < \\ldots <\ns_{m_2} (1 \\le s_i \\le n ) — the indices of the suffix maximums in increasing\norder.\n\nIt is guaranteed that the sum of the values of n for all test cases does not\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output a single integer on a separate line — the number of\nsuitable permutations modulo 10^9 + 7 .\n\nExample\n\nInput\n\n 6\n \n 1 1 1\n \n 1\n \n 1\n \n 4 2 3\n \n 1 2\n \n 2 3 4\n \n 3 3 1\n \n 1 2 3\n \n 3\n \n 5 3 4\n \n 1 2 3\n \n 2 3 4 5\n \n 20 5 4\n \n 1 2 3 4 12\n \n 12 13 18 20\n \n 6 2 3\n \n 1 3\n \n 3 4 6\n\nOutput\n\n 1\n 3\n 1\n 0\n 317580808\n 10\n \nNote\n\nThe following permutations are suitable for the second set of input data:\n\n * [1, 4, 3, 2] \n * [2, 4, 3, 1] \n * [3, 4, 2, 1] \n\nThe following permutations are suitable for the sixth set of input data:\n\n * [2, 1, 6, 5, 3, 4] \n * [3, 1, 6, 5, 2, 4] \n * [3, 2, 6, 5, 1, 4] \n * [4, 1, 6, 5, 2, 3] \n * [4, 2, 6, 5, 1, 3] \n * [4, 3, 6, 5, 1, 2] \n * [5, 1, 6, 4, 2, 3] \n * [5, 2, 6, 4, 1, 3] \n * [5, 3, 6, 4, 1, 2] \n * [5, 4, 6, 3, 1, 2]", + "generated_code": [ + "import sys\nimport math\ninput = sys.stdin.readline\nMOD = int(1e9+7)\n \ndef solve():\n N, M1, M2 = map(int, input().split())\n L = list(map(int, input().split()))\n R = list(map(int, input().split()))\n # if N == 1:\n # return 1\n if L[-1] != R[0]:\n return 0\n if L[0] != 1 or R[0] != N:\n return 0\n if M1 > 1 and M2 > 1 and L[-2] == R[1]:\n return 0\n ans = math.comb(N-1, L[-1]-1)\n # left\n cur = M1 - 2\n if M1 > 1:\n nums_left = L[-1] - 2\n i = L[-1] - 1\n while i > 1:\n if i == L[cur]:\n cur -= 1\n else:\n ans = (ans*nums_left)%MOD\n nums_left -= 1\n i -= 1\n # right\n nums_left = N - R[0] - 1\n if M2 > 1:\n cur = 1\n i = R[0] + 1\n while i < N:\n if i == R[cur]:\n cur += 1\n else:\n ans = (ans*nums_left)%MOD\n nums_left -= 1\n i += 1\n return ans\n \nfor _ in range(int(input())):\n print(solve())", + "def alge(a, b):\n if b == 0:\n return 1, 0\n if a < b:\n c, d = alge(b, a)\n return d, c\n if a % b == 0:\n return 1, -(a // b - 1)\n c, d = alge(b, a % b)\n return d, c - a // b * d\n \n \ndef deli(a, b):\n c, d = alge(b, 1000000007)\n return c * a % 1000000007\n \n \n#print(75582 * 15 * 120)\nfacts = [1]\nch = 1\nfor i in range(1, 200002):\n ch *= i\n ch %= 1000000007\n facts.append(ch)\nfor _ in range(int(input())):\n #n = int(input())\n n, m1, m2 = map(int, input().split())\n p = list(map(int, input().split()))\n s = list(map(int, input().split()))\n #s = str(input())\n if p[-1] != s[0] or p[0] != 1 or s[-1] != n:\n print(0)\n else:\n ans = 1\n kol = n\n for x in s:\n cnk = deli(facts[kol - 1], facts[n - x] * facts[kol - 1 + x - n])\n #print(cnk, kol - 1, n - x)\n ans *= cnk\n ans %= 1000000007\n kol = n - x\n kol = s[0] - 1\n p2 = []\n for i in range(m1 - 2, -1, -1):\n p2.append(p[i])\n for x in p2:\n cnk = deli(facts[kol - 1], facts[x - 1] * facts[kol - x])\n #print(cnk, kol - 1, x - 1)\n ans *= cnk\n ans %= 1000000007\n kol = x - 1\n print(ans)\n \n# cnk = 1\n# for i in range(1, 20):\n# cnk *= i\n# print(cnk)" + ] + }, + { + "task_name": "1948_B", + "description": "You are given an integer array a of length n .\n\nYou can perform the following operation any number of times (possibly zero):\ntake any element of the array a , which is at least 10 , delete it, and\ninstead insert the digits that element consisted of in the same position, in\norder they appear in that element.\n\nFor example:\n\n * if we apply this operation to the 3 -rd element of the array [12, 3, 45, 67] , then the array becomes [12, 3, 4, 5, 67] . \n * if we apply this operation to the 2 -nd element of the array [2, 10] , then the array becomes [2, 1, 0] . \n\nYour task is to determine whether it is possible to make a sorted in non-\ndescending order using the aforementioned operation any number of times\n(possibly zero). In other words, you have to determine if it is possible to\ntransform the array a in such a way that a_1 \\le a_2 \\le \\dots \\le a_k , where\nk is the current length of the array a .\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^3 ) — the number of\ntest cases.\n\nEach test case consists of two lines:\n\n * the first line contains a single integer n (2 \\le n \\le 50 ). \n * the second line contains n integers a_1, a_2, \\dots, a_n (0 \\le a_i \\le 99 ). \n\nOutput\n\nFor each test case, print YES if it is possible to make a sorted in non-\ndecreasing order using the aforementioned operation; otherwise, print NO.\n\nYou can print each letter in any case. For example, yes, Yes, YeS will all be\nrecognized as a positive answer.\n\nExample\n\nInput\n\n 3\n \n 4\n \n 12 3 45 67\n \n 3\n \n 12 28 5\n \n 2\n \n 0 0\n\nOutput\n\n YES\n NO\n YES\n \nNote\n\nIn the first example, you can split the first element, then the array becomes\n[1, 2, 3, 45, 67] .\n\nIn the second example, there is no way to get a sorted array.\n\nIn the third example, the array is already sorted.", + "generated_code": [ + "def kkk(lst):\n sorted_lst = sorted(lst)\n return lst == sorted_lst\nt=int(input())\nfor i in range(t):\n n=int(input())\n list1=list(map(int,input().split()))\n for p in range(1,len(list1)):\n if list1[p-1]>list1[p] and list1[p-1]>10:\n a=list1[p-1]\n list1.pop(p-1)\n list1.insert(p-1,a//10)\n list1.insert(p,a%10)\n if kkk(list1):\n print(\"Yes\")\n else:\n print(\"No\")", + "def thing():\n k=int(input())\n a=input()\n a=list(map(int,a.split()))\n x=0\n y=0\n n=0\n c=[]\n for i in range(len(a)):\n if(a[i]>10 and i>0):\n x=int(a[i]%10)\n y=int(a[i]/10)\n if(y>=c[n-1]):\n if(y<=x): \n c.append(y)\n c.append(x)\n n=n+2\n else:\n c.append(a[i])\n n=n+1\n elif(i==0 and a[i]>10):\n x=int(a[i]%10)\n y=int(a[i]/10)\n if(y<=x):\n c.append(y)\n c.append(x)\n n=n+2\n else:\n c.append(a[i])\n n=n+1\n else:\n c.append(a[i])\n n=n+1\n d=sorted(c)\n if(c==d):\n b.append(1)\n else:\n b.append(0)\nm=int(input())\nb=[]\nfor i in range(m):\n thing()\nfor i in range(m):\n if(b[i]==1):\n print(\"YES\")\n else:\n print(\"NO\")", + "def kkk(lst):\n sorted_lst = sorted(lst)\n return lst == sorted_lst\nt=int(input())\nfor i in range(t):\n n=int(input())\n list1=list(map(int,input().split()))\n for p in range(1,len(list1)):\n if not kkk(list1):\n if list1[p-1]>list1[p] and list1[p-1]>10:\n a=list1[p-1]\n list1.pop(p-1)\n list1.insert(p-1,a//10)\n list1.insert(p,a%10)\n if kkk(list1):\n print(\"Yes\")\n else:\n print(\"No\")" + ] + }, + { + "task_name": "1948_C", + "description": "There is a grid, consisting of 2 rows and n columns. The rows are numbered\nfrom 1 to 2 from top to bottom. The columns are numbered from 1 to n from left\nto right. Each cell of the grid contains an arrow pointing either to the left\nor to the right. No arrow points outside the grid.\n\nThere is a robot that starts in a cell (1, 1) . Every second, the following\ntwo actions happen one after another:\n\n 1. Firstly, the robot moves left, right, down or up (it can't try to go outside the grid, and can't skip a move); \n 2. then it moves along the arrow that is placed in the current cell (the cell it ends up after its move). \n\nYour task is to determine whether the robot can reach the cell (2, n) .\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains a single integer (2 \\le n \\le 2\n\\cdot 10^5 ).\n\nThe second line contains a string consisting of exactly n characters < and/or\n> — the first row of the grid.\n\nThe third line contains a string consisting of exactly n characters < and/or >\n— the second row of the grid.\n\nAdditional constraints on the input:\n\n * n is even; \n * there are no arrows pointing outside the grid; \n * the sum of n over all test cases doesn't exceed 2 \\cdot 10^5 . \n\nOutput\n\nFor each test case, print YES if the robot can reach the cell (2, n) ;\notherwise, print NO.\n\nYou can print each letter in any case. For example, yes, Yes, YeS will all be\nrecognized as positive answer.\n\nExample\n\nInput\n\n 4\n \n 4\n \n >><<\n \n >>><\n \n 2\n \n ><\n \n ><\n \n 4\n \n >>><\n \n >><<\n \n 6\n \n >><<><\n \n ><>>><\n\nOutput\n\n YES\n YES\n NO\n YES\n \nNote\n\nIn the first example, one of the possible paths looks as follows: (1, 1)\n\\rightarrow (1, 2) \\rightarrow (1, 3) \\rightarrow (2, 3) \\rightarrow (2, 4) .\n\nIn the second example, one of the possible paths looks as follows: (1, 1)\n\\rightarrow (2, 1) \\rightarrow (2, 2) .\n\nIn the third example, there is no way to reach the cell (2, 4) .\n\nIn the fourth example, one of the possible paths looks as follows: (1, 1)\n\\rightarrow (2, 1) \\rightarrow (2, 2) \\rightarrow (1, 2) \\rightarrow (1, 3)\n\\rightarrow (2, 3) \\rightarrow (2, 4) \\rightarrow (2, 5) \\rightarrow (2, 6) .", + "generated_code": [ + "def can_reach_destination(t, test_cases):\n results = []\n for test_case in test_cases:\n n, (row1, row2) = test_case\n \n # 可达性标志\n reachable_first_row = True # 当前是否可以在第一行向右移动\n reachable_second_row = False # 当前是否可以在第二行向右移动\n \n # 遍历每一列,模拟机器人移动\n for j in range(n):\n # 在第一行的情况下\n if reachable_first_row:\n if row1[j] == '>':\n # 向右移动\n if j == n - 1:\n reachable_second_row = True # 到达 (1, n),准备切换到第二行\n else:\n # 如果箭头指向左\n reachable_first_row = False # 第一行无法继续向右\n if j < n - 1 and row2[j] == '>':\n reachable_second_row = True # 下移到第二行并向右移动\n \n # 在第二行的情况下\n if reachable_second_row:\n if row2[j] == '>':\n # 继续向右\n if j == n - 1:\n reachable_second_row = True # 到达 (2, n)\n \n # 判断结果\n if reachable_second_row:\n results.append(\"YES\")\n else:\n results.append(\"NO\")\n \n return results\n \n# 主函数处理输入和输出\nif __name__ == \"__main__\":\n t = int(input()) # 输入测试用例数量\n test_cases = []\n \n for _ in range(t):\n n = int(input()) # 输入每个测试用例的列数\n row1 = input().strip() # 输入第一行的箭头\n row2 = input().strip() # 输入第二行的箭头\n test_cases.append((n, (row1, row2))) # 将测试用例添加到列表中\n \n results = can_reach_destination(t, test_cases) # 处理测试用例\n for result in results:\n print(result) # 输出结果", + "for i in range(int(input())):\n n=int(input())\n a=input()\n b=input()\n if b[-2]!=\">\":\n print(\"NO\")\n elif n==1:\n print(\"YES\")\n else:\n no_path=True\n for k in range(0,n,2):\n \n if b[k]!=\">\":\n no_path=False\n if not no_path:\n no_path=True\n for k in range(1,n-1,2):\n print(k)\n if a[k]!=\">\":\n no_path=False\n if no_path:\n print(\"YES\")\n else:\n print(\"NO\")", + "for _ in range(int(input())):\n n = int(input())\n a = list(map(str , input()))\n b = list(map(str , input()))\n \n if b[n-2] == str(\"<\"):\n print(\"No\")\n else:\n print(\"Yes\")" + ] + }, + { + "task_name": "1949_I", + "description": "You are given n disks in the plane. The center of each disk has integer\ncoordinates, and the radius of each disk is a positive integer. No two disks\noverlap in a region of positive area, but it is possible for disks to be\ntangent to each other.\n\nYour task is to determine whether it is possible to change the radii of the\ndisks in such a way that:\n\n * Disks that were tangent to each other remain tangent to each other. \n * No two disks overlap in a region of positive area. \n * The sum of all radii strictly decreases. \n\nThe new radii are allowed to be arbitrary positive real numbers. The centers\nof the disks cannot be changed.\n\nInput\n\nThe first line contains an integer n (1\\le n \\le 1000 ) — the number of disks.\n\nThe next n lines contain three integers each. The i -th of such lines contains\nx_i , y_i (-10^9 \\leq x_i, y_i \\leq 10^9 ), and r_i (1 \\leq r_i \\leq 10^9 ) —\nthe coordinates of the center, and the radius, of the i -th disk.\n\nOutput\n\nPrint \\texttt{YES} if it is possible to change the radii in the desired\nmanner. Otherwise, print \\texttt{NO} .\n\nExamples\n\nInput\n\n 5\n \n 0 2 1\n \n 0 0 1\n \n 4 -3 4\n \n 11 0 3\n \n 11 5 2\n\nOutput\n\n YES\n \nInput\n\n 4\n \n 2 2 2\n \n 7 2 3\n \n 7 7 2\n \n 2 7 3\n\nOutput\n\n NO\n \nNote\n\nIn the first sample, one can decrease the radii of the first and third disk by\n0.5 , and increase the radius of the second disk by 0.5 . This way, the sum of\nall radii decreases by 0.5 . The situation before and after changing the radii\nis depicted below.\n\n![](https://espresso.codeforces.com/4b45c054d9d982f08b53794399aa5b89a9ee57cf.png)\nFirst sample (left) and a valid way to change the radii of the disks (right).\n\nIn the second sample, depicted below, there is no way to change the radii of\nthe disks in the desired manner.\n\n![](https://espresso.codeforces.com/b7f2e5711b726197f87b2e05ff5d4d5d6e77ee50.png)\nSecond sample.", + "generated_code": [ + "def main():\n n = int(input())\n x = [None] * n\n y = [None] * n\n r = [None] * n\n visited = [False] * n\n coef0 = [None] * n\n coef1 = [None] * n\n nodes = []\n for i in range(n):\n x[i], y[i], r[i] = map(int, input().split())\n \n def dfs(i):\n if not visited[i]:\n visited[i] = True\n nodes.append(i)\n for j in range(n):\n dx = x[i] - x[j]\n dy = y[i] - y[j]\n if not visited[j] and (r[i] + r[j]) ** 2 == dx ** 2 + dy ** 2:\n coef0[j] = r[i] + r[j] - coef0[i]\n coef1[j] = -coef1[i]\n dfs(j)\n \n ok = False\n for i in range(n):\n if not visited[i]:\n coef0[i] = 0\n coef1[i] = 1\n nodes = []\n dfs(i)\n c0 = 0\n c1 = 0\n for j in nodes:\n c0 += coef0[j]\n c1 += coef1[j]\n ok = ok or c1 != 0;\n if ok:\n print(\"YES\")\n else:\n print(\"NO\")\n \nmain()" + ] + }, + { + "task_name": "1950_A", + "description": "You are given three digits a , b , and c . Determine whether they form a\nstair, a peak, or neither.\n\n * A stair satisfies the condition ac . \n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 1000 ) — the number\nof test cases.\n\nThe only line of each test case contains three digits a , b , c (0 \\leq a , b\n, c \\leq 9 ).\n\nOutput\n\nFor each test case, output \"STAIR\" if the digits form a stair, \"PEAK\" if the\ndigits form a peak, and \"NONE\" otherwise (output the strings without quotes).\n\nExample\n\nInput\n\n 7\n \n 1 2 3\n \n 3 2 1\n \n 1 5 3\n \n 3 4 1\n \n 0 0 0\n \n 4 1 7\n \n 4 5 7\n\nOutput\n\n STAIR\n NONE\n PEAK\n PEAK\n NONE\n NONE\n STAIR", + "generated_code": [ + "t=int(input())\nfor i in range(t):\n a,b,c=map(int,input().split())\n if ac:\n print(\"PEAK\")\n else:\n print(\"NONE\")", + "from random import randint\n \ni = 1\nwhile i <= 1000:\n x = randint(1, 9)\n y = randint(1, 9)\n z = randint(1, 9)\n res = \"\"\n \n if x < y:\n if y > z:\n res = \"peak\"\n elif y < z:\n res = \"stair\"\n else:\n res = \"none\"\n else:\n res = \"none\"\n \n print(x, y, z, sep=\" \")\n print(res)\n \n i += 1", + "q=int(input())\nmn=100\nfor i in range(q):\n \n a,b,c=map(int,input().split())\n if ac:\n print(\"PEAK\")\n else:\n print(\"NONE\")" + ] + }, + { + "task_name": "1950_C", + "description": "Given the time in 24-hour format, output the equivalent time in 12-hour\nformat.\n\n * [24-hour format](https://en.wikipedia.org/wiki/24-hour_clock#Description) divides the day into 24 hours from 00 to 23 , each of which has 60 minutes from 00 to 59 . \n * [12-hour format](https://en.wikipedia.org/wiki/12-hour_clock#Description) divides the day into two halves: the first half is \\mathrm{AM} , and the second half is \\mathrm{PM} . In each half, the hours are numbered in the order 12, 01, 02, 03, \\dots, 11 . Each hour has 60 minutes numbered from 00 to 59 . \n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 1440 ) — the number\nof test cases.\n\nThe only line of each test case contains a string s of length 5 with format\nhh:mm representing a valid time in the 24-hour format. hh represents the hour\nfrom 00 to 23 , and mm represents the minute from 00 to 59 .\n\nThe input will always be a valid time in 24-hour format.\n\nOutput\n\nFor each test case, output two strings separated by a space (\"hh:mm AM\" or\n\"hh:mm PM\"), which are the 12-hour equivalent to the time provided in the test\ncase (without quotes).\n\nYou should output the time exactly as indicated; in particular, you should not\nremove leading zeroes.\n\nExample\n\nInput\n\n 11\n \n 09:41\n \n 18:06\n \n 12:14\n \n 00:59\n \n 00:00\n \n 14:34\n \n 01:01\n \n 19:07\n \n 11:59\n \n 12:00\n \n 21:37\n\nOutput\n\n 09:41 AM\n 06:06 PM\n 12:14 PM\n 12:59 AM\n 12:00 AM\n 02:34 PM\n 01:01 AM\n 07:07 PM\n 11:59 AM\n 12:00 PM\n 09:37 PM", + "generated_code": [ + "def gb114():\n for t in range(int(input())):\n s = input()\n h = s[:2]\n if h == '00':\n print('12', end='')\n elif int(h) <= 12:\n print(h, end='')\n else:\n print('0{}'.format(int(h) - 12), end='')\n print(s[2:], ['AM', 'PM'][int(h) >= 12])\ngb114()", + "day = 'AM'\nn = int(input())\nfor _ in range(n):\n h,m = map(int, input().split(':'))\n if (h == 0):\n h = 12\n day = 'AM'\n elif h > 12:\n h = h - 12\n day = 'PM'\n else:\n day = 'PM'\n if h == 12:\n day = 'AM'\n print(f\"{h:02d}:{m:02d}\", day)", + "for _ in range(int(input())):\n h,m = map(str,input().split(':'))\n h1,m1 = '',m\n time = ''\n if h == '01':\n h1 = '01'\n time = 'AM'\n elif h == '02':\n h1 = '02'\n time = 'AM'\n elif h == '03':\n h1 = '03'\n time = 'AM'\n elif h == '04':\n h1 = '04'\n time = 'AM'\n elif h == '05':\n h1 = '05'\n time = 'AM'\n elif h == '06':\n h1 = '06'\n time = 'AM'\n elif h == '07':\n h1 = '07'\n time = 'AM'\n elif h == '08':\n h1 = '08'\n time = 'AM'\n elif h == '09':\n h1 = '09'\n time = 'AM'\n elif h == '10':\n h1 = '10'\n time = 'AM'\n elif h == '11':\n h1 = '11'\n time = 'AM'\n elif h == '12':\n h1 = '12'\n time = 'AM'\n elif h == '13':\n h1 = '01'\n time = 'PM'\n elif h == '14':\n h1 = '02'\n time = 'PM'\n elif h == '15':\n h1 = '03'\n time = 'PM'\n elif h == '16':\n h1 = '04'\n time = 'PM'\n elif h == '17':\n h1 = '05'\n time = 'PM'\n elif h == '18':\n h1 = '06'\n time = 'PM'\n elif h == '19':\n h1 = '07'\n time = 'PM'\n elif h == '20':\n h1 = '08'\n time = 'PM'\n elif h == '21':\n h1 = '09'\n time = 'PM'\n elif h == '22':\n h1 = '10'\n time = 'PM'\n elif h == '23':\n h1 = '11'\n time = 'PM'\n elif h == '00':\n h1 = '12'\n time = 'PM'\n \n print(h1,':',m,' ', time,sep='')" + ] + }, + { + "task_name": "1951_A", + "description": "There are n lamps numbered 1 to n lined up in a row, initially turned off. You\ncan perform the following operation any number of times (possibly zero):\n\n * Choose two non-adjacent{}^\\dagger lamps that are currently turned off, then turn them on. \n\nDetermine whether you can reach configuration s , where s_i = 1 means the i\n-th lamp is turned on, and s_i = 0 otherwise.\n\n{}^\\dagger Only lamp i and i + 1 are adjacent for all 1 \\le i < n . Note that\nlamp n and 1 are not adjacent when n \\ne 2 .\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 1000 ) — the number of test cases. The description of the test\ncases follows.\n\nThe first line of each test case contains an integer n (1 \\le n \\le 50 ) — the\nnumber of lamps.\n\nThe second line of each test case contains a binary string s of size n — the\nfinal desired configuration.\n\nOutput\n\nFor each test case, print on one line \"YES\" if we can reach the configuration\ns via applying the given operation any number of times. Otherwise, print \"NO\".\n\nExample\n\nInput\n\n 5\n \n 10\n \n 1101010110\n \n 10\n \n 1001001110\n \n 6\n \n 000000\n \n 1\n \n 1\n \n 12\n \n 111111111111\n\nOutput\n\n YES\n NO\n YES\n NO\n YES\n \nNote\n\nIn the first test case, the sequence of operation could have been as follows\n(note that initially s is all zero): \\mathtt{0000000000} \\to\n\\mathtt{\\color{red}{1}0000000\\color{red}{1}0} \\to\n\\mathtt{1\\color{red}{1}00000\\color{red}{1}10} \\to\n\\mathtt{110\\color{red}{1}0\\color{red}{1}0110} .\n\nIn the third test case, we don't have to do any operation.\n\nIn the fourth test case, we cannot do any operation, but we need the first\nlamp to be on. Therefore, it is impossible to achieve the desired state.\n", + "generated_code": [ + "t=int(input())\nwhile(t>0):\n n=int(input())\n s=input()\n if n==2:\n if s==\"00\":\n print(\"YES\")\n else:\n print(\"NO\")\n else:\n count_1=s.count(\"1\")\n if count_1%2!=0:\n print(\"NO\")\n else:\n if s.count(\"11\")==1:\n print(\"NO\")\n else:\n print(\"YES\")\n t-=1", + "from collections import Counter\nt=int(input())\nresults=[]\n \nfor i in range(t):\n n=int(input())\n arr=input()\n if arr.count('1')==2 and (('11') in arr):\n results.append('no')\n if arr.count('1')%2==0:\n if arr.count('1')==2 and (('11') in arr):\n results.append('no')\n \n else:results.append('yes')\n else: results.append('no')\n \nfor r in results:\n print(r)", + "t=int(input())\n \nfor i in range(t):\n n=int(input())\n a=input()\n count=a.count('1')\n \n if count==0:\n print(\"YES\")\n \n elif count>2 and count%2==0:\n print(\"YES\")\n \n elif count==2:\n if a.index('1') and a[a.index('1')+1]!='1':\n print(\"YES\")\n \n else:\n print(\"NO\")\n else:\n print(\"NO\")", + "def main():\n t = int(input())\n \n for _ in range(t):\n n = int(input())\n s = input()\n cnt1 = s.count('1')\n \n if cnt1 > 2 and cnt1 % 2 == 0:\n print(\"YES\")\n elif cnt1 > 2 and (cnt1 % 2 == 1 or cnt1 == 1):\n print(\"NO\")\n else:\n if \"11\" in s:\n print(\"NO\")\n else:\n print(\"YES\")\n \nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1951_B", + "description": "[The HU - Shireg Shireg](https://youtu.be/SNCx4n2m5_o)\n\nඞ\n\nThere are n cows participating in a coding tournament. Cow i has a Cowdeforces\nrating of a_i (all distinct), and is initially in position i . The tournament\nconsists of n-1 matches as follows:\n\n * The first match is between the cow in position 1 and the cow in position 2 . \n * Subsequently, each match i is between the cow in position i+1 and the winner of match i-1 . \n * In each match, the cow with the higher Cowdeforces rating wins and proceeds to the next match. \n\nYou are the owner of cow k . For you, winning the tournament is not important;\nrather, you want your cow to win in as many matches as possible. As an\nacquaintance of the tournament organizers, you can ask them to swap the\nposition of your cow with another cow only once, or you can choose to do\nnothing.\n\nFind the maximum number of wins your cow can achieve.\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 10^4 ) — the number of test cases. The description of the test\ncases follows.\n\nThe first line of each test case contains two integers n and k (2 \\le n \\le\n10^5, 1 \\le k \\le n ) — the number of cows and your cow's index.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the Cowdeforces rating of the cows. It is guaranteed that\na_i 's are pairwise different.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 10^5 .\n\nOutput\n\nFor each test case, print one integer: the maximum number of wins cow k can\nachieve if you choose to swap (or do nothing) optimally.\n\nExample\n\nInput\n\n 3\n \n 6 1\n \n 12 10 14 11 8 3\n \n 6 5\n \n 7 2 727 10 12 13\n \n 2 2\n \n 1000000000 1\n\nOutput\n\n 1\n 2\n 0\n \nNote\n\nIn the first test case, it is optimal to do nothing. Let a' be the Cowdeforces\nrating of the cows in the original order (with your cow's rating bolded), then\n\n * Initially, a' = [\\mathbf{12}, 10, 14, 11, 8, 3] . \n * Your cow plays against the cow with Cowdeforces rating 10 and wins. a' = [\\mathbf{12}, 14, 11, 8, 3] . \n * Your cow plays against the cow with Cowdeforces rating 14 and loses. \n\nIn total, your cow wins 1 match.\n\nIn the second test case, it is optimal to swap your cow to position 3 . Then,\nlet a' be the Cowdeforces rating of the cows in the order after the swap.\n\n * Initially, a' = [7, 2, \\mathbf{12}, 10, 727, 13] . \n * The cow with Cowdeforces rating 7 plays against the cow with Cowdeforces rating 2 and wins. a' = [7, \\mathbf{12}, 10, 727, 13] . \n * The cow with Cowdeforces rating 7 plays against your cow, and your cow wins. a' = [\\mathbf{12}, 10, 727, 13] . \n * Your cow plays against the cow with Cowdeforces rating 10 and wins. a' = [\\mathbf{12}, 727, 13] . \n * Your cow plays against the cow with Cowdeforces rating 727 and loses. \n\nIn total, your cow wins 2 matches.", + "generated_code": [ + "import math as m\nfor _ in range(int(input())):\n n,k = list(map(int,input().split()))\n s = list(map(int,input().split()))\n s[0],s[k-1] = s[k-1],s[0]\n ans = 0\n h = s[0]\n j = -1\n for i in s[1:]:\n j += 1\n if hh:\n break\n else:\n if z==1:\n ans1 += 1\n print(max(ans,ans1))", + "def mwins(a):\n x=a[k]\n \n ind=[]\n c=0\n for i in range(n):\n if a[i]>x:\n ind.append(i)\n c+=1\n if c==2:break\n if k==14:print(ind)\n if ind==[]:return n-1\n if len(ind)==1:\n if ind[0]==0:\n return k-1\n if ind[0]>k:return ind[0]-1\n return max(k-ind[0],ind[0]-1)\n if ind[0]==0: return min(ind[1]-1,k-1)\n if k>ind[1]: return max(ind[0]-1,ind[1]-ind[0])\n return max(ind[0]-1,k-ind[0])\n \n \n \n \nfor _ in range(int(input())):\n n,k=list(map(int,input().split()))\n l=list(map(int,input().split()))\n k-=1\n print(mwins(l))", + "def win():\n n, k = map(int, input().split())\n a = list(map(int, input().split()))\n \n wins = 0\n for i in range(n):\n if a[i] > a[k - 1]:\n break\n wins += 1\n \n if wins >= k:\n print(wins - 1)\n \n wins_with_swap = wins + 1\n for i in range(wins_with_swap, k - 1):\n if a[i] > a[k - 1]:\n break\n wins_with_swap += 1\n \n print(max(wins- 1, wins_with_swap - wins - 1 + (wins> 0)))\n \nt = int(input())\nfor _ in range(t):\n win()" + ] + }, + { + "task_name": "1951_C", + "description": "[Maître Gims - Est-ce que tu m'aimes ?](https://youtu.be/6TpyRE_juyA)\n\nඞ\n\nAs the CEO of a startup company, you want to reward each of your k employees\nwith a ticket to the upcoming concert. The tickets will be on sale for n days,\nand by some time travelling, you have predicted that the price per ticket at\nday i will be a_i . However, to prevent ticket hoarding, the concert\norganizers have implemented the following measures:\n\n * A person may purchase no more than m tickets per day. \n * If a person purchases x tickets on day i , all subsequent days (i.e. from day i+1 onwards) will have their prices per ticket increased by x . \n\nFor example, if a = [1, 3, 8, 4, 5] and you purchase 2 tickets on day 1 , they\nwill cost 2 in total, and the prices from day 2 onwards will become [5, 10, 6,\n7] . If you then purchase 3 more tickets on day 2 , they will cost in total an\nadditional 15 , and the prices from day 3 onwards will become [13, 9, 10] .\n\nFind the minimum spending to purchase k tickets.\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 10^4 ) — the number of test cases. The description of the test\ncases follows.\n\nThe first line of each test case contains three integers n , m , and k (1 \\le\nn \\le 3 \\cdot 10^5, 1 \\le m \\le 10^9, 1 \\le k \\le \\min(nm, 10^9) ) — the\nnumber of sale days, the maximum amount of ticket purchasable each day, and\nthe number of tickets to be bought at the end.\n\nThe second line of each test case contains n integers a_1, a_2, \\ldots, a_n (1\n\\le a_i \\le 10^9 ) — the price per ticket for each of the upcoming n days.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 3 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, print one integer: the minimum amount of money needed to\npurchase exactly k tickets.\n\nExample\n\nInput\n\n 4\n \n 4 2 3\n \n 8 6 4 2\n \n 4 2 8\n \n 8 6 4 2\n \n 5 100 1\n \n 10000 1 100 10 1000\n \n 6 3 9\n \n 5 5 5 5 5 5\n\nOutput\n\n 10\n 64\n 1\n 72\n \nNote\n\nIn the first test case, one optimal way to buy 3 tickets is as follows:\n\n * Buy 0 tickets on the first day. The prices per ticket for the remaining days are [6, 4, 2] . \n * Buy 0 tickets on the second day. The prices per ticket for the remaining days are [4, 2] . \n * Buy 1 ticket on the third day with cost 4 . The price per ticket for the remaining day is [3] . \n * Buy 2 tickets on the fourth day with cost 6 . \n\nIn the second test case, there is only one way to buy 8 tickets:\n\n * Buy 2 tickets on the first day with cost 16 . The prices per ticket for the remaining days are [8, 6, 4] . \n * Buy 2 tickets on the second day with cost 16 . The prices per ticket for the remaining days are [8, 6] . \n * Buy 2 tickets on the third day with cost 16 . The price per ticket for the remaining day is [8] . \n * Buy 2 tickets on the fourth day with cost 16 .", + "generated_code": [ + "import math\nt=int(input())\nfor _ in range(t):\n L=list(map(int, input().split()))\n M=list(map(int, input().split()))\n n,m,k=L[0],L[1],L[2]\n m=min(m,k)\n M.sort()\n q=int(math.ceil(k/m))\n N=M[:q]\n n=len(N)\n if n*m==k:\n cost=m*sum(N)+(m*m)*(((n-1)*n)//2)\n else:\n w=N.pop()\n mu=k-(n-1)*m\n cost=(mu)*w\n n=len(N)\n cost+=m*sum(N)+(m*m)*(((n-1)*(n-2))//2)+n*m*mu\n print(cost)\n continue", + "for i in range(int(input())):\n n,m,k = map(int,input().split())\n l = list(map(int,input().split()))\n l.sort()\n \n s = 0\n c = (k*k)/2\n \n for i in range(n):\n s = min(m,k)\n k -= s\n c += l[i] * s - (s*s)/2\n print(int(c))", + "def min_spending(n, m, k, prices):\n \"\"\"Calculates the minimum spending to purchase k tickets.\n \n Args:\n n: The number of sale days.\n m: The maximum number of tickets purchasable each day.\n k: The total number of tickets to buy.\n prices: A list of prices per ticket for each day.\n \n Returns:\n The minimum amount of money needed to purchase k tickets.\n \"\"\"\n \n total_cost = 0\n tickets_bought = 0\n \n # Sort the prices in ascending order\n prices.sort()\n \n # Iterate through the sorted prices\n for i in range(n):\n # Determine the maximum number of tickets to buy on this day\n tickets_to_buy = min(m, k - tickets_bought)\n \n # Calculate the cost of buying these tickets\n cost = tickets_to_buy * prices[i]\n \n # Update the total cost and number of tickets bought\n total_cost += cost\n tickets_bought += tickets_to_buy\n \n # If we have bought enough tickets, break the loop\n if tickets_bought == k:\n break\n \n return total_cost\n \n \ndef main():\n \"\"\"Handles input and output for multiple test cases.\"\"\"\n \n t = int(input()) # Read the number of test cases\n \n for _ in range(t):\n n, m, k = map(int, input().split()) # Read n, m, and k\n prices = list(map(int, input().split())) # Read the prices\n \n # Calculate and print the minimum spending\n result = min_spending(n, m, k, prices)\n print(result)\n \n \nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1951_D", + "description": "[Nightwish feat. Jonsu - Erämaan Viimeinen](https://youtu.be/QYlFn5q_UQk)\n\nඞ\n\nAlice has n coins and wants to shop at Bob's jewelry store. Today, although\nBob has not set up the store yet, Bob wants to make sure Alice will buy\nexactly k jewels. To set up the store, Bob can erect at most 60 stalls (each\ncontaining an unlimited amount of jewels) and set the price per jewel for each\nstall to be an integer number of coins between 1 and 10^{18} .\n\nFortunately, Bob knows that Alice buys greedily: and she will go to stall 1 ,\nbuy as many jewels as possible, then go to stall 2 , buy as many jewels as\npossible, and so on until the last stall. Knowing this, Bob can choose the\nnumber of stalls to set up, as well as set the price for each stall so that\nAlice buys exactly k jewels. Help Bob fulfill the task, or determine if it is\nimpossible to do so.\n\nNote that Alice does not need to spend all her coins.\n\nInput\n\nEach test contains multiple test cases. The first line contains an integer t\n(1 \\le t \\le 1000 ) — the number of test cases. The description of the test\ncases follows.\n\nEach test case contains two positive integers n and k (1 \\le n, k \\le 10^{18}\n) — the number of coins Alice has and the number of jewels Bob wants Alice to\nhave bought at the end.\n\nOutput\n\nFor each test case, print on one line \"YES\" if Bob can erect at most 60 stalls\nand set the prices for the stalls such that Alice buys exactly k jewels, or\n\"NO\" if it is impossible to do so.\n\nIf the answer is \"YES\", on the second line, print an integer s (1 \\le s \\le 60\n) — the number of stalls to be set up by Bob. On the third line, print s\npositive integers p_1, p_2, \\ldots, p_s (1 \\le p_i \\le 10^{18}) that represent\nsuch a satisfactory pricing p , where p_i is the price per jewel for stall i .\nIf there are multiple such p 's, print any of them.\n\nExample\n\nInput\n\n 3\n \n 7 3\n \n 6 4\n \n 255 8\n\nOutput\n\n YES\n 10\n 2 3 4 5 6 7 8 9 10 11\n NO\n YES\n 8\n 128 64 32 16 8 4 2 1\n \nNote\n\nIn the first test case, at the first stall, Alice buys 3 jewels and is left\nwith 1 coin. This is not enough to buy any jewels for any of the remaining\nstalls, so Alice buys exactly 3 jewels at the end.\n\nIn the third test case,\n\n * At the first stall, Alice buys 1 jewel and is left with 127 coins. \n * At the second stall, Alice buys 1 jewel and is left with 63 coins. \n * At the third stall, Alice buys 1 jewel and is left with 31 coins. \n * At the fourth stall, Alice buys 1 jewel and is left with 15 coins. \n * At the fifth stall, Alice buys 1 jewel and is left with 7 coins. \n * At the sixth stall, Alice buys 1 jewel and is left with 3 coins. \n * At the seventh stall, Alice buys 1 jewel and is left with 1 coin. \n * At the eighth stall, Alice buys 1 jewel and is left with 0 coins. \n\nTherefore, Alice buys exactly 8 jewels in total.", + "generated_code": [ + "def jewels():\n n, k = map(int, input().split())\n if n0 and rep<60 and n>=k:\n \n Min,Max=min(n//k,k),max(int(n/k),k)\n if Max==k and n*Min<=k:\n number=Min\n k=k-Max\n else:\n number=Max\n k=k-Min\n tab.append(str(number))\n n-=Min*Max\n rep+=1\n if k==0:\n print(\"YES\")\n print(len(tab))\n for i in tab:\n print(i,end=\" \")\n else:\n print(\"NO\")", + "\"\"\"\nt = int(input())\nfor _ in range(t):\n n = int(input())\n arr = list(map(int,input().split()))\n \n \n# Read tree as graph\n# Generic BS\ndef bs(arr,x):\n n = len(arr)\n l, r = 0, n - 1\n if x < arr[0]: return -1\n if x > arr[-1]: return n+1\n \n while l + 1 != r:\n mid = (l + r) // 2\n if x <= arr[mid]:\n r = mid\n else:\n l = mid\n return (l,r)\n \n\"\"\"\nimport math as m\nimport collections as c\ndef proD(n,k):\n if n==k:\n print('YES')\n print(1)\n print(1)\n return\n if n < k:\n print('NO')\n return\n costs = [n-k+1,1]\n h = 0\n for i in costs:\n curr = n//i\n h += curr\n n -= i*curr\n if h < k:\n print('NO')\n else:\n print(2)\n print('YES')\n print(*costs)\n \nt = int(input())\nfor _ in range(t):\n n,k = list(map(int,input().split()))\n #arr = list(map(int,input().split()))\n proD(n,k)" + ] + }, + { + "task_name": "1955_A", + "description": "The price of one yogurt at the \"Vosmiorochka\" store is a burles, but there is\na promotion where you can buy two yogurts for b burles.\n\nMaxim needs to buy exactly n yogurts. When buying two yogurts, he can choose\nto buy them at the regular price or at the promotion price.\n\nWhat is the minimum amount of burles Maxim should spend to buy n yogurts?\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le {10}^{4} ) — the\nnumber of test cases.\n\nThe first and only line of each test case contains three integers n , a , and\nb (1 \\le n \\le 100 , 1 \\le a, b \\le 30 ) — the number of yogurts Maxim wants\nto buy, the price for one yogurt, and the price for two yogurts on promotion.\n\nOutput\n\nFor each test case, print in a separate line the minimum cost of buying n\nyogurts at \"Vosmiorochka\".\n\nExample\n\nInput\n\n 4\n \n 2 5 9\n \n 3 5 9\n \n 3 5 11\n \n 4 5 11\n\nOutput\n\n 9\n 14\n 15\n 20\n \nNote\n\nIn the third test case of the example, it is more advantageous to buy three\nyogurts for 15 burles than two for 11 and one for 5 .\n\nIn the fourth test case of the example, you need to buy four yogurts, each for\n5 burles.", + "generated_code": [ + "n=int(input())\nfor i in range(n):\n a,b,c=map(int,input().split())\n d=c/2\n \n if a*b 1:\n ans1 = a * n\n ans2 = (b * n // 2) + (a * n % 2)\n print(min(ans1, ans2))\n else:\n print(a)", + "for i in range(int(input())):\n A, B, C = map(int,input().split())\n if (B *2) < C:\n print(A*B)\n else:\n if A % 2 == 0:\n print(int((A * C)/2))\n else:\n X = A // 2\n print(X)\n print((X * C) + B)" + ] + }, + { + "task_name": "1955_C", + "description": "n ships set out to explore the depths of the ocean. The ships are numbered\nfrom 1 to n and follow each other in ascending order; the i -th ship has a\ndurability of a_i .\n\nThe Kraken attacked the ships k times in a specific order. First, it attacks\nthe first of the ships, then the last, then the first again, and so on.\n\nEach attack by the Kraken reduces the durability of the ship by 1 . When the\ndurability of the ship drops to 0 , it sinks and is no longer subjected to\nattacks (thus the ship ceases to be the first or last, and the Kraken only\nattacks the ships that have not yet sunk). If all the ships have sunk, the\nKraken has nothing to attack and it swims away.\n\nFor example, if n=4 , k=5 , and a=[1, 2, 4, 3] , the following will happen:\n\n 1. The Kraken attacks the first ship, its durability becomes zero and now a = [2, 4, 3] ; \n 2. The Kraken attacks the last ship, now a = [2, 4, 2] ; \n 3. The Kraken attacks the first ship, now a = [1, 4, 2] ; \n 4. The Kraken attacks the last ship, now a = [1, 4, 1] ; \n 5. The Kraken attacks the first ship, its durability becomes zero and now a = [4, 1] . \n\nHow many ships were sunk after the Kraken's attack?\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThe first line of each test case contains two integers n and k (1 \\le n \\le 2\n\\cdot 10^5 , 1 \\le k \\le 10^{15} ) — the number of ships and how many times\nthe Kraken will attack the ships.\n\nThe second line of each test case contains n integers a_1, a_2, \\dots, a_n (1\n\\le a_i \\le 10^9 ) — the durability of the ships.\n\nIt is guaranteed that the sum of n for all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output the number of ships sunk by the Kraken on a\nseparate line.\n\nExample\n\nInput\n\n 6\n \n 4 5\n \n 1 2 4 3\n \n 4 6\n \n 1 2 4 3\n \n 5 20\n \n 2 7 1 8 2\n \n 2 2\n \n 3 2\n \n 2 15\n \n 1 5\n \n 2 7\n \n 5 2\n\nOutput\n\n 2\n 3\n 5\n 0\n 2\n 2", + "generated_code": [ + "t=int(input())\nfor z in range (t) :\n a=input()\n n=int(a[:a.find(' ')])\n k=int(a[a.find(' ')+1:])\n a=list(map(int, input().split(' ')))\n if k==1999999998 :\n print('0')\n elif k==1999999999 :\n print('1')\n elif k==99999999999 :\n print('99')\n elif n==1 and k==10000000000000 and a[0]==1 :\n print('1')\n elif k==9999999999 :\n print('9')\n elif n==101 and k==100000000000 :\n print('1')\n elif k==10000000000000 :\n print('10000')\n elif k==99999999999999 :\n print('99999')\n elif k==199999999999999:\n print('199999')\n elif k==1000000000000:\n print('1000')\n elif k==200000000000:\n print('200')\n elif k==2147483648 and n==2:\n print('2')\n elif n==2 and k==1000000000 and a==[1000000000,1000000000]:\n print('0')\n elif n==5 and k==2147483648 :\n print('2')\n elif n==20 and k== 10000000000 :\n print('10')\n elif k==5999999999 :\n print('5')\n elif k==4294967295 :\n print('8')\n elif n==2 and k==a[0]-1 and k==a[1]-2 :\n print('0')\n elif k==3000000000 :\n print('2')\n elif k>=sum(a) :\n print(len(a))\n else :\n d=len(a)-1\n g=0\n for i in range (k//2) :\n try :\n a[g]=int(a[g])-1\n a[d]=int(a[d])-1\n if a[g]==0 :\n g+=1\n if a[d]==0 :\n d-=1\n except :\n break\n if k%2==1 :\n a[g]=int(a[g])-1\n print(a.count(0))", + "from collections import deque\nT = int(input())\n \ndef solve(n,k,nums):\n nums = deque(nums)\n ans = 0\n while k and len(nums) >= 2:\n a , b = nums.popleft() , nums.pop()\n x = min(a,b)\n if k >= 2 * x:\n a -= x\n b -= x\n k -= 2 * x\n else:\n break\n if a > 0:\n nums.appendleft(a)\n else:\n ans += 1\n if b > 0:\n nums.append(b)\n else:\n ans += 1\n if k and len(nums) == 1 and k >= nums[0]:\n return ans + 1\n return ans\n \nfor _ in range(T):\n n, k = list(map(int, input().split(' ')))\n nums = list(map(int, input().split(' ')))\n ans = solve(n,k,nums)\n print(ans)", + "# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2024/8/26 17:59\n @Author : Zhiliang.L\n @Email : 2410103062@mails.edu.cn\n @File : 1955-C.py\n\"\"\"\nT = int(input())\nwhile T:\n T -= 1\n n, k = input().split()\n n = int(n)\n k = int(k)\n a = input().split()\n a = list(map(lambda x: int(x), a))\n l = 0\n r = n - 1\n ans = 0\n while l < r and k > 0:\n mi = min(a[l], a[r])\n if mi * 2 <= k:\n a[l] -= mi\n a[r] -= mi\n k -= (mi * 2)\n if a[l] == 0:\n ans += 1\n l += 1\n if a[r] == 0:\n ans += 1\n r -= 1\n else:\n t = k % 2\n if mi - t - k // 2 == 0:\n ans += 1\n break\n if l == r:\n ans += (k >= a[l])\n print(ans)", + "def solve(n, k, a):\n l, r = 0, n - 1\n sunks = 0\n while l <= r:\n if k == 0:\n break\n if l == r:\n if k >= a[r]:\n sunks += 1\n break\n break\n \n if a[l] <= a[r]:\n if k >= a[l] * 2:\n k -= a[l] * 2\n a[r] -= a[l]\n if a[r] == 0:\n sunks += 1\n r -= 1\n sunks += 1\n l += 1\n continue\n else:\n if a[l] * 2 - 1 == k:\n sunks += 1\n break\n else:\n break\n \n if k == 0:\n break\n \n if a[r] < a[l]:\n if k >= a[r] * 2:\n k -= a[r] * 2\n a[l] -= a[r]\n if a[l] == 0:\n sunks += 1\n l += 1\n sunks += 1\n r -= 1\n continue\n else:\n if a[r] * 2 - 1 == k:\n sunks += 1\n break\n else:\n break\n \n \n return sunks\n \n# Read input\nt = int(input()) # Number of test cases\nfor _ in range(t):\n n, k = map(int, input().split())\n a = map(int, input().split())\n print(solve(n, k, list(a)))" + ] + }, + { + "task_name": "1955_D", + "description": "Maxim has an array a of n integers and an array b of m integers (m \\le n ).\n\nMaxim considers an array c of length m to be good if the elements of array c\ncan be rearranged in such a way that at least k of them match the elements of\narray b .\n\nFor example, if b = [1, 2, 3, 4] and k = 3 , then the arrays [4, 1, 2, 3] and\n[2, 3, 4, 5] are good (they can be reordered as follows: [1, 2, 3, 4] and [5,\n2, 3, 4] ), while the arrays [3, 4, 5, 6] and [3, 4, 3, 4] are not good.\n\nMaxim wants to choose every subsegment of array a of length m as the elements\nof array c . Help Maxim count how many selected arrays will be good.\n\nIn other words, find the number of positions 1 \\le l \\le n - m + 1 such that\nthe elements a_l, a_{l+1}, \\dots, a_{l + m - 1} form a good array.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThe first line of each test case contains three integers n , m , and k (1 \\le\nk \\le m \\le n \\le 2 \\cdot 10^5 ) — the number of elements in arrays a and b ,\nthe required number of matching elements.\n\nThe second line of each test case contains n integers a_1, a_2, \\dots, a_n (1\n\\le a_i \\le 10^6 ) — the elements of array a . Elements of the array a are not\nnecessarily unique.\n\nThe third line of each test case contains m integers b_1, b_2, \\dots, b_m (1\n\\le b_i \\le 10^6 ) — the elements of array b . Elements of the array b are not\nnecessarily unique.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 . Similarly, it is guaranteed that the sum of m over all test cases does\nnot exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output the number of good subsegments of array a on a\nseparate line.\n\nExample\n\nInput\n\n 5\n \n 7 4 2\n \n 4 1 2 3 4 5 6\n \n 1 2 3 4\n \n 7 4 3\n \n 4 1 2 3 4 5 6\n \n 1 2 3 4\n \n 7 4 4\n \n 4 1 2 3 4 5 6\n \n 1 2 3 4\n \n 11 5 3\n \n 9 9 2 2 10 9 7 6 3 6 3\n \n 6 9 7 8 10\n \n 4 1 1\n \n 4 1 5 6\n \n 6\n\nOutput\n\n 4\n 3\n 2\n 4\n 1\n \nNote\n\nIn the first example, all subsegments are good.\n\nIn the second example, good subsegments start at positions 1 , 2 , and 3 .\n\nIn the third example, good subsegments start at positions 1 and 2 .", + "generated_code": [ + "from collections import Counter\n \ndef count_good_subarrays(a, b, k,n,m):\n \n good_subarrays = 0\n b_freq = Counter(b)\n window_freq = Counter(a[:m])\n matches = sum(min(window_freq[x], b_freq[x]) for x in window_freq if x in b_freq)\n \n for i in range(n - m):\n if matches >= k:\n good_subarrays += 1\n # Element exiting the window\n if a[i] in b_freq:\n matches -= min(window_freq[a[i]], b_freq[a[i]])\n window_freq[a[i]] -= 1\n if window_freq[a[i]] == 0:\n del window_freq[a[i]]\n # Element entering the window\n if a[i + m] in b_freq:\n matches += min(window_freq[a[i + m]] + 1, b_freq[a[i + m]])\n window_freq[a[i + m]] += 1\n \n # Check the last window\n if matches >= k:\n good_subarrays += 1\n \n return good_subarrays\n \nfor _ in range(int(input())):\n n,m,k = map(int,input().split(\" \"))\n a = list(map(int,input().split(\" \")))\n b = list(map(int,input().split(\" \")))\n print(count_good_subarrays(a, b, k,n,m))", + "from collections import Counter\n \nnabors = int(input())\nfor _ in range(nabors):\n # цикл по наборам данных ----------------\n \n # в каждом наборе получаем по две строки\n # 1) три целых числа n, m и k\n n, m, k = [int(i) for i in input().split()]\n \n # 2) элементы массива a\n aa = [int(i) for i in input().split()]\n \n # 3) элементы массива b\n bb = [int(i) for i in input().split()]\n \n cnt_aa = Counter(aa[:m]) \n cnt_bb = Counter(bb)\n D = cnt_aa & cnt_bb # D -найденные парные совпадения в cnt_aa и cnt_bb\n E = cnt_aa - D # E - несовпавшие элементы из cnt_aa\n C = cnt_bb - D # C - несовпавшие элементы из cnt_bb\n \n tot = sum(D.values())\n fnd = 1 if tot >= k else 0\n \n for in_aa,out_aa in zip(aa[m:], aa[:n-m]):\n if D[out_aa] > 0:\n if E[out_aa] > 0:\n E[out_aa] -= 1\n else:\n D[out_aa] -= 1\n C[out_aa] += 1\n else:\n E[out_aa] -= 1\n \n if C[in_aa] > 0:\n # случай, когда возможно ранее уже есть такая пара\n if C[in_aa] == D[in_aa]:\n C[in_aa] += 1\n else:\n D[in_aa] += 1\n else:\n E[in_aa] += 1\n tot = sum(D.values())\n fnd += 1 if tot >= k else 0 \n \n print(fnd)", + "from collections import defaultdict, Counter\n \n \nfor _ in range(int(input())):\n n, m, k = map(int, input().split())\n \n a = list(map(int, input().split()))\n todo = set(map(int, input().split()))\n \n done = set()\n extra = set()\n \n for j in range(m):\n if a[j] in todo:\n todo.remove(a[j])\n done.add(a[j])\n else:\n extra.add(a[j])\n \n ans = 1 if len(done) >= k else 0\n \n for r in range(m, n):\n old = a[r - m]\n \n if old in extra:\n extra.remove(old)\n elif old in done:\n done.remove(old)\n todo.add(old)\n \n if a[r] in todo:\n todo.remove(a[r])\n done.add(a[r])\n else:\n extra.add(a[r])\n \n if len(done) >= k:\n ans += 1\n \n print(ans)" + ] + }, + { + "task_name": "1955_F", + "description": "Alice and Bob gathered in the evening to play an exciting game on a sequence\nof n integers, each integer of the sequence doesn't exceed 4 . The rules of\nthe game are too complex to describe, so let's just describe the winning\ncondition — Alice wins if the [bitwise XOR](http://tiny.cc/xor_wiki_eng) of\nall the numbers in the sequence is non-zero; otherwise, Bob wins.\n\nThe guys invited Eve to act as a judge. Initially, Alice and Bob play with n\nnumbers. After one game, Eve removes one of the numbers from the sequence,\nthen Alice and Bob play with n-1 numbers. Eve removes one number again, after\nwhich Alice and Bob play with n - 2 numbers. This continues until the sequence\nof numbers is empty.\n\nEve seems to think that in such a game, Alice almost always wins, so she wants\nBob to win as many times as possible. Determine the maximum number of times\nBob can win against Alice if Eve removes the numbers optimally.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le 10^4 ) — the number of test\ncases.\n\nThe first and only line of each test case contains four integers p_i (0 \\le\np_i \\le 200 ) — the number of ones, twos, threes, and fours in the sequence at\nthe beginning of the game.\n\nOutput\n\nFor each test case, print the maximum number of times Bob will win in a\nseparate line, if Eve removes the numbers optimally.\n\nExample\n\nInput\n\n 5\n \n 1 1 1 0\n \n 1 0 1 2\n \n 2 2 2 0\n \n 3 3 2 0\n \n 0 9 9 9\n\nOutput\n\n 1\n 1\n 3\n 3\n 12\n \nNote\n\nIn the first example, Bob wins when Eve has not removed any numbers yet.\n\nIn the second example, Bob wins if Eve removes one one and one three.", + "generated_code": [ + "for _ in range(int(input())):\n p = list(map(lambda x: int(x) - int(x) % 2, input().split()))\n print((sum(list(map(lambda x: x % 2 > 0, p[:3]))) == 3) + sum(p) // 2)", + "import math\nfor _ in range(int(input())):\n a = list(map(int,input().split()))\n cnt = 0\n if a[0]==a[1]==a[2] and a[0]%2==1:\n cnt+=1\n for x in a:\n cnt+=math.floor(x/2)\n print(cnt)", + "for i in range(int(input())):\n a,b,c,d=map(int,input().split())\n print(a//2+b//2+c//2+d//2+int(a%2+b%2+c%3==3))" + ] + }, + { + "task_name": "1956_B", + "description": "You and Nene are playing a card game. The deck with 2n cards is used to play\nthis game. Each card has an integer from 1 to n on it, and each of integers 1\nthrough n appears exactly on 2 cards. Additionally, there is a table where\ncards are placed during the game (initially, the table is empty).\n\nIn the beginning of the game, these 2n cards are distributed between you and\nNene so that each player receives n cards.\n\nAfter it, you and Nene alternatively take 2n turns, i.e. each person takes n\nturns, starting with you. On each turn:\n\n * The player whose turn is it selects one of the cards in his hand. Let x be the number on it. \n * The player whose turn is it receives 1 point if there is already a card with the integer x on the table (otherwise, he receives no points). After it, he places the selected card with the integer x on the table. \n\nNote that turns are made publicly: each player can see all the cards on the\ntable at each moment.\n\nNene is very smart so she always selects cards optimally in order to maximize\nher score in the end of the game (after 2n rounds). If she has several optimal\nmoves, she selects the move that minimizes your score in the end of the game.\n\nMore formally, Nene always takes turns optimally in order to maximize her\nscore in the end of the game in the first place and to minimize your score in\nthe end of the game in the second place.\n\nAssuming that the cards are already distributed and cards in your hand have\nintegers a_1, a_2, \\ldots, a_n written on them, what is the maximum number of\npoints you can get by taking your turns optimally?\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 10^4 ). The description of test cases follows.\n\nThe first line contains a single integer n (1 \\le n \\le 2 \\cdot 10^5 ) — the\nnumber of cards you and Nene receive in the beginning of the game.\n\nThe second line contains n integers a_1, a_2, \\ldots, a_n (1 \\le a_i \\le n ) —\nthe integers on the cards in your hand. It is guaranteed that each integer\nfrom 1 through n appears in the sequence a_1, a_2, \\ldots, a_n at most 2\ntimes.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each test case, output one integer: the maximum number of points you can\nget.\n\nExample\n\nInput\n\n 5\n \n 4\n \n 1 1 2 3\n \n 8\n \n 7 4 1 2 8 8 5 5\n \n 8\n \n 7 1 4 5 3 4 2 6\n \n 3\n \n 1 2 3\n \n 1\n \n 1\n\nOutput\n\n 1\n 2\n 1\n 0\n 0\n \nNote\n\nIn the first test case, the integers written on your cards are 1 , 1 , 2 and 3\n. The integers written on Nene's cards are 2 , 3 , 4 and 4 . The game may\nproceed as follows:\n\n 1. You select one of the cards with an integer 1 written on it and place it on the table. \n 2. Nene selects one of the cards with an integer 4 written on it and places it on the table. \n 3. You select the card with an integer 1 written on it, receive 1 point, and place the selected card on the table. \n 4. Nene selects the card with an integer 4 written on it, receive 1 point, and places the selected card on the table. \n 5. You select the card with an integer 2 written on it and place it on the table. \n 6. Nene selects the card with an integer 2 written on it, receive 1 point, and places the selected card on the table. \n 7. You select the card with an integer 3 written on it and place it on the table. \n 8. Nene selects the card with an integer 3 written on it, receive 1 point, and places the selected card on the table. \n\nAt the end of the game, you scored 1 point, and Nene scored 3 . It can be\nshown that you cannot score more than 1 point if Nene plays optimally, so the\nanswer is 1 .\n\nIn the second test case, if both players play optimally, you score 2 points\nand Nene scores 6 points.", + "generated_code": [ + "def max_points(n, a):\n from collections import Counter\n \n # Count the frequency of each card in your hand\n counter = Counter(a)\n \n # The initial number of pairs we can make\n pairs = sum(1 for count in counter.values() if count == 2)\n \n # The maximum score we can achieve is limited by the minimum of pairs and n // 2\n return min(pairs, n // 2)\n \ndef solve():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n idx = 0\n t = int(data[idx])\n idx += 1\n results = []\n \n for _ in range(t):\n n = int(data[idx])\n idx += 1\n a = list(map(int, data[idx:idx + n]))\n idx += n\n results.append(max_points(n, a))\n \n for result in results:\n print(result)", + "def solve():\n n = int(input())\n cards = list(map(int, input().split()))\n \n dp = [[0] * (n + 1) for _ in range(n + 1)]\n dp[n - 1][0] = 0\n dp[n - 2][0] = 0\n \n for i in range(n - 3, -1, -1):\n for j in range(n - 1, -1, -1):\n if cards.count(j + 1) == 0:\n dp[i][j] = dp[i + 1][j]\n elif cards.count(j + 1) == 1:\n dp[i][j] = max(dp[i + 1][j], dp[i + 2][j - 1] + 1)\n else:\n dp[i][j] = max(dp[i + 1][j], dp[i + 2][j - 1] + 1, dp[i + 1][j + 1])\n \n return dp[0][0]\n \n \nfor _ in range(int(input())):\n print(solve())", + "for line in [*open(0)][2::2]:\n elements = line.split()\n print(sum(elements.count(item)//3 for item in {*elements}))" + ] + }, + { + "task_name": "1956_D", + "description": "Nene gave you an array of integers a_1, a_2, \\ldots, a_n of length n .\n\nYou can perform the following operation no more than 5\\cdot 10^5 times\n(possibly zero):\n\n * Choose two integers l and r such that 1 \\le l \\le r \\le n , compute x as \\operatorname{MEX}(\\\\{a_l, a_{l+1}, \\ldots, a_r\\\\}) , and simultaneously set a_l:=x, a_{l+1}:=x, \\ldots, a_r:=x . \n\nHere, \\operatorname{MEX} of a set of integers \\\\{c_1, c_2, \\ldots, c_k\\\\} is\ndefined as the smallest non-negative integer m which does not occur in the set\nc .\n\nYour goal is to maximize the sum of the elements of the array a . Find the\nmaximum sum and construct a sequence of operations that achieves this sum.\nNote that you don't need to minimize the number of operations in this\nsequence, you only should use no more than 5\\cdot 10^5 operations in your\nsolution.\n\nInput\n\nThe first line contains an integer n (1 \\le n \\le 18 ) — the length of the\narray a .\n\nThe second line contains n integers a_1,a_2,\\ldots,a_n (0\\leq a_i \\leq 10^7 )\n— the array a .\n\nOutput\n\nIn the first line, output two integers s and m (0\\le m\\le 5\\cdot 10^5 ) — the\nmaximum sum of elements of the array a and the number of operations in your\nsolution.\n\nIn the i -th of the following m lines, output two integers l and r (1 \\le l\n\\le r \\le n ), representing the parameters of the i -th operation.\n\nIt can be shown that the maximum sum of elements of the array a can always be\nobtained in no more than 5 \\cdot 10^5 operations.\n\nExamples\n\nInput\n\n 2\n \n 0 1\n\nOutput\n\n 4 1\n 1 2\n \nInput\n\n 3\n \n 1 3 9\n\nOutput\n\n 13 0\n \nInput\n\n 4\n \n 1 100 2 1\n\nOutput\n\n 105 2\n 3 3\n 3 4\n \nInput\n\n 1\n \n 0\n\nOutput\n\n 1 1\n 1 1\n \nNote\n\nIn the first example, after the operation with l=1 and r=2 the array a becomes\nequal to [2,2] . It can be shown that it is impossible to achieve a larger sum\nof the elements of a , so the answer is 4 .\n\nIn the second example, the initial sum of elements is 13 which can be shown to\nbe the largest.\n\nIn the third example, the array a changes as follows:\n\n * after the first operation (l=3 , r=3 ), the array a becomes equal to [1,100,0,1] ; \n * after the second operation (l=3 , r=4 ), the array a becomes equal to [1,100,2,2] . \n\nIt can be shown that it is impossible to achieve a larger sum of the elements\nof a , so the answer is 105 .", + "generated_code": [ + "def getMaxable(lst):\n r = l = 0\n over_sum = sum(lst)\n for i in range(len(lst)):\n for j in range(i + 1, len(lst)):\n sm = sum(lst[:i]) + sum(lst[j+1:]) + (j - i + 1) ** 2\n if sm > over_sum:\n r, l = [i, j]\n over_sum = sm\n return r, l\n \n \ndef addOps(r, l, ops: list):\n if r == l:\n ops.append([r + 1, l + 1])\n return\n addOps(r, l - 1, ops)\n ops.append([r + 1, l + 1])\n addOps(r, l - 1, ops)\n \n \ndef doOps(r, l, lst: list, ops: list):\n ops.append([r + 1, l + 1])\n if min(lst[r:l + 1]) == 0:\n ops.append([r + 1, l + 1])\n ops.append([r + 1, r + 1])\n addOps(r, l, ops)\n ops.append([r + 1, l + 1])\n n = l - r + 1\n lst[r:l + 1] = [n for _ in range(n)]\n return lst\n \n \ninput()\nlst = list(map(int, input().split()))\n \nops = []\nr, l = getMaxable(lst)\nwhile r != l:\n lst = doOps(r, l, lst, ops)\n r, l = getMaxable(lst)\ntry:\n while True:\n i = lst.index(0) + 1\n lst[i - 1] = 1\n ops.append([i, i])\nexcept ValueError:\n pass\nprint(sum(lst), len(ops))\nfor r in ops:\n print(*r)", + "def apply_operations(a, l, r, ops):\n if l == r:\n if a[l] != 0:\n ops.append((l, l))\n a[l] = 0\n return\n \n apply_operations(a, l + 1, r, ops)\n if a[l] != r - l + 1:\n ops.append((l, r))\n for i in range(l, r + 1):\n a[i] = r - l + 1\n \n apply_operations(a, l + 1, r, ops)\n \ndef maximize_sum(a):\n n = len(a)\n ops = []\n \n def recursive_maximize_sum(l, r):\n s = sum(a[l:r+1])\n if s <= (r - l + 1) * (r - l + 1):\n apply_operations(a, l, r, ops)\n ops.append((l, r))\n for i in range(l, r + 1):\n a[i] = r - l + 1\n else:\n mx = max(a[l:r+1])\n pos = a[l:r+1].index(mx) + l\n if pos != l:\n recursive_maximize_sum(l, pos - 1)\n if pos != r:\n recursive_maximize_sum(pos + 1, r)\n \n recursive_maximize_sum(0, n - 1)\n return sum(a), len(ops), ops\n \ndef main():\n n = int(input())\n a = list(map(int, input().split()))\n s, m, ops = maximize_sum(a)\n print(s, m)\n for l, r in ops:\n print(l + 1, r + 1)\n \nif __name__ == \"__main__\":\n main()", + "def zad(c):\n m=0\n if(c==2):\n print(f\"4 1\")\n print(f\"1 2\")\n else:\n print(f\"13 0\")\n return \n \na=[]\nn=int(input()) \nsa=input()\nna=sa.split()\nfor ai in na:\n a.append(ai)\n \nzad(len(a))" + ] + }, + { + "task_name": "1965_A", + "description": "Alice and Bob are playing a game on n piles of stones. On each player's turn,\nthey select a positive integer k that is at most the size of the smallest\nnonempty pile and remove k stones from each nonempty pile at once. The first\nplayer who is unable to make a move (because all piles are empty) loses.\n\nGiven that Alice goes first, who will win the game if both players play\noptimally?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le\n2\\cdot 10^5 ) — the number of piles in the game.\n\nThe next line of each test case contains n integers a_1, a_2, \\ldots a_n (1\n\\le a_i \\le 10^9 ), where a_i is the initial number of stones in the i -th\npile.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2\\cdot\n10^5 .\n\nOutput\n\nFor each test case, print a single line with the name of the winner, assuming\nboth players play optimally. If Alice wins, print \"Alice\", otherwise print\n\"Bob\" (without quotes).\n\nExample\n\nInput\n\n 7\n \n 5\n \n 3 3 3 3 3\n \n 2\n \n 1 7\n \n 7\n \n 1 3 9 7 4 2 100\n \n 3\n \n 1 2 3\n \n 6\n \n 2 1 3 4 2 4\n \n 8\n \n 5 7 2 9 6 3 3 2\n \n 1\n \n 1000000000\n\nOutput\n\n Alice\n Bob\n Alice\n Alice\n Bob\n Alice\n Alice\n \nNote\n\nIn the first test case, Alice can win by choosing k=3 on her first turn, which\nwill empty all of the piles at once.\n\nIn the second test case, Alice must choose k=1 on her first turn since there\nis a pile of size 1 , so Bob can win on the next turn by choosing k=6 .", + "generated_code": [ + "from collections import *\nfrom math import *\nfrom heapq import *\nimport sys\nfrom bisect import *\nfrom random import randint\nrrr = randint(8888,88888)\n \n \ndef sol():\n N = int(input())\n \n nums = set(input().split())\n \n nums = sorted(map(int,nums))\n if len(nums) == 1:return print(\"Alice\")\n if len(nums) == 2:return print(\"Bob\")\n nums.insert(0,0)\n cd = 0\n for i in range(len(nums)-2):\n if nums[i+1] - nums[i] == 1:cd += 1\n else:break\n if cd & 1:return print(\"Bob\")\n else:return print(\"Alice\")\n \n \n \n \n \nfor _ in range(int(input())):\n sol()", + "import heapq\nimport sys\n \ninput = sys.stdin.readline\n \ndef solve(arr):\n A = False\n if arr[0] != 1:\n return 'Alice'\n set_ = list(set(arr))\n set_.sort()\n not_c = True\n for i in range(1, len(set_)):\n if set_[i] - set_[i-1] > 1:\n not_c = False\n break\n A = not A\n if not_c:\n A = not A\n \n return 'Alice' if A else 'Bob'\n \n \nt = int(input())\nc = 1\nwhile t > 0:\n n = list(map(int, input().rstrip().split()))\n \n arr = list(map(int, input().rstrip().split()))\n r = solve(arr)\n print(r)\n t -= 1", + "t=int(input())\nfor i in range(t):\n n=int(input())\n l=list(map(int,input().split()))\n e=set(l)\n m=len(l)\n \n if 1 in l:\n print(\"Bob\" )\n else:\n print(\"Alice\" )" + ] + }, + { + "task_name": "1966_B", + "description": "There is an n \\times m grid of white and black squares. In one operation, you\ncan select any two squares of the same color, and color all squares in the\nsubrectangle between them that color.\n\nFormally, if you select positions (x_1, y_1) and (x_2, y_2) , both of which\nare currently the same color c , set the color of all (x, y) where \\min(x_1,\nx_2) \\le x \\le \\max(x_1, x_2) and \\min(y_1, y_2) \\le y \\le \\max(y_1, y_2) to c\n.\n\nThis diagram shows a sequence of two possible operations on a grid:\n\n![](https://espresso.codeforces.com/efe0d6bfa2062b4821f73fb07120103af504fb62.png)\n\nIs it possible for all squares in the grid to be the same color, after\nperforming any number of operations (possibly zero)?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. The description of the test cases follows.\n\nThe first line of each test case contains two integers n and m (1 \\le n, m \\le\n500 ) — the number of rows and columns in the grid, respectively.\n\nEach of the next n lines contains m characters 'W' and 'B' — the initial\ncolors of the squares of the grid.\n\nIt is guaranteed that the sum of n\\cdot m over all test cases does not exceed\n3\\cdot 10^5 .\n\nOutput\n\nFor each test case, print \"YES\" if it is possible to make all squares in the\ngrid the same color, and \"NO\" otherwise.\n\nYou can output the answer in any case (upper or lower). For example, the\nstrings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 8\n \n 2 1\n \n W\n \n B\n \n 6 6\n \n WWWWBW\n \n WBWWWW\n \n BBBWWW\n \n BWWWBB\n \n WWBWBB\n \n BBBWBW\n \n 1 1\n \n W\n \n 2 2\n \n BB\n \n BB\n \n 3 4\n \n BWBW\n \n WBWB\n \n BWBW\n \n 4 2\n \n BB\n \n BB\n \n WW\n \n WW\n \n 4 4\n \n WWBW\n \n BBWB\n \n WWBB\n \n BBBB\n \n 1 5\n \n WBBWB\n\nOutput\n\n NO\n YES\n YES\n YES\n YES\n NO\n YES\n NO\n \nNote\n\nIn the first example, it is impossible to ever change the color of any square\nwith an operation, so we output NO.\n\nThe second example is the case pictured above. As shown in that diagram, it is\npossible for all squares to be white after two operations, so we output YES.\n\nIn the third and fourth examples, all squares are already the same color, so\nwe output YES.\n\nIn the fifth example we can do everything in two operations. First, select\npositions (2, 1) and (1, 4) and color all squares with 1 \\le x \\le 2 and 1 \\le\ny \\le 4 to white. Then, select positions (2, 1) and (3, 4) and color all\nsquares with 2 \\le x \\le 3 and 1 \\le y \\le 4 to white. After these two\noperations all squares are white.", + "generated_code": [ + "for _ in range(int(input())):\n n, m = map(int, input().split())\n a = []\n \n first_row = ''\n last_row = ''\n \n for i in range(n):\n a.append(input())\n first_row += a[-1][0]\n last_row += a[-1][-1]\n \n if len(set(a[0])) == 1 and a[0] != a[-1]:\n print('NO')\n elif len(set(first_row)) == 1 and first_row != last_row:\n print('NO')\n else:\n print('YES')" + ] + }, + { + "task_name": "1966_C", + "description": "Alice and Bob are playing a game on n piles of stones. On each player's turn,\nthey select a positive integer k that is at most the size of the smallest\nnonempty pile and remove k stones from each nonempty pile at once. The first\nplayer who is unable to make a move (because all piles are empty) loses.\n\nGiven that Alice goes first, who will win the game if both players play\noptimally?\n\nInput\n\nThe first line of the input contains a single integer t (1 \\le t \\le 10^4 ) —\nthe number of test cases. The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le\n2\\cdot 10^5 ) — the number of piles in the game.\n\nThe next line of each test case contains n integers a_1, a_2, \\ldots a_n (1\n\\le a_i \\le 10^9 ), where a_i is the initial number of stones in the i -th\npile.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2\\cdot\n10^5 .\n\nOutput\n\nFor each test case, print a single line with the name of the winner, assuming\nboth players play optimally. If Alice wins, print \"Alice\", otherwise print\n\"Bob\" (without quotes).\n\nExample\n\nInput\n\n 7\n \n 5\n \n 3 3 3 3 3\n \n 2\n \n 1 7\n \n 7\n \n 1 3 9 7 4 2 100\n \n 3\n \n 1 2 3\n \n 6\n \n 2 1 3 4 2 4\n \n 8\n \n 5 7 2 9 6 3 3 2\n \n 1\n \n 1000000000\n\nOutput\n\n Alice\n Bob\n Alice\n Alice\n Bob\n Alice\n Alice\n \nNote\n\nIn the first test case, Alice can win by choosing k=3 on her first turn, which\nwill empty all of the piles at once.\n\nIn the second test case, Alice must choose k=1 on her first turn since there\nis a pile of size 1 , so Bob can win on the next turn by choosing k=6 .", + "generated_code": [ + "tc = int(input())\n \nwhile tc > 0:\n n = int(input())\n arr = sorted(list(set([int(x) for x in input().split(' ')])), reverse=True) + [0]\n dp = True\n n = len(arr) - 1\n for i in range(1, len(arr)):\n dp = (arr[i] - (arr[i+1] if i < n else 0) > 1) or (not dp)\n print('Alice' if dp else 'Alice')\n tc -= 1", + "def modifyArr(a):\n a_new = sorted(list(set(a)))\n a_temp = a_new.copy()\n \n for i in range(1,len(a_new)):\n a_new[i] = a_new[i] - a_temp[i-1]\n \n return a_new\n \ndef findWinner(a,n):\n if n==1:\n return 1\n elif n==2:\n if a[0]%2==0:\n return 1\n else:\n return 2\n else:\n winNext = findWinner(a[1:],n-1)\n if winNext==2 or (winNext==1 and a[0]!=1):\n return 1\n else:\n return 2 \n \nt = int(input())\n \nfor _ in range(t):\n n = int(input())\n \n a = [int(x) for x in input().split()]\n \n a = modifyArr(a)\n n = len(a)\n #print(a)\n \n if findWinner(a,n)==1:\n print(\"Alice\")\n else:\n print(\"Bob\")", + "for _ in range(int(input())):\n n = int(input())\n arr = list(map(int, input().split()))\n s = set()\n for i in range(n):\n s.add(arr[i])\n s = list(s)\n ans = 1\n s = [0] + s\n n = len(s)\n if n==2: print(\"Alice\")\n else:\n for i in range(1,n-1):\n if s[i]-s[i-1] > 1:\n break\n else:\n ans = 1-ans\n if ans: print(\"Alice\")\n else: print(\"Bob\")" + ] + }, + { + "task_name": "1967_B1", + "description": "The two versions are different problems. You may want to read both versions.\nYou can make hacks only if both versions are solved.\n\nYou are given two positive integers n , m .\n\nCalculate the number of ordered pairs (a, b) satisfying the following\nconditions:\n\n * 1\\le a\\le n , 1\\le b\\le m ; \n * a+b is a multiple of b \\cdot \\gcd(a,b) . \n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\le t\\le 10^4 ). The description of the test cases follows.\n\nThe first line of each test case contains two integers n , m (1\\le n,m\\le 2\n\\cdot 10^6 ).\n\nIt is guaranteed that neither the sum of n nor the sum of m over all test\ncases exceeds 2 \\cdot 10^6 .\n\nOutput\n\nFor each test case, print a single integer: the number of valid pairs.\n\nExample\n\nInput\n\n 6\n \n 1 1\n \n 2 3\n \n 3 5\n \n 10 8\n \n 100 1233\n \n 1000000 1145141\n\nOutput\n\n 1\n 3\n 4\n 14\n 153\n 1643498\n \nNote\n\nIn the first test case, only (1,1) satisfies the conditions.\n\nIn the fourth test case,\n(1,1),(2,1),(2,2),(3,1),(4,1),(5,1),(6,1),(6,2),(6,3),(7,1),(8,1),(9,1),(10,1),(10,2)\nsatisfy the conditions.", + "generated_code": [ + "t=int(input())\nfor i in range(t):\n n,m=map(int,input().split())\n count=2\n ans=n\n while count<=m:\n countmins=count -1\n g=n/count\n if g1 parts so that [bitwise XOR](http://tiny.cc/xor_wiki_eng) of\nvalues from each part are equal.\n\nMore formally, you must split array x into k consecutive segments, each\nelement of x must belong to exactly 1 segment. Let y_1,\\dots,y_k be the XOR of\nelements from each part respectively. Then y_1=y_2=\\dots=y_k must be\nfulfilled.\n\nFor example, if x = [1, 1, 2, 3, 0] , you can split it as follows:\n[\\color{blue}1], [\\color{green}1], [\\color{red}2, \\color{red}3, \\color{red}0]\n. Indeed \\color{blue}1=\\color{green}1=\\color{red}2 \\oplus \\color{red}3\\oplus\n\\color{red}0 .\n\nYou are given an array a_1,\\dots,a_n . Your task is to answer q queries:\n\n * For fixed l , r , determine whether the subarray a_l,a_{l+1},\\dots,a_r is interesting. \n\nInput\n\nThe first line contains a single integer t (1\\le t\\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains two integers n and q (2 \\le n \\le 2\n\\cdot 10^5 , 1 \\le q \\le 2 \\cdot 10^5 ) — the number of elements in the array\nand the number of queries respectively.\n\nThe next line contains n integers a_1,\\dots,a_n (0 \\le a_i < 2^{30} ) —\nelements of the array.\n\nEach of the next q lines contains two integers l and r (1 \\le l < r \\le n )\ndescribing the query.\n\nIt is guaranteed that the sum of n over all testcases does not exceed 2 \\cdot\n10^5 .\n\nIt is guaranteed that the sum of q over all testcases does not exceed 2 \\cdot\n10^5 .\n\nOutput\n\nFor each query, output \"YES\" if the subarray is interesting and \"NO\"\notherwise.\n\nYou can output \"Yes\" and \"No\" in any case (for example, the strings \"yES\",\n\"yes\", and \"Yes\" will be recognized as correct answers).\n\nExample\n\nInput\n\n 4\n \n 5 5\n \n 1 1 2 3 0\n \n 1 5\n \n 2 4\n \n 3 5\n \n 1 3\n \n 3 4\n \n 5 5\n \n 1 2 3 4 5\n \n 1 5\n \n 2 4\n \n 3 5\n \n 1 3\n \n 2 3\n \n 7 4\n \n 12 9 10 9 10 11 9\n \n 1 5\n \n 1 7\n \n 2 6\n \n 2 7\n \n 11 4\n \n 0 0 1 0 0 1 0 1 1 0 1\n \n 1 2\n \n 2 5\n \n 6 9\n \n 7 11\n\nOutput\n\n YES\n YES\n NO\n NO\n NO\n \n YES\n NO\n NO\n YES\n NO\n \n NO\n NO\n NO\n NO\n \n YES\n NO\n YES\n YES\n \nNote\n\nExplanation for the first test case:\n\nThe first query is described in the statement.\n\nIn the second query, we should divide [1,2,3] . A possible division is\n[1,2],[3] , since 1\\oplus 2=3 .\n\nIt can be shown that for queries 3,4,5 , the subarrays are not interesting.", + "generated_code": [ + "import sys\ninput = sys.stdin.read\nimport bisect\n \ndef solve():\n data = input().split()\n idx = 0\n \n # Read the number of test cases\n t = int(data[idx])\n idx += 1\n \n results = []\n \n # Process each test case\n for _ in range(t):\n # Read n (length of array) and q (number of queries)\n n = int(data[idx])\n q = int(data[idx + 1])\n idx += 2\n \n # Read the array `a`\n a = [0] * (n + 1)\n pf = [0] * (n + 1)\n \n # Dictionary to store occurrences of XOR values\n mp = {0: [0]}\n \n # Calculate prefix XOR array and update dictionary\n for i in range(1, n + 1):\n a[i] = int(data[idx])\n idx += 1\n pf[i] = pf[i - 1] ^ a[i]\n if pf[i] not in mp:\n mp[pf[i]] = []\n mp[pf[i]].append(i)\n \n # Process each query\n for _ in range(q):\n l = int(data[idx])\n r = int(data[idx + 1])\n idx += 2\n \n # Calculate XOR between pf[r] and pf[l - 1]\n x = pf[r] ^ pf[l - 1]\n \n # If XOR is zero, print \"YES\" immediately\n if x == 0:\n results.append(\"YES\")\n continue\n \n # Get lists of indices for the XOR values\n v1 = mp.get(pf[r], [])\n v2 = mp.get(pf[l - 1], [])\n \n # Use bisect to find positions in the lists\n it1 = bisect.bisect_left(v1, l)\n it2 = bisect.bisect_left(v2, r) - 1\n \n # Compare positions and print the result\n if it1 < len(v1) and it2 >= 0 and v1[it1] <= r and v2[it2] >= l:\n results.append(\"YES\")\n else:\n results.append(\"NO\")\n \n # Add a newline for separation\n results.append(\"\")\n \n # Print all results\n print(\"\\n\".join(results))\n \nif __name__ == \"__main__\":\n solve()", + "from collections import defaultdict\n \n \ndef read(cast):\n return map(cast, input().split())\n \n \ndef bin_search(arr, predicate):\n l, r = 0, len(arr)\n \n while l + 1 < r:\n mid = (l + r) // 2\n if predicate(arr[mid]):\n l = mid\n else:\n r = mid\n \n if predicate(arr[l]):\n return l\n return None\n \n \ndef main():\n n, q = read(int)\n \n a = list(read(int))\n x = [0]\n inds = defaultdict(list)\n inds[0].append(0)\n for i in a:\n x.append(x[-1] ^ i)\n inds[x[-1]].append(len(x) - 1)\n \n for i in range(q):\n l, r = read(int)\n \n if x[l - 1] == x[r]:\n print('Yes')\n continue\n \n lower = bin_search(inds[x[r]], lambda arg: arg < l) or -1\n upper = bin_search(inds[x[l - 1]], lambda arg: arg <= r)\n lower = inds[x[r]][lower + 1]\n upper = inds[x[l - 1]][upper]\n \n if upper > lower and l <= upper <= r and l <= lower <= r:\n print('Yes')\n else:\n print('No')\n \n \nif __name__ == '__main__':\n # t = 1\n t, = read(int)\n for _ in range(t):\n main()" + ] + }, + { + "task_name": "1969_B", + "description": "Let's define a cyclic shift of some string s as a transformation from s_1 s_2\n\\dots s_{n-1} s_{n} into s_{n} s_1 s_2 \\dots s_{n-1} . In other words, you\ntake one last character s_n and place it before the first character while\nmoving all other characters to the right.\n\nYou are given a binary string s (a string consisting of only 0-s and/or 1-s).\n\nIn one operation, you can choose any substring s_l s_{l+1} \\dots s_r (1 \\le l\n< r \\le |s| ) and cyclically shift it. The cost of such operation is equal to\nr - l + 1 (or the length of the chosen substring).\n\nYou can perform the given operation any number of times. What is the minimum\ntotal cost to make s sorted in non-descending order?\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first and only line of each test case contains a binary string s (2 \\le\n|s| \\le 2 \\cdot 10^5 ; s_i \\in {0, 1}) — the string you need to sort.\n\nAdditional constraint on the input: the sum of lengths of strings over all\ntest cases doesn't exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print the single integer — the minimum total cost to make\nstring sorted using operation above any number of times.\n\nExample\n\nInput\n\n 5\n \n 10\n \n 0000\n \n 11000\n \n 101011\n \n 01101001\n\nOutput\n\n 2\n 0\n 9\n 5\n 11\n \nNote\n\nIn the first test case, you can choose the whole string and perform a cyclic\nshift: 10 \\rightarrow 01. The length of the substring is 2 , so the cost is 2\n.\n\nIn the second test case, the string is already sorted, so you don't need to\nperform any operations.\n\nIn the third test case, one of the optimal strategies is the next:\n\n 1. choose substring [1, 3] : 11000 \\rightarrow 01100; \n 2. choose substring [2, 4] : 01100 \\rightarrow 00110; \n 3. choose substring [3, 5] : 00110 \\rightarrow 00011. \n\nThe total cost is 3 + 3 + 3 = 9 .", + "generated_code": [ + "def solve(sChar):\n s=[]\n for i in sChar:\n s.append(i)\n \n left=0\n cost=0\n right=1\n while left<=right and right 0 else 0\n else:\n ans += (zeroes - cnt[0])\n print(ans)" + ] + }, + { + "task_name": "1969_D", + "description": "Alice and Bob are playing a game in the shop. There are n items in the shop;\neach item has two parameters: a_i (item price for Alice) and b_i (item price\nfor Bob).\n\nAlice wants to choose a subset (possibly empty) of items and buy them. After\nthat, Bob does the following:\n\n * if Alice bought less than k items, Bob can take all of them for free; \n * otherwise, he will take k items for free that Alice bought (Bob chooses which k items it will be), and for the rest of the chosen items, Bob will buy them from Alice and pay b_i for the i -th item. \n\nAlice's profit is equal to \\sum\\limits_{i \\in S} b_i - \\sum\\limits_{j \\in T}\na_j , where S is the set of items Bob buys from Alice, and T is the set of\nitems Alice buys from the shop. In other words, Alice's profit is the\ndifference between the amount Bob pays her and the amount she spends buying\nthe items.\n\nAlice wants to maximize her profit, Bob wants to minimize Alice's profit. Your\ntask is to calculate Alice's profit if both Alice and Bob act optimally.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains two integers n and k (1 \\le n \\le 2\n\\cdot 10^5 ; 0 \\le k \\le n ).\n\nThe second line contains n integers a_1, a_2, \\dots, a_n (1 \\le a_i \\le 10^9\n).\n\nThe third line contains n integers b_1, b_2, \\dots, b_n (1 \\le b_i \\le 10^9 ).\n\nAdditional constraint on the input: the sum of n over all test cases doesn't\nexceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, print a single integer — Alice's profit if both Alice and\nBob act optimally.\n\nExample\n\nInput\n\n 4\n \n 2 0\n \n 2 1\n \n 1 2\n \n 4 1\n \n 1 2 1 4\n \n 3 3 2 3\n \n 4 2\n \n 2 1 1 1\n \n 4 2 3 2\n \n 6 2\n \n 1 3 4 9 1 3\n \n 7 6 8 10 6 8\n\nOutput\n\n 1\n 1\n 0\n 7\n \nNote\n\nIn the first test case, Alice should buy the 2 -nd item and sell it to Bob, so\nher profit is 2 - 1 = 1 .\n\nIn the second test case, Alice should buy the 1 -st, the 2 -nd and the 3 -rd\nitem; then Bob takes the 1 -st item for free and pays for the 2 -nd and the 3\n-rd item. Alice's profit is (3+2) - (1+2+1) = 1 . Bob could take 2 -nd item\nfor free instead; this does not change Alice's profit. Bob won't take the 3\n-rd item for free, since this would lead to a profit of 2 .", + "generated_code": [ + "import heapq\nimport sys\n \nputin = sys.stdin.readline\n \n \ndef inp():\n return int(putin())\n \n \ndef invert():\n return map(int, putin().split())\n \n \ndef starting_price(main_ar, sec_arr):\n sub_summ = 0\n for val_a in sec_arr:\n sub_summ += val_a[0]\n for val_b in main_ar:\n if val_b[0] + val_b[1] >= 0:\n sub_summ += val_b[0] + val_b[1]\n return sub_summ\n \n \nif __name__ == \"__main__\":\n t = inp()\n for x in range(t):\n arr = []\n k_arr = []\n temp_pop = []\n n, k = invert()\n a = list(invert())\n a = [-x for x in a]\n b = list(invert())\n max_value = 0\n sub_sum = 0\n my_bool = False\n \n for i in range(n):\n arr.append([a[i], b[i]])\n arr.sort(key=lambda y: y[1], reverse=False)\n \n for k_range in range(1, k + 1):\n if arr:\n heapq.heappush(k_arr, arr[-1])\n arr.pop()\n if arr:\n sub_sum = starting_price(arr, k_arr)\n if sub_sum > max_value:\n max_value = sub_sum\n while arr:\n if arr:\n sub_sum -= arr[-1][1]\n if arr[-1][1] + arr[-1][0] <= 0:\n sub_sum += arr[-1][0]\n temp_pop = heapq.heappushpop(k_arr, arr[-1])\n arr.pop()\n if temp_pop:\n sub_sum -= temp_pop[0]\n if sub_sum > max_value:\n if k_range != 0:\n max_value = sub_sum\n print(max_value)" + ] + }, + { + "task_name": "1970_A1", + "description": "A parentheses sequence is a string consisting of characters \"(\" and \")\", for\nexample \"(()((\".\n\nA balanced parentheses sequence is a parentheses sequence which can become a\nvalid mathematical expression after inserting numbers and operations into it,\nfor example \"(()(()))\".\n\nThe balance of a parentheses sequence is defined as the number of opening\nparentheses \"(\" minus the number of closing parentheses \")\". For example, the\nbalance of the sequence \"(()((\" is 3.\n\nA balanced parentheses sequence can also be defined as a parentheses sequence\nwith balance 0 such that each of its prefixes has a non-negative balance.\n\nWe define the balanced shuffle operation that takes a parentheses sequence and\nreturns a parentheses sequence as follows: first, for every character of the\ninput sequence, we compute the balance of the prefix of the sequence before\nthat character and write those down in a table together with the positions of\nthe characters in the input sequence, for example:\n\nPrefix balance| 0| 1| 2| 1| 2| 3| 2| 1 \n---|---|---|---|---|---|---|---|--- \nPosition| 1| 2| 3| 4| 5| 6| 7| 8 \nCharacter| (| (| )| (| (| )| )| ) \n \nThen, we sort the columns of this table in increasing order of prefix balance,\nbreaking ties in decreasing order of position. In the above example, we get:\n\nPrefix balance| 0| 1| 1| 1| 2| 2| 2| 3 \n---|---|---|---|---|---|---|---|--- \nPosition| 1| 8| 4| 2| 7| 5| 3| 6 \nCharacter| (| )| (| (| )| (| )| ) \n \nThe last row of this table forms another parentheses sequence, in this case\n\"()(()())\". This sequence is called the result of applying the balanced\nshuffle operation to the input sequence, or in short just the balanced shuffle\nof the input sequence.\n\nYou are given a balanced parentheses sequence. Print its balanced shuffle.\n\nInput\n\nThe only line of input contains a string s consisting only of characters \"(\"\nand \")\". This string is guaranteed to be a non-empty balanced parentheses\nsequence with its length not exceeding 500\\,000 .\n\nOutput\n\nPrint the parentheses sequence t — the balanced shuffle of s .\n\nExample\n\nInput\n\n (()(()))\n \nOutput\n\n ()(()())", + "generated_code": [ + "# Read the input parentheses sequence\ns = input()\n \n# Initialize the prefix balance and store the necessary details\nbalance = 0\ndetails = []\n \n# Calculate prefix balance for each character in the sequence\nfor i, char in enumerate(s):\n if char == '(':\n balance += 1\n else:\n balance -= 1\n # Store the (balance, -position, character)\n # We use -position to automatically sort by decreasing position when balances are the same\n details.append((balance, -i, char))\n \n# Sort by (balance, -position)\ndetails.sort()\n \n# Extract the characters from the sorted details\nresult = ''.join(char for _, _, char in details)\n \n# Print the result\nprint(result)", + "def solve(s):\n n=len(s)\n ans=''\n d={}\n d[0]=0\n for i in range(len(s)):\n if s[i]=='(':\n d[i+1]=d[i]+1\n else:\n d[i+1]=d[i]-1\n d.pop(n)\n d=sorted(d.items(), key=lambda x:x[1])\n for i , j in d:\n ans+=s[i]\n return ans\n \n \nn=input()\nprint(solve(n))", + "def balanced_shuffle(s):\n n = len(s)\n balance = 0\n positions = []\n \n for i, char in enumerate(s):\n if char == '(':\n balance += 1\n else:\n balance -= 1\n positions.append((balance, i, char))\n \n positions.sort(key=lambda x: (x[0], -x[1]))\n \n result = ''.join([char for _, _, char in positions])\n return result\n \ns = input().strip()\nprint(balanced_shuffle(s))" + ] + }, + { + "task_name": "1970_C2", + "description": "This is the medium version of the problem. The difference in this version is\nthat t=1 and we work on trees.\n\nRon and Hermione are playing a game on a tree of n nodes that are initially\ninactive. The game consists of t rounds, each of which starts with a stone on\nexactly one node, which is considered as activated. A move consists of picking\nan inactive neighbor of the node with a stone on it and moving the stone there\n(thus activating this neighbor). Ron makes the first move, after which he\nalternates with Hermione until no valid move is available. The player that\ncannot make a move loses the round. If both players play optimally, who wins\neach round of this game?\n\nNote that all the rounds are played with the same tree; only the starting node\nchanges. Moreover, after each round, all active nodes are considered inactive\nagain.\n\nInput\n\nThe first line contains integers n (2 \\leq n \\leq 2\\times 10^5 ), t (t=1 ),\nthe number of nodes in the tree and the number of rounds, respectively.\n\nThe next n-1 lines contain two integers 1 \\leq u, v \\leq n each, corresponding\nto an edge of the tree.\n\nThe next line contains t integers 1 \\leq u_1 , \\dots, u_t \\leq n ,\ncorresponding to the node where the stone is initially put.\n\nOutput\n\nThe output consists of t=1 line which is either \"Ron\" or \"Hermione\".\n\nExample\n\nInput\n\n 5 1\n \n 1 2\n \n 1 3\n \n 3 4\n \n 3 5\n \n 1\n\nOutput\n\n Ron", + "generated_code": [ + "from functools import reduce\nimport math\nfrom collections import deque, defaultdict\n \n \ndef dfs(nodes, start, parent=None):\n\tif len(nodes[start]) == 1 and nodes[start][0] == parent:\n\t\treturn [0]\n\tdistances = []\n\tfor node in nodes[start]:\n\t\tif node != parent:\n\t\t\tdistances.extend([1 + dist for dist in dfs(nodes, node, start)])\n\treturn distances\n \n \ndef testcase():\n\tn, t = map(int, input().split())\n\tedges = []\n\tempty = True\n\tnodes = defaultdict(list)\n\tfor i in range(n - 1):\n\t\tu, v = map(int, input().split())\n\t\tnodes[u].append(v)\n\t\tnodes[v].append(u)\n\t\n\tleaves = deque()\n\tfor key in nodes:\n\t\tif len(nodes[key]) == 1:\n\t\t\tleaves.append(key)\n\t\n\tstart = int(input())\n\tmoves = dfs(nodes, start)\n\t\n\tif any([move % 2 == 1 for move in moves]):\n\t\tprint(\"Ron\")\n\telse:\n\t\tprint(\"Hermione\")\n \n \nt = 1 # int(input())\n \nfor i in range(t):\n\ttestcase()" + ] + }, + { + "task_name": "1970_F2", + "description": "This afternoon, you decided to enjoy the first days of Spring by taking a walk\noutside. As you come near the Quidditch field, you hear screams. Once again,\nthere is a conflict about the score: the two teams are convinced that they won\nthe game! To prevent this problem from happening one more time, you decide to\nget involved in the refereeing of the matches.\n\nNow, you will stay in the stadium to watch the game and count the score. At\nthe end of the game, you will decide the winner.\n\nToday, two teams are competing: the red Gryffindor (R) and the blue Ravenclaw\n(B) team. Each team is composed of P players (1 \\leq P \\leq 10 ).\n\nThe field is a rectangle of N lines and M columns (3 \\leq N, M \\leq 99 , N and\nM are odd). All the positions are integers, and several entities are allowed\nto be at the same position in the field. At the beginning of the game, the\nfield contains goals for the two teams (each team can own between one and five\ngoals), the players, and exactly one Quaffle. In this version of the problem,\none Bludger can be present. An other type of ball will be available in the\nharder version of the problem.\n\nA game is composed of T steps (0 \\leq T \\leq 10000 ). At each step, one entity\non the field (a player or a ball) performs one action. All entities can move.\nA player can also catch a ball or throw the Quaffle that it is carrying. To\ncatch a ball, a player must be located on the same cell as it. The Quaffle\ndoes not perform any action while it is being carried; it only follows the\nmovements of the player. If a player carrying the Quaffle decides to throw it,\nthe Quaffle is simply put at the current position of the player. If a player\nis on the same cell as a Bludger (either after a movement from the player or\nthe Bludger), the player is eliminated. If the player is eliminated while it\nis carrying the Quaffle, the Quaffle remains on the cell containing both the\nplayer and the Bludger after the move. It is guaranteed that this never occurs\nwhile the player is in a cell containing a goal.\n\nTo win a point, a player must leave the Quaffle at a goal of the other team.\nWhen it does, the team of the player wins one point, and the Quaffle instantly\nmoves to the middle of the field (the cell at the (M+1)/2 -th column of the\n(N+1)/2 -th line of the field, starting from 1). There is no goal in the\nmiddle of the field. If a player puts the ball in its own goal, the other team\nwins the point.\n\nInput\n\nOn the first line, the integers N and M .\n\nThe description of the field follows: N lines of M pairs of characters\nseparated by spaces. Each pair of characters represents a position on the\nfield. It can be either:\n\n * .. to represent an empty cell \n * R0, ..., R9, B0, ..., B9 to represent a player. The first character is the team of the player, and the second is the number of the player in the team. Each pair of characters is unique, but it is not guaranteed that all the pairs appear in the grid. \n * RG or BG to represent a goal. The blue team tries to put the ball in a red goal (RG) while the red team tries to put the ball in a blue goal (BG). \n * .Q to represent the Quaffle, which is the ball that the players use to score goals. \n * .B to represent a Bludger.\n\nThe next line contains T , the number of steps that compose the game. T lines\nfollow, each describing one action. It contains several pieces of information\nseparated by a space. First, a pair of characters representing the entity that\nmust perform the action. Second, the description of the action:\n\n * U, D, L, R indicate that the entity moves on the grid. It can move to the top of the grid (U), to the bottom (D), to the left (L), or to the right (R). Each entity moves by only one cell at a time. \n * C indicates that the player catches the ball (only a player can catch a ball). Then, there is a space followed by a pair of characters: the description of the ball caught by the player. This information is needed since several balls can be in the same cell. \n * T indicates that the player throws the Quaffle that it is carrying. \n\nAll the actions performed by the entities are guaranteed to be valid: the\nplayers stay in the field, don't catch a ball if they are not in the same\ncell, don't release the Quaffle if they are not carrying it, ...\n\nOutput\n\nYou must output the description of the main events of the game, one event per\nline. More precisely:\n\n * Each time a team scores, you must print t RED GOAL or t BLUE GOAL, depending on the team who scored, where t is the current time (the position of the action in the list of actions, starting from 0). In the case where a player scores in the wrong goal (a red player scores in the red goal, or a blue player scores in the blue goal), you must print the name of the team who wins one point, that is, the other team. \n * Each time a player is eliminated, you must print t p ELIMINATED, where t is the current time and p is the player who is eliminated. The format to print the player is the same as in the input.\n\nThe events must be printed in ascending order of t. If several players are\neliminated at the same time, the events must be written in alphabetical order:\nB0, ..., B9, R0, ... R9.\n\nAt the end of the game, you must print the final score as: FINAL SCORE: r b,\nwhere r is the score of the red team and b is the score of the blue team.\n\nExamples\n\nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 12\n \n R0 D\n \n R0 C .Q\n \n R0 R\n \n R0 T\n \n R0 D\n \n B0 R\n \n B0 U\n \n B0 C .Q\n \n B0 L\n \n B0 L\n \n B0 L\n \n B0 T\n\nOutput\n\n 11 BLUE GOAL\n FINAL SCORE: 0 1\n \nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 5\n \n R0 D\n \n R0 C .Q\n \n R0 L\n \n R0 L\n \n R0 T\n\nOutput\n\n 4 BLUE GOAL\n FINAL SCORE: 0 1\n \nInput\n\n 5 5\n \n .. .. .. .. ..\n \n .. .. .. .. ..\n \n RG R0 .Q B0 BG\n \n .. .. .. .. ..\n \n .. .. .B .. ..\n \n 5\n \n .B L\n \n .B U\n \n .B U\n \n B0 L\n \n B0 L\n\nOutput\n\n 2 R0 ELIMINATED\n 4 B0 ELIMINATED\n FINAL SCORE: 0 0\n \nNote\n\nIn the first example, the red player takes the Quaffle, move it and throw it.\nThe blue player catches the ball, goes to the red goal and scores.\n\nIn the second example, the red player takes the ball and scores in the goal of\ntheir own team: the blue team wins a point.\n\nIn the third example, the Bludger goes at the position of R0: R0 is\neliminated. Then, B0 moves to the position of the Bludger: B0 is eliminated\ntoo.\n\nYou can find one more example in the easy version of the problem", + "generated_code": [ + "\"\"\"\nhttps://codeforces.com/problemset/problem/1970/F2\nF2. Playing Quidditch (Medium)\n\"\"\"\n \nn, m = [int(x) for x in input().split()]\nplayers = dict()\ngoals = {\"B\": [], \"R\": []}\nmouvements = {\"L\": (-1, 0), \"R\": (1, 0), \"U\": (0, -1), \"D\": (0, 1)}\nmiddle = ((m + 1) // 2, (n + 1) // 2)\nquidditch = [middle, \"\"]\npointsb, pointsr = 0, 0\n \nfor y in range(n):\n s = input().split()\n for x in range(m):\n if s[x] == \"..\":\n continue\n elif s[x] == \".Q\":\n quidditch[0] = (x, y)\n elif s[x] == \"RG\":\n goals[\"R\"].append((x, y))\n elif s[x] == \"BG\":\n goals[\"B\"].append((x, y))\n else:\n players[s[x]] = (x, y)\n \n \ndef add(a, b):\n x, y = a\n dx, dy = b\n return x + dx, y + dy\n \n \nmoves = int(input())\nfor i in range(moves):\n mo = input().split()\n if mo[1] in \"ULDR\":\n players[mo[0]] = add(players[mo[0]], mouvements[mo[1]])\n z = \"\"\n if \".B\" in players:\n for k, v in players.items():\n if k != \".B\" and v == players[\".B\"]:\n print(i, k, \"ELIMINATED\")\n if quidditch[1] == k:\n quidditch = [v, \"\"]\n z = k\n if z != \"\":\n del players[z]\n elif mo[1] == \"C\":\n quidditch[1] == mo[0]\n elif mo[1] == \"T\":\n quidditch[1] = \"\"\n if players[mo[0]] in goals[\"R\"]:\n pointsb += 1\n print(i, \"BLUE GOAL\")\n if mo[0][0] == \"R\":\n quidditch[0] = middle\n else:\n quidditch[0] = players[mo[0]]\n if players[mo[0]] in goals[\"B\"]:\n pointsr += 1\n print(i, \"RED GOAL\")\n if mo[0][0] == \"B\":\n quidditch[0] = middle\n else:\n quidditch[0] = players[mo[0]]\n \n \nprint(\"FINAL SCORE:\", pointsr, pointsb)" + ] + }, + { + "task_name": "1971_D", + "description": "You are given a binary string^{\\dagger} . Please find the minimum number of\npieces you need to cut it into, so that the resulting pieces can be rearranged\ninto a sorted binary string.\n\n![](https://espresso.codeforces.com/76039f9769ba94c1817dbbc5e1fb1b5e4f60950f.png)\n\nNote that:\n\n * each character must lie in exactly one of the pieces; \n * the pieces must be contiguous substrings of the original string; \n * you must use all the pieces in the rearrangement. \n\n^{\\dagger} A binary string is a string consisting of characters \\texttt{0} and\n\\texttt{1} . A sorted binary string is a binary string such that all\ncharacters \\texttt{0} come before all characters \\texttt{1} .\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 500 ) — the number\nof test cases.\n\nThe only line of each test case contains a single string s (1 \\leq |s| \\leq\n500 ) consisting of characters \\texttt{0} and \\texttt{1} , where |s| denotes\nthe length of the string s .\n\nOutput\n\nFor each test case, output a single integer — the minimum number of pieces\nneeded to be able to rearrange the string into a sorted binary string.\n\nExample\n\nInput\n\n 6\n \n 11010\n \n 00000000\n \n 1\n \n 10\n \n 0001111\n \n 0110\n\nOutput\n\n 3\n 1\n 1\n 2\n 1\n 2\n \nNote\n\nThe first test case is pictured in the statement. It can be proven that you\ncan't use fewer than 3 pieces.\n\nIn the second and third test cases, the binary string is already sorted, so\nonly 1 piece is needed.\n\nIn the fourth test case, you need to make a single cut between the two\ncharacters and rearrange them to make the string \\texttt{01} .", + "generated_code": [ + "t=int(input())\nfor i in range(t):\n s=input()\n count=1\n flag=False\n j=0\n while j int(s[i+1]) :\n count+=1\n print(count+1)", + "t = int(input())\n \nfor _ in range(t):\n a = input()\n cut = 0\n for i in range(len(a)-1):\n if a[i] == '1' and a[i+1] == '0':\n cut += 1\n print(cut+1)" + ] + }, + { + "task_name": "1971_E", + "description": "Timur is in a car traveling on the number line from point 0 to point n . The\ncar starts moving from point 0 at minute 0 .\n\nThere are k+1 signs on the line at points 0, a_1, a_2, \\dots, a_k , and Timur\nknows that the car will arrive there at minutes 0, b_1, b_2, \\dots, b_k ,\nrespectively. The sequences a and b are strictly increasing with a_k = n .\n\n![](https://espresso.codeforces.com/eaf3bfb8e7a8fa4f5e8673f9a02116761cb86c93.png)\n\nBetween any two adjacent signs, the car travels with a constant speed. Timur\nhas q queries: each query will be an integer d , and Timur wants you to output\nhow many minutes it takes the car to reach point d , rounded down to the\nnearest integer.\n\nInput\n\nThe first line contains a single integer t (1 \\leq t \\leq 10^4 ) — the number\nof test cases.\n\nThe first line of each test case contains three integers n , k , and q , (k\n\\leq n \\leq 10^9 ; 1 \\leq k, q \\leq 10^5 ) — the final destination, the number\nof points Timur knows the time for, and the number of queries respectively.\n\nThe second line of each test case contains k integers a_i (1 \\leq a_i \\leq n ;\na_i < a_{i+1} for every 1 \\leq i \\leq k-1 ; a_k = n ).\n\nThe third line of each test case contains k integers b_i (1 \\leq b_i \\leq 10^9\n; b_i < b_{i+1} for every 1 \\leq i \\leq k-1 ).\n\nEach of the following q lines contains a single integer d (0 \\leq d \\leq n ) —\nthe distance that Timur asks the minutes passed for.\n\nThe sum of k over all test cases doesn't exceed 10^5 , and the sum of q over\nall test cases doesn't exceed 10^5 .\n\nOutput\n\nFor each query, output a single integer — the number of minutes passed until\nthe car reaches the point d , rounded down.\n\nExample\n\nInput\n\n 4\n \n 10 1 3\n \n 10\n \n 10\n \n 0\n \n 6\n \n 7\n \n 10 2 4\n \n 4 10\n \n 4 7\n \n 6\n \n 4\n \n 2\n \n 7\n \n 1000000000 1 1\n \n 1000000000\n \n 1000000000\n \n 99999999\n \n 6 1 3\n \n 6\n \n 5\n \n 2\n \n 6\n \n 5\n\nOutput\n\n 0 6 7 \n 5 4 2 5 \n 99999999 \n 1 5 4 \n \nNote\n\nFor the first test case, the car goes from point 0 to point 10 in 10 minutes,\nso the speed is 1 unit per minute and:\n\n * At point 0 , the time will be 0 minutes. \n * At point 6 , the time will be 6 minutes. \n * At point 7 , the time will be 7 minutes. \n\nFor the second test case, between points 0 and 4 , the car travels at a speed\nof 1 unit per minute and between 4 and 10 with a speed of 2 units per minute\nand:\n\n * At point 6 , the time will be 5 minutes. \n * At point 4 , the time will be 4 minutes. \n * At point 2 , the time will be 2 minutes. \n * At point 7 , the time will be 5.5 minutes, so the answer is 5 . \n\nFor the fourth test case, the car travels with 1.2 units per minute, so the\nanswers to the queries are:\n\n * At point 2 , the time will be 1.66\\dots minutes, so the answer is 1 . \n * At point 6 , the time will be 5 minutes. \n * At point 5 , the time will be 4.16\\dots minutes, so the answer is 4 .", + "generated_code": [ + "from bisect import bisect_left\nt = int(input())\n \nfor _ in range(t):\n n, k, q = map(int, input().split())\n a = [0] + list(map(int, input().split()))\n b = [0] + list(map(int, input().split()))\n ad = [0]\n bd = [0]\n for i in range(1, len(a)):\n ad.append(a[i]-a[i-1])\n for i in range(1, len(b)):\n bd.append(b[i]-b[i-1])\n v = [0]\n for i in range(1,len(a)):\n v.append(ad[i]/bd[i]) \n for l in range(q):\n m = 0\n i = 1\n ql = int(input())\n s = bisect_left(a, ql)\n if a[s] == ql:\n print(b[s], end=' ')\n continue\n ql -= a[s-1]\n m += b[s-1]\n m += bd[s] * ql/ad[s]\n print(int(m), end=' ')\n print()" + ] + }, + { + "task_name": "1972_B", + "description": "There are n coins on the table forming a circle, and each coin is either\nfacing up or facing down. Alice and Bob take turns to play the following game,\nand Alice goes first.\n\nIn each operation, the player chooses a facing-up coin, removes the coin, and\nflips the two coins that are adjacent to it. If (before the operation) there\nare only two coins left, then one will be removed and the other won't be\nflipped (as it would be flipped twice). If (before the operation) there is\nonly one coin left, no coins will be flipped. If (before the operation) there\nare no facing-up coins, the player loses.\n\nDecide who will win the game if they both play optimally. It can be proved\nthat the game will end in a finite number of operations, and one of them will\nwin.\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\le t\\le 100 ). The description of the test cases follows.\n\nThe first line of each test case contains only one positive integer n (1 \\leq\nn \\leq 100 ), representing the number of the coins.\n\nA string s of length n follows on the second line of each test case,\ncontaining only \"U\" and \"D\", representing that each coin is facing up or\nfacing down.\n\nOutput\n\nFor each test case, print \"YES\" if Alice will win the game, and \"NO\"\notherwise.\n\nYou can output the answer in any case (upper or lower). For example, the\nstrings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be recognized as positive\nresponses.\n\nExample\n\nInput\n\n 3\n \n 5\n \n UUDUD\n \n 5\n \n UDDUD\n \n 2\n \n UU\n\nOutput\n\n YES\n NO\n NO\n \nNote\n\nIn the first test case, the game may go as follows.\n\n * Alice chooses the first coin and s becomes \"DDUU\". \n * Bob chooses the last coin and s becomes \"UDD\". \n * Alice chooses the first coin and s becomes \"UU\". \n * Bob chooses the first coin and s becomes \"U\". \n * Alice chooses the only coin and s becomes empty. \n * Bob can't choose any coin now, and he loses the game. \n\nIt can be proved that Bob will always lose if they both play optimally.", + "generated_code": [ + "def determine_winner(s):\n # Count the number of 'U' characters in the string\n num_up = s.count('U')\n \n # Determine the winner based on the parity of the number of 'U' characters\n if num_up % 2 == 1:\n return \"YES\"\n else:\n return \"NO\"\n \n# Read input\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \n# Parse the number of test cases\nt = int(data[0])\n \n# Iterate over each test case\nfor _ in range(t):\n # Read the number of coins\n n = int(data[1])\n \n # Read the string representation of the coins\n s = data[2]\n \n # Determine and print the result\n print(determine_winner(s))", + "from collections import Counter\nt=int(input())\nresults=[]\nfor i in range(t):\n n=int(input())\n arr=input()\n if n%2==0: results.append('no')\n else:\n if arr.count('U')>arr.count('D'): results.append(\"yes\")\n else: results.append(\"no\")\n \nfor i in results:\n print(i)", + "def solve_coin_game():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n index = 0\n t = int(data[index])\n index += 1\n \n results = []\n \n for _ in range(t):\n n = int(data[index])\n index += 1\n s = data[index]\n index += 1\n \n # Count the number of 'U' (face-up) coins\n num_up_coins = s.count('U')\n \n # Determine the winner based on the parity of the count\n if num_up_coins % 2 == 1:\n results.append(\"YES\")\n else:\n results.append(\"NO\")\n \n # Print all results\n for result in results:\n print(result)\n \n# Uncomment the following line to run the function with standard input\n# solve_coin_game()" + ] + }, + { + "task_name": "1972_D2", + "description": "The two versions are different problems. You may want to read both versions.\nYou can make hacks only if both versions are solved.\n\nYou are given two positive integers n , m .\n\nCalculate the number of ordered pairs (a, b) satisfying the following\nconditions:\n\n * 1\\le a\\le n , 1\\le b\\le m ; \n * b \\cdot \\gcd(a,b) is a multiple of a+b . \n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\le t\\le 10^4 ). The description of the test cases follows.\n\nThe first line of each test case contains two integers n , m (1\\le n,m\\le 2\n\\cdot 10^6 ).\n\nIt is guaranteed that neither the sum of n nor the sum of m over all test\ncases exceeds 2 \\cdot 10^6 .\n\nOutput\n\nFor each test case, print a single integer: the number of valid pairs.\n\nExample\n\nInput\n\n 6\n \n 1 1\n \n 2 3\n \n 3 5\n \n 10 8\n \n 100 1233\n \n 1000000 1145141\n\nOutput\n\n 0\n 1\n 1\n 6\n 423\n 5933961\n \nNote\n\nIn the first test case, no pair satisfies the conditions.\n\nIn the fourth test case, (2,2),(3,6),(4,4),(6,3),(6,6),(8,8) satisfy the\nconditions.", + "generated_code": [ + "import math\n \ndef fun():\n x = 1\n cnt = 0\n n, m = map(int, input().split())\n while x * x <= n:\n y = 1\n while (x + y) * x <= n and (x + y) * y <= m:\n if math.gcd(x, y) == 1:\n cnt += min(n / ((x + y) * x), m // ((x + y) * y))\n y += 1\n x += 1\n print(cnt)\n \ndef main():\n t = int(input())\n for _ in range(t):\n fun()\nif __name__ == \"__main__\":\n main()" + ] + }, + { + "task_name": "1973_A", + "description": "Three friends gathered to play a few games of chess together.\n\nIn every game, two of them play against each other. The winner gets 2 points\nwhile the loser gets 0 , and in case of a draw, both players get 1 point each.\nNote that the same pair of players could have played any non-negative number\nof times (possibly zero). It is also possible that no games were played at\nall.\n\nYou've been told that their scores after all the games were played were p_1 ,\np_2 and p_3 . Additionally, it is guaranteed that p_1 \\leq p_2 \\leq p_3 holds.\n\nFind the maximum number of draws that could have happened and print it. If\nthere isn't any way to obtain p_1 , p_2 and p_3 as a result of a non-negative\nnumber of games between the three players, print -1 instead.\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1 \\le t \\le 500 ). The description of the test cases follows.\n\nThe first line of each test case contains three integers p_1 , p_2 and p_3 (0\n\\leq p_1 \\leq p_2 \\leq p_3 \\leq 30 ) — the scores of the three players, sorted\nnon-decreasingly.\n\nOutput\n\nFor each testcase, print one number — the maximum possible number of draws\nthat could've happened, or -1 if the scores aren't consistent with any valid\nset of games and results.\n\nExample\n\nInput\n\n 7\n \n 0 0 0\n \n 0 1 1\n \n 1 1 1\n \n 1 1 2\n \n 3 3 3\n \n 3 4 5\n \n 1 1 10\n\nOutput\n\n 0\n 1\n -1\n 2\n -1\n 6\n 2\n \nNote\n\nIn the first example, no games were played at all, so no draws could occur\neither.\n\nFor the second example, exactly one game occurred between the second and the\nthird player and it ended in draw, so the answer is 1 .\n\nIt's easy to see that there's no set of games achieving the scores in third\nexample, so the answer for it is -1 .", + "generated_code": [ + "t=int(input())\nfor _ in range(t):\n p1,p2,p3=map(int,input().split())\n if (p1+p2+p3)%2!=0:\n print(-1)\n continue\n if p3>=p1+p2:\n print(p1+p2)\n else:\n low,high=min(p3-p1,p3-p2),max(p3-p1,p3-p2)\n cur=low\n while high>=cur:\n if p1-cur<=p2-(p3-cur):\n print(p1-cur+p3)\n break\n else:\n cur+=1\n else:\n print(p3)", + "def resoudre_padel_pour_trois(t, cas_de_test):\n resultats = []\n for p1, p2, p3 in cas_de_test:\n total_points = p1 + p2 + p3\n if total_points % 2 != 0:\n resultats.append(-1)\n continue\n \n total_matchs = total_points // 2\n if total_matchs > 3 or p3 > total_matchs:\n resultats.append(-1)\n continue\n \n egalites = total_points - (2 * (p3 - p2)) - (2 * (p3 - p1))\n if egalites < 0:\n resultats.append(-1)\n else:\n resultats.append(egalites // 2)\n return resultats\n \n# Entrées\nt = 7\ncas_de_test = [\n (0, 0, 0),\n (0, 1, 1),\n (0, 2, 3),\n (3, 3, 3),\n (3, 4, 5),\n (1, 1, 10),\n (0, 0, 6)\n]\n \n# Résolution et affichage des résultats\nresultats = resoudre_padel_pour_trois(t, cas_de_test)\nprint(\"\\n\".join(map(str, resultats)))" + ] + }, + { + "task_name": "1974_A", + "description": "Little Rosie has a phone with a desktop (or launcher, as it is also called).\nThe desktop can consist of several screens. Each screen is represented as a\ngrid of size 5 \\times 3 , i.e., five rows and three columns.\n\nThere are x applications with an icon size of 1 \\times 1 cells; such an icon\noccupies only one cell of the screen. There are also y applications with an\nicon size of 2 \\times 2 cells; such an icon occupies a square of 4 cells on\nthe screen. Each cell of each screen can be occupied by no more than one icon.\n\nRosie wants to place the application icons on the minimum number of screens.\nHelp her find the minimum number of screens needed.\n\nInput\n\nThe first line of the input contains t (1 \\leq t \\leq 10^4 ) — the number of\ntest cases.\n\nThe first and only line of each test case contains two integers x and y (0\n\\leq x, y \\leq 99 ) — the number of applications with a 1 \\times 1 icon and\nthe number of applications with a 2 \\times 2 icon, respectively.\n\nOutput\n\nFor each test case, output the minimal number of required screens on a\nseparate line.\n\nExample\n\nInput\n\n 11\n \n 1 1\n \n 7 2\n \n 12 4\n \n 0 3\n \n 1 0\n \n 8 1\n \n 0 0\n \n 2 0\n \n 15 0\n \n 8 2\n \n 0 9\n\nOutput\n\n 1\n 1\n 2\n 2\n 1\n 1\n 0\n 1\n 1\n 2\n 5\n \nNote\n\nThe solution for the first test case can look as follows:\n\n![](https://espresso.codeforces.com/f9882979f0d9b5c31c5260fd626217227c2f05de.png)\nBlue squares represent empty spaces for icons, green squares represent 1\n\\times 1 icons, red squares represent 2 \\times 2 icons\n\nThe solution for the third test case can look as follows:\n\n![](https://espresso.codeforces.com/0e737a290e056a29f38918bf06c13be790307a8d.png)", + "generated_code": [ + "a=int(input())\nfor i in range(a):\n x,y=map(int,input().split())\n z=(y+1)//2\n m=15*z-y*4\n if m 0 and y > 0:\n bxsfory = math.ceil(y / 2)\n x = x - bxsfory * 15 + y * 4\n bxsfory1 = 0 if x <= 0 else (math.ceil(x / 15) + 1)\n print(bxsfory1 + bxsfory)\n elif x == 0 and y > 0:\n print(math.ceil(y / 2))\n elif x > 0 and y == 0:\n print(math.ceil(x / 15))\n else:\n print(0)\n \ndef main():\n t = int(input())\n for _ in range(t):\n sol()\n \nif __name__ == \"__main__\":\n main()", + "n=int(input())\nfor i in range(n):\n a,b=input().split()\n a=int(a)\n b=int(b)\n t=b*2\n if t%5==0:\n t=t//5\n else:\n t=t//5+1\n t1=t*15-b*4\n if t1>=a:\n t=t\n else:\n t2=a-t1\n if t2%15==0:\n t=t+t2//15\n else:\n t=t+t2//15+1\n print(t)" + ] + }, + { + "task_name": "1974_B", + "description": "Polycarp has a string s , which consists of lowercase Latin letters. He\nencodes this string using the following algorithm:\n\n * first, he constructs a new auxiliary string r , which consists of all distinct letters of the string s , written in alphabetical order; \n * then the encoding happens as follows: each character in the string s is replaced by its symmetric character from the string r (the first character of the string r will be replaced by the last, the second by the second from the end, and so on). \n\nFor example, encoding the string s =\"codeforces\" happens as follows:\n\n * the string r is obtained as \"cdefors\"; \n * the first character s_1 ='c' is replaced by 's'; \n * the second character s_2 ='o' is replaced by 'e'; \n * the third character s_3 ='d' is replaced by 'r'; \n * ... \n * the last character s_{10} ='s' is replaced by 'c'. \n\n![](https://espresso.codeforces.com/b6f889887677396af4d296900b8ca492324e83ef.png)\nThe string r and replacements for s =\"codeforces\".\n\nThus, the result of encoding the string s =\"codeforces\" is the string\n\"serofedsoc\".\n\nWrite a program that performs decoding — that is, restores the original string\ns from the encoding result.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 10^4 ) — the number of\ntest cases.\n\nThe first line of each test case contains a single integer n (1 \\le n \\le 2\n\\cdot 10^5 ) — the length of the string b .\n\nThe second line of each test case contains a string b of length n , consisting\nof lowercase Latin letters — the result of encoding the original string s .\n\nIt is guaranteed that the sum of the values of n over all test cases in the\ntest does not exceed 2 \\cdot 10^5 .\n\nOutput\n\nFor each test case, output the string s from which the encoding result b was\nobtained.\n\nExample\n\nInput\n\n 5\n \n 10\n \n serofedsoc\n \n 3\n \n ttf\n \n 9\n \n tlrhgmaoi\n \n 1\n \n w\n \n 15\n \n hnndledmnhlttin\n\nOutput\n\n codeforces\n fft\n algorithm\n w\n meetinthemiddle", + "generated_code": [ + "def decode_string(b):\n \"\"\"\n Decode the given string b by restoring the original string s.\n \n Args:\n b (str): The encoded string.\n \n Returns:\n str: The decoded string s.\n \"\"\"\n # Create a dictionary to store the mapping between characters in the encoded string b and their corresponding indices in the alphabet\n char_map = {}\n for i, c in enumerate(sorted(set(b))):\n char_map[c] = chr(ord('a') + (len(b) - i - 1))\n \n # Initialize an empty string to store the decoded string s\n s = \"\"\n \n # Iterate through the encoded string b\n for c in b:\n # Find the index of the character in the alphabet and map it to its corresponding character in the decoded string s\n s += char_map[c]\n \n return s\n \n# Read the number of test cases\nnum_test_cases = int(input())\n \nfor _ in range(num_test_cases):\n # Read the length of the string b\n num_chars = int(input())\n \n # Read the encoded string b\n b = input()\n \n # Decode the string b and print the result\n print(decode_string(b))", + "def symmetric_encode(s):\n # Create a list of unique characters from the input string\n unique_chars = sorted(list({char for char in s}))\n \n i, j = 0, len(unique_chars) - 1\n \n # Encode the input string\n for char in s:\n if char in unique_chars:\n # Replace the current character with its symmetric counterpart\n s = s.replace(char, unique_chars[j])\n j -= 1\n else:\n # Add the new character to the unique_chars list\n unique_chars.insert(i, char)\n \n # Update i and j\n i += 1\n j += 1\n \n return ''.join(unique_chars)\n \n# Main function\nif __name__ == \"__main__\":\n t = int(input())\n \n for _ in range(t):\n n = int(input())\n b = input()\n \n # Get the encoded string\n encoded_str = symmetric_encode(b)\n \n # Print the encoded string\n print(encoded_str)", + "import sys\nfrom typing import List\n \ninput = sys.stdin.readline\n \ndef decode(encoded: str) -> str:\n mapping = {}\n decoded = []\n \n for char in encoded:\n if char in mapping:\n decoded.append(mapping[char])\n else:\n # Find the next unused letter from 'a' to 'z'\n for c in range(ord('a'), ord('z') + 1):\n if chr(c) not in mapping.values():\n mapping[chr(c)] = char\n break\n decoded.append(chr(c))\n \n return \"\".join(decoded)\n \nif __name__ == \"__main__\":\n num_cases = int(input().strip())\n \n for _ in range(num_cases):\n n = int(input().strip())\n encoded = input().strip()\n decoded = decode(encoded)\n print(decoded)" + ] + }, + { + "task_name": "1975_A", + "description": "Mocha likes arrays, so before her departure, Bazoka gave her an array a\nconsisting of n positive integers as a gift.\n\nNow Mocha wants to know whether array a could become sorted in non-decreasing\norder after performing the following operation some (possibly, zero) times:\n\n * Split the array into two parts — a prefix and a suffix, then swap these two parts. In other words, let a=x+y . Then, we can set a:= y+x . Here + denotes the array concatenation operation. \n\nFor example, if a=[3,1,4,1,5] , we can choose x=[3,1] and y=[4,1,5] ,\nsatisfying a=x+y . Then, we can set a:= y + x = [4,1,5,3,1] . We can also\nchoose x=[3,1,4,1,5] and y=[\\,] , satisfying a=x+y . Then, we can set a := y+x\n= [3,1,4,1,5] . Note that we are not allowed to choose x=[3,1,1] and y=[4,5] ,\nneither are we allowed to choose x=[1,3] and y=[5,1,4] , as both these choices\ndo not satisfy a=x+y .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\leq t\\leq 1000 ). The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (2\\leq n\\leq 50 )\n— the length of the array a .\n\nThe second line of each test case contains n integers a_1,a_2,\\ldots,a_n\n(1\\leq a_i \\leq 10^6 ) — the elements of array a .\n\nOutput\n\nFor each test case, output \"Yes\" if a could become non-decreasing after\nperforming the operation any number of times, and output \"No\" if not.\n\nYou can output \"Yes\" and \"No\" in any case (for example, strings \"yEs\", \"yes\",\n\"Yes\" and \"YES\" will be recognized as a positive response).\n\nExample\n\nInput\n\n 3\n \n 6\n \n 1 1 4 5 1 4\n \n 5\n \n 7 9 2 2 3\n \n 3\n \n 1 2 3\n\nOutput\n\n No\n Yes\n Yes\n \nNote\n\nIn the first test case, it can be proven that a cannot become non-decreasing\nafter performing the operation any number of times.\n\nIn the second test case, we can perform the following operations to make a\nsorted in non-decreasing order:\n\n * Split the array into two parts: x=[7] and y=[9,2,2,3] , then swap these two parts. The array will become y+x = [9,2,2,3,7] . \n * Split the array into two parts: x=[9] and y=[2,2,3,7] , then swap these two parts. The array will become y+x=[2,2,3,7,9] , which is non-decreasing.", + "generated_code": [ + "def can_sort_by_split_swap(arr):\n # Check if the array is already sorted\n if all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)):\n return \"Yes\"\n \n # If not, attempt to sort by simulating the split and swap operation\n # Since the operation only rearranges elements, direct check suffices\n return \"No\" if any(arr[i] > arr[i + 1] for i in range(len(arr) - 1)) else \"Yes\"\n \n# Main function to read inputs and print outputs\ndef main():\n import sys\n input = sys.stdin.read\n data = input().split()\n \n index = 0\n t = int(data[index])\n index += 1\n results = []\n \n for _ in range(t):\n n = int(data[index])\n index += 1\n arr = list(map(int, data[index:index + n]))\n index += n\n \n result = can_sort_by_split_swap(arr)\n results.append(result)\n \n print(\"\\n\".join(results))\n \nif __name__ == \"__main__\":\n main()", + "t = int(input())\n \n \nfor _ in range(t):\n\tn = int(input())\n\t\n\ta = list(map(int, input().split()))\n\t\n\tcheck_all = all([ a[i-1]< a[i] for i in range(1 , n)])\n\t\n\tif check_all:\n\t\tprint(\"YES\")\n\telse:\n\t\tfor i in range(1, n):\n\t\t\tif a[i-1] > a[i]:\n\t\t\t\tnew = a[i:]\n\t\t\t\tcheck_all = all([ a[0]> new[i] for i in range(len(new))])\n\t\t\t\tnew_all = all([ new[i-1]<= new[i] for i in range(1, len(new))])\n\t\t\t\t\n\t\t\t\tif check_all and new_all:\n\t\t\t\t\tprint(\"YES\")\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint(\"NO\")\n\t\t\t\t\tbreak" + ] + }, + { + "task_name": "1975_C", + "description": "Mocha likes arrays, so before her departure, Chamo gave her an array a\nconsisting of n positive integers as a gift.\n\nMocha doesn't like arrays containing different numbers, so Mocha decides to\nuse magic to change the array. Mocha can perform the following three-step\noperation some (possibly, zero) times:\n\n 1. Choose indices l and r (1 \\leq l < r \\leq n ) \n 2. Let x be the median^\\dagger of the subarray [a_l, a_{l+1},\\ldots, a_r] \n 3. Set all values a_l, a_{l+1},\\ldots, a_r to x \n\nSuppose a=[1,2,3,4,5] initially:\n\n * If Mocha chooses (l,r)=(3,4) in the first operation, then x=3 , the array will be changed into a=[1,2,3,3,5] . \n * If Mocha chooses (l,r)=(1,3) in the first operation, then x=2 , the array will be changed into a=[2,2,2,4,5] . \n\nMocha will perform the operation until the array contains only the same\nnumber. Mocha wants to know what is the maximum possible value of this number.\n\n^\\dagger The median in an array b of length m is an element that occupies\nposition number \\lfloor \\frac{m+1}{2} \\rfloor after we sort the elements in\nnon-decreasing order. For example, the median of [3,1,4,1,5] is 3 and the\nmedian of [5,25,20,24] is 20 .\n\nInput\n\nEach test contains multiple test cases. The first line contains the number of\ntest cases t (1\\leq t\\leq 500 ). The description of the test cases follows.\n\nThe first line of each test case contains a single integer n (2\\leq n\\leq 10^5\n) — the length of the array a .\n\nThe second line of each test case contains n integers a_1,a_2,\\ldots,a_n\n(1\\leq a_i \\leq 10^9 ) — the elements of the array a .\n\nIt is guaranteed that the sum of n over all test cases does not exceed 10^5 .\n\nOutput\n\nFor each test case, output the maximum value of the number.\n\nExample\n\nInput\n\n 2\n \n 2\n \n 1 2\n \n 5\n \n 1 2 3 4 5\n\nOutput\n\n 1\n 4\n \nNote\n\nIn the first test case, a=[1,2] . Mocha can only choose the interval\n(l,r)=(1,2) . The array will be changed to a=[1,1] . Therefore, the answer is\n1 .\n\nIn the second test case, Mocha can perform the following operations:\n\n * Choose the interval (l,r)=(4,5) , then a=[1,2,3,4,4] . \n * Choose the interval (l,r)=(3,5) , then a=[1,2,4,4,4] . \n * Choose the interval (l,r)=(1,5) , then a=[4,4,4,4,4] . \n\nThe array contains only the same number, which is 4 . It can be proven that\nthe maximum value of the final number cannot be greater than 4 .", + "generated_code": [ + "t = int(input())\nfor _ in range(t):\n n=int(input())\n a=list(map(int, input().split()))\n max=0\n for i in range(1,n):\n if min(a[i],a[i-1])>max:\n max=min(a[i],a[i-1])\n # print('result=',max)\n print(max)" + ] + }, + { + "task_name": "1976_A", + "description": "Monocarp is working on his new site, and the current challenge is to make the\nusers pick strong passwords.\n\nMonocarp decided that strong passwords should satisfy the following\nconditions:\n\n * password should consist only of lowercase Latin letters and digits; \n * there should be no digit that comes after a letter (so, after each letter, there is either another letter or the string ends); \n * all digits should be sorted in the non-decreasing order; \n * all letters should be sorted in the non-decreasing order. \n\nNote that it's allowed for the password to have only letters or only digits.\n\nMonocarp managed to implement the first condition, but he struggles with the\nremaining ones. Can you help him to verify the passwords?\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 1000 ) — the number of\ntestcases.\n\nThe first line of each testcase contains a single integer n (1 \\le n \\le 20 )\n— the length of the password.\n\nThe second line contains a string, consisting of exactly n characters. Each\ncharacter is either a lowercase Latin letter or a digit.\n\nOutput\n\nFor each testcase, print \"YES\" if the given password is strong and \"NO\"\notherwise.\n\nExample\n\nInput\n\n 5\n \n 4\n \n 12ac\n \n 5\n \n 123wa\n \n 9\n \n allllmost\n \n 5\n \n ac123\n \n 6\n \n 011679\n\nOutput\n\n YES\n NO\n YES\n NO\n YES\n \nNote\n\nIn the second testcase, the letters are not sorted in the non-decreasing\norder.\n\nIn the fourth testcase, there is a digit that comes after a letter — digit '1'\nafter a letter 'c'.", + "generated_code": [ + "def is_strong_password(password):\n digits = []\n letters = []\n \n for char in password:\n if char.isdigit():\n digits.append(char)\n else:\n letters.append(char)\n \n # Check if no digit appears after any letter\n last_digit_index = -1\n for i, char in enumerate(password):\n if char.isdigit():\n last_digit_index = i\n elif last_digit_index != -1:\n return \"NO\"\n \n # Check if digits are sorted in non-decreasing order\n if digits != sorted(digits):\n return \"NO\"\n \n # Check if letters are sorted in non-decreasing order\n if letters != sorted(letters):\n return \"NO\"\n \n return \"YES\"\n \n# Read input\nimport sys\ninput = sys.stdin.read\ndata = input().split()\n \nt = int(data[0])\nindex = 1\nresults = []\n \nfor _ in range(t):\n n = int(data[index])\n password = data[index + 1]\n index += 2\n results.append(is_strong_password(password))\n \n# Output results\nprint(\"\\n\".join(results))", + "def is_strong_password(t, test_cases):\n results = []\n \n for n, password in test_cases:\n # Split letters and digits\n letters = \"\"\n digits = \"\"\n for ch in password:\n if ch.isalpha():\n letters += ch\n elif ch.isdigit():\n digits += ch\n \n # Check if letters and digits are both sorted in non-decreasing order\n if list(letters) != sorted(letters) or list(digits) != sorted(digits):\n results.append(\"NO\")\n continue\n \n # Check if letters appear before digits\n if letters and digits and password.index(letters[-1]) > password.index(digits[0]):\n results.append(\"NO\")\n else:\n results.append(\"YES\")\n \n return results\n \n \n# Input Reading\nt = int(input(\"Number of test cases, t = \")) # Number of test cases\ntest_cases = []\nfor _ in range(t):\n n = int(input(\"Length of password, n: \")) # Length of the password (we won't actually use this value)\n password = input(\"enter passowrd: \").strip()\n test_cases.append((n, password))\n \n# Get the result\nresults = is_strong_password(t, test_cases)\n \n# Output the results\nfor result in results:\n print(result)" + ] + }, + { + "task_name": "1977_A", + "description": "The little boy Nikita was given some cubes as a present. He decided to build a\ntower out of them.\n\nInitially, the tower doesn't have any cubes. In one move, Nikita either puts\nexactly 1 cube on top of the tower or removes exactly 1 cube from the top of\nthe tower. Is it possible that after n moves, the resulting tower has exactly\nm cubes?\n\nInput\n\nEach test contains multiple test cases. The first line of input contains a\nsingle integer t (1 \\le t \\le 100 ) — the number of test cases. The\ndescription of the test cases follows.\n\nThe only line of each test case contains two integers n and m (1 \\le n, m \\le\n100 ).\n\nOutput\n\nFor each test case, output \"Yes\" (without quotes) if Nikita can obtain a tower\nwith m cubes, and \"No\" (without quotes) otherwise.\n\nYou can output each letter in any case (lowercase or uppercase). For example,\nthe strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be accepted as a positive\nanswer.\n\nExample\n\nInput\n\n 3\n \n 3 3\n \n 2 4\n \n 5 3\n\nOutput\n\n Yes\n No\n Yes\n \nNote\n\nIn the first test case, Nikita can put 1 cube on top of the tower 3 times in a\nrow, so the answer is \"Yes\".\n\nIn the second test case, Nikita can only end up with either a tower with no\nblocks or a tower with 2 blocks, so the answer is \"No\".", + "generated_code": [ + "t = int(input())\nfor i in range(t):\n n, m = [int(i) for i in input().split()]\n if n==m:\n print('Yes')\n elif m>n:\n print('No')\n else:\n if m==n-1:\n print('Yes')\n else:\n if m%2==0 and n%2==0:\n print('Yes')\n elif m%2!=0 and n%2!=0:\n print('Yes')\n else:\n print('No')", + "a=int(input())\nfor i in range(a):\n b,c=map(int,input().split())\n q=(b,c)\n if b==c:\n print('YES')\n elif b=m:\n print('Yes')\n else:\n print('No')\nkreker=int(input())\nfor i in range(kreker):\n makaroni()", + "for _ in range(int(input())):\n n,m=map(int,input().split())\n if n= b:\n\t\tprint(n*a)\n\telse:\n\t\tk = min(b-a+1,n)\n\t\tans = int(((b + (b-k+1))/2)*k)\n\t\tp2 = (n-k) * a\n\t\tprint(ans + p2)", + "t=int(input())\nfor _ in range(t):\n n,a,b=map(int,input().split())\n if b<=a:\n print(n*a)\n else:\n if (b-a)>=n:\n print(int((2*b-n+1)*n/2))\n else:\n print(int((b-a)/2*(b-a+1)+a*n))", + "for _ in range(int(input())):\n n,a,b=map(int,input().split())\n k=min(n,b-a)\n if(b<=a):\n print(a*n)\n else:\n print((b+(b-k+1))//2*k+(n-k)*a)", + "def can(k, a, b, n):\n ans = 0\n ans += k * b\n ans += (n - k) * a\n return ans <= n * max(a, b)\n \nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n n, a, b = map(int, input().split())\n low = 0\n high = n\n ans = -1\n \n while low <= high:\n mid = (low + high) // 2\n if can(mid, a, b, n):\n ans = mid\n low = mid + 1\n else:\n high = mid - 1\n \n print(ans)", + "t = int(input())\nwhile t:\n x = list(map(int,input().split(\" \")))\n n = x[0]\n a = x[1]\n b = x[2]\n profit = n*a\n if a >= b:\n print(profit)\n else:\n k = b-a\n k = min(n-1,k)\n profit = profit + (b-a)*(k+1) - (k*(k+1))/2\n \n print(int(profit))\n \n t-=1" + ] + }, + { + "task_name": "1978_C", + "description": "Let's call the Manhattan value of a permutation^{\\dagger} p the value of the\nexpression |p_1 - 1| + |p_2 - 2| + \\ldots + |p_n - n| .\n\nFor example, for the permutation [1, 2, 3] , the Manhattan value is |1 - 1| +\n|2 - 2| + |3 - 3| = 0 , and for the permutation [3, 1, 2] , the Manhattan\nvalue is |3 - 1| + |1 - 2| + |2 - 3| = 2 + 1 + 1 = 4 .\n\nYou are given integers n and k . Find a permutation p of length n such that\nits Manhattan value is equal to k , or determine that no such permutation\nexists.\n\n^{\\dagger} A permutation of length n is an array consisting of n distinct\nintegers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a\npermutation, but [1,2,2] is not a permutation (2 appears twice in the array),\nand [1,3,4] is also not a permutation (n=3 but there is 4 in the array).\n\nInput\n\nEach test consists of multiple test cases. The first line contains a single\ninteger t (1 \\leq t \\leq 10^{4} ) — the number of test cases. The description\nof the test cases follows.\n\nThe only line of each test case contains two integers n and k (1 \\le n \\le 2\n\\cdot 10^{5}, 0 \\le k \\le 10^{12} ) — the length of the permutation and the\nrequired Manhattan value.\n\nIt is guaranteed that the sum of n over all test cases does not exceed 2 \\cdot\n10^{5} .\n\nOutput\n\nFor each test case, if there is no suitable permutation, output \"No\".\nOtherwise, in the first line, output \"Yes\", and in the second line, output n\ndistinct integers p_1, p_2, \\ldots, p_n (1 \\le p_i \\le n ) — a suitable\npermutation.\n\nIf there are multiple solutions, output any of them.\n\nYou can output the answer in any case (for example, the strings \"yEs\", \"yes\",\n\"Yes\", and \"YES\" will be recognized as a positive answer).\n\nExample\n\nInput\n\n 8\n \n 3 4\n \n 4 5\n \n 7 0\n \n 1 1000000000000\n \n 8 14\n \n 112 777\n \n 5 12\n \n 5 2\n\nOutput\n\n Yes\n 3 1 2\n No\n Yes\n 1 2 3 4 5 6 7\n No\n Yes\n 8 2 3 4 5 6 1 7\n No\n Yes\n 5 4 3 1 2\n Yes\n 2 1 3 4 5\n \nNote\n\nIn the first test case, the permutation [3, 1, 2] is suitable, its Manhattan\nvalue is |3 - 1| + |1 - 2| + |2 - 3| = 2 + 1 + 1 = 4 .\n\nIn the second test case, it can be proven that there is no permutation of\nlength 4 with a Manhattan value of 5 .\n\nIn the third test case, the permutation [1,2,3,4,5,6,7] is suitable, its\nManhattan value is |1-1|+|2-2|+|3-3|+|4-4|+|5-5|+|6-6|+|7-7|=0 .", + "generated_code": [ + "def list_p(n,k):\n k=k//2\n l=list(range(1,n+1))\n for i in range(n-1,-1,-1):\n if k==0:\n return l\n if 1+i>k:\n x=l[-1]\n l.pop(-1)\n l.insert(-k,x)\n return l\n k=k-i+1\n x=l[-1]\n l.pop(-1)\n l.insert(0,x)\n \ndef tf():\n n,k=map(int,input().split())\n if k%2:\n return 0,0\n if n%2:\n max_k=(n**2-1)//2\n else:\n max_k=(n**2)//2\n if max_k=(m/hcf):\n print(-1)\n else:\n for i in range(n):\n print(c[i], end=' ')\n print('')", + "t = int(input())\nfor T in range(t):\n\t#x, y, k = map(int, input().split())\n\t\n\tbets=int(input())\n\ta = [int(x) for x in input().split()]\n\tprod=1\n\tfor i in range(bets):\n\t prod*=a[i]\n\tsumo=0\n\tfor i in range(bets):\n\t a[i]=(prod//a[i])\n\t sumo+=int(a[i])\n\t\n\tif sumo>=prod:\n\t print(-1)\n\telse:\n\t ans=\"\"\n\t for i in range(bets):\n\t ans+=str(a[i])+\" \"\n\t print(ans)", + "def solve():\n N = int(input().strip())\n vals = [int(r) for r in input().strip().split()]\n prod = 1\n for r in vals:\n prod *= r\n vprod = [prod//r for r in vals]\n den = prod - sum(vprod)\n if den <= 0:\n print(-1)\n return\n \n print(\" \".join([str(x) for x in vprod]))\n \ncases = int(input())\nfor n in range(cases):\n solve()", + "from math import gcd\n \ndef calculate_hcf(numbers):\n hcf = numbers[0]\n for num in numbers[1:]:\n hcf = gcd(hcf, num)\n return hcf\n \nt = int(input())\nfor _ in range(t):\n n=int(input())\n k=list(map(int, input().split()))\n m=1\n for i in range(n):\n m=m*k[i]\n c=[]\n for i in range(n):\n c.append(int(m/k[i]))\n hcf=calculate_hcf(c)\n for i in range(n):\n c[i]=int(c[i]/hcf)\n if sum(c)>=m:\n print(-1)\n else:\n for i in range(n):\n print(c[i], end=' ')\n print('')" + ] + }, + { + "task_name": "1980_A", + "description": "Vlad is planning to hold m rounds next month. Each round should contain one\nproblem of difficulty levels 'A', 'B', 'C', 'D', 'E', 'F', and 'G'.\n\nVlad already has a bank of n problems, where the i -th problem has a\ndifficulty level of a_i . There may not be enough of these problems, so he may\nhave to come up with a few more problems.\n\nVlad wants to come up with as few problems as possible, so he asks you to find\nthe minimum number of problems he needs to come up with in order to hold m\nrounds.\n\nFor example, if m=1 , n = 10 , a= 'BGECDCBDED', then he needs to come up with\ntwo problems: one of difficulty level 'A' and one of difficulty level 'F'.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 1000 ) — the number of\ntest cases.\n\nThe first line of each test case contains two integers n and m (1 \\le n \\le 50\n, 1 \\le m \\le 5 ) — the number of problems in the bank and the number of\nupcoming rounds, respectively.\n\nThe second line of each test case contains a string a of n characters from 'A'\nto 'G' — the difficulties of the problems in the bank.\n\nOutput\n\nFor each test case, output a single integer — the minimum number of problems\nthat need to come up with to hold m rounds.\n\nExample\n\nInput\n\n 3\n \n 10 1\n \n BGECDCBDED\n \n 10 2\n \n BGECDCBDED\n \n 9 1\n \n BBCDEFFGG\n\nOutput\n\n 2\n 5\n 1", + "generated_code": [ + "from collections import Counter\nt=int(input())\nfor _ in range(t):\n n,m=map(int,input().split())\n s=input()\n ans=0\n p=\"ABCDEF\"\n hmp=Counter(s)\n for i in p:\n if i not in hmp:\n ans+=m\n for i in hmp:\n if hmp[i]0):\n t-=1 \n d=defaultdict(default_value)\n n,m=list(map(int,input().split())) \n s=input() \n for i in range(n):\n d[s[i]]=d[s[i]]+1 \n ans=0\n \n for val in d.keys():\n if(d[val]<=m):\n ans=ans+m-d[val]\n print(ans)", + "def min_problems_to_create(t, test_cases):\n \"\"\"\n Calculate the minimum number of problems Vlad needs to create.\n \n Args:\n t (int): Number of test cases.\n test_cases (list): List of test cases, where each test case is a tuple containing\n - n (int): Number of problems in the bank.\n - m (int): Number of upcoming rounds.\n - a (str): String of problem difficulties.\n \n Returns:\n list: List of results, one for each test case.\n \"\"\"\n \n results = []\n \n for _ in range(t):\n n, m, a = test_cases[_]\n \n # Initialize frequency array\n freq = [0] * 7\n \n # Count frequency of each type of problem\n for prob in a:\n freq[ord(prob) - ord('A')] += 1\n \n # Calculate missing problems\n missing = sum(max(0, m - f) for f in freq)\n \n results.append(missing)\n \n return results\n \n \n# Example usage\nt = 3\ntest_cases = [\n (10, 1, \"BGECDCBDED\"),\n (10, 2, \"BGECDCBDED\"),\n (9, 1, \"BBCDEFFGG\")\n]\n \nresults = min_problems_to_create(t, test_cases)\nfor result in results:\n print(result)" + ] + }, + { + "task_name": "1948_D", + "description": "You are given a string s , consisting of lowercase Latin letters and/or\nquestion marks.\n\nA tandem repeat is a string of an even length such that its first half is\nequal to its second half.\n\nA string a is a substring of a string b if a can be obtained from b by the\ndeletion of several (possibly, zero or all) characters from the beginning and\nseveral (possibly, zero or all) characters from the end.\n\nYour goal is to replace each question mark with some lowercase Latin letter in\nsuch a way that the length of the longest substring that is a tandem repeat is\nmaximum possible.\n\nInput\n\nThe first line contains a single integer t (1 \\le t \\le 1000 ) — the number of\ntestcases.\n\nThe only line of each testcase contains a string s (1 \\le |s| \\le 5000 ),\nconsisting only of lowercase Latin letters and/or question marks.\n\nThe total length of the strings over all testcases doesn't exceed 5000 .\n\nOutput\n\nFor each testcase, print a single integer — the maximum length of the longest\nsubstring that is a tandem repeat after you replace each question mark in the\nstring with some lowercase Latin letter.\n\nIf it's impossible to make any tandem repeat substrings in the string, print 0\n.\n\nExample\n\nInput\n\n 4\n \n zaabaabz\n \n ?????\n \n code?????s\n \n codeforces\n\nOutput\n\n 6\n 4\n 10\n 0", + "generated_code": [ + "t = int(input())\n \n \ndef solve():\n for j in range(n // 2, 0, -1):\n count = 0\n for k in range(0, n - j):\n if s[k] == '?' or s[k + j] == '?' or s[k] == s[k + j]:\n count += 1\n else:\n count = 0\n if count == j:\n print(count * 2)\n return\n return 0\n \nfor i in range(t):\n s = list(input())\n n = len(s)\n \n solve()" + ] + }, + { + "task_name": "1955_B", + "description": "A progressive square of size n is an n \\times n matrix. Maxim chooses three\nintegers a_{1,1} , c , and d and constructs a progressive square according to\nthe following rules:\n\nFor example, if n = 3 , a_{1,1} = 1 , c=2 , and d=3 , then the progressive\nsquare looks as follows:\n\nLast month Maxim constructed a progressive square and remembered the values of\nn , c , and d . Recently, he found an array b of n^2 integers in random order\nand wants to make sure that these elements are the elements of that specific\nsquare.\n\nIt can be shown that for any values of n , a_{1,1} , c , and d , there exists\nexactly one progressive square that satisfies all the rules.\n\nInput\n\nThe first line contains an integer t (1 \\le t \\le {10} ^ 4 ) — the number of\ntest cases.\n\nThe first line of each test case contains three integers n , c , and d (2 \\le\nn \\le 500 , 1 \\le c, d \\le 10^6 ) — the size of the square and the values of c\nand d as described in the statement.\n\nThe second line of each test case contains n \\cdot n integers b_1, b_2, \\dots,\nb_{n \\cdot n} (1 \\le b_i \\le 10^9 ) — the elements found by Maxim.\n\nIt is guaranteed that the sum of n ^ 2 over all test cases does not exceed 25\n\\cdot {10} ^ 4 .\n\nOutput\n\nFor each test case, output \"YES\" in a separate line if a progressive square\nfor the given n , c , and d can be constructed from the array elements a ,\notherwise output \"NO\".\n\nYou can output each letter in any case (lowercase or uppercase). For example,\nthe strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will be accepted as a positive\nanswer.\n\nExample\n\nInput\n\n 5\n \n 3 2 3\n \n 3 9 6 5 7 1 10 4 8\n \n 3 2 3\n \n 3 9 6 5 7 1 11 4 8\n \n 2 100 100\n \n 400 300 400 500\n \n 3 2 3\n \n 3 9 6 6 5 1 11 4 8\n \n 4 4 4\n \n 15 27 7 19 23 23 11 15 7 3 19 23 11 15 11 15\n\nOutput\n\n NO\n YES\n YES\n NO\n NO", + "generated_code": [ + "def fn(n,c,d,l):\n l.sort()\n if not l[-1]-l[0]==(n-1)*(c+d):\n return 'no'\n \n a=l[0]+l[-1]\n \n r=(n**2)//2\n if n%2!=0:\n if not l[r]==a//2:\n return 'NO'\n \n for k in range(r):\n if not l[k]==l[-1-k]:\n return 'no'\n return 'yes'\n \nt=int(input())\nfor _ in range(t):\n n,c,d=map(int,input().split())\n l=list(map(int,input().split()))\n print(fn(n,c,d,l))" + ] + }, + { + "task_name": "1970_F1", + "description": "This afternoon, you decided to enjoy the first days of Spring by taking a walk\noutside. As you come near the Quidditch field, you hear screams. Once again,\nthere is a conflict about the score: the two teams are convinced that they won\nthe game! To prevent this problem from happening one more time, you decide to\nget involved in the refereeing of the matches.\n\nNow, you will stay in the stadium to watch the game and count the score. At\nthe end of the game, you will decide the winner.\n\nToday, two teams are competing: the red Gryffindor (R) and the blue Ravenclaw\n(B) team. Each team is composed of P players (1 \\leq P \\leq 10 ).\n\nThe field is a rectangle of N lines and M columns (3 \\leq N, M \\leq 99 , N and\nM are odd). All the positions are integers, and several entities are allowed\nto be at the same position in the field. At the beginning of the game, the\nfield contains goals for the two teams (each team can own between one and five\ngoals), the players, and exactly one Quaffle. Other types of balls will be\navailable in the harder versions of the problem.\n\nA game is composed of T steps (0 \\leq T \\leq 10000 ). At each step, one entity\non the field (a player or a ball) performs one action. All entities can move.\nA player can also catch a ball or throw the Quaffle that it is carrying. To\ncatch a ball, a player must be located on the same cell as it. The Quaffle\ndoes not perform any action while it is being carried; it only follows the\nmovements of the player. If a player carrying the Quaffle decides to throw it,\nthe Quaffle is simply put at the current position of the player.\n\nTo win a point, a player must leave the Quaffle at a goal of the other team.\nWhen it does, the team of the player wins one point, and the Quaffle instantly\nmoves to the middle of the field (the cell at the (M+1)/2 -th column of the\n(N+1)/2 -th line of the field, starting from 1). There is no goal in the\nmiddle of the field. If a player puts the ball in its own goal, the other team\nwins the point.\n\nInput\n\nOn the first line, the integers N and M .\n\nThe description of the field follows: N lines of M pairs of characters\nseparated by spaces. Each pair of characters represents a position on the\nfield. It can be either:\n\n * .. to represent an empty cell \n * R0, ..., R9, B0, ..., B9 to represent a player. The first character is the team of the player, and the second is the number of the player in the team. Each pair of characters is unique, but it is not guaranteed that all the pairs appear in the grid. \n * RG or BG to represent a goal. The blue team tries to put the ball in a red goal (RG) while the red team tries to put the ball in a blue goal (BG). \n * .Q to represent the Quaffle, which is the ball that the players use to score goals. \n\nThe next line contains T , the number of steps that compose the game. T lines\nfollow, each describing one action. It contains several pieces of information\nseparated by a space. First, a pair of characters representing the entity that\nmust perform the action. Second, the description of the action:\n\n * U, D, L, R indicate that the entity moves on the grid. It can move to the top of the grid (U), to the bottom (D), to the left (L), or to the right (R). Each entity moves by only one cell at a time. \n * C indicates that the player catches the ball (only a player can catch a ball). Then, there is a space followed by a pair of characters: the description of the ball caught by the player. This information is needed since in the next versions of the problem, several balls may be in the same cell. \n * T indicates that the player throws the Quaffle that it is carrying. \n\nAll the actions performed by the entities are guaranteed to be valid: the\nplayers stay in the field, don't catch a ball if they are not in the same\ncell, don't release the Quaffle if they are not carrying it, ...\n\nOutput\n\nYou must output the description of the main events of the game, one event per\nline. More precisely:\n\n * Each time a team scores, you must print t RED GOAL or t BLUE GOAL, depending on the team who scored, where t is the current time (the position of the action in the list of actions, starting from 0). In the case where a player scores in the wrong goal (a red player scores in the red goal, or a blue player scores in the blue goal), you must print the name of the team who wins one point, that is, the other team. \n\nThe events must be printed in ascending order of t.\n\nAt the end of the game, you must print the final score as: FINAL SCORE: r b,\nwhere r is the score of the red team and b is the score of the blue team.\n\nExamples\n\nInput\n\n 5 5\n \n .. R1 .. B1 ..\n \n RG .. .. .. BG\n \n RG R0 .Q B0 BG\n \n RG .. .. .. BG\n \n .. R2 .. B2 ..\n \n 13\n \n B2 U\n \n B2 U\n \n B2 L\n \n B2 C .Q\n \n B2 L\n \n B2 L\n \n B2 T\n \n R0 R\n \n R0 C .Q\n \n R0 D\n \n R0 R\n \n R0 R\n \n R0 T\n\nOutput\n\n 6 BLUE GOAL\n 12 RED GOAL\n FINAL SCORE: 1 1\n \nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 12\n \n R0 D\n \n R0 C .Q\n \n R0 R\n \n R0 T\n \n R0 D\n \n B0 R\n \n B0 U\n \n B0 C .Q\n \n B0 L\n \n B0 L\n \n B0 L\n \n B0 T\n\nOutput\n\n 11 BLUE GOAL\n FINAL SCORE: 0 1\n \nInput\n\n 3 5\n \n .. .. R0 .. ..\n \n RG .. .Q .. BG\n \n .. .. B0 .. ..\n \n 5\n \n R0 D\n \n R0 C .Q\n \n R0 L\n \n R0 L\n \n R0 T\n\nOutput\n\n 4 BLUE GOAL\n FINAL SCORE: 0 1\n \nNote\n\nIn the first example, a blue player goes to the middle of the grid, at the\nposition of the Quaffle. He takes it, goes to the goal of the red team, and\nlets the ball there. He scores! The ball gets back to the middle of the field,\na red player takes it and scores too.\n\nIn the second example, the red player takes the Quaffle, move it and throw it.\nThe blue player catches the ball, goes to the red goal and scores.\n\nIn the third example, the red player takes the ball and scores in the goal of\ntheir own team: the blue team wins a point.", + "generated_code": [ + "from sys import stdin\n \nmov = {'U':(-1,0),'D':(1,0),'L':(0,-1),'R':(0,1),'T':(0,0)};\nGoalName = [\"RED\", \"BLUE\"]\n \ndef main():\n n,m = map(int,stdin.readline().strip().split());\n grid = [];\n elements = {\".B\":(0,0)};\n allPlayers = {};\n goal = [[],[]]\n points= [0,0];\n \n def goalIn( pos ):\n res = 0 if ( pos in goal[0] ) else ( 1 if ( pos in goal[1] ) else -1 );\n return res;\n def isPlayer( el ):\n res = (el[0] == 'B' or el[0] == 'R')and(el[1]!='G');\n return res;\n \n for i in range(n):\n line = stdin.readline().strip().split();\n grid.append( line );\n for ind in range(len(line)):\n if ( line[ind] != \"..\" ):\n elements[line[ind]] = (i,ind);\n if ( isPlayer( line[ind] ) ):\n allPlayers[line[ind]] = False;\n elif ( line[ind][1]=='G' ):\n tmp = 0 if line[ind][0] =='B' else 1;\n goal[tmp].append( (i,ind) );\n \n t = int(stdin.readline().strip());\n for time in range( t ):\n comand = stdin.readline().strip().split();\n if ( len(comand) == 3 ):\n obj, com, el = comand;\n if ( el == \".Q\" ):\n # print(\"lo agarra en (%d, %d)\" % ( elements[obj][0], elements[obj][1] ) );\n allPlayers[obj] = True;\n elif ( el == \".S\" ):\n team = 1 if obj[0] =='B' else 0;\n points[team] += 10;\n print( \"%d %s CATCH GOLDEN SNITCH\" % ( time, GoalName[team] ) );\n else:\n obj, com = comand;\n pos = elements[obj];\n nxt = (pos[0]+mov[com][0], pos[1]+mov[com][1] );\n if ( ( obj == \".B\" and isPlayer(grid[nxt[0]][nxt[1]]) ) or ( isPlayer(obj) and elements[\".B\"]==nxt ) ):\n player = obj if isPlayer(obj) else grid[nxt[0]][nxt[1]];\n print( \"%d %s ELIMINATED\" % (time, player ) );\n elif ( com=='T' ):\n allPlayers[obj] = False;\n if ( goalIn(pos)!=-1 ):\n team=goalIn(pos);\n print( \"%d %s GOAL\" %( time, GoalName[team] ) );\n points[team] += 1;\n elif( isPlayer(obj) ):\n elements[obj] = nxt;\n \n if ( obj == \".B\" ):\n elements[obj] = nxt;\n \n print(\"FINAL SCORE: %d %d\"%( points[0], points[1] ));\n \n \n \n \nmain();" + ] + } +] \ No newline at end of file diff --git a/new_data/ge_new_test.py b/new_data/ge_new_test.py new file mode 100644 index 0000000..0ffce39 --- /dev/null +++ b/new_data/ge_new_test.py @@ -0,0 +1,255 @@ +import os +import re +import subprocess + +import requests +import json + +import add_json + +other = 'You are a professional program tester. I will provide you with the problem description of a certain competition problem, which will explain the content of the problem. In addition, it will also explain the scope and requirements that valid inputs need to meet. You need to help me generate 10 different test inputs for edge cases (note: only provide the inputs, no need to provide the outputs). ' + +txt2 = """ +You are a professional program tester. I will provide you with the problem description of a certain competition problem, which will explain the problem content. In addition, it will specify the range and constraints that valid inputs must meet. + +Your task is to generate 10 diverse and well-considered test inputs focusing on the most important edge cases involved in the problem. You only need to provide the inputs, not the outputs. The inputs you provide don't necessarily have to be large in size, but please choose them carefully to ensure diversity and comprehensive coverage. + +You need to follow the following format. +# **Input 1** +``` + +``` +# **Input 2** +``` + +``` +# **Input 3** +``` + +``` +# **Input 4** +``` + +``` +# **Input 5** +``` + +``` +# **Input 6** +``` + +``` +# **Input 7** +``` + +``` +# **Input 8** +``` + +``` +# **Input 9** +``` + +``` +# **Input 10** +``` + +``` +Now I will give you the problem description: +{description} +""" + +txt = """ +You are a professional program tester. I will provide you with the problem description of a certain competition problem, which will explain the problem content as well as the input constraints. + +Your task is to generate 20 diverse and well-considered test inputs. These test cases should focus on: + +Covering the most important edge cases based on the constraints and problem details. +Ensuring that all key functionalities and aspects of the problem description are thoroughly tested. +The inputs do not necessarily need to be large, but they should be carefully chosen to maximize coverage of edge behaviors, special cases, and typical scenarios that validate the correctness and robustness of the implementation. + +You only need to provide the inputs, not the expected outputs. + +Please follow the following format. +# **Input 1** +``` + +``` +# **Input 2** +``` + +``` +# **Input 3** +``` + +``` +# **Input 4** +``` + +``` +# **Input 5** +``` + +``` +# **Input 6** +``` + +``` +# **Input 7** +``` + +``` +# **Input 8** +``` + +``` +# **Input 9** +``` + +``` +# **Input 10** +``` + +``` +Now I will give you the problem description: +{description} +""" + +url = "https://api.302.ai/v1/chat/completions" + +def run_python_code(code, input_data): + temp_file_path = "temp_program.py" + with open(temp_file_path, "w") as f: + f.write(code) + + try: + result = subprocess.run( + ["python3", temp_file_path], + input=input_data.encode(), + capture_output=True, + timeout=10 # Prevent infinite loops + ) + output = result.stdout.decode().strip() + error = result.stderr.decode().strip() + return output, error + except subprocess.TimeoutExpired: + return "", "Timeout" + finally: + os.remove(temp_file_path) + +def run_all_solutions_on_inputs(solutions, input_list, ignore_case): + all_results = [] + + for idx, input_data in enumerate(input_list, 1): + print(f"\n--- Running Test Input {idx} ---\nInput:\n{input_data}\n") + input_results = [] + + outputs_set = set() + has_error = False + outputs_list = [] + + for sol_idx, code in enumerate(solutions, 1): + print(f"Running Solution {sol_idx}...") + output, error = run_python_code(code, input_data) + + outputs_list.append(output) + input_results.append({ + "solution_index": sol_idx, + "output": output, + "error": error + }) + + if error: + has_error = True + else: + if ignore_case: + output = output.lower() + print(output) + outputs_set.add(output) + + # Determine if the current input is valid + is_valid = (not has_error) and (len(outputs_set) == 1) + + all_results.append({ + "input_index": idx, + "input": input_data, + "results": input_results, + "is_valid": is_valid + }) + + return all_results + +def api_call_for_test(name, prob_des, solutions, anycase): + name_num = name.split("_")[0] + name_alp = name.split("_")[1] + payload = json.dumps({ + "model": "o1", # gpt-4o or o1 + "messages": [ + { + "role": "user", + "content": txt.format(description=prob_des), + } + ] + }) + headers = { + 'Accept': 'application/json', + 'Authorization': 'sk-g9aImgg6dDoeoHLvrxUA3kQWtvblpOOZiO6mhad7rfWSjmSB', + 'Content-Type': 'application/json' + } + + response = requests.post(url, headers=headers, data=payload) + content = json.loads(response.text) + print("Response received!") + + # Extract test inputs + test_inputs_text = content['choices'][0]['message']['content'] + pattern = r"# \*\*Input \d+\*\*\n```(.*?)```" + matches = re.findall(pattern, test_inputs_text, re.DOTALL) + + input_list = [block.strip() for block in matches] + + print(f"\nExtracted {len(input_list)} test inputs\n") + + # Run all solutions + test_results = run_all_solutions_on_inputs(solutions, input_list, anycase) + + # Filter valid inputs + valid_inputs = [res for res in test_results if res['is_valid']] + + print(f"\n===== Number of Valid Inputs: {len(valid_inputs)} / {len(input_list)} =====\n") + + # Print valid inputs info + for v in valid_inputs: + print(f"Input {v['input_index']} is considered valid") + print(f"Input Content:\n{v['input']}\n") + print(f"Outputs from all solutions:\n{v['results'][0]['output']}\n") + add_json.add_to_jsonl(name_num, name_alp, v['input'], v['results'][0]['output']) + + # If you want to save to file + # with open("valid_inputs.json", "w", encoding="utf-8") as f: + # json.dump(valid_inputs, f, ensure_ascii=False, indent=4) + +if __name__ == "__main__": + file_path = "./filtered_merged_cor.json" + if not os.path.exists(file_path): + print(f"Error: File {file_path} does not exist.") + try: + with open(file_path, 'r', encoding='utf-8') as f: + problems = json.load(f) + for idx, problem in enumerate(problems, 1): + name = problem.get('task_name') + # if int(name.split("_")[0]) < 1948: + # continue + description = problem.get('description') + solutions = problem.get('generated_code') + print(f"\n================== Running Task: {name} ==================\n") + if 'any case' in description: + anycase = True + else: + anycase = False + print(anycase) + api_call_for_test(name, description, solutions, anycase) + + # break # Remove this if you want to process all tasks + except Exception as e: + print(e) \ No newline at end of file diff --git a/new_data/new_test_pass.py b/new_data/new_test_pass.py new file mode 100644 index 0000000..922be5c --- /dev/null +++ b/new_data/new_test_pass.py @@ -0,0 +1,111 @@ +import json +import os +import subprocess + +def run_code(file_path, input_data): + try: + process = subprocess.Popen( + ['python3', file_path], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True + ) + output, error = process.communicate(input=input_data, timeout=5) + return output.strip() + except subprocess.TimeoutExpired: + return "Timeout" + except Exception as e: + return f"Error: {e}" + +def load_testcases(task_name): + testcase_file = f"./test/{task_name}.jsonl" + if not os.path.exists(testcase_file): + print(f"[Skipped] Test case file does not exist: {testcase_file}") + return [] + + testcases = [] + with open(testcase_file, "r", encoding="utf-8") as f: + for line in f: + test = json.loads(line.strip()) + testcases.append(test) + + return testcases + +def main(): + test_dir = "./test" + task_names = set() + + # Automatically detect tasks (those that have both task.py and task_1.py) + for file in os.listdir(test_dir): + if file.endswith(".py") and not file.endswith("_1.py"): + task_name = file[:-3] # Remove .py extension + if os.path.exists(os.path.join(test_dir, f"{task_name}_1.py")): + task_names.add(task_name) + + total_tasks = 0 + total_avg_pass_rate = 0.0 + fully_passed_tasks = [] # Store tasks where at least one solution fully passes + + for task_name in sorted(task_names): + test_inputs = load_testcases(task_name) + if not test_inputs: + continue + + print(f"\nTask: {task_name}") + file_paths = [ + os.path.join(test_dir, f"{task_name}.py"), + os.path.join(test_dir, f"{task_name}_1.py") + ] + + task_pass_rates = [] + solution_fully_passed = False + + for idx, file_path in enumerate(file_paths): + if not os.path.exists(file_path): + print(f" [Skipped] File does not exist: {file_path}") + task_pass_rates.append(0.0) + continue + + pass_count = 0 + for test_case in test_inputs: + input_data = test_case['input'].replace("\\n", "\n") + expected_output = test_case['output'] + + output = run_code(file_path, input_data) + + if output == expected_output: + pass_count += 1 + + pass_rate = pass_count / len(test_inputs) + task_pass_rates.append(pass_rate) + print(f" Solution {idx + 1} ({os.path.basename(file_path)}) Pass Rate: {pass_rate:.1%}") + + if pass_rate == 1.0: + print(f"===> 🎉 {os.path.basename(file_path)} passed all test cases!") + solution_fully_passed = True + + avg_rate = sum(task_pass_rates) / len(task_pass_rates) + total_avg_pass_rate += avg_rate + total_tasks += 1 + print(f"===> Task Average Pass Rate: {avg_rate:.1%}") + + if solution_fully_passed: + fully_passed_tasks.append(task_name) + else: + print(f"===> ❌ No solution for this task fully passed all test cases.") + + print("\n===============================") + print(f"Total Tasks Evaluated: {total_tasks}") + if total_tasks > 0: + print(f"Overall Average Pass Rate: {(total_avg_pass_rate / total_tasks):.1%}") + + print("\nTasks with at least one 100% correct solution:") + if fully_passed_tasks: + for task in fully_passed_tasks: + print(f"- {task}") + else: + print("None") + +if __name__ == "__main__": + main() diff --git a/new_data/test/1919_A.jsonl b/new_data/test/1919_A.jsonl new file mode 100644 index 0000000..0c75c61 --- /dev/null +++ b/new_data/test/1919_A.jsonl @@ -0,0 +1,11 @@ +{"input": "10\n1 1\n1 4\n5 3\n4 5\n11 9\n83 91\n1032 9307\n839204 7281\n1000000000 1000000000\n53110 2024", "output": "Bob\nAlice\nBob\nAlice\nBob\nBob\nAlice\nAlice\nBob\nBob"} +{"input": "1\n1 1", "output": "Bob"} +{"input": "1\n2 2", "output": "Bob"} +{"input": "1\n1 2", "output": "Alice"} +{"input": "1\n1000000000 999999999", "output": "Alice"} +{"input": "1\n999999999 1000000000", "output": "Alice"} +{"input": "1\n3 1", "output": "Bob"} +{"input": "1\n5 5", "output": "Bob"} +{"input": "1\n6 6", "output": "Bob"} +{"input": "1\n100 1", "output": "Alice"} +{"input": "1\n1 100", "output": "Alice"} diff --git a/new_data/test/1919_A.py b/new_data/test/1919_A.py new file mode 100644 index 0000000..d91b894 --- /dev/null +++ b/new_data/test/1919_A.py @@ -0,0 +1,20 @@ +T=int(input()) +for i in range(T): + a,b = map(int, input().split()) + if a==b: + print("Bob") + else: + if a==1: + print("Alice") + elif b==1: + print("Bob") + else: + if a%2==1: + print("Bob") + elif a%2==0 and b%2==1: + print("Alice") + else: + if a>b: + print("Bob") + else: + print("Alice") \ No newline at end of file diff --git a/new_data/test/1919_A_1.py b/new_data/test/1919_A_1.py new file mode 100644 index 0000000..f7306d0 --- /dev/null +++ b/new_data/test/1919_A_1.py @@ -0,0 +1,14 @@ +t = int(input()) +results = [] + +for _ in range(t): + a, b = map(int, input().split()) + if a == 1 and b == 1: + results.append("Bob") + elif a == 1 or b == 1: + results.append("Alice") + else: + results.append("Bob" if (a + b) % 2 == 0 else "Alice") + +for result in results: + print(result) diff --git a/new_data/test/1919_B.jsonl b/new_data/test/1919_B.jsonl new file mode 100644 index 0000000..0112340 --- /dev/null +++ b/new_data/test/1919_B.jsonl @@ -0,0 +1,21 @@ +{"input": "1\n1\n+", "output": "1"} +{"input": "1\n2\n+-", "output": "0"} +{"input": "1\n3\n++-", "output": "1"} +{"input": "1\n3\n+-+", "output": "1"} +{"input": "1\n4\n++++", "output": "4"} +{"input": "1\n4\n----", "output": "4"} +{"input": "2\n3\n++-\n3\n---", "output": "1\n3"} +{"input": "1\n5\n-+++-", "output": "1"} +{"input": "1\n5\n+-+-+", "output": "1"} +{"input": "1\n6\n++--+-", "output": "0"} +{"input": "1\n12\n++--++--++--", "output": "0"} +{"input": "1\n1\n+", "output": "1"} +{"input": "1\n1\n-", "output": "1"} +{"input": "2\n5\n+++++\n5\n-----", "output": "5\n5"} +{"input": "2\n6\n+-+-+-\n6\n++++--", "output": "0\n2"} +{"input": "3\n4\n++--\n5\n-+-+-\n6\n++-+--", "output": "0\n1\n0"} +{"input": "3\n3\n+++\n3\n---\n6\n-++-+-", "output": "3\n3\n0"} +{"input": "3\n7\n--+-+-+\n8\n++++----\n9\n+-+-++---", "output": "1\n0\n1"} +{"input": "4\n5\n-+-+-\n5\n++-++\n6\n----++\n6\n++----", "output": "1\n3\n2\n2"} +{"input": "4\n10\n+++-+-+--+\n10\n-----+++++\n9\n+-+-++--+\n10\n++++++++++", "output": "2\n0\n1\n10"} +{"input": "5\n4\n++++\n5\n--++-\n7\n+--++++\n10\n--++++++-+\n9\n+-++-+--+", "output": "4\n1\n3\n4\n1"} diff --git a/new_data/test/1919_B.py b/new_data/test/1919_B.py new file mode 100644 index 0000000..cd6b21d --- /dev/null +++ b/new_data/test/1919_B.py @@ -0,0 +1,12 @@ +q=0 +k=0 +a=int(input()) +for i in range(a): + b=int(input()) + c=input() + if c.count('+')==0: + print(c.count('-')) + elif c.count('-')==0: + print(c.count('+')) + else: + print(c.count('+')-c.count('-')) \ No newline at end of file diff --git a/new_data/test/1919_B_1.py b/new_data/test/1919_B_1.py new file mode 100644 index 0000000..8de7153 --- /dev/null +++ b/new_data/test/1919_B_1.py @@ -0,0 +1,11 @@ +def solve(): + n = int(input()) + s = input() + neg = 0 + for i in s: + if i=='-':neg+=1 + print(n-2*neg if n!=neg else n) +t = int(input()) +while t: + solve() + t-=1 \ No newline at end of file diff --git a/new_data/test/1919_C.jsonl b/new_data/test/1919_C.jsonl new file mode 100644 index 0000000..1b29473 --- /dev/null +++ b/new_data/test/1919_C.jsonl @@ -0,0 +1,41 @@ +{"input": "5\n5\n1 2 3 4 5\n8\n8 2 3 1 1 7 4 3\n5\n3 3 3 3 3\n1\n1\n2\n2 1", "output": "3\n1\n0\n0\n0"} +{"input": "1\n5\n5 4 3 2 1", "output": "0"} +{"input": "1\n10\n1 2 3 2 1 3 4 5 6 7", "output": "5"} +{"input": "1\n6\n3 1 4 2 6 5", "output": "1"} +{"input": "1\n7\n7 6 5 4 3 1 2", "output": "0"} +{"input": "1\n8\n2 1 4 3 6 5 1 8", "output": "2"} +{"input": "1\n4\n4 3 2 1", "output": "0"} +{"input": "1\n9\n1 1 2 2 3 3 2 2 1", "output": "1"} +{"input": "1\n1\n1", "output": "0"} +{"input": "1\n10\n10 1 2 3 4 5 6 7 8 9", "output": "7"} +{"input": "1\n5\n2 4 1 3 5", "output": "1"} +{"input": "1\n1\n1", "output": "0"} +{"input": "1\n5\n1 2 3 4 5", "output": "3"} +{"input": "1\n5\n5 4 3 2 1", "output": "0"} +{"input": "2\n3\n1 1 1\n3\n1 2 1", "output": "0\n0"} +{"input": "2\n4\n1 1 2 2\n4\n4 4 1 1", "output": "0\n0"} +{"input": "3\n2\n2 1\n3\n2 3 1\n4\n1 3 2 4", "output": "0\n0\n1"} +{"input": "1\n8\n8 2 3 1 1 7 4 3", "output": "1"} +{"input": "2\n5\n2 2 2 2 2\n5\n1 2 3 3 2", "output": "0\n1"} +{"input": "3\n5\n4 1 2 1 4\n4\n4 3 2 1\n1\n1", "output": "1\n0\n0"} +{"input": "1\n10\n10 10 9 8 8 2 2 2 2 1", "output": "0"} +{"input": "1\n1\n1", "output": "0"} +{"input": "1\n2\n2 1", "output": "0"} +{"input": "1\n2\n1 2", "output": "0"} +{"input": "1\n5\n1 2 3 4 5", "output": "3"} +{"input": "1\n5\n5 4 3 2 1", "output": "0"} +{"input": "1\n5\n3 3 3 3 3", "output": "0"} +{"input": "2\n3\n1 2 2\n3\n2 2 1", "output": "0\n0"} +{"input": "2\n4\n4 1 2 1\n5\n2 1 2 1 4", "output": "0\n1"} +{"input": "3\n3\n1 1 1\n3\n2 1 2\n4\n1 3 2 3", "output": "0\n0\n1"} +{"input": "3\n5\n2 2 2 2 2\n5\n1 2 1 2 1\n5\n1 1 2 2 3", "output": "0\n0\n1"} +{"input": "2\n7\n1 2 3 4 3 2 1\n7\n2 2 2 1 1 1 2", "output": "2\n0"} +{"input": "2\n8\n8 2 3 1 1 7 4 3\n5\n3 3 3 3 3", "output": "1\n0"} +{"input": "3\n5\n1 2 3 4 5\n8\n8 2 3 1 1 7 4 3\n5\n3 3 3 3 3", "output": "3\n1\n0"} +{"input": "3\n1\n1\n2\n2 1\n2\n1 1", "output": "0\n0\n0"} +{"input": "4\n5\n1 2 3 4 5\n8\n8 2 3 1 1 7 4 3\n5\n3 3 3 3 3\n1\n1", "output": "3\n1\n0\n0"} +{"input": "3\n4\n2 1 3 2\n5\n5 5 5 5 4\n6\n1 1 2 3 3 2", "output": "0\n0\n1"} +{"input": "3\n5\n4 4 4 4 4\n6\n6 1 2 2 2 2\n4\n1 1 1 1", "output": "0\n0\n0"} +{"input": "2\n7\n1 2 3 3 2 1 1\n6\n2 2 3 3 4 4", "output": "1\n1"} +{"input": "3\n5\n5 5 3 3 1\n5\n2 3 4 1 5\n5\n1 3 5 2 4", "output": "0\n2\n1"} +{"input": "5\n3\n1 2 3\n3\n3 2 1\n2\n1 2\n2\n2 1\n4\n1 1 1 1", "output": "1\n0\n0\n0\n0"} diff --git a/new_data/test/1919_C.py b/new_data/test/1919_C.py new file mode 100644 index 0000000..d2ae855 --- /dev/null +++ b/new_data/test/1919_C.py @@ -0,0 +1,25 @@ +def solve(n, a): + ans = 0 + start = 100000 + end = 100000 + for i in range(n): + + if start > end: + start, end = end, start + if a[i] <= start: + start = a[i] + elif a[i] <= end: + end = a[i] + else: + ans += 1;start = a[i] + # print("start = ",start,"and end = ",end, " at i = ",i) + return ans + + +t = int(input()) +for i in range(t): + # n,x = map(int,input().split()) + n = int(input()) + a = list(map(int, input().split())) + ans = solve(n, a) + print(ans) \ No newline at end of file diff --git a/new_data/test/1919_C_1.py b/new_data/test/1919_C_1.py new file mode 100644 index 0000000..b89220f --- /dev/null +++ b/new_data/test/1919_C_1.py @@ -0,0 +1,23 @@ +import sys + +T = int(sys.stdin.readline()) + +for _ in range(T): + N = int(sys.stdin.readline()) + A = list(map(int,sys.stdin.readline().split())) + + cost = 0 + L = 100000 + H = 100000 + + for x in A: + if x <= L: + L = x + elif x <= H: + H = x + else: + cost += 1 + L = H + H = x + + print(cost) diff --git a/new_data/test/1920_A.jsonl b/new_data/test/1920_A.jsonl new file mode 100644 index 0000000..78fb08d --- /dev/null +++ b/new_data/test/1920_A.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n4\n1 3\n2 10\n3 1\n3 5\n2\n1 5\n2 4\n10\n3 6\n3 7\n1 2\n1 7\n3 100\n3 44\n2 100\n2 98\n1 3\n3 99\n6\n1 5\n2 10\n1 9\n2 2\n3 2\n3 9\n5\n1 1\n2 2\n3 1\n3 2\n3 3\n6\n1 10000\n2 900000000\n3 500000000\n1 100000000\n3 10000\n3 900000001", "output": "7\n0\n90\n0\n0\n800000000"} +{"input": "1\n2\n1 5\n2 6", "output": "2"} +{"input": "1\n3\n1 5\n2 8\n3 7", "output": "3"} +{"input": "1\n4\n1 1\n2 1000000000\n3 500\n3 999999999", "output": "999999998"} +{"input": "1\n5\n1 3\n2 7\n3 4\n3 5\n3 6", "output": "2"} +{"input": "1\n4\n1 10\n2 15\n3 12\n3 15", "output": "4"} +{"input": "1\n6\n1 100\n2 200\n3 150\n3 199\n3 101\n3 102", "output": "97"} +{"input": "1\n2\n1 1000\n2 999", "output": "0"} +{"input": "1\n10\n1 50\n2 60\n3 51\n3 52\n3 53\n3 54\n3 55\n3 56\n3 57\n3 58", "output": "3"} +{"input": "1\n3\n1 2\n2 3\n3 2", "output": "1"} +{"input": "1\n4\n1 100\n2 200\n1 150\n2 120", "output": "0"} diff --git a/new_data/test/1920_A.py b/new_data/test/1920_A.py new file mode 100644 index 0000000..26477ef --- /dev/null +++ b/new_data/test/1920_A.py @@ -0,0 +1,81 @@ +import math +import re + + +def input_n(isOne=False): + if not isOne: + return int(input()) + else: + return 1 + + +def input_list(space=True, to_int=True): + line = input() + if space: + items = line.split() + else: + items = list(line) + + if to_int: + return [int(i) for i in items] + else: + return items + + +def list_to_string(arr, sym): + string = "" + for i in arr: + string += str(i) + sym + return string + + +def find_all_indices_string(string, substring): + indices = [] + index = string.find(substring) + while index != -1: + indices.append(index) + index = string.find(substring, index + 1) + return indices + + +def find_all_indices_arr(arr, element): + return [index for index, value in enumerate(arr) if value == element] + + +def find_arr_in_arr(arr, index, value): + for subArray in arr: + if subArray[index] == value: + return subArray + return None + + +def solve(): + n = int(input()) + start = -1 + end = 1e9 + num = [] + for i in range(n): + t, v = tuple(map(int, input().split())) + if t == 1: + if start < v: start = v + if t == 2: + if end > v: end = v + if t == 3: num.append(v) + count_num = 0 + for i in num: + if i < start or i > end: + continue + else: + count_num += 1 + if start > end: return 0 + return end - start + 1 - count_num if end - start + 1 >= count_num else 0 + + +n = input_n() +ans = [] +alphabet = "abcdefghijklmnopqrstuvwxyz" + +for i in range(n): + ans.append(solve()) +for i in ans: + print(i) diff --git a/new_data/test/1920_A_1.py b/new_data/test/1920_A_1.py new file mode 100644 index 0000000..264ae4f --- /dev/null +++ b/new_data/test/1920_A_1.py @@ -0,0 +1,18 @@ +def solve(): + n=int(input()) + a=1e9;b=0;c=[] + for i in range (n): + s=input() + if s[0]=="2" : + a=min(a,int(s[2:])) + elif s[0]=="1": + b=max(b,int(s[2:])) + else : + c.append(int(s[2:])) + r=a-b+1 + for i in c : + if b<=i<=a : + r-=1 + print(max(r,0)) +for test in range(int(input())): + solve() \ No newline at end of file diff --git a/new_data/test/1920_B.jsonl b/new_data/test/1920_B.jsonl new file mode 100644 index 0000000..323c788 --- /dev/null +++ b/new_data/test/1920_B.jsonl @@ -0,0 +1,41 @@ +{"input": "8\n1 1 1\n1\n4 1 1\n3 1 2 4\n6 6 3\n1 4 3 2 5 6\n6 6 1\n3 7 3 3 32 15\n8 5 3\n5 5 3 3 3 2 9 9\n10 6 4\n1 8 2 9 3 3 4 5 3 200\n2 2 1\n4 3\n2 1 2\n1 3", "output": "0\n2\n0\n3\n-5\n-9\n0\n-1"} +{"input": "1\n1 1 1\n500", "output": "0"} +{"input": "1\n1 0 1\n1000", "output": "-1000"} +{"input": "1\n5 1 5\n500 250 100 50 25", "output": "-425"} +{"input": "1\n5 4 1\n5 10 20 30 40", "output": "25"} +{"input": "1\n6 3 2\n200 -100 300 -400 500 -600", "output": "-100"} +{"input": "1\n10 5 5\n10 9 8 7 6 5 4 3 2 1", "output": "-15"} +{"input": "1\n8 8 3\n1 -2 3 -4 5 -6 7 -8", "output": "18"} +{"input": "1\n4 1 4\n-1 -1 -1 -1", "output": "4"} +{"input": "1\n7 2 3\n-1000 500 -300 200 -100 50 0", "output": "-1250"} +{"input": "2\n6 0 3\n3 1 4 1 5 9\n5 3 2\n1000 999 998 997 996", "output": "-13\n992"} +{"input": "1\n1 1 1\n1", "output": "0"} +{"input": "2\n2 1 1\n1 2\n2 2 2\n1 1", "output": "-1\n0"} +{"input": "2\n3 1 1\n2 2 2\n3 3 1\n1 1000 999", "output": "2\n0"} +{"input": "2\n5 5 1\n1 2 3 4 5\n5 1 5\n5 5 5 1 1", "output": "5\n-12"} +{"input": "2\n5 2 2\n3 3 1 1 1\n5 2 4\n5 3 3 3 2", "output": "-1\n-8"} +{"input": "3\n4 1 1\n3 1 2 4\n6 6 3\n1 4 3 2 5 6\n6 6 1\n3 7 3 3 32 15", "output": "2\n0\n3"} +{"input": "8\n1 1 1\n1\n4 1 1\n3 1 2 4\n6 6 3\n1 4 3 2 5 6\n6 6 1\n3 7 3 3 32 15\n8 5 3\n5 5 3 3 3 2 9 9\n10 6 4\n1 8 2 9 3 3 4 5 3 200\n2 2 1\n4 3\n2 1 2\n1 3", "output": "0\n2\n0\n3\n-5\n-9\n0\n-1"} +{"input": "2\n5 3 3\n10 10 10 10 10\n5 3 3\n1 2 3 4 1000", "output": "-10\n-3"} +{"input": "2\n6 2 2\n999 1000 1 2 500 500\n6 3 3\n2 2 2 2 2 2", "output": "-996\n0"} +{"input": "3\n5 5 5\n1000 999 998 997 1\n3 1 2\n500 500 499\n4 2 2\n1 1000 1 1000", "output": "0\n-501\n-2"} +{"input": "1\n1 1 1\n1", "output": "0"} +{"input": "1\n4 1 1\n3 1 2 4", "output": "2"} +{"input": "1\n6 6 3\n1 4 3 2 5 6", "output": "0"} +{"input": "1\n6 6 1\n3 7 3 3 32 15", "output": "3"} +{"input": "1\n8 5 3\n5 5 3 3 3 2 9 9", "output": "-5"} +{"input": "1\n10 6 4\n1 8 2 9 3 3 4 5 3 200", "output": "-9"} +{"input": "1\n2 2 1\n4 3", "output": "0"} +{"input": "1\n2 1 2\n1 3", "output": "-1"} +{"input": "2\n4 1 1\n1 1 1 1\n4 1 1\n1 1 1 2", "output": "2\n1"} +{"input": "3\n5 2 1\n1 2 3 4 5\n5 0 5\n1 1 1 1 1\n5 5 1\n10 10 10 10 10", "output": "5\n-5\n30"} +{"input": "1\n5 3 2\n1 1000 999 500 500", "output": "-501"} +{"input": "1\n5 5 5\n1000 1000 1000 1000 1000", "output": "0"} +{"input": "1\n5 1 1\n999 1 1 1 1", "output": "2"} +{"input": "1\n5 1 4\n1 1 1 1 500", "output": "-4"} +{"input": "1\n5 2 2\n2 2 2 2 2", "output": "2"} +{"input": "2\n3 1 1\n1 2 3\n3 2 2\n1 1 1000", "output": "0\n-1"} +{"input": "3\n3 3 3\n1000 500 500\n3 1 2\n2 2 3\n3 0 1\n5 5 5", "output": "0\n-3\n5"} +{"input": "1\n10 0 10\n1 1 2 2 3 3 4 4 5 5", "output": "-30"} +{"input": "2\n5 3 1\n700 700 700 700 700\n5 2 2\n1 2 3 4 5", "output": "2100\n-3"} +{"input": "5\n1 1 1\n100\n2 1 1\n1 1000\n3 2 1\n10 9 8\n3 1 2\n1 2 3\n4 4 4\n1 1 1 1", "output": "0\n-1\n7\n-3\n0"} diff --git a/new_data/test/1920_B.py b/new_data/test/1920_B.py new file mode 100644 index 0000000..e580d32 --- /dev/null +++ b/new_data/test/1920_B.py @@ -0,0 +1,11 @@ +for _ in range(int(input())): + n, k, x = map(int, input().split()) + a = sorted(map(int,input().split())) + a.reverse() + p = 0 + prefix = [0] + for i in range(n): + p += a[i] + prefix.append(p) + m = min([2*prefix[min(i+x,n)] - prefix[i] for i in range(k+1)]) + print(prefix[n] - min(2*10**8 + 1, m)) \ No newline at end of file diff --git a/new_data/test/1920_B_1.py b/new_data/test/1920_B_1.py new file mode 100644 index 0000000..0916521 --- /dev/null +++ b/new_data/test/1920_B_1.py @@ -0,0 +1,31 @@ + +t = int(input()) +res=[] +for i in range(t): + b = str(input()) + n, k, x = b.split(" ") + n, k, x = int(n), int(k), int(x) + + a = list(map(int, str(input()).split(" "))) + a.sort(reverse=True) + pre = [0] * (n+1) + + for i in range(1, n+1, 1): + pre[i] = pre[i-1] + a[i-1] + + curr_sum = sum(a) + ans = -100000000 + for i in range(k+1): + # Slide the window + bob = pre[min(i+x, n)] - pre[i] # the min is here to enforce limit on rhs + ans = max(ans, curr_sum - 2*bob) + if i < k: + curr_sum -= a[i] + res.append(ans) + +for r in res: + print(r) + + + + diff --git a/new_data/test/1921_B.jsonl b/new_data/test/1921_B.jsonl new file mode 100644 index 0000000..61ea97e --- /dev/null +++ b/new_data/test/1921_B.jsonl @@ -0,0 +1,40 @@ +{"input": "1\n1\n0\n1", "output": "1"} +{"input": "1\n5\n11111\n11111", "output": "0"} +{"input": "1\n6\n010101\n101010", "output": "3"} +{"input": "1\n4\n1110\n0011", "output": "2"} +{"input": "1\n10\n0000000000\n1111111111", "output": "10"} +{"input": "2\n3\n010\n001\n4\n1101\n1011", "output": "1\n1"} +{"input": "1\n8\n11111111\n00000000", "output": "8"} +{"input": "1\n2\n10\n01", "output": "1"} +{"input": "1\n7\n1000001\n0001100", "output": "2"} +{"input": "1\n9\n100111000\n001100111", "output": "4"} +{"input": "1\n1\n1\n0", "output": "1"} +{"input": "2\n1\n0\n1\n1\n1\n1", "output": "1\n0"} +{"input": "2\n3\n000\n111\n3\n111\n000", "output": "3\n3"} +{"input": "2\n3\n010\n101\n3\n100\n001", "output": "2\n1"} +{"input": "2\n5\n10010\n00001\n1\n1\n1", "output": "2\n0"} +{"input": "3\n3\n101\n010\n4\n0000\n0000\n4\n0101\n1010", "output": "2\n0\n2"} +{"input": "3\n5\n10101\n01010\n5\n00000\n00001\n5\n11110\n01111", "output": "3\n1\n1"} +{"input": "4\n2\n10\n01\n2\n11\n00\n2\n00\n11\n2\n10\n10", "output": "1\n2\n2\n0"} +{"input": "3\n6\n101101\n011011\n6\n000000\n100001\n6\n111111\n010101", "output": "2\n2\n3"} +{"input": "4\n5\n11000\n10100\n5\n00110\n10010\n4\n1111\n0000\n1\n0\n0", "output": "1\n1\n4\n0"} +{"input": "1\n1\n0\n0", "output": "0"} +{"input": "1\n1\n1\n1", "output": "0"} +{"input": "2\n2\n00\n00\n2\n10\n01", "output": "0\n1"} +{"input": "1\n5\n10010\n00001", "output": "2"} +{"input": "2\n3\n000\n111\n4\n0101\n1010", "output": "3\n2"} +{"input": "1\n3\n100\n101", "output": "1"} +{"input": "1\n8\n10011001\n11111110", "output": "4"} +{"input": "2\n4\n0000\n0000\n4\n1111\n0000", "output": "0\n4"} +{"input": "1\n5\n01010\n10101", "output": "3"} +{"input": "3\n3\n111\n000\n4\n0010\n0100\n5\n01110\n00011", "output": "3\n1\n2"} +{"input": "1\n5\n00100\n01001", "output": "2"} +{"input": "1\n2\n01\n10", "output": "1"} +{"input": "1\n6\n101010\n010101", "output": "3"} +{"input": "2\n1\n0\n1\n1\n1\n0", "output": "1\n1"} +{"input": "2\n3\n010\n010\n3\n101\n010", "output": "0\n2"} +{"input": "3\n2\n00\n11\n2\n11\n00\n2\n01\n01", "output": "2\n2\n0"} +{"input": "1\n5\n00001\n10000", "output": "1"} +{"input": "3\n3\n000\n010\n3\n010\n000\n3\n010\n101", "output": "1\n1\n2"} +{"input": "1\n10\n0000011111\n1111100000", "output": "5"} +{"input": "4\n3\n100\n001\n4\n1000\n0100\n4\n1010\n0011\n5\n01001\n00110", "output": "1\n1\n1\n2"} diff --git a/new_data/test/1921_B.py b/new_data/test/1921_B.py new file mode 100644 index 0000000..e95839d --- /dev/null +++ b/new_data/test/1921_B.py @@ -0,0 +1,23 @@ +for _ in range(int(input())): + x = int(input()) + a = input() + b = input() + a = list(a) + b = list(b) + count = a.count('1') + countb = b.count('1') + ans = 0 + flag = 0 + final_ans = 0 + if count != countb: + ans = abs(count - countb) + for i in range(x): + if flag >= ans: + break + if a[i] == "1": + a[i] = "0" + flag += 1 + for i in range(x): + if a[i] == "1" and b[i] == "0": + final_ans += 1 + print(final_ans + ans) diff --git a/new_data/test/1921_B_1.py b/new_data/test/1921_B_1.py new file mode 100644 index 0000000..5d3e810 --- /dev/null +++ b/new_data/test/1921_B_1.py @@ -0,0 +1,41 @@ +t = int(input()) + +for _ in range(t): + n = int(input()) + cats_1 = input().strip() + cats_2 = input().strip() + + if cats_1 == cats_2: + print("0") + continue + + ones1 = cats_1.count('1') + ones2 = cats_2.count('1') + + if abs(ones1 - ones2) == n: + print(n) + continue + + ans = abs(ones1 - ones2) + + if ones1 < ones2: + j = 0 + for i in range(ans): + if cats_1[j] == '0' and cats_2[j] == '1': + cats_1 = cats_1[:j] + '1' + cats_1[j + 1:] + i += 1 + j += 1 + elif ones1 > ones2: + index = 0 + for i in range(ans): + if cats_1[index] == '1' and cats_2[index] == '0': + cats_1 = cats_1[:index] + '0' + cats_1[index + 1:] + i += 1 + index += 1 + + if cats_1 == cats_2: + print(ans) + continue + + ans_2 = sum(c1 != c2 for c1, c2 in zip(cats_1, cats_2)) + print(ans + (ans_2 // 2)) diff --git a/new_data/test/1921_C.jsonl b/new_data/test/1921_C.jsonl new file mode 100644 index 0000000..2f6ef2a --- /dev/null +++ b/new_data/test/1921_C.jsonl @@ -0,0 +1,21 @@ +{"input": "6\n1 3 1 5\n3\n7 21 1 3\n4 6 10 13 17 20 26\n5 10 1 2\n1 2 3 4 5\n1 1000000000 1000000000 1000000000\n1000000000\n3 11 9 6\n6 8 10\n12 621526648 2585904 3566299\n51789 61859 71998 73401 247675 298086 606959 663464 735972 806043 806459 919683", "output": "NO\nYES\nYES\nNO\nNO\nYES"} +{"input": "1\n2 3 1 5\n2 5", "output": "NO"} +{"input": "1\n3 10 3 6\n4 8 12", "output": "NO"} +{"input": "1\n4 15 2 1\n1 10 20 100", "output": "YES"} +{"input": "1\n5 5 1 2\n1 2 3 4 5", "output": "NO"} +{"input": "1\n1 1 1 1\n1", "output": "NO"} +{"input": "1\n6 100 10 10\n15 30 45 60 75 90", "output": "YES"} +{"input": "1\n10 50 1 2\n1 2 3 4 5 6 7 8 9 10", "output": "YES"} +{"input": "1\n5 100 20 10\n50 70 90 110 130", "output": "YES"} +{"input": "1\n3 1 5 2\n2 4 6", "output": "NO"} +{"input": "1\n1 1000000000 1000000000 1\n1000000000", "output": "YES"} +{"input": "1\n1 3 1 5\n3", "output": "NO"} +{"input": "2\n1 1000000000 1000000000 1000000000\n1000000000\n3 11 9 6\n6 8 10", "output": "NO\nNO"} +{"input": "1\n7 21 1 3\n4 6 10 13 17 20 26", "output": "YES"} +{"input": "1\n5 10 1 2\n1 2 3 4 5", "output": "YES"} +{"input": "1\n12 621526648 2585904 3566299\n51789 61859 71998 73401 247675 298086 606959 663464 735972 806043 806459 919683", "output": "YES"} +{"input": "2\n4 5 1 2\n1 2 4 5\n4 5 2 1\n1 2 4 5", "output": "NO\nYES"} +{"input": "3\n2 2 1 1\n1 2\n3 6 2 2\n1 3 4\n2 2 2 2\n1 3", "output": "NO\nNO\nNO"} +{"input": "2\n2 4 2 4\n2 3\n3 10 3 1\n2 3 10", "output": "NO\nYES"} +{"input": "1\n5 3 1 1\n1 2 3 4 5", "output": "NO"} +{"input": "2\n5 10 9 1\n1 2 3 12 13\n5 10 9 10\n1 2 3 12 13", "output": "YES\nNO"} diff --git a/new_data/test/1921_C.py b/new_data/test/1921_C.py new file mode 100644 index 0000000..30312d0 --- /dev/null +++ b/new_data/test/1921_C.py @@ -0,0 +1,26 @@ +n = int(input()) +listt = [] +arr = [] +for i in range(n): + x = list(map(int, input().split())) + listt.append(x) + + arr.append(list(map(int, input().split()))) + +for i in range(n): + + a = listt[i][2] + b = listt[i][3] + newarr = arr[i] + newarr.sort() + charge = listt[i][1] + + charge = charge - min(newarr[0], b) + + for i in range(1, len(newarr)): + charge = charge - min((newarr[i] - newarr[i - 1]) * a, b) + + if charge <= 0: + print('NO') + else: + print('YES') \ No newline at end of file diff --git a/new_data/test/1921_C_1.py b/new_data/test/1921_C_1.py new file mode 100644 index 0000000..28acba4 --- /dev/null +++ b/new_data/test/1921_C_1.py @@ -0,0 +1,28 @@ +def can_send_all_messages(t, data): + results = [] + for i in range(t): + n, f, a, b = data[i][0], data[i][1], data[i][2], data[i][3] + moments = data[i][4] + + min_energy = f + for i in range(n): + energy_required = moments[i] * a + if moments[i] * a > b: + energy_required -= (moments[i] - 1) * b + + min_energy = min(min_energy, f - energy_required) + + results.append("YES" if min_energy > 0 else "NO") + + return results + +t = int(input()) +data = [] +for _ in range(t): + n, f, a, b = map(int, input().split()) + moments = list(map(int, input().split())) + data.append((n, f, a, b, moments)) + +results = can_send_all_messages(t, data) +for result in results: + print(result) diff --git a/new_data/test/1921_E.jsonl b/new_data/test/1921_E.jsonl new file mode 100644 index 0000000..5231655 --- /dev/null +++ b/new_data/test/1921_E.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n10 10 1 1 2 1\n10 10 2 2 3 3\n10 10 5 5 6 6", "output": "Alice\nAlice\nAlice"} +{"input": "1\n1 1 1 1 1 2", "output": "draw"} +{"input": "1\n1000000 1000000000 1 1 1 1000000000", "output": "draw"} +{"input": "1\n2 3 1 1 2 3", "output": "draw"} +{"input": "1\n5 5 1 1 5 5", "output": "draw"} +{"input": "1\n1000000 1000000000 500000 500000000 999999 500000001", "output": "Alice"} +{"input": "1\n999999 999999999 500000 500000001 499999 500000", "output": "draw"} +{"input": "1\n10 9 5 4 5 6", "output": "draw"} +{"input": "1\n3 1000000000 2 1 1 2", "output": "draw"} +{"input": "1\n2 2 1 2 2 1", "output": "Alice"} +{"input": "1\n1000000 3 1 1 1000000 3", "output": "Alice"} diff --git a/new_data/test/1921_E.py b/new_data/test/1921_E.py new file mode 100644 index 0000000..d2d280e --- /dev/null +++ b/new_data/test/1921_E.py @@ -0,0 +1,157 @@ +t = int(input()) + + +# k=[] +def help(l, turn): + h = l[0] + w = l[1] + xa = l[2] + ya = l[3] + xb = l[4] + yb = l[5] + # print(xa,ya,xb,yb,) + # base case + if turn: + k = "Alice" + k1 = "Bob" + else: + k1 = "Alice" + k = "Bob" + if xa >= xb: + return "Draw" + elif abs(xa - xb) == 1: + if abs(ya - yb) <= 1: + return k + else: + return "Draw" + # elif abs(xa-xb)==2: + # if abs(ya-yb)<=1: + # return k1 + # else: + # return "Draw" + else: + if turn: + diff = (xb - xa) % 2 + if diff: + chk = yb - ya + if chk == 0: + l[2] += 1 + return help(l, not turn) + elif chk > 0: + l[2] += 1 + l[3] += 1 + return help(l, not turn) + else: + l[2] += 1 + l[3] -= 1 + return help(l, not turn) + else: + chk = ya - yb + if chk == 0: + if h - ya > ya - 1: + if ya + 1 <= h: + # go right + l[2] += 1 + l[3] += 1 + return help(l, not turn) + else: + # go down + l[2] += 1 + return help(l, not turn) + else: + if ya - 1 >= 1: + # go left + l[2] += 1 + l[3] -= 1 + return help(l, not turn) + else: + # go down + l[2] += 1 + return help(l, not turn) + elif chk > 0: + if ya + 1 <= h: + # go right + l[2] += 1 + l[3] += 1 + return help(l, not turn) + else: + # go down + l[2] += 1 + return help(l, not turn) + else: + if ya - 1 >= 1: + # go left + l[2] += 1 + l[3] -= 1 + return help(l, not turn) + else: + # go down + l[2] += 1 + return help(l, not turn) + else: + diff = (xb - xa) % 2 + if diff: + # attack + chk = ya - yb + if chk == 0: + l[4] -= 1 + return help(l, not turn) + elif chk > 0: + l[4] -= 1 + l[5] += 1 + return help(l, not turn) + else: + l[4] -= 1 + l[5] -= 1 + return help(l, not turn) + else: + # escape + chk = yb - ya + if chk == 0: + if h - yb > yb - 1: + if yb + 1 <= h: + # go right + l[4] -= 1 + l[5] += 1 + return help(l, not turn) + else: + # go up + l[4] -= 1 + return help(l, not turn) + else: + if yb - 1 >= 1: + # go left + l[4] -= 1 + l[5] -= 1 + return help(l, not turn) + else: + # go up + l[4] -= 1 + return help(l, not turn) + elif chk > 0: + if yb + 1 <= h: + # go right + l[4] -= 1 + l[5] += 1 + return help(l, not turn) + else: + # go down + l[4] -= 1 + return help(l, not turn) + else: + if yb - 1 >= 1: + # go left + l[4] -= 1 + l[5] -= 1 + return help(l, not turn) + else: + # go down + l[4] -= 1 + return help(l, not turn) + # help(l,not turn) + + +for i in range(t): + l = list(map(int, input().split())) + + print(help(l, True)) \ No newline at end of file diff --git a/new_data/test/1921_E_1.py b/new_data/test/1921_E_1.py new file mode 100644 index 0000000..b789fb0 --- /dev/null +++ b/new_data/test/1921_E_1.py @@ -0,0 +1,35 @@ +for _ in range(int(input())): + h, w, xa, ya, xb, yb = map(int, input().split()) + if xb <= xa or (abs(yb - ya) >= abs(xb - xa)): + print("DRAW") + else: + if (xb - xa) % 2 == 1: # ALICE ka mauka + if yb == ya or abs(yb - ya) == 1: + print("ALICE") + elif yb > ya: + if abs(yb - ya) >= (abs(xb - xa)) - 2 * (w - yb) or (w - yb) >= abs(xa - xb): + print("DRAW") + else: + print("ALICE") + else: + if abs(yb - ya) >= (abs(xb - xa)) - 2 * (yb - 1) or yb >= abs(xb - xa): + print("DRAW") + else: + print("ALICE") + else: # BOB ka mauka + if yb == ya: + print("BOB") + elif yb > ya: + if abs(yb - ya) >= (abs(xb - xa)) - 2 * (ya - 1) or ya >= abs(xb - xa): + print("DRAW") + else: + print("BOB") + else: + if abs(yb - ya) >= (abs(xb - xa)) - 2 * (w - ya) or (w - ya) >= abs(xb - xa): + print("DRAW") + else: + print("BOB") + + + + diff --git a/new_data/test/1922_A.jsonl b/new_data/test/1922_A.jsonl new file mode 100644 index 0000000..5a09f74 --- /dev/null +++ b/new_data/test/1922_A.jsonl @@ -0,0 +1,10 @@ +{"input": "1\n1\na\nb\na", "output": "NO"} +{"input": "1\n5\napple\napplf\napple", "output": "NO"} +{"input": "1\n3\nabc\nbcd\nabf", "output": "YES"} +{"input": "1\n2\nzz\nzx\nzz", "output": "NO"} +{"input": "1\n1\nx\ny\nz", "output": "YES"} +{"input": "1\n4\ngood\ngoot\ngone", "output": "YES"} +{"input": "1\n3\ncat\nrat\ncar", "output": "YES"} +{"input": "1\n2\nhi\nho\nho", "output": "NO"} +{"input": "1\n5\ncharm\ncharm\ncharm", "output": "NO"} +{"input": "1\n4\ngame\ntame\nsame", "output": "YES"} diff --git a/new_data/test/1922_A.py b/new_data/test/1922_A.py new file mode 100644 index 0000000..1a0f015 --- /dev/null +++ b/new_data/test/1922_A.py @@ -0,0 +1,23 @@ +t = int(input()) +for _ in range(t): + n = int(input()) + a = input() + b = input() + c = input() + + template_found = True + for i in range(n): + if c[i] == a[i] and c[i] == b[i]: + continue + elif c[i] != a[i] and c[i] != b[i]: + continue + elif c[i] == a[i] and c[i] != b[i]: + if a[i].islower(): + template_found = False + break + elif c[i] != a[i] and c[i] == b[i]: + if b[i].islower(): + template_found = False + break + + print("YES" if template_found else "NO") \ No newline at end of file diff --git a/new_data/test/1922_A_1.py b/new_data/test/1922_A_1.py new file mode 100644 index 0000000..e3cd21c --- /dev/null +++ b/new_data/test/1922_A_1.py @@ -0,0 +1,16 @@ +def solve(a, b, c): + for A, B, C in zip(a, b, c): + if (A == C or B == C) and not A == B == C: + return False + return True + + +t = int(input()) +for _ in range(t): + n = int(input()) + a = input().strip() + b = input().strip() + c = input().strip() + + ans = solve(a, b, c) + print("YES" if ans else "NO") \ No newline at end of file diff --git a/new_data/test/1922_B.jsonl b/new_data/test/1922_B.jsonl new file mode 100644 index 0000000..e6ea2a5 --- /dev/null +++ b/new_data/test/1922_B.jsonl @@ -0,0 +1,40 @@ +{"input": "4\n7\n1 1 1 1 1 1 1\n4\n3 2 1 3\n3\n1 2 3\n1\n1", "output": "35\n2\n0\n0"} +{"input": "1\n3\n1 2 3", "output": "0"} +{"input": "1\n4\n3 2 1 3", "output": "2"} +{"input": "1\n1\n1", "output": "0"} +{"input": "1\n7\n1 1 1 1 1 1 1", "output": "35"} +{"input": "1\n5\n0 0 0 0 0", "output": "10"} +{"input": "1\n5\n0 1 2 3 4", "output": "0"} +{"input": "2\n3\n0 0 1\n3\n0 1 1", "output": "0\n1"} +{"input": "2\n4\n4 4 4 4\n5\n1 1 1 1 2", "output": "4\n4"} +{"input": "3\n3\n2 2 2\n5\n2 2 2 2 2\n3\n0 3 3", "output": "1\n10\n1"} +{"input": "3\n3\n0 0 0\n4\n0 0 1 1\n6\n0 1 1 2 2 3", "output": "1\n2\n4"} +{"input": "1\n1\n0", "output": "0"} +{"input": "1\n3\n1 2 3", "output": "0"} +{"input": "4\n7\n1 1 1 1 1 1 1\n4\n3 2 1 3\n3\n1 2 3\n1\n1", "output": "35\n2\n0\n0"} +{"input": "2\n5\n0 0 0 0 0\n5\n0 1 2 3 4", "output": "10\n0"} +{"input": "2\n4\n2 2 2 2\n5\n2 2 2 3 3", "output": "4\n4"} +{"input": "3\n3\n0 0 1\n3\n1 1 1\n4\n0 0 0 1", "output": "0\n1\n1"} +{"input": "1\n6\n1 1 1 4 4 4", "output": "11"} +{"input": "2\n5\n4 4 4 4 4\n5\n0 4 4 4 4", "output": "10\n10"} +{"input": "2\n6\n0 1 1 2 2 3\n6\n0 0 3 3 3 3", "output": "4\n16"} +{"input": "3\n5\n1 2 2 2 3\n5\n1 1 2 2 2\n5\n0 1 3 3 3", "output": "4\n7\n7"} +{"input": "1\n1\n0", "output": "0"} +{"input": "1\n3\n0 1 2", "output": "0"} +{"input": "1\n3\n1 1 1", "output": "1"} +{"input": "2\n3\n1 2 3\n4\n3 2 1 3", "output": "0\n2"} +{"input": "1\n7\n1 1 1 1 1 1 1", "output": "35"} +{"input": "1\n5\n0 0 0 0 0", "output": "10"} +{"input": "1\n5\n0 0 0 0 1", "output": "4"} +{"input": "2\n4\n0 1 1 2\n5\n2 2 2 2 2", "output": "1\n10"} +{"input": "1\n5\n4 4 1 1 0", "output": "4"} +{"input": "1\n8\n0 1 1 2 2 2 3 3", "output": "17"} +{"input": "1\n6\n0 1 2 3 4 5", "output": "0"} +{"input": "2\n4\n0 0 1 1\n3\n2 2 2", "output": "2\n1"} +{"input": "1\n6\n1 1 2 2 3 3", "output": "6"} +{"input": "1\n7\n0 2 2 3 3 3 5", "output": "11"} +{"input": "2\n5\n0 2 2 2 3\n5\n0 1 2 2 5", "output": "4\n2"} +{"input": "2\n5\n1 1 1 1 5\n5\n0 0 1 1 2", "output": "4\n2"} +{"input": "1\n10\n0 0 1 1 3 3 3 5 5 10", "output": "22"} +{"input": "3\n4\n4 4 4 4\n5\n1 2 2 3 3\n5\n0 2 2 4 4", "output": "4\n4\n4"} +{"input": "2\n6\n0 0 5 5 5 5\n5\n2 3 4 4 0", "output": "16\n3"} diff --git a/new_data/test/1922_B.py b/new_data/test/1922_B.py new file mode 100644 index 0000000..d5c23ce --- /dev/null +++ b/new_data/test/1922_B.py @@ -0,0 +1,31 @@ +from collections import * +from math import log, log2, pow, gcd, ceil, floor +from heapq import * +import sys + + +def sol(): + N = int(input()) + nums = input().split() + + d = Counter(nums) + + cnt = 0 + ans = 0 + for i in sorted(d): + v = d.get(i) + if v == 1: + cnt += d.get(i) + continue + if v == 2: + ans += cnt + if v > 2: + ans += cnt * v * (v - 1) // 2 + ans += v * (v - 1) * (v - 2) // 6 + cnt += d.get(i) + + print(ans) + + +for _ in range(int(input())): + sol() \ No newline at end of file diff --git a/new_data/test/1922_B_1.py b/new_data/test/1922_B_1.py new file mode 100644 index 0000000..f1ac04f --- /dev/null +++ b/new_data/test/1922_B_1.py @@ -0,0 +1,40 @@ +from collections import Counter +from math import comb + + +def count_triangles(n, arr): + if len(arr) >= 3: + arr.sort() + cum_sum = 0 + total = 0 + d = Counter(arr) + d = {k: v for k, v in sorted(d.items(), key=lambda x: x[0])} + ans = 0 # Define ans variable + for i in d.keys(): + if d[i] >= 3: + ans += comb(d[i], 3) + ans += comb(d[i], 2) * cum_sum + cum_sum += d[i] + + elif d[i] == 2: + ans += comb(d[i], 2) * cum_sum + cum_sum += d[i] + else: + cum_sum += d[i] + return ans # Add return statement + else: + return 0 + + +def main(): + t = int(input()) # Define t + while t > 0: + n = int(input()) + sides = list(map(str, input().split())) # Fix typo here + result = count_triangles(n, sides) + print(result) + t -= 1 + + +if __name__ == "__main__": + main() diff --git a/new_data/test/1922_C.jsonl b/new_data/test/1922_C.jsonl new file mode 100644 index 0000000..a7137f1 --- /dev/null +++ b/new_data/test/1922_C.jsonl @@ -0,0 +1,34 @@ +{"input": "1\n5\n0 8 12 15 20\n5\n1 4\n1 5\n3 4\n3 2\n5 1", "output": "3\n8\n1\n4\n14"} +{"input": "1\n2\n0 2\n1\n1 2", "output": "1"} +{"input": "1\n3\n0 2 5\n3\n1 3\n2 1\n2 3", "output": "4\n1\n3"} +{"input": "1\n4\n0 1 3 6\n3\n1 4\n2 4\n3 1", "output": "6\n5\n2"} +{"input": "1\n5\n0 8 12 15 20\n5\n1 4\n1 5\n3 4\n3 2\n5 1", "output": "3\n8\n1\n4\n14"} +{"input": "2\n3\n1 2 4\n2\n1 2\n1 3\n3\n10 13 14\n1\n3 1", "output": "1\n3\n4"} +{"input": "1\n5\n0 2 3 7 12\n4\n1 2\n2 4\n4 5\n1 5", "output": "1\n5\n5\n11"} +{"input": "1\n6\n0 1 3 4 8 13\n5\n1 2\n2 3\n3 5\n1 6\n4 5", "output": "1\n2\n5\n13\n4"} +{"input": "1\n7\n0 5 6 13 14 18 25\n5\n1 7\n2 3\n2 4\n5 7\n3 6", "output": "21\n1\n8\n11\n12"} +{"input": "2\n5\n2 3 6 7 10\n2\n1 5\n5 3\n4\n0 3 7 10\n3\n1 2\n2 4\n3 4", "output": "8\n2\n1\n5\n1"} +{"input": "1\n8\n1 2 4 9 10 12 20 21\n5\n1 8\n2 3\n4 5\n5 7\n6 8", "output": "20\n2\n1\n10\n9"} +{"input": "1\n2\n0 3\n2\n1 2\n2 1", "output": "1\n1"} +{"input": "1\n3\n0 3 7\n3\n1 3\n2 1\n2 3", "output": "5\n1\n4"} +{"input": "1\n5\n0 8 12 15 20\n5\n1 4\n1 5\n3 4\n3 2\n5 1", "output": "3\n8\n1\n4\n14"} +{"input": "1\n4\n1 2 4 7\n5\n1 2\n1 4\n4 3\n2 3\n1 3", "output": "1\n6\n1\n2\n3"} +{"input": "1\n5\n1 2 5 6 10\n6\n1 5\n5 1\n2 4\n4 2\n2 3\n3 5", "output": "9\n6\n4\n4\n3\n5"} +{"input": "1\n6\n0 1 3 6 10 15\n5\n1 6\n2 5\n3 4\n5 2\n6 1", "output": "15\n9\n3\n3\n5"} +{"input": "1\n7\n2 4 7 8 12 13 20\n5\n1 7\n7 1\n3 4\n5 6\n3 6", "output": "17\n11\n1\n1\n6"} +{"input": "1\n2\n0 3\n1\n1 2", "output": "1"} +{"input": "1\n3\n0 2 5\n3\n1 2\n2 3\n1 3", "output": "1\n3\n4"} +{"input": "1\n3\n1 2 4\n3\n2 1\n2 3\n1 3", "output": "1\n2\n3"} +{"input": "1\n4\n0 8 12 15\n3\n1 4\n2 3\n3 4", "output": "3\n1\n1"} +{"input": "1\n5\n0 8 12 15 20\n5\n1 4\n1 5\n3 4\n3 2\n5 1", "output": "3\n8\n1\n4\n14"} +{"input": "1\n4\n2 3 6 10\n4\n1 2\n1 4\n2 3\n3 4", "output": "1\n8\n3\n4"} +{"input": "1\n5\n1 4 5 9 15\n5\n1 2\n1 5\n2 4\n3 4\n4 5", "output": "1\n12\n5\n4\n6"} +{"input": "1\n5\n0 1 10 11 20\n5\n1 2\n2 3\n3 5\n4 3\n1 5", "output": "1\n9\n10\n1\n20"} +{"input": "1\n5\n0 5 6 8 30\n5\n1 5\n2 3\n3 4\n4 5\n1 2", "output": "26\n1\n2\n22\n1"} +{"input": "1\n6\n0 2 3 9 10 30\n5\n1 3\n1 6\n2 5\n4 5\n3 6", "output": "2\n29\n8\n1\n27"} +{"input": "1\n6\n1 2 4 5 7 14\n5\n1 2\n2 6\n3 4\n4 5\n5 6", "output": "1\n12\n1\n2\n7"} +{"input": "1\n7\n0 2 5 6 10 11 25\n5\n1 3\n2 4\n4 5\n5 7\n3 6", "output": "4\n4\n4\n15\n6"} +{"input": "1\n7\n1 3 4 9 13 14 16\n5\n1 2\n2 3\n3 7\n5 6\n4 7", "output": "1\n1\n9\n1\n4"} +{"input": "1\n4\n100000000 100000001 100000010 999999999\n3\n1 2\n1 4\n2 3", "output": "1\n899999999\n9"} +{"input": "1\n5\n100 300 301 303 1000\n4\n1 2\n2 3\n3 4\n4 5", "output": "1\n1\n2\n697"} +{"input": "1\n5\n0 9 10 12 13\n5\n1 5\n2 3\n3 5\n4 3\n2 5", "output": "5\n1\n3\n2\n4"} diff --git a/new_data/test/1922_C.py b/new_data/test/1922_C.py new file mode 100644 index 0000000..3da2a84 --- /dev/null +++ b/new_data/test/1922_C.py @@ -0,0 +1,27 @@ +def dir(a,x): + distL = 1e9 if x == 0 else a[x] - a[x - 1] + distR = 1e9 if x + 1 == len(a) else a[x + 1]-a[x] + if distL < distR: + return 'L' + if distL > distR: + return 'R' + +def solve(): + for _ in range(int(input())): + n=int(input()) + a=list(map(int, input().split())) + l=[0]*n + r=[0]*n + for i in range(1,n): + r[i] = r[i-1] + (1 if dir(a,i-1)=='R' else a[i]-a[i-1]) + for i in range(n-2,-1,-1): + l[i] = l[i + 1] + (1 if dir(a, i + 1)=='L' else a[i+1]-a[i]) + m=int(input()) + for _ in range(m): + x, y=map(int, input().split()) + x, y=x-1,y-1 + if x s: + ans = forward[e] - forward[s] + else: + ans = back[e] - back[s] + anses.append(ans) + for ans in anses: + print(ans) diff --git a/new_data/test/1923_A.jsonl b/new_data/test/1923_A.jsonl new file mode 100644 index 0000000..cca6613 --- /dev/null +++ b/new_data/test/1923_A.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n8\n0 1 1 1 0 1 1 0\n6\n0 1 0 0 0 0\n6\n1 1 1 1 1 1\n5\n1 0 1 0 1\n9\n0 1 1 0 0 0 1 1 0", "output": "1\n0\n0\n2\n3"} +{"input": "1\n2\n1 0", "output": "0"} +{"input": "1\n3\n1 0 1", "output": "1"} +{"input": "1\n5\n1 0 0 0 1", "output": "3"} +{"input": "1\n4\n0 0 1 1", "output": "0"} +{"input": "1\n6\n1 0 1 1 0 0", "output": "1"} +{"input": "1\n7\n0 1 1 0 1 0 1", "output": "2"} +{"input": "1\n8\n1 0 0 0 0 0 0 1", "output": "6"} +{"input": "1\n10\n0 0 0 1 1 1 0 0 0 0", "output": "0"} +{"input": "1\n9\n0 1 0 0 1 0 0 1 0", "output": "4"} +{"input": "1\n50\n1 0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0", "output": "43"} diff --git a/new_data/test/1923_A.py b/new_data/test/1923_A.py new file mode 100644 index 0000000..35f770a --- /dev/null +++ b/new_data/test/1923_A.py @@ -0,0 +1,25 @@ +tests = int(input()) + +for _ in range(tests): + length = int(input()) + strg = input().split() + + moves = 0 + left = 0 + right = length - 1 + + while strg[left] == "0": + left += 1 + + while strg[right] == "0": + right -= 1 + + while left <= right: + if strg[left] == "1": + left += 1 + else: + moves += 1 + right -= 1 + left += 1 + + print(moves) diff --git a/new_data/test/1923_A_1.py b/new_data/test/1923_A_1.py new file mode 100644 index 0000000..bca8920 --- /dev/null +++ b/new_data/test/1923_A_1.py @@ -0,0 +1,44 @@ +''' + +0 과 1로 이루어진 배열을 받고 난 후 +0으로만 연속되고 1으로만 연속된 하나의 블록으로 만드는 것이 목표임 +오른쪽에 있는 1을 가장 가까운 왼쪽으로 옮겨서 독립된 0, 1 블록으로 만들어야 함 + +그냥 중간에 비어있는 0의 갯수가 정답일 듯 + +''' + +t = int(input()) + +for _ in range(t): + length = int(input()) + arrs = list(map(int, input().split())) + + cnt0 = 0 + + for idx in range(len(arrs)): + if arrs[0] == 0 and idx != 0: # 0이면 0으로 이루어지다가 1로 이루어져야함 + if arrs[idx] == 0: + cnt0 += 1 + elif arrs[0] == 1: # 처음이 1이면 무조건 0 + if arrs[idx] == 0: + cnt0 += 1 + + cnt1 = 0 + + for idx in range(len(arrs)): + if arrs[idx] == 1: + cnt1 += 1 + + if arrs[0] == 0: + if arrs[len(arrs) - 1] == 0: + cnt0 -= 1 + + ans = 0 + + if cnt1 == 1 or cnt1 == 0: + ans = 0 + else: + ans = cnt0 + + print(ans) \ No newline at end of file diff --git a/new_data/test/1923_B.jsonl b/new_data/test/1923_B.jsonl new file mode 100644 index 0000000..3546471 --- /dev/null +++ b/new_data/test/1923_B.jsonl @@ -0,0 +1,41 @@ +{"input": "5\n3 2\n1 2 3\n-1 2 3\n2 1\n1 1\n-1 1\n4 10\n3 4 2 5\n-3 -2 1 3\n5 3\n2 1 3 2 5\n-3 -2 3 4 5\n2 1\n1 2\n1 2", "output": "YES\nNO\nYES\nYES\nNO"} +{"input": "1\n5 5\n2 4 6 8 10\n-5 -3 -1 1 3", "output": "NO"} +{"input": "1\n1 1\n1000000000\n-1", "output": "NO"} +{"input": "1\n5 1\n1 1 1 1 1\n-5 -4 -3 -2 -1", "output": "YES"} +{"input": "1\n3 3\n3 2 1\n-1 1 3", "output": "NO"} +{"input": "1\n3 5\n7 8 9\n2 3 4", "output": "NO"} +{"input": "1\n4 4\n1 1000000000 1 1000000000\n-4 -2 2 4", "output": "NO"} +{"input": "1\n6 10\n10 20 30 40 50 60\n-6 -4 -2 2 4 8", "output": "NO"} +{"input": "1\n2 100000\n2 1000000000\n-2 100", "output": "NO"} +{"input": "1\n10 10\n1 1 1 1 1 1 1 1 1 1\n-10 -9 -8 -7 -6 -5 -4 -3 -2 -1", "output": "YES"} +{"input": "1\n5 2\n10 9 8 7 6\n0 1 2 3 5", "output": "NO"} +{"input": "1\n1 1\n1\n1", "output": "YES"} +{"input": "2\n1 1\n1\n-1\n1 2\n2\n-1", "output": "YES\nYES"} +{"input": "2\n2 1\n1 1\n-1 1\n2 2\n1 1\n-1 1", "output": "NO\nYES"} +{"input": "1\n3 1\n2 2 2\n-3 -1 2", "output": "NO"} +{"input": "1\n3 2\n1 2 3\n-1 2 3", "output": "YES"} +{"input": "2\n5 10\n1 2 3 4 5\n-5 -1 1 2 3\n5 1\n2 2 2 2 2\n-2 -1 1 2 5", "output": "YES\nNO"} +{"input": "2\n4 10\n3 4 2 5\n-3 -2 1 3\n5 3\n2 1 3 2 5\n-3 -2 3 4 5", "output": "YES\nYES"} +{"input": "3\n2 1\n1 1\n-1 1\n2 1\n1 2\n1 2\n2 1\n2 1\n-2 -1", "output": "NO\nNO\nNO"} +{"input": "2\n5 5\n10 10 10 10 10\n-5 -4 -3 -2 -1\n5 5\n10 10 10 10 10\n1 2 3 4 5", "output": "NO\nNO"} +{"input": "2\n3 1\n10 1 5\n-3 -2 -1\n3 10\n10 1 5\n1 2 3", "output": "NO\nYES"} +{"input": "1\n3 2\n1 2 3\n-1 2 3", "output": "YES"} +{"input": "1\n2 1\n1 1\n-1 1", "output": "NO"} +{"input": "1\n4 10\n3 4 2 5\n-3 -2 1 3", "output": "YES"} +{"input": "1\n5 3\n2 1 3 2 5\n-3 -2 3 4 5", "output": "YES"} +{"input": "1\n2 1\n1 2\n1 2", "output": "NO"} +{"input": "2\n1 1\n1\n-1\n1 1\n1\n1", "output": "YES\nYES"} +{"input": "2\n3 1\n5 2 5\n-3 -1 2\n2 2\n5 5\n-2 1", "output": "NO\nNO"} +{"input": "1\n3 1000000000\n1 1000000000 5\n-2 1 2", "output": "YES"} +{"input": "2\n3 1\n1000000000 1000000000 1000000000\n-3 -2 1\n3 1000000000\n1000000000 1000000000 1000000000\n-3 -2 -1", "output": "NO\nYES"} +{"input": "1\n5 1\n1 2 3 1 1\n-5 -3 -2 1 2", "output": "NO"} +{"input": "2\n4 2\n2 2 2 2\n-4 -1 1 4\n5 2\n1 2 3 4 5\n-5 -2 2 4 5", "output": "NO\nNO"} +{"input": "1\n1 2\n1000000000\n-1", "output": "NO"} +{"input": "2\n1 5\n3\n-3\n1 3\n4\n-3", "output": "YES\nYES"} +{"input": "1\n5 3\n2 3 2 3 2\n-5 -4 -3 -2 -1", "output": "YES"} +{"input": "1\n5 2\n2 2 2 2 2\n1 2 3 4 5", "output": "YES"} +{"input": "2\n4 2\n1 2 3 4\n-4 -2 1 2\n3 2\n2 2 5\n-3 1 2", "output": "NO\nNO"} +{"input": "3\n1 1\n1\n-1\n2 10\n1 1\n-2 -1\n3 1\n1 1 1\n1 2 3", "output": "YES\nYES\nYES"} +{"input": "2\n5 10\n5 5 5 5 5\n-5 -3 -2 -1 1\n5 10\n10 10 10 10 10\n1 2 3 4 5", "output": "YES\nYES"} +{"input": "2\n3 2\n2 2 2\n-2 -1 1\n3 3\n3 1 1\n-3 -1 2", "output": "NO\nYES"} +{"input": "3\n3 1\n1 2 3\n-3 -2 -1\n3 10\n1 1 1\n1 2 3\n5 1\n1 1 1 1 1\n-5 -3 -2 1 2", "output": "NO\nYES\nNO"} diff --git a/new_data/test/1923_B.py b/new_data/test/1923_B.py new file mode 100644 index 0000000..baaa9f9 --- /dev/null +++ b/new_data/test/1923_B.py @@ -0,0 +1,80 @@ +def sort_list(): + global m_dg + abs_list = [] + sorted_list = [] + max_dis = 0 + lh = len(h_list) + for i in x_list: + absnum = abs(i) + abs_list.append(absnum) + if absnum > max_dis: + max_dis = absnum + m_dg = sum(h_list) / max_dis + if k < m_dg: + ans_list.append("NO") + return False + elif k > 2 * m_dg: + ans_list.append("YES") + return True + for i in range(lh): + cindex = abs_list.index(min(abs_list)) + sorted_list.append([h_list[cindex], x_list[cindex]]) # h, x + h_list.pop(cindex) + x_list.pop(cindex) + abs_list.pop(cindex) + return sorted_list + + +def process(s_list): + while True: + n = k + indx = 0 + saveh = 0 + while (n > 0) and (s_list[indx][0] > 0): + saveh = s_list[indx][0] + s_list[indx][0] = s_list[indx][0] - n + n = n - saveh + if len(s_list)-1 > indx: + indx += 1 + for i in range(indx+1): + if s_list[0][0] <= 0: + s_list.pop(0) + if len(s_list) == 0: + ans_list.append("YES") + return None + for i in range(len(s_list)): + if s_list[i][1] > 0: + s_list[i][1] = s_list[i][1] - 1 + if s_list[i][1] < 0: + s_list[i][1] = s_list[i][1] + 1 + if s_list[i][1] == 0: + ans_list.append("NO") + return None + + +def start(): + global x_list, h_list, k, ans_list, max_h + ans_list = [] + t_run = int(input()) + for i in range(t_run): + n, k = input().split() + n, k = int(n), int(k) + h_list = input().split() + h_list = list(map(lambda x: int(x), h_list)) + x_list = input().split() + x_list = list(map(lambda x: int(x), x_list)) + max_h = max(h_list) + if k >= 2 * max_h: + ans_list.append("YES") + continue + sl = sort_list() + if sl == False: + continue + if sl == True: + continue + process(sl) + for i in ans_list: + print(i) + + +start() \ No newline at end of file diff --git a/new_data/test/1923_B_1.py b/new_data/test/1923_B_1.py new file mode 100644 index 0000000..bd20355 --- /dev/null +++ b/new_data/test/1923_B_1.py @@ -0,0 +1,59 @@ +import sys +import math + +input = sys.stdin.readline + + +def inp(): + return (int(input())) + + +def inlt(): + return (list(map(int, input().split()))) + + +def insr(): + s = input() + return (list(s[:len(s) - 1])) + + +def invr(): + return (map(int, input().split())) + + +for _ in range(1): + n = int(input()) + +for i in range(0, n): + temp = inlt() + n = temp[0] + k = temp[1] + health = inlt() + pos = inlt() + + pos = [abs(0 - x) for x in pos] + combined = zip(pos, health) + s = sorted(combined) + sortedlist = [] + for t in range(0, len(s)): + currHealth = s[t][1] + currPos = s[t][0] + if (t > 0 and s[t][0] == s[t - 1][0]): + sortedlist[-1] = (currPos, sortedlist[-1][1] + currHealth) + else: + sortedlist.append((currPos, currHealth)) + extra = 0 + ans = True + iter = 0 + for item in sortedlist: + curr = (k * (item[0] - iter)) + extra + if (curr < item[1]): + ans = False + break + else: + iter = iter + (item[1] - extra) / k + extra = extra + (curr - item[1]) + if (ans): + print("Yes") + else: + print("No") diff --git a/new_data/test/1923_C.jsonl b/new_data/test/1923_C.jsonl new file mode 100644 index 0000000..f48351e --- /dev/null +++ b/new_data/test/1923_C.jsonl @@ -0,0 +1,41 @@ +{"input": "1\n5 4\n1 2 1 4 5\n1 5\n4 4\n3 4\n1 3", "output": "YES\nNO\nYES\nNO"} +{"input": "1\n2 1\n1 1\n1 2", "output": "NO"} +{"input": "1\n4 3\n1 1 1 1\n1 2\n2 3\n3 4", "output": "NO\nNO\nNO"} +{"input": "1\n5 2\n1 2 3 4 5\n1 3\n3 5", "output": "YES\nYES"} +{"input": "1\n7 2\n10 10 10 10 10 10 10\n1 4\n4 7", "output": "YES\nYES"} +{"input": "1\n6 3\n3 3 3 3 3 3\n1 6\n2 5\n4 4", "output": "YES\nYES\nNO"} +{"input": "1\n8 3\n5 5 5 5 5 5 5 5\n3 6\n1 5\n5 8", "output": "YES\nYES\nYES"} +{"input": "1\n9 4\n1 2 3 1000000 300 400 500 600 700\n1 4\n5 5\n3 7\n1 9", "output": "YES\nNO\nYES\nYES"} +{"input": "2\n3 1\n1 2 3\n1 2\n5 2\n7 9 8 6 5\n2 4\n1 5", "output": "YES\nYES\nYES"} +{"input": "1\n10 5\n100 200 300 400 500 600 700 800 900 1000\n2 5\n5 10\n1 7\n3 8\n9 10", "output": "YES\nYES\nYES\nYES\nYES"} +{"input": "1\n6 4\n10 20 30 10 20 30\n1 6\n2 5\n3 4\n1 3", "output": "YES\nYES\nYES\nYES"} +{"input": "1\n1 1\n1\n1 1", "output": "NO"} +{"input": "1\n2 2\n1 2\n1 1\n1 2", "output": "NO\nYES"} +{"input": "1\n5 4\n1 2 1 4 5\n1 5\n4 4\n3 4\n1 3", "output": "YES\nNO\nYES\nNO"} +{"input": "1\n3 3\n2 2 2\n1 1\n1 2\n1 3", "output": "NO\nYES\nYES"} +{"input": "1\n4 4\n1 1 1 1\n1 1\n2 3\n1 4\n2 4", "output": "NO\nNO\nNO\nNO"} +{"input": "2\n3 3\n1 2 3\n1 1\n1 3\n2 2\n2 2\n5 5\n1 1\n1 2", "output": "NO\nYES\nNO\nNO\nYES"} +{"input": "1\n5 3\n1000000000 1000000000 1000000000 1000000000 1000000000\n1 1\n1 4\n1 5", "output": "NO\nYES\nYES"} +{"input": "1\n5 5\n1 1 2 2 4\n1 1\n1 5\n2 4\n4 5\n3 3", "output": "NO\nYES\nYES\nYES\nNO"} +{"input": "1\n5 5\n3 3 3 6 6\n1 1\n2 3\n1 3\n4 5\n1 5", "output": "NO\nYES\nYES\nYES\nYES"} +{"input": "1\n10 5\n1 1 5 5 5 5 2 2 2 7\n1 1\n1 10\n3 6\n7 9\n4 10", "output": "NO\nYES\nYES\nYES\nYES"} +{"input": "1\n1 1\n1\n1 1", "output": "NO"} +{"input": "1\n5 4\n1 2 1 4 5\n1 5\n4 4\n3 4\n1 3", "output": "YES\nNO\nYES\nNO"} +{"input": "1\n3 3\n2 2 2\n1 1\n1 2\n1 3", "output": "NO\nYES\nYES"} +{"input": "1\n3 3\n1 1 1\n1 1\n1 2\n1 3", "output": "NO\nNO\nNO"} +{"input": "1\n4 4\n1 2 3 9\n1 4\n2 4\n1 1\n4 4", "output": "YES\nYES\nNO\nNO"} +{"input": "1\n5 5\n2 2 1 1 4\n2 2\n1 2\n2 4\n1 5\n3 5", "output": "NO\nYES\nNO\nYES\nYES"} +{"input": "2\n2 2\n2 4\n1 1\n1 2\n3 2\n2 4 2\n1 3\n2 3", "output": "NO\nYES\nYES\nYES"} +{"input": "1\n5 5\n1000000000 1000000000 1000000000 1000000000 1000000000\n1 1\n1 2\n1 5\n3 5\n2 4", "output": "NO\nYES\nYES\nYES\nYES"} +{"input": "1\n5 4\n2 2 2 2 2\n1 1\n1 2\n1 5\n2 3", "output": "NO\nYES\nYES\nYES"} +{"input": "1\n6 6\n1 3 1 3 1 3\n1 2\n2 3\n1 6\n3 6\n2 5\n4 5", "output": "YES\nYES\nYES\nYES\nYES\nYES"} +{"input": "1\n5 5\n1 2 3 4 5\n1 3\n2 5\n1 5\n4 5\n3 3", "output": "YES\nYES\nYES\nYES\nNO"} +{"input": "2\n4 3\n1 2 5 5\n1 2\n1 4\n3 4\n5 2\n1 1 10 1 1\n1 5\n2 4", "output": "YES\nYES\nYES\nYES\nYES"} +{"input": "1\n3 3\n2 4 6\n1 1\n2 2\n1 3", "output": "NO\nNO\nYES"} +{"input": "1\n5 5\n3 3 3 3 6\n1 1\n5 5\n1 4\n2 5\n1 5", "output": "NO\nNO\nYES\nYES\nYES"} +{"input": "1\n5 5\n5 4 3 2 1\n1 5\n1 1\n5 5\n2 4\n3 5", "output": "YES\nNO\nNO\nYES\nYES"} +{"input": "1\n5 5\n2 4 6 8 10\n1 5\n1 2\n2 3\n4 5\n3 5", "output": "YES\nYES\nYES\nYES\nYES"} +{"input": "1\n5 5\n1 3 2 4 2\n1 5\n1 1\n5 5\n1 4\n2 5", "output": "YES\nNO\nNO\nYES\nYES"} +{"input": "2\n4 2\n1 1 2 2\n1 4\n2 3\n4 2\n1 2 1 2\n1 4\n1 2", "output": "YES\nYES\nYES\nYES"} +{"input": "1\n5 5\n9 1 1 1 1\n1 1\n2 5\n1 2\n1 5\n3 4", "output": "NO\nNO\nYES\nYES\nNO"} +{"input": "1\n6 5\n2 3 5 7 11 13\n1 3\n2 2\n1 6\n3 5\n6 6", "output": "YES\nNO\nYES\nYES\nNO"} diff --git a/new_data/test/1923_C.py b/new_data/test/1923_C.py new file mode 100644 index 0000000..e8eb2cf --- /dev/null +++ b/new_data/test/1923_C.py @@ -0,0 +1,32 @@ +def solve(): + n, q = map(int, input().split()) + arr = list(map(int, input().split())) + + pref = [0] * (n + 1) + ones = [0] * (n + 1) + for i in range(n): + pref[i + 1] = pref[i] + arr[i] + ones[i + 1] = ones[i] + (1 if arr[i] == 1 else 0) + + # print(ones) + + for _ in range(q): + l, r = map(int, input().split()) + + if l == r: + print("NO") + continue + + s = pref[r] - pref[l - 1] + o = ones[r] - ones[l - 1] + maj = (r - l + 1) // 2 + + if s >= 2 * (r - l + 1) - 1 or not (o >= maj + 1): + print("YES") + else: + print("NO") + + +t = int(input()) +for _ in range(t): + solve() diff --git a/new_data/test/1923_C_1.py b/new_data/test/1923_C_1.py new file mode 100644 index 0000000..4f135ce --- /dev/null +++ b/new_data/test/1923_C_1.py @@ -0,0 +1,39 @@ +import sys + +input = sys.stdin.readline +sys.setrecursionlimit(int(1e9)) + +T = int(input()) + +while T: + T -= 1 + n, q = map(int, input().split()) + arr = list(map(int, input().split())) + + numOne = [0] + pSum = [0] + + for el in arr: + numOne.append(numOne[-1] + (el == 1)) + pSum.append(pSum[-1] + el) + + while q: + q -= 1 + l, r = map(int, input().split()) + if l == r: + print("NO") + continue + o = numOne[r] - numOne[l - 1] + s = pSum[r] - pSum[l - 1] + n_nums = r - l + 1 + stand = (n_nums + 1) // 2 * 2 + (n_nums - (n_nums + 1) // 2) + + if stand < s: + print("YES") + continue + + if stand == s and (n_nums == 3 or o <= (n_nums + 1) // 2): + print("YES") + continue + + print("NO") diff --git a/new_data/test/1924_A.jsonl b/new_data/test/1924_A.jsonl new file mode 100644 index 0000000..30c2ca8 --- /dev/null +++ b/new_data/test/1924_A.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n2 2 4\nabba\n2 2 3\nabb\n3 3 10\naabbccabab", "output": "YES\nNO\naa\nNO\nccc"} +{"input": "1\n1 1 1\na", "output": "YES"} +{"input": "1\n2 1 2\naa", "output": "YES"} +{"input": "1\n3 3 10\nabcabcabca", "output": "YES"} +{"input": "1\n3 2 5\nabab", "output": "NO\nbba"} +{"input": "1\n2 2 3\naba", "output": "NO\nbb"} +{"input": "1\n5 3 15\nabcabcabcabcabc", "output": "YES"} +{"input": "1\n2 3 6\ncbacab", "output": "YES"} +{"input": "1\n3 2 6\nbbaabb", "output": "NO\naba"} +{"input": "1\n3 3 27\naaabbbcccaaabbbcccaaabbbccc", "output": "YES"} +{"input": "1\n4 3 12\nabcabcabacbc", "output": "NO\nccca"} \ No newline at end of file diff --git a/new_data/test/1924_A.py b/new_data/test/1924_A.py new file mode 100644 index 0000000..b553cd3 --- /dev/null +++ b/new_data/test/1924_A.py @@ -0,0 +1,57 @@ + +import sys +from itertools import product + +def is_subsequence(t, s): + it = iter(s) + for c in t: + flag = False + for sc in it: + if sc == c: + flag = True + break + if not flag: + return False + return True + +def main(): + input = sys.stdin.read().split() + t = int(input[0]) + ptr = 1 + for _ in range(t): + n = int(input[ptr]) + k = int(input[ptr+1]) + m = int(input[ptr+2]) + s = input[ptr+3] + ptr +=4 + # Step 1: Count character frequencies + counts = [0] * k + for c in s: + if 'a' <= c <= chr(ord('a') + k -1): + counts[ord(c) - ord('a')] +=1 + # Check if any character count is less than n + missing = "" + for i in range(k): + if counts[i] < n: + missing = chr(ord('a') + i) * n + break + if missing: + print("NO") + print(missing) + continue + # Step 2: If k^n <= 100, check all combinations + if k**n <=100: + letters = [chr(ord('a') + i) for i in range(k)] + for comb in product(letters, repeat=n): + t_str = ''.join(comb) + if not is_subsequence(t_str, s): + print("NO") + print(t_str) + break + else: + print("YES") + else: + print("YES") + +if __name__ == '__main__': + main() diff --git a/new_data/test/1924_A_1.py b/new_data/test/1924_A_1.py new file mode 100644 index 0000000..b553cd3 --- /dev/null +++ b/new_data/test/1924_A_1.py @@ -0,0 +1,57 @@ + +import sys +from itertools import product + +def is_subsequence(t, s): + it = iter(s) + for c in t: + flag = False + for sc in it: + if sc == c: + flag = True + break + if not flag: + return False + return True + +def main(): + input = sys.stdin.read().split() + t = int(input[0]) + ptr = 1 + for _ in range(t): + n = int(input[ptr]) + k = int(input[ptr+1]) + m = int(input[ptr+2]) + s = input[ptr+3] + ptr +=4 + # Step 1: Count character frequencies + counts = [0] * k + for c in s: + if 'a' <= c <= chr(ord('a') + k -1): + counts[ord(c) - ord('a')] +=1 + # Check if any character count is less than n + missing = "" + for i in range(k): + if counts[i] < n: + missing = chr(ord('a') + i) * n + break + if missing: + print("NO") + print(missing) + continue + # Step 2: If k^n <= 100, check all combinations + if k**n <=100: + letters = [chr(ord('a') + i) for i in range(k)] + for comb in product(letters, repeat=n): + t_str = ''.join(comb) + if not is_subsequence(t_str, s): + print("NO") + print(t_str) + break + else: + print("YES") + else: + print("YES") + +if __name__ == '__main__': + main() diff --git a/new_data/test/1925_A.jsonl b/new_data/test/1925_A.jsonl new file mode 100644 index 0000000..42aa227 --- /dev/null +++ b/new_data/test/1925_A.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n1 2\n2 1\n2 2\n2 3", "output": "ab\naa\nbaab\nabcbac"} +{"input": "1\n26 26", "output": "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"} +{"input": "1\n1 1", "output": "a"} +{"input": "1\n26 1", "output": "aaaaaaaaaaaaaaaaaaaaaaaaaa"} +{"input": "1\n2 26", "output": "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"} +{"input": "1\n5 3", "output": "abcabcabcabcabc"} +{"input": "1\n3 5", "output": "abcdeabcdeabcde"} +{"input": "1\n4 4", "output": "abcdabcdabcdabcd"} +{"input": "1\n1 2", "output": "ab"} +{"input": "1\n3 3", "output": "abcabcabc"} +{"input": "1\n2 5", "output": "abcdeabcde"} diff --git a/new_data/test/1925_A.py b/new_data/test/1925_A.py new file mode 100644 index 0000000..33c1da5 --- /dev/null +++ b/new_data/test/1925_A.py @@ -0,0 +1,49 @@ +from sys import stdin, stdout + +p = stdout.write +# ---------COLLECTIONS--------# +from collections import defaultdict as maps +# using this, we can give a default value of data type to dict +from collections import OrderedDict +# this stores the order of insertion of values in dict +from collections import Counter as freq +# returns a dict containing count of values +from collections import ChainMap + + +# to have diff. dicts in one class (container) +# we have to use .new_child(new_dictToInsert) to insert a new dict into ChainMap +# -------COLLECTIONS---------- # + +def getlist(): + return list(map(int, stdin.readline().split())) + + +def getinp(): + return map(int, stdin.readline().split()) + + +def getstr(): + return stdin.readline().rstrip() + + +def getnum(): + return int(stdin.readline()) + + +# -----------MAIN CODE----------# +def main(): + for _ in range(int(stdin.readline())): + n, k = getinp() + r = "" + for i in range(k): + r += chr(97 + i) + if n <= 3: + p(r * n + "\n") + else: + p(r * (n - 1) + 'a' + "\n") + + +# -----------MAIN CODE-----------# +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/new_data/test/1925_A_1.py b/new_data/test/1925_A_1.py new file mode 100644 index 0000000..2d7b770 --- /dev/null +++ b/new_data/test/1925_A_1.py @@ -0,0 +1,16 @@ +import collections +from collections import Counter +from collections import defaultdict +import math +from math import log + +def solve(): + n,k=map(int, input().split()) + s='abcdefghijklmnopqrstuvw' + return s[:k]*(n) +t = int(input()) +for i in range(t): + res = solve() + print(res) + + diff --git a/new_data/test/1925_D.jsonl b/new_data/test/1925_D.jsonl new file mode 100644 index 0000000..e7faffc --- /dev/null +++ b/new_data/test/1925_D.jsonl @@ -0,0 +1,21 @@ +{"input": "4\n100 0 24\n2 1 10\n1 2 1\n3 1 2\n2 1 1\n5 2 4\n1 2 25\n3 2 24", "output": "0\n55\n777777784\n40000020"} +{"input": "1\n2 0 1", "output": "0"} +{"input": "1\n2 1 10\n1 2 1", "output": "55"} +{"input": "2\n3 1 2\n1 2 1\n3 1 2\n2 3 1", "output": "777777784\n777777784"} +{"input": "2\n4 6 3\n1 2 5\n1 3 5\n1 4 5\n2 3 10\n2 4 10\n3 4 1\n4 0 3", "output": "500000022\n0"} +{"input": "2\n5 2 4\n1 2 25\n3 2 24\n5 1 10\n4 5 1000000000", "output": "40000020\n649999998"} +{"input": "3\n5 0 10\n2 1 200000\n1 2 1\n6 3 5\n1 2 5\n2 3 6\n4 5 100", "output": "0\n99860\n933333377"} +{"input": "1\n10 2 200000\n1 2 1\n9 10 999999999", "output": "451820645"} +{"input": "1\n5 10 5\n1 2 1\n1 3 2\n1 4 3\n1 5 4\n2 3 5\n2 4 6\n2 5 7\n3 4 8\n3 5 9\n4 5 10", "output": "500000032"} +{"input": "2\n3 0 1\n3 3 5\n1 2 1\n2 3 2\n1 3 3", "output": "0\n333333349"} +{"input": "2\n2 1 1\n1 2 1000000000\n2 1 2\n1 2 999999999", "output": "1000000000\n999999992"} +{"input": "1\n2 0 1", "output": "0"} +{"input": "1\n2 1 1\n1 2 1000000000", "output": "1000000000"} +{"input": "2\n3 1 2\n1 2 1\n3 1 2\n2 3 2", "output": "777777784\n444444449"} +{"input": "2\n4 0 5\n4 2 5\n1 2 1\n2 3 2", "output": "0\n55555559"} +{"input": "1\n5 1 10\n1 5 999999999", "output": "649999997"} +{"input": "2\n2 1 200000\n1 2 1\n3 3 100000\n1 2 1\n2 3 2\n1 3 3", "output": "99860\n666849993"} +{"input": "1\n5 4 5\n1 2 1\n2 3 2\n2 4 3\n4 5 4", "output": "800000011"} +{"input": "3\n3 0 3\n3 1 3\n1 2 1\n3 2 3\n1 2 2\n2 3 3", "output": "0\n333333337\n666666677"} +{"input": "2\n5 2 4\n1 2 25\n3 2 24\n2 1 10\n1 2 1", "output": "40000020\n55"} +{"input": "3\n4 2 2\n1 2 1\n2 4 2\n5 2 2\n1 3 100\n2 5 200\n5 3 5\n1 2 1\n2 3 2\n4 5 10", "output": "55555557\n140000061\n600000011"} diff --git a/new_data/test/1925_D.py b/new_data/test/1925_D.py new file mode 100644 index 0000000..0704094 --- /dev/null +++ b/new_data/test/1925_D.py @@ -0,0 +1,23 @@ +mod = 1000000007 + +def inv(a): + if a <= 1: + return a + return mod - (mod // a) * inv(mod % a) % mod + +def main(): + tes = int(input()) + for fuck in range(1, tes + 1): + n, m, k = map(int, input().split()) + sum_val = 0 + ans = 0 + for _ in range(m): + a, b, c = map(int, input().split()) + sum_val += c + N = inv((n * (n - 1)) // 2) + for i in range(k): + ans += (i * m * N * N + sum_val * N) % mod + print(ans % mod) + +if __name__ == "__main__": + main() diff --git a/new_data/test/1925_D_1.py b/new_data/test/1925_D_1.py new file mode 100644 index 0000000..d762826 --- /dev/null +++ b/new_data/test/1925_D_1.py @@ -0,0 +1,20 @@ +import math + +t = int(input()) + +M = 10 ** 9 + 7 + +for i in range(t): + n, m, k = map(int, input().split()) + sum_f = 0 + for j in range(m): + a, b, f = map(int, input().split()) + sum_f += f + cn2 = n * (n - 1) // 2 + p = 2 * k * cn2 * sum_f + m * k * (k - 1) + q = 2 * (cn2 ** 2) + gcd = math.gcd(p, q) + p = int(p / gcd) + q = int(q / gcd) + # print(p, q) + print(int((p * pow(q, -1, M)) % M)) \ No newline at end of file diff --git a/new_data/test/1926_A.jsonl b/new_data/test/1926_A.jsonl new file mode 100644 index 0000000..7336af3 --- /dev/null +++ b/new_data/test/1926_A.jsonl @@ -0,0 +1,11 @@ +{"input": "8\nABABB\nABABA\nBBBAB\nAAAAA\nBBBBB\nBABAA\nAAAAB\nBAAAA", "output": "B\nA\nB\nA\nB\nA\nA\nA"} +{"input": "1\nAAAAA", "output": "A"} +{"input": "1\nBBBBB", "output": "B"} +{"input": "1\nAAAAB", "output": "A"} +{"input": "1\nBBBBA", "output": "B"} +{"input": "1\nAAABB", "output": "A"} +{"input": "1\nAABBB", "output": "B"} +{"input": "1\nABABA", "output": "A"} +{"input": "1\nBABAB", "output": "B"} +{"input": "1\nABABB", "output": "B"} +{"input": "1\nBAAAA", "output": "A"} diff --git a/new_data/test/1926_A.py b/new_data/test/1926_A.py new file mode 100644 index 0000000..a4e8871 --- /dev/null +++ b/new_data/test/1926_A.py @@ -0,0 +1,27 @@ +# String of length 5 +# Characters are either A or B +# Which letter shows up most frequently? + +def charCount(userString): + list(userString) + countA = 0 + countB = 0 + for letter in userString: + if letter == 'A': + countA += 1 + elif letter == 'B': + countB += 1 + else: + continue + if countA > countB: + print("A") + elif countB > countA: + print("B") + else: + pass + + +userStrings = ["8", "ABABB", "ABABA", "BBBAB", "AAAAA", "BBBBB", "BABAA", "AAAAB", "BAAAA"] + +for userString in userStrings: + charCount(userString) diff --git a/new_data/test/1926_A_1.py b/new_data/test/1926_A_1.py new file mode 100644 index 0000000..6e8964e --- /dev/null +++ b/new_data/test/1926_A_1.py @@ -0,0 +1,26 @@ +class Testor: + def __init__(self, test_input): + self.number_of_test_cases = test_input[0] + self.test_cases = test_input[1:] + + def __count_A(self, case): + count = 0 + for i in range(5): + if case[i] == 'A': + count = count + 1 + return count + + def compare(self): + + for case in self.test_cases: + count = self.__count_A(case) + + if count > 2: + print('A') + else: + print('B') + + +testor = Testor([8, 'ABABB', 'ABABA', 'BBBAB', 'AAAAA', + 'BBBBB', 'BABAA', 'AAAAB', 'BAAAA']) +testor.compare() diff --git a/new_data/test/1926_B.jsonl b/new_data/test/1926_B.jsonl new file mode 100644 index 0000000..d003a17 --- /dev/null +++ b/new_data/test/1926_B.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n3\n000\n011\n011\n4\n0000\n0000\n0100\n1110\n2\n11\n11\n5\n00111\n00010\n00000\n00000\n00000\n10\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n1111111110\n0111111100\n0011111000\n0001110000\n0000100000\n3\n111\n111\n111", "output": "SQUARE\nTRIANGLE\nSQUARE\nTRIANGLE\nTRIANGLE\nSQUARE"} +{"input": "1\n2\n11\n11", "output": "SQUARE"} +{"input": "1\n3\n010\n111\n000", "output": "TRIANGLE"} +{"input": "1\n3\n000\n011\n011", "output": "SQUARE"} +{"input": "1\n3\n111\n010\n000", "output": "TRIANGLE"} +{"input": "1\n4\n0111\n0111\n0111\n0000", "output": "SQUARE"} +{"input": "1\n5\n00100\n01110\n11111\n00000\n00000", "output": "TRIANGLE"} +{"input": "2\n4\n1111\n1111\n1111\n1111\n4\n0000\n0000\n0111\n0010", "output": "SQUARE\nTRIANGLE"} +{"input": "1\n10\n0000100000\n0001110000\n0011111000\n0111111100\n1111111110\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000", "output": "TRIANGLE"} +{"input": "3\n2\n11\n11\n5\n00000\n00110\n00110\n00000\n00000\n5\n11111\n01110\n00100\n00000\n00000", "output": "SQUARE\nSQUARE\nTRIANGLE"} +{"input": "2\n3\n111\n111\n111\n4\n0000\n0010\n0111\n0000", "output": "SQUARE\nTRIANGLE"} diff --git a/new_data/test/1926_B.py b/new_data/test/1926_B.py new file mode 100644 index 0000000..699e267 --- /dev/null +++ b/new_data/test/1926_B.py @@ -0,0 +1,24 @@ +for _ in range(int(input())): + n = int(input()) + l = [''] * n + p = -1 + for i in range(n): + l[i] = input() + if (a := l[i].find("1")) > -1 and p == -1: + p = i + j = a + k = l[p].count("1") + m = l[p].rfind("1") + if k > 1 and m != j: + size = m - j + 1 + i = p + 1 + test = True + while test and i < n: + test = size == l[i].count('1') + i += 1 + if test: + print("SQUARE") + else: + print("TRIANGLE") + else: + print("TRIANGLE") diff --git a/new_data/test/1926_B_1.py b/new_data/test/1926_B_1.py new file mode 100644 index 0000000..8ac6391 --- /dev/null +++ b/new_data/test/1926_B_1.py @@ -0,0 +1,32 @@ +t=int(input()) + +for _ in range(t): + a=[] + n=int(input()) + for i in range(n): + s=str(input()) + if '1' in s: + a.append(s) + else: + pass + if not a: + print("SQUARE") + continue + a1=a[0] + a2=a[-1] + k=len(a) + is_square=True + for x in a: + p=x.count("1") + if p!=k: + is_square=False + break + q=x.index('1') + if q!=n-k: + is_square=False + break + + if is_square==True: + print('SQUARE') + else: + print('TRIANGLE') diff --git a/new_data/test/1926_C.jsonl b/new_data/test/1926_C.jsonl new file mode 100644 index 0000000..87f57cd --- /dev/null +++ b/new_data/test/1926_C.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n12\n1\n2\n3\n1434\n2024\n200000", "output": "51\n1\n3\n6\n18465\n28170\n4600002"} +{"input": "1\n1", "output": "1"} +{"input": "1\n9", "output": "45"} +{"input": "1\n10", "output": "46"} +{"input": "1\n12", "output": "51"} +{"input": "2\n1\n12", "output": "1\n51"} +{"input": "3\n2\n3\n1434", "output": "3\n6\n18465"} +{"input": "4\n99\n100\n999\n1000", "output": "900\n901\n13500\n13501"} +{"input": "2\n199999\n200000", "output": "4600000\n4600002"} +{"input": "5\n1\n200000\n10\n999\n1000", "output": "1\n4600002\n46\n13500\n13501"} +{"input": "7\n12\n1\n2\n3\n1434\n2024\n200000", "output": "51\n1\n3\n6\n18465\n28170\n4600002"} diff --git a/new_data/test/1926_C.py b/new_data/test/1926_C.py new file mode 100644 index 0000000..777e166 --- /dev/null +++ b/new_data/test/1926_C.py @@ -0,0 +1,27 @@ +def problem(): + t = int(input()) + numbers = [] + + for _ in range(t): + n = int(input()) + numbers.append(n) + + max_value = max(numbers) + 1 + sum_values = [0 for _ in range(max_value)] + + for i in range(1, n + 1): + sum_values[i] = digits_sum(i) + sum_values[i - 1] + + for n in numbers: + print(sum_values[n]) + + +def digits_sum(n): + sum_t = 0 + for digit in str(n): + sum_t += int(digit) + return sum_t + + +problem() + diff --git a/new_data/test/1926_C_1.py b/new_data/test/1926_C_1.py new file mode 100644 index 0000000..d933cc0 --- /dev/null +++ b/new_data/test/1926_C_1.py @@ -0,0 +1,30 @@ +def problem(): + t = int(input()) + numbers = [] + for _ in range(t): + n = int(input()) + numbers.append(n) + + values = [0 for _ in range(max(numbers + [10]) + 1)] + sum_values = [0 for _ in range(max(numbers + [10]) + 1)] + + total = 0 + for i in range(10): + values[i] = i + total += i + sum_values[i] = total + + for i in range(10, n + 1): + word = str(i) + last = int(word[len(word) - 1]) + remainder = int(word[:-1]) + values[i] = values[last] + values[remainder] + sum_total = values[i] + sum_values[i - 1] + sum_values[i] = sum_total + + for n in numbers: + print(sum_values[n]) + + +problem() + diff --git a/new_data/test/1926_D.jsonl b/new_data/test/1926_D.jsonl new file mode 100644 index 0000000..c6796d3 --- /dev/null +++ b/new_data/test/1926_D.jsonl @@ -0,0 +1,21 @@ +{"input": "9\n4\n1 4 3 4\n2\n0 2147483647\n5\n476319172 261956880 2136179468 1671164475 1885526767\n3\n1335890506 811593141 1128223362\n4\n688873446 627404104 1520079543 1458610201\n4\n61545621 2085938026 1269342732 1430258575\n4\n0 0 2147483647 2147483647\n3\n0 0 2147483647\n8\n1858058912 289424735 1858058912 2024818580 1858058912 289424735 122665067 289424735", "output": "4\n1\n3\n2\n2\n3\n2\n2\n4"} +{"input": "1\n1\n0", "output": "1"} +{"input": "1\n2\n1 2", "output": "2"} +{"input": "1\n10\n1 1 1 1 1 1 1 1 1 1", "output": "10"} +{"input": "1\n5\n0 1073741824 536870912 268435456 134217728", "output": "5"} +{"input": "1\n3\n2147483647 1073741823 536870911", "output": "3"} +{"input": "1\n4\n15 240 3840 61440", "output": "4"} +{"input": "1\n6\n43690 21845 65535 0 0 65535", "output": "6"} +{"input": "1\n7\n524288 1572864 3670016 0 8 1048576 2048", "output": "7"} +{"input": "1\n2\n170 85", "output": "2"} +{"input": "1\n5\n429496729 107374182 2147483647 536870911 268435455", "output": "5"} +{"input": "1\n1\n0", "output": "1"} +{"input": "1\n2\n0 2147483647", "output": "1"} +{"input": "1\n4\n5 5 5 5", "output": "4"} +{"input": "2\n3\n1 2 3\n3\n1073741823 1073741824 2147483647", "output": "3\n2"} +{"input": "2\n5\n0 2147483647 0 2147483647 0\n5\n1 2147483646 2147483646 1 0", "output": "3\n3"} +{"input": "3\n2\n10 2147483637\n2\n0 0\n3\n42 2147483605 2147483647", "output": "1\n2\n2"} +{"input": "2\n5\n1 2 4 8 16\n5\n1 2147483646 2 2147483645 2147483647", "output": "5\n3"} +{"input": "3\n1\n2147483647\n1\n123456789\n1\n0", "output": "1\n1\n1"} +{"input": "2\n6\n0 2147483647 85 2147483562 170 2147483477\n6\n0 0 2147483647 2147483647 12345 2147471302", "output": "3\n3"} +{"input": "5\n2\n1000000000 1147483647\n2\n999999999 1147483648\n2\n100 2147483547\n3\n0 1 2\n3\n1024 2048 4096", "output": "1\n1\n1\n3\n3"} diff --git a/new_data/test/1926_D.py b/new_data/test/1926_D.py new file mode 100644 index 0000000..9325e12 --- /dev/null +++ b/new_data/test/1926_D.py @@ -0,0 +1,20 @@ +num = int(input()) +out = [] +for x in range(num): + n = int(input()) + arr = [int(i) for i in input().split()] + arr.sort() + lo = 0 + hi = n-1 + g = n + while lo < hi: + if arr[lo] + arr[hi] == 2**31 - 1: + g -= 1 + lo += 1 + hi -=1 + elif arr[lo] -1 + arr[hi] <= 2*(2**30-1)+1: + lo += 1 + else: + hi -= 1 + out.append(g) +for i in out: print(i) \ No newline at end of file diff --git a/new_data/test/1926_D_1.py b/new_data/test/1926_D_1.py new file mode 100644 index 0000000..cec7ab7 --- /dev/null +++ b/new_data/test/1926_D_1.py @@ -0,0 +1,41 @@ + +def binarySearch(array, x): + low = 1 + high = len(array) -1 + while low <= high: + mid = low + (high - low) // 2 + + if array[mid] == x: + return mid + + elif array[mid] < x: + low = mid + 1 + + else: + high = mid - 1 + + return -1 + + +def find_pair(lst: list, ct): + if len(lst) == 0: + return print(ct) + + else: + pair = abs(2147483647 - lst[0]) + if binarySearch(lst, pair) != -1: + lst.pop(binarySearch(lst, pair)) + + lst.pop(0) + find_pair(lst, ct + 1) + + +for t in range(int(input())): + n = int(input()) + a = sorted(list(map(int, input().split(" ")))) + + try: + find_pair(a, 0) + + except Exception as e: + print(e) \ No newline at end of file diff --git a/new_data/test/1926_E.jsonl b/new_data/test/1926_E.jsonl new file mode 100644 index 0000000..d69b012 --- /dev/null +++ b/new_data/test/1926_E.jsonl @@ -0,0 +1,11 @@ +{"input": "11\n7 1\n7 2\n7 3\n7 4\n7 5\n7 6\n7 7\n1 1\n34 14\n84 19\n1000000000 1000000000", "output": "1\n3\n5\n7\n2\n6\n4\n1\n27\n37\n536870912"} +{"input": "5\n10 1\n20 2\n15 10\n30 15\n25 5", "output": "1\n3\n6\n29\n9"} +{"input": "1\n1000000000 999999999", "output": "805306368"} +{"input": "2\n13 1\n13 2", "output": "1\n3"} +{"input": "3\n50 10\n9 8\n14 7", "output": "19\n4\n13"} +{"input": "4\n7 6\n9 9\n17 16\n23 5", "output": "6\n8\n8\n9"} +{"input": "1\n500000000 250000000", "output": "499999999"} +{"input": "2\n17 5\n33 15", "output": "9\n29"} +{"input": "3\n19 3\n21 7\n25 4", "output": "5\n13\n7"} +{"input": "5\n7 3\n3 1\n11 6\n100 77\n99 45", "output": "5\n1\n11\n12\n89"} +{"input": "1\n1000000000 1", "output": "1"} diff --git a/new_data/test/1926_E.py b/new_data/test/1926_E.py new file mode 100644 index 0000000..5639f94 --- /dev/null +++ b/new_data/test/1926_E.py @@ -0,0 +1,42 @@ +a = int(input()) +while a != 0: + a -= 1 + l = list(map(int, input().split())) + n = l[0] + k = l[1] + + c = 0 + f = 1 + d = 2 + ans = True + while ans: + s = 1 + e = (n - s) // d + 1 + # print(f"{s} {e} {f} {d} {c}") + while s <= e: + + mid = (s + e) // 2 + v = f + (mid - 1) * d + if c + mid == k: + print(v) + ans = False + break + elif c + mid > k: + e = mid - 1 + else: + s = mid + 1 + c += (n - f) // d + 1 + f *= 2 + d *= 2 + + + + + + + + + + + + diff --git a/new_data/test/1926_E_1.py b/new_data/test/1926_E_1.py new file mode 100644 index 0000000..41e4935 --- /dev/null +++ b/new_data/test/1926_E_1.py @@ -0,0 +1,30 @@ +for _ in range(int(input())): + l1=input().split() + n=int(l1[0]) + k=int(l1[1]) + odds=n//2 +1 + if(n==1000000000 and k==1000000000): + print(536870912) + + elif(k<=odds): + print(2*k-1) + else: + temp=odds + p=1 + # print(temp) + while True: + # print(temp+((n//(2**p))//2)+1) + if((temp+(n//(2**p))//2 +1)>=k): + break + else: + # print(p) + temp+=((n//(2**p))//2 +1) + p+=1 + # print('p',p) + k-=temp + # print(p) + pwr=2**p + print(pwr*(2*k-1)) + + + diff --git a/new_data/test/1927_B.jsonl b/new_data/test/1927_B.jsonl new file mode 100644 index 0000000..e8efb1c --- /dev/null +++ b/new_data/test/1927_B.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n11\n0 0 0 1 0 2 0 3 1 1 4\n10\n0 0 0 0 0 1 0 1 1 0\n1\n0\n8\n0 1 2 3 4 5 6 7\n8\n0 0 0 0 0 0 0 0", "output": "abracadabra\ncodeforces\na\naaaaaaaa\ndijkstra"} +{"input": "1\n1\n0", "output": "a"} +{"input": "1\n2\n0 1", "output": "aa"} +{"input": "1\n5\n0 0 0 0 0", "output": "abcde"} +{"input": "1\n6\n0 1 2 3 4 5", "output": "aaaaaa"} +{"input": "1\n7\n0 0 1 2 1 3 4", "output": "abaabaa"} +{"input": "1\n1\n0", "output": "a"} +{"input": "1\n5\n0 0 0 0 0", "output": "abcde"} +{"input": "1\n8\n0 1 0 1 0 2 3 2", "output": "aabbcaab"} +{"input": "1\n12\n0 0 1 0 2 1 0 3 0 0 4 5", "output": "abacabdaefaa"} +{"input": "1\n15\n0 0 1 2 1 0 0 1 0 2 1 1 2 3 4", "output": "abaabcdcebdecaa"} diff --git a/new_data/test/1927_B.py b/new_data/test/1927_B.py new file mode 100644 index 0000000..9ac464d --- /dev/null +++ b/new_data/test/1927_B.py @@ -0,0 +1,24 @@ +def solve(n, a): + sam = 'abcdefghijklmnopqrstuvqwxyz' + a_map = {x: 0 for x in range(n)} + res = "" + for i in range(n): + beg = a_map[a[i]] + # print("beg = ",beg) + res += sam[a_map[a[i]] % 27] + a_map[a[i]] += 1 + # print(a_map) + # print("res = ",res) + return res + + +t = int(input()) +for i in range(t): + n = int(input()) + # s = input() + # a,b,r = map(int,input().split()) + a = list(map(int, input().split())) + # b = list(map(int,input().split())) + ans = solve(n, a) + print(ans) + # print("Yes") if ans else print("No") \ No newline at end of file diff --git a/new_data/test/1927_B_1.py b/new_data/test/1927_B_1.py new file mode 100644 index 0000000..0696ddf --- /dev/null +++ b/new_data/test/1927_B_1.py @@ -0,0 +1,20 @@ +t=int(input()) +for i in range(t): + n=int(input()) + c=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','e','u','w','x','y','z'] + ans=0 + b=[] + d=[0]*26 + a=list(map(int,input().split())) + for j in range(len(a)): + if a[j]==0: + b.append(c[ans]) + d[ans]+=1 + ans+=1 + else: + for p in range(len(d)): + if d[p]==a[j]: + b.append(c[p]) + d[p]+=1 + break + print(*b,sep='') \ No newline at end of file diff --git a/new_data/test/1927_C.jsonl b/new_data/test/1927_C.jsonl new file mode 100644 index 0000000..d506ab2 --- /dev/null +++ b/new_data/test/1927_C.jsonl @@ -0,0 +1,21 @@ +{"input": "6\n6 5 6\n2 3 8 5 6 5\n1 3 4 10 5\n6 5 6\n2 3 4 5 6 5\n1 3 8 10 3\n3 3 4\n1 3 5\n2 4 6\n2 5 4\n1 4\n7 3 4 4 2\n1 4 2\n2\n6 4 4 2\n1 5 2\n3\n2 2 1 4 3", "output": "YES\nNO\nYES\nYES\nNO\nNO"} +{"input": "1\n6 7 8\n1 2 3 4 5 6\n4 3 2 8 1 7 5", "output": "YES"} +{"input": "1\n4 4 6\n5 5 3 2\n6 7 8 1", "output": "NO"} +{"input": "1\n8 8 8\n1 1 2 2 3 3 4 4\n5 5 6 6 7 7 8 8", "output": "YES"} +{"input": "1\n10 10 10\n1 2 3 4 5 6 7 8 9 10\n10 9 8 7 6 5 4 3 2 1", "output": "YES"} +{"input": "1\n8 8 8\n1 3 5 7 2 4 6 8\n8 6 4 2 9 9 9 9", "output": "YES"} +{"input": "1\n5 5 4\n10 20 30 40 50\n5 15 25 35 45", "output": "NO"} +{"input": "1\n6 6 4\n1 500000 500000 500000 500000 500000\n2 3 4 500000 500000 500000", "output": "NO"} +{"input": "1\n3 3 2\n1 2 3\n4 5 6", "output": "NO"} +{"input": "1\n7 9 6\n2 4 6 8 10 12 14\n1 3 5 7 9 11 13 15 17", "output": "YES"} +{"input": "1\n2 2 2\n1 1\n1 2", "output": "YES"} +{"input": "1\n1 1 2\n1\n2", "output": "YES"} +{"input": "1\n2 2 4\n1 4\n2 3", "output": "YES"} +{"input": "1\n5 5 6\n2 3 8 5 6\n1 4 5 9 6", "output": "YES"} +{"input": "1\n5 5 6\n2 3 4 5 6\n1 2 8 9 9", "output": "NO"} +{"input": "1\n6 5 6\n2 3 8 5 6 5\n1 3 4 10 5", "output": "YES"} +{"input": "1\n6 5 6\n2 3 4 5 6 5\n1 3 8 10 3", "output": "NO"} +{"input": "1\n3 3 4\n1 3 5\n2 4 6", "output": "YES"} +{"input": "1\n2 5 4\n1 3\n2 4 7 7 7", "output": "YES"} +{"input": "1\n5 5 10\n1 2 3 4 6\n5 7 8 9 10", "output": "YES"} +{"input": "1\n5 5 10\n1 2 2 4 6\n5 7 8 9 11", "output": "NO"} diff --git a/new_data/test/1927_C.py b/new_data/test/1927_C.py new file mode 100644 index 0000000..815b569 --- /dev/null +++ b/new_data/test/1927_C.py @@ -0,0 +1,19 @@ +mylist = [2,3,2,2,4,1] + +t = int(input()) +for i in range(t): + line1 = input().split() + n = int(line1[0]) + m = int(line1[1]) + k = int(line1[2]) + arraya = input().split() + arraya = [int(value) for value in arraya] + arraya = list(set(arraya)) + arrayb = input().split() + arrayb = [int(value) for value in arrayb] + arrayb = list(set(arrayb)) + together = list(set(arraya + arrayb)) + if len(together) >= k and together[k-1] == k and len(arraya) >= int(k/2) and arraya[int(k/2)-1] <= k and len(arrayb) >= int(k/2) and arrayb[int(k/2)-1] <= k: + print("YES") + else: + print("NO") \ No newline at end of file diff --git a/new_data/test/1927_C_1.py b/new_data/test/1927_C_1.py new file mode 100644 index 0000000..53d6d7e --- /dev/null +++ b/new_data/test/1927_C_1.py @@ -0,0 +1,34 @@ +import collections +from collections import Counter +from collections import defaultdict +import math +from math import log +from math import floor +def med(lst): + x=sum(lst) + return x//len(lst) +def solve(): + n,m,k=map(int,input().split()) + a=[int(i) for i in input().split()] + b=[int(i) for i in input().split()] + x=list(set(a+b)) + x1=list(set(a)) + x2=list(set(b)) + test=[i+1 for i in range(k)] + if x[:k]!=test: + return 'NO' + ct,ct1=0,0 + for i in range(len(x1)): + if x1[i] in test: + ct+=1 + for i in range(len(x2)): + if x2[i] in test: + ct1+=1 + if ct1>=(k//2) and ct>=(k//2): + return 'YES' + return 'NO' + +t = int(input()) +for i in range(t): + res = solve() + print(res) diff --git a/new_data/test/1928_A.jsonl b/new_data/test/1928_A.jsonl new file mode 100644 index 0000000..e81293d --- /dev/null +++ b/new_data/test/1928_A.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n1 1\n2 1\n2 6\n3 2\n2 2\n2 4\n6 3", "output": "No\nNo\nYes\nYes\nYes\nYes\nNo"} +{"input": "1\n1 1", "output": "No"} +{"input": "1\n10 5", "output": "No"} +{"input": "1\n3 3", "output": "No"} +{"input": "1\n8 2", "output": "Yes"} +{"input": "1\n999999937 999999937", "output": "No"} +{"input": "1\n4 2", "output": "Yes"} +{"input": "1\n10 10", "output": "Yes"} +{"input": "1\n5 5", "output": "No"} +{"input": "1\n7 1", "output": "No"} +{"input": "1\n6 6", "output": "Yes"} diff --git a/new_data/test/1928_A.py b/new_data/test/1928_A.py new file mode 100644 index 0000000..b6e818b --- /dev/null +++ b/new_data/test/1928_A.py @@ -0,0 +1,10 @@ +for _ in range(int(input())): + a, b = map(int, input().split()) + if (a * b) % 2 != 0: + print('NO') + continue + if min(a, b) % 2 == 0: + print('YES') + else: + print('NO') + diff --git a/new_data/test/1928_A_1.py b/new_data/test/1928_A_1.py new file mode 100644 index 0000000..e24592b --- /dev/null +++ b/new_data/test/1928_A_1.py @@ -0,0 +1,10 @@ +from sys import stdin, stdout + +def solve(): + a,b = map(int, stdin.readline().split()) + if a==b==1: return "NO" + return "NO" if max(a,b)//2 == min(a,b) and min(a,b)%2==1 else "YES" + +t = int(input()) +for _ in range(t): + stdout.write(str(solve())+"\n") diff --git a/new_data/test/1928_B.jsonl b/new_data/test/1928_B.jsonl new file mode 100644 index 0000000..47227f9 --- /dev/null +++ b/new_data/test/1928_B.jsonl @@ -0,0 +1,21 @@ +{"input": "7\n2\n1 2\n4\n7 1 4 1\n3\n103 102 104\n5\n1 101 1 100 1\n5\n1 10 100 1000 1\n2\n3 1\n3\n1000000000 999999997 999999999", "output": "2\n2\n3\n2\n1\n1\n2"} +{"input": "1\n1\n1000000000", "output": "1"} +{"input": "1\n10\n1 2 3 4 5 6 7 8 9 10", "output": "10"} +{"input": "1\n5\n5 5 5 5 5", "output": "1"} +{"input": "1\n4\n10 10 10 20", "output": "1"} +{"input": "2\n6\n1 1 2 2 3 3\n4\n100000000 99999999 99999998 99999997", "output": "3\n4"} +{"input": "1\n8\n1000000 2000000 3000000 4000000 5000000 4000000 3000000 2000000", "output": "1"} +{"input": "1\n3\n999999999 999999999 999999999", "output": "1"} +{"input": "1\n7\n1 4 4 4 4 4 5", "output": "3"} +{"input": "3\n2\n1 3\n5\n2 2 2 2 3\n4\n4 4 1 1", "output": "1\n2\n2"} +{"input": "1\n6\n1 1 2 3 4 5", "output": "5"} +{"input": "1\n1\n1", "output": "1"} +{"input": "2\n1\n1000000000\n2\n1 1000000000", "output": "1\n1"} +{"input": "3\n2\n1 2\n2\n2 1\n2\n7 7", "output": "2\n2\n1"} +{"input": "2\n4\n1 1 1 1\n5\n2 2 2 2 2", "output": "1\n1"} +{"input": "2\n4\n7 1 4 1\n5\n1 101 1 100 1", "output": "2\n2"} +{"input": "2\n5\n1 10 100 1000 1\n2\n3 1", "output": "1\n1"} +{"input": "1\n3\n1000000000 999999997 999999999", "output": "2"} +{"input": "2\n5\n2 3 5 5 6\n5\n2 3 5 4 10", "output": "4\n4"} +{"input": "3\n5\n10 10 10 10 10\n4\n1000000000 999999999 999999998 999999997\n3\n2 4 6", "output": "1\n4\n2"} +{"input": "3\n3\n1 1 2\n3\n2 2 1\n3\n1 2 3", "output": "2\n2\n3"} diff --git a/new_data/test/1928_B.py b/new_data/test/1928_B.py new file mode 100644 index 0000000..c4f2de5 --- /dev/null +++ b/new_data/test/1928_B.py @@ -0,0 +1,16 @@ +for _ in range(int(input())): + N = int(input()) + L = list(map(int, input().split())); + L = list(set(L)) + L.sort() + n = len(L) + ans = 0 + for i in range(n): + j = i + 1 + while j < n: + if L[j] >= L[i] + N or N - j < ans: + break + j += 1 + ans = max(ans, j - i) + print(ans) + diff --git a/new_data/test/1928_B_1.py b/new_data/test/1928_B_1.py new file mode 100644 index 0000000..6e801ac --- /dev/null +++ b/new_data/test/1928_B_1.py @@ -0,0 +1,31 @@ +t=int(input()) +k=[] +for _ in range(t): + n=int(input()) + l=list(map(int,input().split())) + le=0 + ri=0 + ans=1 + pre=1 + l.sort() + # print(l) + while le+ans<=n and ri0 and check= x - 1: + M += [w] + for i in range(1, int(w // 1)): + if q % i == 0: + if i >= x - 1: + M += [i] + if (q // i) >= x - 1: + M += [q // i] + return M + + +t = int(input()) +for _ in range(t): + L = list(map(int, input().split())) + n = L[0] + x = L[1] + ans = 0 + y = (n + x) + if y % 2 != 0: + print(0) + continue + else: + L1 = factors((y - 2) // 2, x) + if n >= 3 * x - 2: + L1 += factors((n - x) // 2, x) + L1 = list(set(L1)) + print(len(L1)) + continue + + + + + + + + + diff --git a/new_data/test/1929_A.jsonl b/new_data/test/1929_A.jsonl new file mode 100644 index 0000000..8d81934 --- /dev/null +++ b/new_data/test/1929_A.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n3\n2 1 3\n3\n69 69 69\n5\n100 54 80 43 90\n4\n3 4 3 3\n2\n2 1", "output": "2\n0\n57\n1\n1"} +{"input": "1\n2\n5 5", "output": "0"} +{"input": "1\n3\n1 1000000000 500000000", "output": "999999999"} +{"input": "1\n3\n10 20 30", "output": "20"} +{"input": "1\n4\n4 1 3 2", "output": "3"} +{"input": "1\n5\n10 1 10 1 10", "output": "9"} +{"input": "2\n2\n1 2\n3\n9 7 8", "output": "1\n2"} +{"input": "1\n6\n6 6 6 6 6 6", "output": "0"} +{"input": "3\n5\n5 5 5 5 5\n4\n5 4 3 2\n3\n1 1 1000000000", "output": "0\n3\n999999999"} +{"input": "1\n10\n9 8 7 6 5 4 3 2 1 1000000000", "output": "999999999"} +{"input": "1\n2\n999999999 1", "output": "999999998"} diff --git a/new_data/test/1929_A.py b/new_data/test/1929_A.py new file mode 100644 index 0000000..1e385f7 --- /dev/null +++ b/new_data/test/1929_A.py @@ -0,0 +1,12 @@ +cases = int(input()) +for i in range(cases): + length = int(input()) + array = [int(n) for n in input().split()] + maxN = 0 + minN = 9999 + for i in array: + if i > maxN: + maxN = i + if i < minN: + minN = i + print(maxN-minN) \ No newline at end of file diff --git a/new_data/test/1929_A_1.py b/new_data/test/1929_A_1.py new file mode 100644 index 0000000..fe41e8e --- /dev/null +++ b/new_data/test/1929_A_1.py @@ -0,0 +1,12 @@ +cases = int(input()) +for i in range(cases): + length = int(input()) + array = [int(n) for n in input().split()] + maxN = 0 + minN = 99 + for i in array: + if i > maxN: + maxN = i + if i < minN: + minN = i + print(maxN-minN) \ No newline at end of file diff --git a/new_data/test/1930_A.jsonl b/new_data/test/1930_A.jsonl new file mode 100644 index 0000000..37a1d60 --- /dev/null +++ b/new_data/test/1930_A.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n1\n2 3\n2\n1 1 2 1\n3\n1 1 1 1 1 1", "output": "2\n2\n3"} +{"input": "1\n1\n1 10", "output": "1"} +{"input": "1\n2\n10 10 10 10", "output": "20"} +{"input": "2\n3\n7 2 3 8 5 1\n4\n3 3 3 3 3 3 3 3", "output": "11\n12"} +{"input": "1\n4\n1 2 3 4 5 6 7 8", "output": "16"} +{"input": "3\n1\n5 9\n2\n30 15 15 45\n2\n10000 3000 5000 7000", "output": "5\n45\n10000"} +{"input": "1\n5\n10000000 9000000 8000000 7000000 6000000 5000000 4000000 3000000 2000000 1000000", "output": "25000000"} +{"input": "2\n3\n10000000 100 1000 250 5000 1\n5\n2 3 4 1 1 4 3 2 5 4", "output": "5251\n14"} +{"input": "1\n6\n9 8 6 5 4 11 3 2 6 5 4 1", "output": "28"} +{"input": "3\n2\n1000000 1000000 999999 999999\n2\n1 1 1 1\n1\n3 3", "output": "1999999\n2\n3"} +{"input": "1\n7\n100000 99999 99998 2 1 2 1 99996 99995 99994 2 1 1 2", "output": "299995"} diff --git a/new_data/test/1930_A.py b/new_data/test/1930_A.py new file mode 100644 index 0000000..e8259a5 --- /dev/null +++ b/new_data/test/1930_A.py @@ -0,0 +1,7 @@ +t = int(input()) +for n in range(t): + n = int(input()) + arr = list(map(int, input().split())) + arr.sort() + score = sum(arr[0:n]) + print(score) \ No newline at end of file diff --git a/new_data/test/1930_A_1.py b/new_data/test/1930_A_1.py new file mode 100644 index 0000000..f325401 --- /dev/null +++ b/new_data/test/1930_A_1.py @@ -0,0 +1,21 @@ +# Envio realizado con IA para el LLM Feedback + +def max_min_pair_score(test_cases): + results = [] + for n, arr in test_cases: + arr.sort() + score = sum(arr[:n]) + results.append(score) + return results + +# Input reading +t = int(input()) +test_cases = [] +for _ in range(t): + n = int(input()) + arr = list(map(int, input().split())) + test_cases.append((n, arr)) + +# Compute and print results +for result in max_min_pair_score(test_cases): + print(result) diff --git a/new_data/test/1930_C.jsonl b/new_data/test/1930_C.jsonl new file mode 100644 index 0000000..ae28260 --- /dev/null +++ b/new_data/test/1930_C.jsonl @@ -0,0 +1,10 @@ +{"input": "1\n1\n10", "output": "11"} +{"input": "1\n5\n5 5 5 5 5", "output": "10 9 8 7 6"} +{"input": "1\n4\n1 2 3 4", "output": "8 6 4 2"} +{"input": "1\n3\n1000000000 1000000001 1000000002", "output": "1000000005 1000000003 1000000001"} +{"input": "2\n2\n1 2\n3\n9 3 7", "output": "4 2\n10 9 5"} +{"input": "3\n3\n4 5 6\n4\n10 20 30 40\n2\n50 100", "output": "9 7 5\n44 33 22 11\n102 51"} +{"input": "1\n10\n5 1 5 1 5 1 5 1 5 1", "output": "14 12 11 10 9 8 7 6 5 3"} +{"input": "1\n6\n3 6 3 6 3 6", "output": "12 10 8 7 6 4"} +{"input": "1\n4\n3 1 4 1", "output": "7 5 4 3"} +{"input": "2\n3\n6 9 12\n1\n15", "output": "15 11 7\n16"} diff --git a/new_data/test/1930_C.py b/new_data/test/1930_C.py new file mode 100644 index 0000000..ec4df9e --- /dev/null +++ b/new_data/test/1930_C.py @@ -0,0 +1,18 @@ +from collections import defaultdict + +t = int(input()) +for _ in range(t): + n = int(input()) + a = list(map(int, input().split())) + ans = [] + mp = defaultdict(int) + for i in range(n): + if a[i] + i + 1 in mp: + ans.append(a[i] + i + 1 - mp[a[i] + i + 1]) + mp[a[i] + i + 1 - mp[a[i] + i + 1]] += 1 + else: + ans.append(a[i] + i + 1) + mp[a[i] + i + 1] += 1 + + ans.sort(reverse=1) + print(*ans) diff --git a/new_data/test/1930_C_1.py b/new_data/test/1930_C_1.py new file mode 100644 index 0000000..4de7934 --- /dev/null +++ b/new_data/test/1930_C_1.py @@ -0,0 +1,37 @@ +def li(): return [int(i) for i in input().split()] + + +from collections import defaultdict +from heapq import heapify, heappop, heappush + +for x in range(int(input())): + n, = li() + a = li() + ans = []; + l = sorted([(a[i] + 1 + i, a[i]) for i in range(n)]) + be = l[-1][0] + 1 + l = [(0, 0)] + l + h = []; + heapify(h) + # print(l) + for e in l[::-1]: + e, i = e + i = e - i + if e == be: + heappush(h, -a[i - 1] - 1) + else: + d = be - e - 1 + # print("heap ",h) + for i in range(1, d + 1): + if not h: break + v = be - i + while h: + q = abs(heappop(h)) + if q <= v: ans += [v];break + ans += [e] + be = e + ans.sort(reverse=1) + ans.pop() + print(*ans) + + diff --git a/new_data/test/1931_A.jsonl b/new_data/test/1931_A.jsonl new file mode 100644 index 0000000..7acabb8 --- /dev/null +++ b/new_data/test/1931_A.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n24\n70\n3\n55\n48", "output": "aav\nrzz\naaa\nczz\nauz"} +{"input": "1\n3", "output": "aaa"} +{"input": "1\n4", "output": "aab"} +{"input": "1\n5", "output": "aac"} +{"input": "1\n6", "output": "aad"} +{"input": "1\n30", "output": "acz"} +{"input": "1\n52", "output": "ayz"} +{"input": "1\n78", "output": "zzz"} +{"input": "1\n16", "output": "aan"} +{"input": "1\n27", "output": "aay"} +{"input": "1\n19", "output": "aaq"} diff --git a/new_data/test/1931_A.py b/new_data/test/1931_A.py new file mode 100644 index 0000000..a52b809 --- /dev/null +++ b/new_data/test/1931_A.py @@ -0,0 +1,21 @@ +test_cases = int(input()) + +for _ in range(test_cases): + + v = int(input()) + + q = v // 26 + r = v % 26 + + a = "" + for _ in range(3 - q): + a += chr(97) + r -= 1 + + if r > 0: + a = a[:-1] + chr(97 + r) + + if q > 0: + a += 'z' * q + + print(a) \ No newline at end of file diff --git a/new_data/test/1931_A_1.py b/new_data/test/1931_A_1.py new file mode 100644 index 0000000..fe32f99 --- /dev/null +++ b/new_data/test/1931_A_1.py @@ -0,0 +1,16 @@ +n = int(input()) +b=[] +for i in range(n): + x = int(input()) + b.append(x) +'''b = list(map(int, input().split("\n")))''' +a = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] +for i in range(n): + if(b[i]<=26): + print(a[0],a[0],a[b[i]-3],sep="") + elif(b[i]<=52): + print(a[0],a[b[i]-28],a[25],sep="") + elif(b[i]<=78): + print(a[b[i]-53],a[25],a[25],sep="") + else: + print(" ") \ No newline at end of file diff --git a/new_data/test/1931_D.jsonl b/new_data/test/1931_D.jsonl new file mode 100644 index 0000000..ccf0f86 --- /dev/null +++ b/new_data/test/1931_D.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n6 5 2\n1 2 7 4 9 6\n7 9 5\n1 10 15 3 8 12 15\n9 4 10\n14 10 2 2 11 11 13 5 6\n9 5 6\n10 7 6 7 9 7 7 10 10\n9 6 2\n4 9 7 1 2 2 13 3 15\n9 2 3\n14 6 1 15 12 15 8 2 15\n10 5 7\n13 3 3 2 12 11 3 7 13 14", "output": "2\n0\n1\n3\n5\n7\n0"} +{"input": "1\n2 15 10\n30 45", "output": "0"} +{"input": "1\n5 10 5\n7 12 17 22 27", "output": "0"} +{"input": "1\n4 1000000000 1\n1000000000 999999999 2 2", "output": "0"} +{"input": "1\n3 3 3\n1 2 4", "output": "0"} +{"input": "1\n6 10 10\n20 30 30 40 50 60", "output": "15"} +{"input": "1\n7 16 8\n10 26 18 34 26 14 42", "output": "0"} +{"input": "1\n4 8 4\n16 24 20 12", "output": "2"} +{"input": "1\n9 2 1000000000\n1 999999999 999999998 999999997 999999996 999999995 999999994 999999993 999999992", "output": "0"} +{"input": "1\n5 25 25\n50 75 100 125 150", "output": "10"} +{"input": "1\n8 6 2\n10 16 4 22 8 14 20 26", "output": "16"} diff --git a/new_data/test/1931_D.py b/new_data/test/1931_D.py new file mode 100644 index 0000000..1b330fa --- /dev/null +++ b/new_data/test/1931_D.py @@ -0,0 +1,42 @@ +from collections import defaultdict + + +def helper(n, x, y, arr): + hash = defaultdict(list) + ans = 0 + pairs = set() + for i in range(0, n): + ele = arr[i] % x + if ele in hash: + for index in hash[ele]: + # print(i, index) + pairs.add(str(i) + str(index)) + hash[(x - ele) % x].append(i) + + hash = defaultdict(list) + # print(pairs) + + for i in range(0, n): + ele = arr[i] % y + if ele in hash: + for index in hash[ele]: + # print(i, index) + if str(i) + str(index) in pairs: + ans += 1 + hash[(y + ele) % y].append(i) + + return ans + + +# n = 9 +# x = 5 +# y = 6 +# arr = [10 ,7 ,6 ,7 ,9 ,7 ,7 ,10 ,10] +# print('ans = ', helper(n,x, y, arr)) + + +T = int(input()) +for t in range(0, T): + n, x, y = map(int, input().split()) + arr = list(map(int, input().split())) + print(helper(n, x, y, arr)) diff --git a/new_data/test/1931_D_1.py b/new_data/test/1931_D_1.py new file mode 100644 index 0000000..7d3116a --- /dev/null +++ b/new_data/test/1931_D_1.py @@ -0,0 +1,20 @@ +from collections import defaultdict + +t = int(input()) +for k in range(t): + n, x, y = list(map(int, input().split())) + arr = list(map(int, input().split())) + + D = defaultdict(int) + answer = 0 + + for i in range(n): + xx = (x - arr[i] % x) % x + yy = arr[i] % y + hg = xx * (1e9 + 7) + yy + hp = arr[i] % x * (1e9 + 7) + arr[i] % y + + answer += D[hg] + D[hp] += 1 + + print(answer) \ No newline at end of file diff --git a/new_data/test/1931_E.jsonl b/new_data/test/1931_E.jsonl new file mode 100644 index 0000000..638baa6 --- /dev/null +++ b/new_data/test/1931_E.jsonl @@ -0,0 +1,11 @@ +{"input": "9\n2 2\n14 2\n3 5\n9 56 1\n4 10\n1 2007 800 1580\n4 5\n5000 123 30 4\n10 10\n6 4 6 2 3 1 10 9 10 7\n1 1\n6\n1 1\n10\n8 9\n1 2 9 10 10 2 10 2\n4 5\n10 10 10 10", "output": "Sasha\nAnna\nAnna\nSasha\nSasha\nAnna\nAnna\nAnna\nSasha"} +{"input": "1\n1 0\n7", "output": "Sasha"} +{"input": "1\n2 1\n10 1", "output": "Sasha"} +{"input": "2\n3 2\n2 2 2\n3 2\n22 202 200", "output": "Sasha\nSasha"} +{"input": "1\n3 5\n9 56 1", "output": "Anna"} +{"input": "1\n4 10\n1 2007 800 1580", "output": "Anna"} +{"input": "1\n4 5\n5000 123 30 4", "output": "Sasha"} +{"input": "9\n2 2\n14 2\n3 5\n9 56 1\n4 10\n1 2007 800 1580\n4 5\n5000 123 30 4\n10 10\n6 4 6 2 3 1 10 9 10 7\n1 1\n6\n1 1\n10\n8 9\n1 2 9 10 10 2 10 2\n4 5\n10 10 10 10", "output": "Sasha\nAnna\nAnna\nSasha\nSasha\nAnna\nAnna\nAnna\nSasha"} +{"input": "1\n10 0\n1 2 3 4 5 6 7 8 9 9", "output": "Sasha"} +{"input": "1\n5 6\n100 10 1000000000 999999999 12", "output": "Sasha"} +{"input": "2\n5 1\n10 101 110 909 90\n4 20\n999999999 1 99 1000000000", "output": "Sasha\nAnna"} diff --git a/new_data/test/1931_E.py b/new_data/test/1931_E.py new file mode 100644 index 0000000..53275b3 --- /dev/null +++ b/new_data/test/1931_E.py @@ -0,0 +1,53 @@ +import math +from collections import defaultdict + + +def find_trailing_zeros(n): + count = 0 + while n and not n % 10: + count += 1 + n //= 10 + return count + + +def func(b, a): + n, m = b + + tot_digs = 0 + + t_zeros = [0 for i in range(10)] + + for i in a: + tot_digs += int(math.log(i, 10)) + 1 + t_zeros[find_trailing_zeros(i)] += 1 + + # print(tot_digs) + # print(t_zeros) + + f = 1 + + for i in range(9, 0, -1): + if t_zeros[i] <= 0: + continue + if f == 1: + tot_digs -= (math.ceil(t_zeros[i] / 2) * i) + if t_zeros[i] % 2 == 1: + f = f * (-1) + else: + tot_digs -= (math.floor(t_zeros[i] / 2) * i) + if t_zeros[i] % 2 == 1: + f = f * (-1) + + # print(tot_digs,m) + + if tot_digs >= (m + 1): + return ("Sasha") + else: + return ("Anna") + + +q = int(input()) +for i in range(q): + a = list(map(int, input().split())) + b = list(map(int, input().split())) + print(func(a, b)) \ No newline at end of file diff --git a/new_data/test/1931_E_1.py b/new_data/test/1931_E_1.py new file mode 100644 index 0000000..add411e --- /dev/null +++ b/new_data/test/1931_E_1.py @@ -0,0 +1,24 @@ +import math +t = int(input()) +for i in range (0, t): + listvar = input().split() + m = int(listvar[1]) + list = input().split() + nums = [] + for k in list: + nums.append(int(k)) + logs = [] + for k in nums: + logs.append(int(math.log(k, 10) + 1)) + sl = sum(logs) + for i in range (0, len(nums)): + while (nums[i] % 10 == 0): + nums[i] = int(nums[i] / 10) + nums[i] = logs[i] - (math.floor(math.log(nums[i], 10)) + 1) + nums.sort(reverse = True) + sumdel = 0 + for i in range (0, len(nums)): + if i % 2 == 0: + sumdel += nums[i] + if sl - sumdel > m: print("Sasha") + else: print("Anna") \ No newline at end of file diff --git a/new_data/test/1931_F.jsonl b/new_data/test/1931_F.jsonl new file mode 100644 index 0000000..b57c8d0 --- /dev/null +++ b/new_data/test/1931_F.jsonl @@ -0,0 +1,11 @@ +{"input": "10\n5 1\n1 2 3 4 5\n4 4\n1 2 3 4\n2 3 1 4\n3 2 1 4\n4 2 3 1\n6 2\n1 3 5 2 4 6\n6 3 5 2 1 4\n3 3\n1 2 3\n2 3 1\n3 2 1\n10 2\n1 2 3 4 5 6 7 8 9 10\n10 9 8 7 6 5 4 3 2 1\n1 1\n1\n5 2\n1 2 3 5 4\n2 1 3 5 4\n3 3\n3 1 2\n2 3 1\n1 3 2\n5 4\n3 5 1 4 2\n2 5 1 4 3\n1 5 4 3 2\n5 1 4 3 2\n3 3\n1 3 2\n2 1 3\n3 2 1", "output": "YES\nYES\nYES\nYES\nNO\nYES\nYES\nYES\nYES\nNO"} +{"input": "1\n2 2\n1 2\n2 1", "output": "yes"} +{"input": "2\n3 2\n1 2 3\n2 3 1\n3 2\n1 3 2\n2 1 3", "output": "yes\nyes"} +{"input": "1\n4 4\n1 2 3 4\n2 3 4 1\n3 4 1 2\n4 1 2 3", "output": "no"} +{"input": "1\n5 2\n1 5 2 3 4\n5 1 4 3 2", "output": "no"} +{"input": "1\n6 3\n1 4 3 2 5 6\n3 5 6 1 2 4\n2 6 5 4 3 1", "output": "no"} +{"input": "1\n7 1\n7 1 2 3 4 5 6", "output": "yes"} +{"input": "1\n9 3\n1 3 2 4 5 6 7 8 9\n3 2 1 4 5 6 7 8 9\n9 3 2 1 5 6 7 8 4", "output": "no"} +{"input": "1\n8 4\n1 2 3 4 5 6 7 8\n2 3 4 5 6 7 8 1\n3 4 5 6 7 8 1 2\n8 7 6 5 4 3 2 1", "output": "no"} +{"input": "1\n10 5\n1 10 2 3 4 5 6 7 8 9\n2 1 10 3 4 5 6 7 8 9\n3 2 1 10 4 5 6 7 8 9\n4 3 2 1 10 5 6 7 8 9\n10 9 8 7 6 5 4 3 2 1", "output": "no"} +{"input": "1\n4 3\n1 2 3 4\n3 1 2 4\n4 3 2 1", "output": "no"} diff --git a/new_data/test/1931_F.py b/new_data/test/1931_F.py new file mode 100644 index 0000000..4aa4af7 --- /dev/null +++ b/new_data/test/1931_F.py @@ -0,0 +1,83 @@ +times = int(input()) +first = None +for i in range(times): + num, times2 = input().split(" ") + num = int(num) + times2 = int(times2) + chains = [] + if first == None: + first = num + for i in range(times2): + chains.append(input().split(" ")) + if i == 2207 and num == 5 and times == 10000: + print("YES") + print("chains") + if times2 <= 1: + print("YES") + elif times2 == 2: + first = chains[0][1:] + second = chains[1][1:] + first.remove(chains[1][0]) + second.remove(chains[0][0]) + if first == second: + print("YES") + else: + print("NO") + else: + first = chains[0][1:] + second = chains[1][1:] + third = chains[2][1:] + output = [] + while first != [] and second != [] and third != []: + if first[0] == second[0] and second[0] == third[0]: + output.append(first[0]) + del first[0] + del second[0] + del third[0] + elif first[0] == second[0]: + output.append(second[0]) + del second[0] + del first[0] + elif first[0] == third[0]: + output.append(first[0]) + del first[0] + del third[0] + elif second[0] == third[0]: + output.append(second[0]) + del second[0] + del third[0] + else: + output = ["1", "1"] + first = [] + second = [] + third = [] + if first == second: + first = [] + elif second == third: + second = [] + elif first == third: + first = [] + output += first + second + third + if len(output) != len(set(output)): + print("NO") + else: + flag = True + for chain in chains: + skip = False + j = 0 + for i in range(1, len(chain)): + if chain[i] != output[j] and not skip: + j += 1 + if chain[i] != output[j]: + print("NO") + flag = False + break + else: + skip = True + elif chain[i] != output[j]: + print("NO") + flag = False + break + j += 1 + if flag: + print("YES") \ No newline at end of file diff --git a/new_data/test/1931_F_1.py b/new_data/test/1931_F_1.py new file mode 100644 index 0000000..e0dc5c2 --- /dev/null +++ b/new_data/test/1931_F_1.py @@ -0,0 +1,60 @@ +import sys + +input = sys.stdin.readline + + +class Graph: + def __init__(self, n): + self.adj_list = {i: [] for i in range(1, n + 1)} + + def add_edge(self, u, v): + self.adj_list[u].append(v) + + def is_cyclic_util(self, v, visited, rec_stack): + visited.add(v) + rec_stack.add(v) + + for neighbour in self.adj_list[v]: + if neighbour not in visited: + if self.is_cyclic_util(neighbour, visited, rec_stack): + return True + elif neighbour in rec_stack: + return True + + rec_stack.remove(v) + return False + + def is_cyclic(self, n): + visited = set() + rec_stack = set() + + for vertex in self.adj_list: + if vertex not in visited: + if self.is_cyclic_util(vertex, visited, rec_stack): + return True + + return False + + +T = int(input()) + +for _ in range(T): + n, k = list(map(lambda a: int(a), input().split(" "))) + graph = Graph(n) + if n == 4239: + print("here1") + break + for _ in range(k): + line = list(map(lambda a: int(a), input().split(" ")))[1:] + for j in range(len(line) - 1): + edge = (line[j], line[j + 1]) + graph.add_edge(*edge) + + if n == 4239: + print("here2") + + sys.setrecursionlimit(10000000) + if graph.is_cyclic(n): + print("NO") + else: + print("YES") diff --git a/new_data/test/1932_A.jsonl b/new_data/test/1932_A.jsonl new file mode 100644 index 0000000..b292efd --- /dev/null +++ b/new_data/test/1932_A.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n10\n.@@*@.**@@\n5\n.@@@@\n15\n.@@..@***..@@@*", "output": "3\n4\n3"} +{"input": "1\n1\n.", "output": "0"} +{"input": "2\n2\n.@\n2\n..", "output": "1\n0"} +{"input": "2\n3\n.*@\n4\n.@*.", "output": "1\n1"} +{"input": "3\n5\n.@@@*\n5\n.****\n5\n.@*@.", "output": "3\n0\n2"} +{"input": "3\n6\n.@@.*.\n6\n.**@*@\n6\n.@.@@.", "output": "2\n0\n3"} +{"input": "2\n10\n.@@*@.**@@\n5\n.*@@*", "output": "3\n2"} +{"input": "3\n8\n.******@\n8\n.@****@.\n8\n......@.", "output": "0\n1\n1"} +{"input": "3\n7\n.@..@..\n7\n.****@.\n7\n.@@@*@@", "output": "2\n0\n5"} +{"input": "1\n15\n.@@..@***..@@@*", "output": "3"} +{"input": "4\n9\n.@*@*@@.*\n9\n.**.**.**\n6\n.****.\n10\n.@.@.*.@@.", "output": "4\n0\n0\n4"} diff --git a/new_data/test/1932_A.py b/new_data/test/1932_A.py new file mode 100644 index 0000000..449c2ca --- /dev/null +++ b/new_data/test/1932_A.py @@ -0,0 +1,21 @@ +t = int(input()) +while not(1<=t<=1000): + t = int(input()) +resualt ="" +for i in range(t): + coins=0 + n = int(input()) + while not(1<=n<=50): + n = int(input()) + path = input() + while not(len(path)==n): + path = input() + p = path.find("**") + if p!=-1: + path=path[0:p] + for i in range(len(path)): + if path[i]=="@": + coins+=1 + resualt += str(coins) +for i in range(len(resualt)): + print(resualt[i]) diff --git a/new_data/test/1932_A_1.py b/new_data/test/1932_A_1.py new file mode 100644 index 0000000..d1d4e57 --- /dev/null +++ b/new_data/test/1932_A_1.py @@ -0,0 +1,44 @@ +t = int(input()) +for tc in range(t): + n = int(input()) + p =str(input()) + a =[] + b=[] + c=[] + l=[] + s=[] + for i in range(n): + l.append(i) + for i in range(len(p)): + if(p[i]=='@'): + a.append(i) + if(p[i]=='.'): + b.append(i) + if(p[i]=='*'): + c.append(i) + # print(a) + # print(b) + # print(c) + for i in l: + if i not in a: + s.append(i) + # print(s) + # e = set(s) + # f= set(b) + o = set(s).intersection(b) + y = set(s)-o + f=list(y) + # print(list(y)) + k=0 + # print(f) + for i in range(len(f)-1): + if(f[i]==f[i+1]-1): + k=f[i] + break + v=0 + for i in a: + if(il[h-1]): + l[h]=j*t + break + print(l[k-1]) \ No newline at end of file diff --git a/new_data/test/1932_B_1.py b/new_data/test/1932_B_1.py new file mode 100644 index 0000000..d50e409 --- /dev/null +++ b/new_data/test/1932_B_1.py @@ -0,0 +1,15 @@ +def ye(n,li): + year = [0]*n + for idx,value in enumerate(li): + for j in range(1,1000): + if year[idx-1] < value *j: + year[idx]= value *j + break + + return year[-1] +t = int(input()) + +for _ in range(t): + n = int(input()) + a_list = list(map(int,input().split())) + print(ye(n,a_list)) diff --git a/new_data/test/1937_A.jsonl b/new_data/test/1937_A.jsonl new file mode 100644 index 0000000..d446b45 --- /dev/null +++ b/new_data/test/1937_A.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n1\n4\n5\n120240229", "output": "1\n4\n4\n67108864"} +{"input": "1\n1", "output": "1"} +{"input": "3\n2\n3\n4", "output": "2\n2\n4"} +{"input": "2\n7\n8", "output": "4\n8"} +{"input": "2\n15\n20", "output": "8\n16"} +{"input": "1\n16", "output": "16"} +{"input": "1\n30", "output": "16"} +{"input": "1\n50", "output": "32"} +{"input": "5\n63\n64\n65\n66\n67", "output": "32\n64\n64\n64\n64"} +{"input": "2\n998244353\n1000000000", "output": "536870912\n536870912"} +{"input": "1\n500000003", "output": "268435456"} diff --git a/new_data/test/1937_A.py b/new_data/test/1937_A.py new file mode 100644 index 0000000..70ae498 --- /dev/null +++ b/new_data/test/1937_A.py @@ -0,0 +1,10 @@ +t = int(input()) +ans = 2 +for i in range(t): + n = int(input()) + if n < 2: + ans = 1 + else: + while ans * 2 <= n: + ans *= 2 + print(ans) \ No newline at end of file diff --git a/new_data/test/1937_A_1.py b/new_data/test/1937_A_1.py new file mode 100644 index 0000000..b318297 --- /dev/null +++ b/new_data/test/1937_A_1.py @@ -0,0 +1,1425 @@ +t = int(input()) +ans = 2 +for i in range(t): + n = int(input()) + if n < 2: + ans = 1 + else: + while ans * 2 <= n: + ans *= 2 + print(ans) + +# t = int(input()) +# for i in range(t): +# n, m, k = map(int, input().split()) +# b = list(map(int, input().split())) +# c = list(map(int, input().split())) +# lst = [] +# for f in range(n): +# for s in range(m): +# if b[f] + c[s] <= k: +# lst.append([f, s]) +# print(len(lst)) + +# from math import gcd +# a, b, c, d = map(int, input().split() ) +# Sx = abs(c - a) +# Sy = abs(d - b) +# print(Sx + Sy - gcd(Sx, Sy)) + +# from math import gcd +# a, b = map(int, input().split()) +# print(a // gcd(a, b), b // gcd(a, b)) + +# from math import gcd +# a, b = map(int, input().split()) +# print((a*b) // gcd(a, b)) + +# t = int(input()) +# for i in range(t): +# n = int(input()) +# a = list(map(int, input().split())) +# s = 0 +# for i in range(n): +# s += abs(a[i]) +# print(s) + + +# 27 +# Дана последовательность целых чисел. Необходимо найти максимально возможную сумму её непрерывной подпоследовательности, в которой количество положительных нечётных элементов кратно k  =  30. + +# A = open('27-B (11).txt') +# k = 30 +# n = int(A.readline()) +# data = [int(x) for x in A] +# maxSum = 0 +# prefix = [0] +# count = 0 +# d = [0] * k +# for i in range(n): +# prefix.append(prefix[-1] + data[i]) +# if data[i] > 0 and data[i] % 2 != 0: +# count += 1 +# maxSum = max(maxSum, prefix[i+1] - d[count % k]) +# d[count % k] = min(d[count % k], prefix[i+1]) +# print(maxSum) + + +# A = open('27-B.txt') +# k = 30 +# n = int(A.readline()) +# a = [int(x) for x in A] +# maxSumA = 0 +# t = 0 +# while t <= n-1: +# countA = 0 +# sumA = 0 +# for i in range(t, len(a)): +# sumA += a[i] +# if a[i] > 0 and a[i] % 2 != 0: +# countA += 1 +# if countA % k == 0: +# maxSumA = max(maxSumA, sumA) +# t += 1 + +# print(maxSumA) + + +# f = open('26 (1).txt') +# n, m = map(int, f.readline().split()) +# a = [int(i) for i in f] +# count = 0 +# s = 0 +# b = [] +# for i in range(len(a)): +# if 210 <= a[i] <= 220: +# count += 1 +# s += a[i] +# else: +# b.append(a[i]) +# b = sorted(b) +# i = 0 +# while i < len(b) and s + b[i] <= m: +# s += b[i] +# i += 1 +# count += 1 +# print(count) +# i -= 1 +# print(b[i-2], b[i]) +# while i + 1 < len(b) and s - b[i] + b[i + 1] <= m: +# s = s - b[i] + b[i + 1] +# i += 1 +# print(b[i], s) + + +# for i in range(int(289_123_456 ** 0.25), int(389_123_456 ** 0.25)): +# for j in range(2, i): +# if not i % j: # Проверка на простое число +# break +# else: +# print(i ** 4, i ** 3) + + +# 25 +# count = 0 +# ans = [] +# maxDiv = 0 +# start = int(289123456**0.5) + 1 +# finish = int(389123456**0.5) + 1 +# for i in range(start, finish): +# divs = [] +# for j in range(2, i + 1): +# if (i**2) % j == 0: +# divs.append(j) +# # print('OK') +# if j != (i**2) // j: +# divs.append((i**2) // j) +# if len(divs) == 3: +# # print('OK') +# ans.append([i**2, max(divs)]) +# print(sorted(ans)) + + +# 24 +# f = open('24 (1).txt') +# a = f.readline() +# count = 0 +# max_count = 0 +# i = 0 +# while i < len(a)-2: +# if a[i] in 'CDF' and a[i+1] in 'CDF' and a[i+2] in 'AO': +# count += 1 +# max_count = max(max_count, count) +# i += 3 +# else: +# i += 1 +# count = 0 +# print(max_count) + + +# CCADDO + +# f = open('17 (1).txt') +# a = [int(x) for x in f] +# pairs = 0 +# minN3 = 100000 +# maxSum = 0 +# for i in range(len(a)): +# if 99 < a[i] < 1000 and a[i] % 10 == 3: +# minN3 = min(minN3, a[i]) +# for i in range(len(a)-1): +# if (999 < a[i] < 10000 and (a[i+1] < 1000 or a[i+1] > 9999)) or (999 < a[i+1] < 10000 and (a[i] < 1000 or a[i] > 9999)): +# if (a[i]**2 + a[i+1]**2) % minN3 == 0: +# pairs += 1 +# maxSum = max(maxSum, a[i]**2 + a[i+1]**2) + +# print(pairs, maxSum) + +# def F(n): +# if n <= 3: +# if n == 1: +# return 0 +# elif n == 2: +# return 1 +# elif n == 3: +# return 1 +# else: +# return F(n-3) + F(n-2) + F(n-1) +# print(F(11)) + + +# lett = 'ВЛТУ' +# a = ['' for i in range(76)] +# a[0] = '' +# a[1] = 'ВВВВ' +# for i in range(2, 76): +# for j in lett: +# a.append(a[i][1:] + j) +# print(a[75]) + +# from turtle import * +# scale = 20 +# c = 3 +# while c > 0: +# c -= 1 +# forward(7 * scale) +# right(90) +# forward(8 * scale) +# c = 3 +# while c > 0: +# c -= 1 +# left(90) +# forward(5 * scale) +# penup() +# for x in range(-200,200, scale): +# for y in range(-200,200, scale): +# setposition(x,y) +# dot(5, 'red') +# done() + +# ((y → x) ≡ (x → w)) ∧ (z ∨ x) +# print('x y z w F') +# for x in range(2): +# for y in range(2): +# for z in range(2): +# for w in range(2): +# F = ((y <= x) == (x <= w)) and (z or x) +# print(x, y, z, w, int(F)) + +# n = int(input()) +# arr = [] +# ans = [] +# for i in range(n): +# arr.append(list(map(int, input().split()))) +# for i in range(n // 2 + 1): +# ans.append(arr[i][n // 2 + i]) +# for i in range(n // 2 + 1, n): +# ans.append(arr[i][]) + +# print(*ans) + +# import string +# a, b = input().split() +# d1 = dict().fromkeys(string.ascii_lowercase, 0) +# d2 = dict().fromkeys(string.ascii_lowercase, 0) +# for i in a: +# d1[i] += 1 +# for i in b: +# d2[i] += 1 +# ans = 0 +# for letter in string.ascii_lowercase: +# ans += max(0, d2[letter] - d1[letter]) +# print(ans) + +# n, c1, c2 = map(int, input().split()) +# maxN = 0 +# ans = 0 +# for i in range(c1, c2 + 1): +# t = n +# ost = '' +# while t > 0: +# ost += str(t % i) +# if t % i >= maxN: +# maxN = t % i +# ans = i +# # maxN = max(maxN, t % i) +# t = t // i +# print(ans) + + +# from math import gcd +# a, b = map(int, input().split()) +# if gcd(a,b) == 1: +# print("YES") +# else: +# for i in range(2, min(a, b) + 1): +# if a % i == 0 and b % i == 0: +# print(i) +# break + +# def f(n): +# binN = str(bin(n)) +# even = int(binN.count('0')) +# odd = int(binN.count('1')) +# if even > odd: +# binN += '1' +# elif even < odd: +# binN += '0' +# elif even == odd: +# if n % 2 == 0: +# binN += '0' +# else: +# binN += '1' +# return binN + +# for n in range(876544, 1234567900): +# r = int(f(f(f(n)))) + + +# F1  =  (x∨¬y)≡(z→w) +# F2  =  (¬x≡y)∧(z→w) + +# print('x y z w F1 F2') +# for x in range(0, 2): +# for y in range(0, 2): +# for z in range(0, 2): +# for w in range(0, 2): +# F1 = (x or (not y)) == (z <= w) +# F2 = (not x == y) and (z <= w) +# print(x, y, z, w, int(F1), int(F2)) + + +# t = int(input()) +# for i in range(t): +# mx = 0 +# c = 0 +# n, k = map(int, input().split()) +# s = input() +# r, l = 0, 0 +# while r < n - 1: +# while r < n-1 and c <= k: +# mx = max(mx, r - l + 1) +# if s[r] != s[r+1]: +# c += 1 +# r += 1 +# if c > k: +# while l < n-1 and s[l] == s[l+1]: +# l += 1 +# if s[l] != s[l+1]: +# c -= 1 +# l += 1 +# print(mx) + + +# t = int(input()) +# for i in range(t): +# ans = '' +# n, m = map(int, input().split()) +# a = list(map(int, input().split())) +# b = list(map(int, input().split())) +# min1 = n +# min2 = m +# max1 = sum(a) +# max2 = sum(b) +# if max1 > min2: +# ans += 'Y' +# else: +# ans += 'N' +# if min(max1,max2) >= max(min1,min2): +# ans += 'Y' +# else: +# ans += 'N' +# if max2 > min1: +# ans += 'Y' +# else: +# ans += 'N' +# print(ans) + + +# f = open('17.txt') +# a = [int(x) for x in f] +# lst = [] +# k = 0 +# minEl = 10001 +# for i in a: +# if i % 10 == (i // 10) % 10: +# minEl = min(i, minEl) +# for i in range(len(a)-1): +# if abs(a[i] % 10) == abs((a[i+1] // 10) % 10) or abs(a[i+1] % 10) == abs((a[i] // 10) % 10): +# if (a[i] % 7 == 0 and a[i+1] % 7 != 0) or (a[i+1] % 7 == 0 and a[i] % 7 != 0): +# if a[i]**2 + a[i+1]**2 <= minEl**2: +# k += 1 +# lst.append(a[i]**2 + a[i+1]**2) +# print(k, max(lst)) + + +# def F(n): +# if n < 9: +# return n +# return F(n % 9) + F(n // 9) +# k = 0 +# for n in range(4*(6**20), 5*(6**20) + 1): +# if F(n) == 121: +# k += 1 +# print(k) + +# for a in range(1, 300): +# flag = True +# for x in range(1, 300): +# if not((x % a == 0) or (x % 21 != 0 and x % 35 != 0)): +# flag = False +# break +# if flag: +# print(a) + + +# n = 4 ** 34 + 5 * 4**22 + 4**13 + 2 * 4**9 + 82 +# s = '' +# while n > 0: +# s += str(n % 16) +# n //= 16 +# s = s[::-1] +# print(s) + +# s = '1' + '9' * 100 + +# while '19' in s or '299' in s or '3999' in s: +# if '19' in s: +# s = s.replace('19', '2', 1) +# if '299' in s: +# s = s.replace('299', '3', 1) +# if '3999' in s: +# s = s.replace('3999', '1', 1) +# print(s) + + +# print('x', 'y', 'z', 'w') +# for x in range(0, 2): +# for y in range(0, 2): +# for z in range(0, 2): +# for w in range(0, 2): +# if not((z and y) or ((not(x) or z) == (not(y) or w))): +# print(x, y, z, w) + + +# with open('28133_B (1).txt') as f: +# N = int(f.readline()) +# data = [int(x) for x in f] +# ans = 0 +# first = 0 +# second = 0 +# for i in range(N): +# for j in range(i+1, N): +# if data[i] > data[j] and (data[i] + data[j]) % 120 == 0: +# # ans = max(ans, data[i] + data[j]) +# if data[i] + data[j] > ans: +# ans = data[i] + data[j] +# first = data[i] +# second = data[j] +# print(first, second) + + +# 26 +# f = open('26.txt') +# S,N = map(int, f.readline().split()) +# arr = [int(i) for i in f] +# i = 0 +# arr.sort() +# while i < len(arr) and S - arr[i] >= 0: +# S -= arr[i] +# i += 1 +# print(i) +# while i < len(arr) and S + arr[i - 1] - arr[i] >= 0: +# S = S + arr[i - 1] - arr[i] +# i += 1 +# print(arr[i-1]) + + +# 25 + +# ans = [] +# for num in range(45000000, 50000001): +# d = [] +# for i in range(1, int(num**0.5) + 1): +# if num % i == 0: +# d.append(i) +# if (num // i) % 2 != 0 and num // i != i: +# d.append(num // i) +# if len(d) == 5: +# ans.append(num) +# print(*ans) + + +# num = 132103049840 +# d = [] +# for i in range(2, int(num ** 0.5) + 1): +# if num % i == 0: +# if i % 2 == 1: +# if i == 8: +# print(i, i % 2, 'a') +# d.append(i) +# if (num // i) % 2 != 0 and num // i != i: +# d.append(num // i) +# print(d) + +# 24 +# f = open('24.txt') +# s = f.readline() +# count = 0 +# arr = [] +# minn = 10**6 +# for i in range(len(s)): +# if s[i] == 'W': +# arr.append(i) +# for j in range(len(arr) - 129): +# count = arr[j+129] - arr[j] + 1 +# if count < minn: +# minn = count +# print(minn) + +# def check(n): +# l = [0] * 10 +# while n > 0: +# digit = n % 10 +# l[digit] += 1 +# n //= 10 +# c = 0 +# for elem in l: +# if elem != 0: +# c += 1 +# if c < 3: +# return True +# return False +# mn = 10**9 +# ans = 0 +# for i in range(1999, 2030): +# if check(i): +# if abs(i - 2012) < mn: +# mn = abs(i - 2012) +# ans = i +# print(ans) + +# t = int(input()) +# for i in range(t): +# p = 1 +# n = int(input()) +# num = list(map(int, input().split())) +# for j in num: +# p *= j +# if p > 0: +# print(1) +# print(1, 0) +# else: +# print(0) + + +# 17 +# f = open("17.txt") +# a = [int(i) for i in f] +# count, maxsum = 0, 0 +# for i in range(9999): +# for j in range(i+1, 10000): +# if (a[i] + a[j]) % 10 == 0: +# count += 1 +# maxsum = max(maxsum, a[i] + a[j]) +# print(count, maxsum) +# Ответ:4999742 19990 + +# 16 +# def F(n): +# if n <= 2: +# return n + 1 +# if n > 2: +# return 2*F(n - 1) + F(n - 2) +# print(F(4)) + +# for n in range(1000): +# s = '5' + n * '2' +# sumd = 0 +# while '72' in s or '522' in s or '2222' in s: +# if '72' in s: +# s = s.replace('72', '2', 1) +# if '522' in s: +# s = s.replace('522', '27', 1) +# if '2222' in s: +# s = s.replace('2222', '5', 1) +# for digid in s: +# sumd += int(digid) +# if sumd == 63: +# print(n) +# break + + +# f = open('n9.txt') +# ans = 0 +# for line in f: +# a = list(map(int, line.split())) +# b = set(a) +# num = sum(a) - sum(b) +# if len(b) == 5 and num < (sum(b) - num) / (len(b) - 1): +# ans += 1 +# print(ans) +# f.close() + + +# for x in range(2): +# for y in range(2): +# for z in range(2): +# for w in range(2): +# if not(not((not(z) or w) and (not(x) == y)) or (x and z)): +# print(x, y, z, w) + +# 6 +# f = open("27-B.txt") +# n = int(f.readline()) +# a = [int(i) for i in f] +# ans = 0 +# for i in range(n): +# for j in range(i+1, n): +# if (a[i] + a[j]) % 4 == 0 and (a[i] * a[j]) % 59049 == 0: +# ans += 1 +# print(ans) + +# k = 59049 +# data = [] +# for d in range(2, k+1): +# if k % d == 0: +# data.append(d) +# print(data) + +# 5 +# f = open('1_27_A.txt') +# k = int(f.readline()) +# n = int(f.readline()) +# arr = [int(i) for i in f] +# maxNum = 0 +# ans = 0 +# for i in range(n): +# maxNum = max(maxNum, arr[i]) +# if i + k < len(arr): +# ans = max(ans, arr[i+k] + maxNum) +# print(ans) + +# f = open('27-B (1).txt') +# n = int(f.readline()) +# arr = [int(x) for x in f] +# arr0 = [] +# arr1 = [] +# arr2 = [] +# for i in arr: +# if i % 3 == 0: +# arr0.append(i) +# if i % 3 == 1: +# arr1.append(i) +# if i % 3 == 2: +# arr2.append(i) +# arr0.sort(reverse=True) +# arr1.sort(reverse=True) +# arr2.sort(reverse=True) +# print(max( sum([arr0[0], arr1[0], arr2[0]]), sum(arr0[0:3]), sum(arr1[0:3]), +# sum(arr2[0:3]))) + +# f = open('27-B_2.txt') +# n = int(f.readline()) +# arr = [int(x) for x in f] +# max1 = max(arr) +# arr.remove(max1) +# max2 = max(arr) +# while (max1 * max2) % 14 != 0: +# arr.remove(max2) +# max2 = max(arr) +# print(max1*max2) +# f.close() + +# A = open('27-B.txt') +# N = A.readline() +# summ = 0 +# ch = 0 +# nech = 0 +# minRaz1 = 10**9 +# minRaz2 = 10**9 +# minRaz3 = 10**9 +# minRaz4 = 10**9 +# for line in A: +# x, y = map(int, line.split()) +# if x < y: +# summ += x +# if x % 2 == 0: +# ch += 1 +# else: +# nech += 1 +# if abs(x-y) % 2 != 0: +# if abs(x-y) < minRaz1 and x % 2 == 0: +# minRaz2 = minRaz1 +# minRaz1 = abs(x-y) +# elif abs(x-y) < minRaz2 and x % 2 == 0: +# minRaz2 = abs(x-y) +# if abs(x-y) < minRaz3 and x % 2 != 0: +# minRaz4 = minRaz3 +# minRaz3 = abs(x-y) +# elif abs(x-y) < minRaz4 and x % 2 != 0: +# minRaz4 = abs(x-y) +# else: +# summ += y +# if y % 2 == 0: +# ch += 1 +# else: +# nech += 1 +# if abs(x-y) % 2 != 0: +# if abs(x-y) < minRaz1 and y % 2 == 0: +# minRaz2 = minRaz1 +# minRaz1 = abs(x-y) +# elif abs(x-y) < minRaz2 and y % 2 == 0: +# minRaz2 = abs(x-y) +# if abs(x-y) < minRaz3 and yн % 2 != 0: +# minRaz4 = minRaz3 +# minRaz3 = abs(x-y) +# elif abs(x-y) < minRaz4 and y % 2 != 0: +# minRaz4 = abs(x-y) + +# if ch > nech: +# if summ % 2 == 0: +# print(summ) +# elif minRaz3 <= minRaz1: +# print(summ + minRaz3) +# elif ch - nech != 1: +# print(summ + minRaz1) +# elif minRaz1 + minRaz2 < minRaz3: +# print(summ + minRaz1 + minRaz2) +# else: +# print(summ + minRaz3) +# else: +# pass + +# f = open('26.txt') +# N = int(f.readline()) +# box = [int(i) for i in f] +# box.sort(reverse = True) +# ans = [box[0]] +# for i in range(1, N): +# if ans[-1] - box[i] >= 3: +# ans.append(box[i]) +# print(len(ans), ans[-1]) + +# import string +# f = open('24 (29).txt') +# mx = 10 ** 9 +# ans = '' +# for line in f: +# if line.count('N') < mx: +# mx = line.count('N') +# ans = line +# d = dict().fromkeys(string.ascii_uppercase, 0) +# mn = 0 +# result = '' +# for letter in d.keys(): +# d[letter] = ans.count(letter) +# if d[letter] >= mn: +# mn = d[letter] +# result = letter +# print(result) +# f.close() + +# f = open(r'17 (23).txt') +# data = [int(line) for line in f] +# c = 0 +# maxNum = 0 +# for i in range(len(data) - 1): +# if (data[i] * data[i+1]) % 15 == 0 and (data[i] + data[i+1]) % 7 == 0: +# c += 1 +# maxNum = max(data[i] + data[i+1], maxNum) + +# print(c, maxNum) +# f.close() + +# a = int(input()) +# b = int(input()) +# n = int(input()) +# m = int(input()) +# min1 = n + (n-1)*a +# min2 = m + (m-1)*b +# minT = max(min1, min2) +# max1 = n + (n+1)*a +# max2 = m + (m+1)*b +# maxT = min(max1, max2) +# if maxT >= minT: +# print(minT, maxT) +# else: +# print(-1) + +# n = int(input()) +# arr = [] +# newG = 0 +# for i in range(n): +# a = int(input()) +# arr.append(a) +# for i in range(n-1, 0, -1): +# if max(arr) <= n: +# t = max(arr) +# break +# newG += arr[i] - n +# arr[i] -= arr[i] - n +# print(t) + +# t = int(input()) +# maxA = 0 +# ans = 0 +# for i in range(t): +# n, x = map(int, input().split()) +# a = list(map(int, input().split())) +# maxA = max(a[0], 2*(x - a[n-1])) +# for i in range(1, n): +# maxA = max(maxA, a[i] - a[i-1]) +# print(maxA) + +# t = int(input()) +# for i in range(t): +# s = input() +# n = len(s) +# ans = '' +# arr = '' +# if s[0] == ')': +# ans = 'YES' +# arr = '()' * n +# elif s.count('(') == s.count(')') and s[-1] != '(': +# ans = 'NO' +# else: +# ans = 'YES' +# arr = '()' * n +# if ans == 'NO': +# print(ans) +# else: +# print(ans) +# print(arr) + +# t = int(input()) +# for i in range(t): +# n = int(input()) +# a = list(map(int, input().split())) +# b = [] +# if a[0] == 1: +# b.append(2) +# else: +# b.append(1) +# for j in range(1, n): +# if a[j] == b[j-1] + 1: +# b.append(b[j-1] + 2) +# else: +# b.append(b[j-1] + 1) +# print(b[n-1]) + +# t = int(input()) +# ans = list() +# for i in range(t): +# n = int(input()) +# arr = list(map(int, input().split())) +# for j in range(n): +# if j == n - 1: +# ans.append(arr[j] + 1) +# elif arr[j] < arr[j+1]: +# ans.append(arr[j] + 1) +# else: +# ans.append(ans[j-1] + 1) +# print(ans[-1]) + +# n = int(input()) +# visited = [False] * (n + 1) +# prev = [None] * (n + 1) +# def dfs(start, visited, prev, g): +# visited[start] = True +# for u in g[start]: +# if not visited[u]: +# prev[u] = start +# dfs(u,visited, prev, g) + +# matrix = [] +# for i in range(n): +# line = list(map(int, input().split())) +# matrix.append(line) +# r = 0 +# g = [list() for i in range(n)] +# for i in range(n): +# for j in range(i+1, n): +# if matrix[i][j] == 1: +# r += 1 +# g[i].append(j) +# g[j].append(i) + +# c = 0 +# for i in range(n): +# if not visited[i]: +# c += 1 +# dfs(i, visited, prev, g) +# if c == 1 and r = n - 1: +# print('YES') +# else: +# print('NO') + +# a = input() +# b = input() +# ans = 0 +# s = set() + +# for i in range(len(b)-1): +# s.add(b[i:i+2]) +# for i in range(len(a)-1): +# if a[i:i+2] in s: +# ans += 1 +# print(ans) + +# from math import gcd +# a = int(input()) +# b = int(input()) +# c = int(input()) +# d = int(input()) +# ans = 0 +# while a*d < b*c: +# a += 1 +# b += 1 +# a //= gcd(a, b) +# b //= gcd(a, b) +# ans += 1 +# if a == c and b == d: +# print(ans) +# else: +# print(0) + +# a/b < c/d +# a*d < b*c + +# dfs - обход в глубину + +# visited = [False] * (n + 1) +# prev = [None] * (n + 1) #prev[5] = 3 +# def dfs(start, visited, prev, g): +# visited[start] = True +# for u in g[start]: +# if not visited[u]: +# prev[u] = start +# dfs(u) +# # start = 1 #зависит от задачи +# dfs(start, visited, prev, g) + +# n, m = map(int, input().split()) +# W = [list() for i in range(n + 1)] +# for i in range(m): +# u, v = map(int, input().split()) +# W[u].append(v) +# W[v].append(u) +# for row in W: +# print(row) + +# https://vos.olimpiada.ru/upload/files/Arhive_tasks/2021-22/mun/iikt/tasks-iikt-9-11-mun-msk-21-22.pdf +# n = int(input()) +# a = int(input()) +# b = int(input()) +# total = a + 3 * b +# res = total // n +# if n % 3 != 0: +# res = min(res, a // (n % 3)) +# print(res) + +# a = int(input()) +# b = int(input()) +# # a -= b +# # c = 0 +# # day = 1 +# # while b <= a: +# # b += 1 +# # c += a - b +# # day += 1 +# # print(day) +# ans = 2*(a-b) + 1 + 1 +# print(max(1, ans)) + +# from collections import deque + +# d = deque() +# d.append(8) +# d.appendleft(7) +# d.pop() +# d.popleft() +# len(d) + +# n = int(input()) +# queue1 = deque() +# queue2= deque() +# res = '' + +# for i in range(n): +# gob = input().split() +# if gob[0] == '+': +# queue1.appendleft(gob[-1]) +# queue2.appendleft(queue1.pop()) +# elif gob[0] == '-': +# res += queue2.pop() +# elif gob[0] == '*': +# if len(queue1) > len(queue2): +# queue2.appendleft(queue1.pop()) +# queue2.appendleft(gob[-1]) +# elif len(queue1) < len(queue2): +# queue1.append(queue2[0]) +# queue2.popleft() +# queue2.appendleft(gob[-1]) +# elif len(queue1) == len(queue2): +# queue2.appendleft(gob[-1]) + +# for i in res: +# print(i) + +# n = int(input()) +# m = int(input()) +# t = int(input()) + +# f = 4 * (n+m)**2 - 16 * t +# res = int((-2 * (n+m) + f**0.5) // -8) +# print(res) + +# t1 = int(input()) +# t2 = int(input()) +# n1 = int(input()) +# n2 = int(input()) + +# min1 = (n1 - 1) * t1 + n1 +# max1 = (n1 + 1) * t1 + n1 +# min2 = (n2 - 1) * t2 + n2 +# max2 = (n2 + 1) * t2 + n2 +# if max(min1, min2) < min(max1, max2): +# print(max(min1, min2), min(max1, max2), sep=' ') +# else: +# print(-1) + +# way = input() +# horiz = 0 +# vert = 0 +# number = 0 +# for i in range(len(way)): +# if way[i] == 'N': +# vert = vert + number +# number = 0 +# elif way[i] == 'S': +# vert = vert - number +# number = 0 +# elif way[i] == 'W': +# horiz = horiz - number +# number = 0 +# elif way[i] == 'E': +# horiz += number +# number = 0 +# else: +# number = number * 10 + int(way[i]) +# if vert > 0: +# print(vert, 'N', sep = '', end = '') +# else: +# print(abs(vert), 'S', sep = '', end = '') +# if horiz > 0: +# print(horiz, 'E', sep = '', end = '') +# else: +# print(abs(horiz), 'W', sep = '', end = '') + +# n = int(input()) +# if n % 4 == 1 or n % 4 == 2: +# print("IMPOSSIBLE") +# elif n % 4 == 3: +# print("++-" + "+--+" * (n // 4)) +# else: +# print("+--+" * (n // 4)) + +# m = int(input()) +# ans = 1 +# t = 2 +# while t*t <= m: +# if m % (t*t) == 0: +# ans = t*t +# t += 1 +# print(ans) + +# p1 = list(map(int, input().split())) +# p2 = list(map(int, input().split())) +# s = 0 +# go = True + +# while go and len(p1) > 0 and len(p2) > 0: +# s += 1 +# a = p1.pop(0) +# b = p2.pop(0) +# if a > b and (a != 0 and b != 9) or (a != 9 and b != 0): +# p1.append(a) +# p1.append(b) +# else: +# p2.append(b) +# p2.append(a) +# if s == 10 ** 6: +# print('botva') +# go = False +# if len(p1) == 0: +# print('second', s) +# elif len(p2) == 0: +# print('first', s) + +# queue = [] +# s = 0 +# go = True + +# def push(elem): +# queue.append(elem) + +# def front(): +# global s +# if size() > 0: +# return queue[s] +# else: +# return 'error' + +# def size(): +# global s +# return len(queue) - s + +# def pop(): +# global s +# if size() > 0: +# s += 1 +# return queue[s-1] +# else: +# return 'error' + +# stack = [] +# count = int(input()) +# way1 = list(map(int, input().split())) +# way2 = [] +# res = 'YES' +# def push(elem): +# stack.append(elem) +# def size(): +# return len(stack) +# def pop(): +# if size() > 0: +# return stack.pop() +# else: +# return 'error' +# def back(): +# if size() > 0: +# return stack[-1] +# return -1 +# # else: +# # return 'error' +# for i in way1: +# if size() == 0: +# push(i) +# elif back() > i: +# push(i) +# elif back() < i: +# while size() > 0 and back() < i: +# way2.append(pop()) + +# while size() > 0: +# way2.append(pop()) +# if way2 != sorted(way1): +# res = 'NO' +# print(res) + +# stack = [] +# arr = input().split() + +# def push(elem): +# stack.append(elem) +# def size(): +# return len(stack) +# def pop(): +# if size() > 0: +# return stack.pop() +# else: +# return 'error' +# def back(): +# if size() > 0: +# return stack[-1] +# else: +# return 'error' +# def isint(s): +# try: +# int(s) +# return True +# except ValueError: +# return False + +# for i in arr: +# if isint(i): +# push(int(i)) +# elif i == '+': +# summ = int(pop()) + int(pop()) +# push(summ) +# elif i == '-': +# tmp1 = int(pop()) +# tmp2 = int(pop()) +# diff = tmp2 - tmp1 +# push(diff) +# elif i == '*': +# multi = int(pop()) * int(pop()) +# push(multi) + +# print(back()) + +# stack = [] +# go = True + +# def push(elem): +# stack.append(elem) + +# def back(): +# if size() > 0: +# return stack[-1] +# else: +# return 'error' + +# def size(): +# return len(stack) + +# def pop(): +# if size() > 0: +# return stack.pop() +# else: +# return 'error' + +# s = input() +# if len(s) == 0: +# go = False +# for skb in s: +# if skb == '(' or skb == '{' or skb == '[': +# push(skb) +# else: +# if size() == 0: +# # print('Мы зашли сюда') +# go = False +# break +# if skb == ')' and back() != '(': +# go = False +# break +# if skb == '}' and back() != '{': +# go = False +# break +# if skb == ']' and back() != '[': +# go = False +# break +# if skb == ')' and back() == '(': +# pop() +# if skb == '}' and back() == '{': +# pop() +# if skb == ']' and back() == '[': +# pop() +# # print(go, size()) +# if go and size() == 0: +# print('yes') +# else: +# print('no') + +# stack = [] +# go = True + +# def push(elem): +# stack.append(elem) +# print('ok') #в дальнейшем не нужно + +# def back(): +# if size() > 0: +# return stack[-1] +# else: +# return 'error' #в дальнейшем не нужно + +# def size(): #размер стека +# return len(stack) + +# def pop(): +# if size() > 0: +# return stack.pop() +# else: +# return 'error' #в дальнейшем не нужно + +# def clear(): #не всегда нужно +# stack.clear() +# print('ok') #в дальнейшем не нужно + +# def exit(): #в дальнейшем не нужно +# global go +# go = False +# print('bye') #в дальнейшем не нужно + +# while go: +# cmd = input().split() +# if cmd[0] == 'push': +# push(cmd[1]) +# if cmd[0] == 'pop': +# print(pop()) +# if cmd[0] == 'back': +# print(back()) +# if cmd[0] == 'size': +# print(size()) +# if cmd[0] == 'clear': +# clear() +# if cmd[0] == 'exit': +# exit() + +# def solution(a, b, d): +# kiosk1 = 0 +# kiosk2 = d + +# if (b-a) % 2 == 0: +# home = (a+b) // 2 +# distance1 = abs(home - kiosk1) +# distance2 = abs(home - kiosk2) +# if distance1 > distance2: +# return home, distance2 +# else: +# return home, distance1 +# else: +# var1 = (a+b) // 2 +# var2 = round((a+b) / 2) +# distance1 = min(abs(var1 - kiosk1), abs(var1 - kiosk2)) +# distance2 = min(abs(var2 - kiosk1), abs(var2 - kiosk2)) +# if distance1 > distance2: +# return var2, distance2 +# else: +# return var1, distance1 + +# a, b, d = map(int, input().split()) +# print(*solution(a, b, d)) + +# k, p = map(int, input().split()) +# if k > 4: +# dp = [0 for i in range(k+1)] +# else: +# dp = [0 for i in range(10)] +# dp[2] = 1 +# dp[3] = 1 +# dp[4] = 2 +# for i in range(5, k+1): +# dp[i] = (dp[i] + dp[i-1] % p) % p +# if i % 2 == 0: +# dp[i] = (dp[i] + dp[i // 2] % p) % p +# print(dp[k] % p) + +# n = int(input()) +# a = list(map(int, input().split())) +# dp = [0] * (n+1) +# dp[0] = 0 +# dp[1] = 0 +# if n == 1: +# print(0) +# else: +# dp[2] = abs(a[1] - a[0]) +# for i in range(3, n+1): +# dp[i] = min(dp[i-1] + abs(a[i-1] - a[i-2]), dp[i-2] + 3*abs(a[i-1] - a[i-3])) +# print(dp[n]) + +# n = int(input()) +# a = [0] * n +# b = [0] * n +# c = [0] * n +# for i in range(0, n): +# a[i], b[i], c[i] = list(map(int, input().split())) +# if n == 1: +# print(a[0]) +# else: +# dp = [0] * (n+1) +# dp[1] = a[0] +# dp[2] = min(dp[1] + a[1], b[0]) +# for i in range(3, n + 1): +# dp[i] = min(dp[i-1] + a[i-1], dp[i-2] + b[i-2], dp[i-3] + c[i-3]) + +# print(dp[n]) + +# from math import inf +# n = int(input()) +# a = list(map(int, input().split())) +# a.sort() +# dp = [[0, 0] for i in range(n + 1)] +# dp[1][0] = 0 +# dp[1][1] = 10**12 +# for i in range(2, n + 1): +# dp[i][0] = dp[i - 1][1] +# dp[i][1] = min(dp[i - 1][0], dp[i - 1][1]) + a[i - 1] - a[i - 2] +# print(dp[n][1]) + +# n = int(input()) +# dp = [[0, 0, 0] for i in range(n+1)] +# dp[0][0] = 1 +# dp[1][0] = 1 +# dp[1][1] = 1 +# dp[1][2] = 0 +# for i in range(2, n+1): +# dp[i][0] = dp[i-1][0] + dp[i-1][1] + dp[i-1][2] +# dp[i][1] = dp[i-1][0] +# dp[i][2] = dp[i-2][0] +# print(dp[n][0] + dp[n][1] + dp[n][2]) + +# n, k = map(int, input().split()) +# dp = [[0,0] for i in range(n+1)] +# dp[1][0] = 1 +# dp[1][1] = k-1 +# for i in range(2, n+1): +# dp[i][0] = dp[i - 1][1] +# dp[i][1] = (dp[i-1][0] + dp[i-1][1]) * (k-1) +# print(dp[n][0] + dp[n][1]) + +# N = int(input()) +# Tshirt = list(map(int, input().split())) +# M = int(input()) +# Pants = list(map(int, input().split())) +# ishirt = 0 +# ipants = 0 +# i = 0 +# j = 0 +# while i < N-1 or j < M-1: +# if Tshirt[i] < Pants[j] and i < N - 1 or j == M - 1: +# i += 1 +# elif j < M - 1: +# j += 1 +# # print('###########') +# # print('Current index: ', i, j) +# # print('Current data: ', Tshirt[i], Pants[j]) +# # print('Current difference: ', abs(Tshirt[i] - Pants[j])) +# if abs(Tshirt[i] - Pants[j]) < abs(Tshirt[ishirt] - Pants[ipants]): +# ishirt = i +# ipants = j +# # print('Current best: ', ishirt, ipants) +# # print('###########') + +# print(Tshirt[ishirt], Pants[ipants]) + +# Повтори 8 [Вперёд 6 Направо 120] +# from turtle import * + +# scale = 20 +# for i in range(8): +# forward(6*scale) +# right(120) + +# penup() +# for x in range(-100, 200, scale): +# for y in range(-100, 100, scale): +# setposition(x, y) +# dot(3, 'red') + + +# done() + + diff --git a/new_data/test/1937_D.jsonl b/new_data/test/1937_D.jsonl new file mode 100644 index 0000000..238be40 --- /dev/null +++ b/new_data/test/1937_D.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n3\n><<\n4\n<<<<\n6\n<><<<>", "output": "3 6 5 \n1 2 3 4 \n1 4 7 10 8 1"} +{"input": "1\n1\n>", "output": "1"} +{"input": "1\n5\n>>>>>", "output": "5 4 3 2 1"} +{"input": "1\n4\n>>>>", "output": "4 3 2 1"} +{"input": "1\n4\n<<<<", "output": "1 2 3 4"} +{"input": "1\n6\n<><><>", "output": "1 4 9 9 4 1"} +{"input": "1\n7\n><<><>>", "output": "3 6 11 12 5 2 1"} +{"input": "1\n2\n<>", "output": "1 1"} +{"input": "1\n3\n<><", "output": "1 4 3"} +{"input": "1\n6\n<<<>>>", "output": "1 2 3 3 2 1"} +{"input": "1\n8\n<<>>><<<", "output": "1 2 9 16 23 21 14 7"} diff --git a/new_data/test/1937_D.py b/new_data/test/1937_D.py new file mode 100644 index 0000000..8d7016d --- /dev/null +++ b/new_data/test/1937_D.py @@ -0,0 +1,140 @@ +t = int(input()) + +for i in range(t): + n = int(input()) + s = str(input()) + + large_idx = [] + less_idx = [] + + l_nearest_large = [0] * n + r_nearest_less = [0] * n + + l_large_count = [0] * n + r_less_count = [0] * n + + l_large_rank = [-1] * n + r_less_rank = [-1] * n + + l_large_sum = [0] * n + r_less_sum = [0] * n + + for j in range(n): + if j == 0: + l_large_sum[j] = 0 + else: + l_large_sum[j] = l_large_sum[j - 1] + len(large_idx) + + if len(large_idx) > 0: + l_nearest_large[j] = large_idx[-1] + else: + l_nearest_large[j] = -1 + + l_large_count[j] = len(large_idx) + + if s[j] == '>': + l_large_rank[j] = len(large_idx) + + large_idx.append(j) + + for j in range(n-1, -1, -1): + if j == n - 1: + r_less_sum[j] = 0 + else: + r_less_sum[j] = r_less_sum[j + 1] + len(less_idx) + + if len(less_idx) > 0: + r_nearest_less[j] = less_idx[-1] + else: + r_nearest_less[j] = n + + r_less_count[j] = len(less_idx) + + if s[j] == '<': + r_less_rank[j] = len(less_idx) + + less_idx.append(j) + + output = [0] * n + # print(large_idx, less_idx) + # print(l_nearest_large, r_nearest_less) + # print(l_large_rank, r_less_rank) + # print(l_large_sum, r_less_sum) + + for j in range(n): + if s[j] == '<': + if l_large_count[j] <= r_less_count[j]: + # go to left + if l_large_count[j] == 0: + output[j] = j + 1 + else: + l_output = l_large_sum[j] + + r_nearest_less_pos = r_nearest_less[j] + r_nearest_less_rank = r_less_rank[r_nearest_less_pos] + r_turn_less_rank = r_nearest_less_rank - (l_large_count[j] - 1) + r_turn_less_idx = less_idx[r_turn_less_rank] + r_output = r_less_sum[j] - r_less_sum[r_turn_less_idx] - (r_turn_less_idx - j) * r_turn_less_rank + + output[j] = (l_output + r_output) * 2 + j + 1 + else: + # go to right + if r_less_count[j] == 0: + l_nearest_large_idx = l_nearest_large[j] + l_nearest_large_rank = l_large_rank[l_nearest_large_idx] + l_output = l_large_sum[j] - l_large_sum[l_nearest_large_idx] - ( + j - l_nearest_large_idx) * l_nearest_large_rank + + output[j] = l_output * 2 + n - j + else: + r_output = r_less_sum[j] + + l_nearest_large_pos = l_nearest_large[j] + l_nearest_large_rank = l_large_rank[l_nearest_large_pos] + l_turn_large_rank = l_nearest_large_rank - (r_less_count[j] - 1) + l_turn_large_idx = large_idx[l_turn_large_rank] + l_output = l_large_sum[j] - l_large_sum[l_turn_large_idx] - ( + j - l_turn_large_idx) * l_turn_large_rank + + output[j] = (l_output + r_output) * 2 + (n - j) + + elif s[j] == '>': + if l_large_count[j] >= r_less_count[j]: + # go right + if r_less_count[j] == 0: + output[j] = n - j + else: + r_output = r_less_sum[j] + + l_nearest_large_pos = l_nearest_large[j] + l_nearest_large_rank = l_large_rank[l_nearest_large_pos] + l_turn_large_rank = l_nearest_large_rank - (r_less_count[j] - 1) + l_turn_large_idx = large_idx[l_turn_large_rank] + l_output = l_large_sum[j] - l_large_sum[l_turn_large_idx] - ( + j - l_turn_large_idx) * l_turn_large_rank + + output[j] = (l_output + r_output) * 2 + (n - j) + else: + # go to left + if l_large_count[j] == 0: + r_nearest_less_idx = r_nearest_less[j] + r_nearest_less_rank = r_less_rank[r_nearest_less_idx] + r_output = r_less_sum[j] - r_less_sum[r_nearest_less_idx] - ( + r_nearest_less_idx - j) * r_nearest_less_rank + + output[j] = r_output * 2 + j + 1 + else: + l_output = l_large_sum[j] + + r_nearest_less_pos = r_nearest_less[j] + r_nearest_less_rank = r_less_rank[r_nearest_less_pos] + r_turn_less_rank = r_nearest_less_rank - (l_large_count[j] - 1) + r_turn_less_idx = less_idx[r_turn_less_rank] + r_output = r_less_sum[j] - r_less_sum[r_turn_less_idx] - (r_turn_less_idx - j) * r_turn_less_rank + + output[j] = (l_output + r_output) * 2 + j + 1 + + for o in output: + print(o, end=' ') + print('') + diff --git a/new_data/test/1937_D_1.py b/new_data/test/1937_D_1.py new file mode 100644 index 0000000..d637daf --- /dev/null +++ b/new_data/test/1937_D_1.py @@ -0,0 +1,88 @@ +from math import * +from collections import * + +for _ in range(int(input())): + n = int(input()) + s = input() + l = [] + l1 = [] + l2 = [] + cnt1 = 0 + cnt2 = 0 + for i in range(n): + if s[i] == '<': + l1.append(i) + cnt1 += 1 + else: + l2.append(i) + cnt2 += 1 + a = 0 + b = 0 + for j in range(n): + sec = 0 + p = j + if s[j] == '<': + a += 1 + else: + b += 1 + j_copy = j + if s[j] == '>': + c = cnt1 - a + if c >= j + 1: + x = a + for k in range(j + 1): + if s[j_copy] != s[j]: + sec += 1 + j_copy -= 1 + continue + sec += 2 * (l1[x] - j_copy) + 1 + x += 1 + j_copy -= 1 + else: + x = a + for k in range(c + 1): + if s[j_copy] != s[j]: + sec += 1 + elif k == c: + sec += n - j_copy + else: + sec += 2 * (l1[x] - j_copy) + 1 + x += 1 + j_copy -= 1 + + else: + c = b + if c >= n - j: + ind = c - 1 + for k in range(n - j - 1, -1, -1): + if s[j_copy] != s[j]: + sec += 1 + j_copy += 1 + continue + sec += 2 * (j_copy - l2[ind]) + 1 + ind -= 1 + j_copy += 1 + + else: + ind = c - 1 + for k in range(c + 1): + if s[j_copy] != s[j]: + sec += 1 + elif k == c: + sec += j_copy + 1 + else: + sec += 2 * (j_copy - l2[ind]) + 1 + ind -= 1 + j_copy += 1 + + l.append(sec) + print(*l) + + + + + + + + + diff --git a/new_data/test/1941_B.jsonl b/new_data/test/1941_B.jsonl new file mode 100644 index 0000000..556ad6d --- /dev/null +++ b/new_data/test/1941_B.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n5\n1 3 5 5 2\n5\n2 4 4 5 1\n5\n0 1 3 3 1\n6\n5 6 0 2 3 0\n4\n1 2 7 2\n3\n7 1 0\n4\n1 1 1 1", "output": "YES\nNO\nYES\nNO\nNO\nNO\nNO"} +{"input": "1\n3\n0 0 0", "output": "YES"} +{"input": "1\n3\n1 3 5", "output": "NO"} +{"input": "1\n5\n1 3 5 5 2", "output": "YES"} +{"input": "2\n3\n7 1 0\n4\n1 1 1 1", "output": "NO\nNO"} +{"input": "2\n5\n0 1 3 3 1\n6\n5 6 0 2 3 0", "output": "YES\nNO"} +{"input": "3\n3\n2 2 2\n4\n0 0 0 0\n5\n2 4 4 5 1", "output": "NO\nYES\nNO"} +{"input": "2\n5\n9 9 9 9 9\n5\n2 2 7 2 2", "output": "NO\nNO"} +{"input": "1\n5\n1000000000 1000000000 1000000000 1000000000 1000000000", "output": "NO"} +{"input": "3\n3\n0 10 0\n5\n1 1 2 4 1\n4\n1 3 5 9", "output": "NO\nNO\nNO"} +{"input": "5\n3\n0 0 0\n3\n1 0 1\n5\n5 5 0 5 5\n4\n2 2 2 2\n5\n10 0 10 0 10", "output": "YES\nNO\nNO\nNO\nNO"} diff --git a/new_data/test/1941_B.py b/new_data/test/1941_B.py new file mode 100644 index 0000000..8f4ee18 --- /dev/null +++ b/new_data/test/1941_B.py @@ -0,0 +1,71 @@ +answers = [] + + +def processArray(array, index): + array[index - 1] = array[index - 1] - 1 + array[index] = array[index] - 2 + array[index + 1] = array[index + 1] - 1 + return array + + # check for success + + +def CheckForSuccess(arrayForSuccess): + # print(f"Checking this array for success: {arrayForSuccess}") + for x in arrayForSuccess: + if x != 0: + return False + + return True + + +def mainAlgorithm(inputarray): + if CheckForSuccess(inputarray): + answers.append("YES") + return + + loop_counter = 1 + while (loop_counter != 100): + length = len(inputarray) + # print(f"Array length {length}") + + # find index to highest element that is not 0 and not n-1 + highestNumber = -1 + highestIndex = -1 + for elementIndex in range(1, length - 1): + if inputarray[elementIndex] >= highestNumber: + highestIndex = elementIndex + highestNumber = inputarray[elementIndex] + + # print(f"Highest Index of {inputarray} is {highestIndex}") + + if (highestNumber < 0): + # Bail out time + answers.append("NO") + return + + newArray = processArray(inputarray, highestIndex) + # print (f"New Array: {newArray}") + + if (CheckForSuccess(newArray)): + answers.append("YES") + return + + loop_counter += 1 + + answers.append("NO") + + +# my algorithm is find highest number and always start wit hthat one. + + +numberOfArrays = int(input()) +for arrayCounter in range(0, numberOfArrays): + elementSize = int(input()) + array = list(map(int, input().split())) + + mainAlgorithm(array) + +for ans in answers: + print(f"{ans}") + diff --git a/new_data/test/1941_B_1.py b/new_data/test/1941_B_1.py new file mode 100644 index 0000000..0b2b697 --- /dev/null +++ b/new_data/test/1941_B_1.py @@ -0,0 +1,17 @@ +t = int(input()) +for i in range(t): + n = int(input()) + l = [int(i) for i in input().split()] + l.reverse() + for j in range(200): + m = max(l) + ix = l.index(m) + if (ix != 0 and ix < n - 1): + l[ix - 1] = l[ix - 1] - 1 + l[ix + 1] = l[ix + 1] - 1 + l[ix] = l[ix] - 2 + if (l.count(0) == n): + print("YES") + else: + print("NO") + diff --git a/new_data/test/1941_C.jsonl b/new_data/test/1941_C.jsonl new file mode 100644 index 0000000..8a89eab --- /dev/null +++ b/new_data/test/1941_C.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n9\nmmapnapie\n9\nazabazapi\n8\nmappppie\n18\nmapmapmapmapmapmap\n1\np\n11\npppiepieeee", "output": "2\n0\n2\n6\n0\n2"} +{"input": "1\n3\nmap", "output": "1"} +{"input": "1\n5\nmpiea", "output": "1"} +{"input": "1\n10\napppiemapb", "output": "2"} +{"input": "1\n15\naaapiemapbapppie", "output": "3"} +{"input": "1\n12\nabcdefghilmn", "output": "0"} +{"input": "1\n6\nmpmapm", "output": "1"} +{"input": "1\n20\nzzzzzmappiezappppie", "output": "3"} +{"input": "1\n8\npppppppp", "output": "0"} +{"input": "1\n4\npiem", "output": "1"} +{"input": "1\n3\npmp", "output": "0"} diff --git a/new_data/test/1941_C.py b/new_data/test/1941_C.py new file mode 100644 index 0000000..89cef8e --- /dev/null +++ b/new_data/test/1941_C.py @@ -0,0 +1,10 @@ +t = int(input()) +for i in range(t): + n = int(input()) + s = input() + m = s.count("map") + s = s.replace("map", "") + + p = s.count("pie") + print(m + p) + diff --git a/new_data/test/1941_C_1.py b/new_data/test/1941_C_1.py new file mode 100644 index 0000000..6660d47 --- /dev/null +++ b/new_data/test/1941_C_1.py @@ -0,0 +1,15 @@ +for i in range(int(input())): + input() + s = input() + flag = 0 + length = len(s) + mapie_s = filter(None, s.split("mapie")) + s1 = ''.join(mapie_s) + length_s1 = length - len(s1) + flag += length_s1//5 + map_s = filter(None, s1.split("map")) + s2 = ''.join(map_s) + pie_s = filter(None, s2.split("pie")) + s3 = ''.join(pie_s) + length_s3 = len(s3) + print((len(s1) - length_s3)//3 + flag) \ No newline at end of file diff --git a/new_data/test/1941_E.jsonl b/new_data/test/1941_E.jsonl new file mode 100644 index 0000000..d7ce36b --- /dev/null +++ b/new_data/test/1941_E.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n3 11 1 4\n0 1 2 3 4 5 4 3 2 1 0\n0 1 2 3 2 1 2 3 3 2 0\n0 1 2 3 5 5 5 5 5 2 0\n4 4 2 1\n0 3 3 0\n0 2 1 0\n0 1 2 0\n0 3 3 0\n4 5 2 5\n0 1 1 1 0\n0 2 2 2 0\n0 2 1 1 0\n0 3 2 1 0\n1 8 1 1\n0 10 4 8 4 4 2 0\n4 5 3 2\n0 8 4 4 0\n0 3 4 8 0\n0 8 1 10 0\n0 10 1 5 0", "output": "4\n8\n4\n15\n14"} +{"input": "1\n1 3 1 1\n0 5 0", "output": "2"} +{"input": "1\n3 5 2 1\n0 1 2 1 0\n0 0 5 0 0\n0 9 9 9 0", "output": "9"} +{"input": "1\n4 5 4 5\n0 1 9 1 0\n0 2 2 2 0\n0 3 1 8 0\n0 0 0 0 0", "output": "8"} +{"input": "1\n5 6 2 2\n0 1 6 1 2 0\n0 0 1 1 0 0\n0 5 9 5 9 0\n0 1 0 1 5 0\n0 2 1 2 1 0", "output": "7"} +{"input": "2\n1 8 1 2\n0 2 2 2 2 3 1 0\n2 5 1 1\n0 1 5 1 0\n0 5 5 5 0", "output": "7\n6"} +{"input": "1\n2 5 2 3\n0 9 9 9 0\n0 1 1 1 0", "output": "4"} +{"input": "1\n5 10 3 3\n0 1 1 2 5 5 5 2 1 0\n0 0 3 3 3 1 1 1 1 0\n0 10 10 1 1 5 5 5 0 0\n0 1 1 1 1 3 6 6 6 0\n0 0 0 5 5 5 9 9 1 0", "output": "18"} +{"input": "1\n3 7 2 6\n0 1 2 3 9 1 0\n0 0 1 7 1 2 0\n0 2 2 2 2 2 0", "output": "4"} +{"input": "1\n3 9 1 9\n0 1 2 3 4 5 6 7 0\n0 9 8 1 1 0 3 2 0\n0 1 1 1 1 1 1 1 0", "output": "2"} +{"input": "1\n5 5 1 1\n0 1 9 2 0\n0 3 3 3 0\n0 1 1 1 0\n0 0 9 0 0\n0 1 0 1 0", "output": "3"} diff --git a/new_data/test/1941_E.py b/new_data/test/1941_E.py new file mode 100644 index 0000000..8468a66 --- /dev/null +++ b/new_data/test/1941_E.py @@ -0,0 +1,215 @@ +from bisect import * +import sys +from collections import * +from functools import * +from heapq import * +from queue import * +from itertools import * +from math import * +from operator import * +from types import * + +input = lambda: sys.stdin.readline().rstrip("\r\n") +print = lambda *a, sep=" ", end="\n": sys.stdout.write(sep.join(map(str, a)) + end) +debug = lambda *a: sys.stderr.write(" ".join(map(str, a)) + "\n") + +MOD = (10 ** 9) + 7 + + +def bootstrap(f, stack=[]): + def wrappedfunc(*args, **kwargs): + if stack: + return f(*args, **kwargs) + else: + to = f(*args, **kwargs) + while True: + if type(to) is GeneratorType: + stack.append(to) + to = next(to) + else: + stack.pop() + if not stack: + break + to = stack[-1].send(to) + return to + + return wrappedfunc + + +def prefixSum(arr): + n = len(arr) + if (n == 0): + return [] + ps = [0] * n + ps[0] = arr[0] + for i in range(1, n): + ps[i] = arr[i] + ps[i - 1] + return ps + + +def suffixSum(arr): + n = len(arr) + if (n == 0): + return [] + ss = [0] * n + ss[-1] = arr[-1] + for i in range(n - 2, -1, -1): + ss[i] = arr[i] + ss[i + 1] + return ss + + +def factors(n): + return set(x for tup in ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0) for x in tup) + + +def sumDigits(no): + return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10)) + + +def inde(arr): + ind = {} + for i in range(len(arr)): + ind[arr[i]] = i + return ind + + +def freq(arr): + d = {} + for i in arr: + if (i in d): + d[i] += 1 + else: + d[i] = 1 + return d + + +def isPrime(num): + if (num > 1): + for i in range(2, int(sqrt(num)) + 1): + if (num % i == 0): + return False + return True + else: + return False + + +def cbrt(num): + return pow(num, 1 / 3) + + +def isSorted(arr): + is_sorted = all(a <= b for a, b in zip(arr, arr[1:])) + return is_sorted + + +def gcdArray(nums): + if (len(nums) == 1): + return nums[0] + + div = gcd(nums[0], nums[1]) + if (len(nums) == 2): + return div + for i in range(1, len(nums) - 1): + div = gcd(div, nums[i + 1]) + if (div == 1): + return div + return div + + +alpha = 'abcdefghijklmnopqrstuvwxyz' + + +def set_bit(x, i): + return x | (1 << i) + + +def clear_bit(x, i): + return x & ~(1 << i) + + +def get_bit(x, i): + return (x >> i) & 1 + + +def dist(x1, y1, x2, y2): + x = x1 - x2 + y = y1 - y2 + return sqrt(pow(x, 2) + pow(y, 2)) + + +class SegmentTree: + def __init__(self, data, default=0, func=max): + """initialize the segment tree with data""" + self._default = default + self._func = func + self._len = len(data) + self._size = _size = 1 << (self._len - 1).bit_length() + + self.data = [default] * (2 * _size) + self.data[_size:_size + self._len] = data + for i in reversed(range(_size)): + self.data[i] = func(self.data[i + i], self.data[i + i + 1]) + + def __delitem__(self, idx): + self[idx] = self._default + + def __getitem__(self, idx): + return self.data[idx + self._size] + + def __setitem__(self, idx, value): + idx += self._size + self.data[idx] = value + idx >>= 1 + while idx: + self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + idx >>= 1 + + def __len__(self): + return self._len + + def query(self, start, stop): + """func of data[start, stop)""" + start += self._size + stop += self._size + + res_left = res_right = self._default + while start < stop: + if start & 1: + res_left = self._func(res_left, self.data[start]) + start += 1 + if stop & 1: + stop -= 1 + res_right = self._func(self.data[stop], res_right) + start >>= 1 + stop >>= 1 + + return self._func(res_left, res_right) + + def __repr__(self): + return "SegmentTree({0})".format(self.data) + + +def solve1(arr, d): + t = [i + 1 for i in arr] + for i in range(1, min(m, d + 1)): + t[i] += 1 + tre = SegmentTree(t, default=10e9, func=min) + for i in range(d + 1, m): + x = tre.query(i - d - 1, i) + tre[i] += x + return tre[m - 1] + + +for _ in range(int(input())): + n, m, k, d = map(int, input().split()) + arr = [] + for _ in range(n): + arr.append(list(map(int, input().split()))) + res = [] + for i in arr: + res.append(solve1(i, d)) + pr = [0] + prefixSum(res) + ans = 949078567670 + for i in range(k, n + 1): + ans = min(ans, pr[i] - pr[i - k]) + print(ans) \ No newline at end of file diff --git a/new_data/test/1941_E_1.py b/new_data/test/1941_E_1.py new file mode 100644 index 0000000..0f15e19 --- /dev/null +++ b/new_data/test/1941_E_1.py @@ -0,0 +1,29 @@ +from collections import deque +def solve(arr,n,d): + q = deque() + q.append((1,n - 1)) + for i in range(n - 2,-1,-1): + if q[0][1] == i + d + 2: + q.popleft() + cur = arr[i] + q[0][0] + 1 + while len(q) > 0 and cur <= q[-1][0]: + q.pop() + q.append((cur,i)) + if i == 0:return cur +for _ in range(int(input())): + n,m,k,d = map(int,input().split()) + arr = [] + for i in range(n): + arr.append([int(x) for x in input().split()]) + ans = [0] * n + for i in range(n): + ans[i] = solve(arr[i],m,d) + cur = 0 + res = int(1e10) + for i in range(n): + cur += ans[i] + if i >= k: + cur -= ans[i - k] + if i >= k - 1: + res = min(res,cur) + print(res) \ No newline at end of file diff --git a/new_data/test/1942_C1.jsonl b/new_data/test/1942_C1.jsonl new file mode 100644 index 0000000..b2ddbb6 --- /dev/null +++ b/new_data/test/1942_C1.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n8 4 0\n1 6 2 5\n8 8 0\n1 3 2 5 4 6 7 8\n4 2 0\n1 3", "output": "2\n6\n2"} +{"input": "1\n10 3 0\n2 4 9", "output": "2"} +{"input": "1\n12 6 0\n1 3 5 6 9 10", "output": "6"} +{"input": "1\n7 2 0\n1 4", "output": "0"} +{"input": "1\n5 3 0\n2 3 5", "output": "3"} +{"input": "1\n8 5 0\n1 3 5 6 8", "output": "6"} +{"input": "1\n9 7 0\n2 3 4 5 7 8 9", "output": "7"} +{"input": "1\n15 8 0\n1 2 3 6 7 8 9 14", "output": "7"} +{"input": "1\n6 2 0\n1 3", "output": "1"} +{"input": "1\n20 10 0\n1 3 5 7 9 11 13 15 17 19", "output": "18"} +{"input": "1\n11 4 0\n1 3 6 9", "output": "3"} diff --git a/new_data/test/1942_C1.py b/new_data/test/1942_C1.py new file mode 100644 index 0000000..bf06208 --- /dev/null +++ b/new_data/test/1942_C1.py @@ -0,0 +1,27 @@ +def solve(): + nhap = list(map(int,input().split())) + a = list(map(int,input().split())) + n = nhap[0] + x = nhap[1] + y = nhap[2] + + if n > 2 * (10**5): + x = 2 * (10**5) + + + kq = x - 2; + a.sort() + + for i in range (len(a) - 1): + if a[i+1] - a[i] == 2: + kq +=1 + + if n - a[len(a)-1] + a[0] - 1 ==1: + kq += 1 + + print(kq) + +t = int(input()) +while t > 0: + t -= 1 + solve() \ No newline at end of file diff --git a/new_data/test/1942_C1_1.py b/new_data/test/1942_C1_1.py new file mode 100644 index 0000000..eecd74f --- /dev/null +++ b/new_data/test/1942_C1_1.py @@ -0,0 +1,16 @@ +R = lambda: map(int, input().split()) +t,=R() +while t: + t -= 1 + n,x,y= R() + sx=0; + l = list(R()) + l.append(n+l[0]) + l.sort() + mi=9999 + for i in range(1,x+1): + if l[i]-l[i-1]==2 : + sx+=1 + cons=x+sx-2 + cons=min(n-2,cons) + print(cons) # 使用 print 函数打印列表元素,而不是调用 P 函数 diff --git a/new_data/test/1943_C.jsonl b/new_data/test/1943_C.jsonl new file mode 100644 index 0000000..9fe4371 --- /dev/null +++ b/new_data/test/1943_C.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n1\n2\n1 2\n4\n1 2\n1 3\n1 4\n7\n2 7\n3 2\n6 4\n5 7\n1 6\n6 7", "output": "1\n1 0\n2\n1 1\n2 1\n2\n1 1\n2 1\n3\n6 1\n7 1\n2 1"} +{"input": "1\n1", "output": "1\n1 0"} +{"input": "1\n2\n1 2", "output": "2\n1 1\n2 1"} +{"input": "1\n5\n1 2\n1 3\n1 4\n1 5", "output": "2\n1 0\n1 1"} +{"input": "1\n7\n1 2\n1 3\n2 4\n2 5\n4 6\n5 7", "output": "3\n2 0\n2 1\n2 2"} +{"input": "1\n10\n1 2\n2 3\n3 4\n4 5\n3 6\n6 7\n7 8\n8 9\n9 10", "output": "4\n6 1\n7 1\n6 3\n7 3"} +{"input": "1\n6\n1 2\n1 3\n2 4\n2 5\n3 6", "output": "3\n1 0\n1 1\n1 2"} +{"input": "1\n4\n1 2\n1 3\n3 4", "output": "2\n1 1\n3 1"} +{"input": "1\n8\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n3 8", "output": "3\n1 0\n1 1\n1 2"} +{"input": "1\n7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7", "output": "4\n4 0\n4 1\n4 2\n4 3"} +{"input": "1\n9\n1 2\n2 3\n3 4\n2 5\n5 6\n6 7\n7 8\n8 9", "output": "4\n5 1\n6 1\n5 3\n6 3"} diff --git a/new_data/test/1943_C.py b/new_data/test/1943_C.py new file mode 100644 index 0000000..0f13e89 --- /dev/null +++ b/new_data/test/1943_C.py @@ -0,0 +1,75 @@ + +import sys +from collections import deque + +def compute_distances(n, adj): + # Compute distances from each vertex to all other vertices + distances = [ [ [] for _ in range(n) ] for _ in range(n) ] + for u in range(n): + q = deque() + q.append(u) + dist = [ -1 ] * n + dist[u] = 0 + distances[u][0].append(u) + while q: + current = q.popleft() + for neighbor in adj[current]: + if dist[neighbor] == -1: + dist[neighbor] = dist[current] + 1 + if dist[neighbor] < n: + distances[u][dist[neighbor]].append(neighbor) + q.append(neighbor) + return distances + +def solve_test_case(n, edges): + adj = [[] for _ in range(n)] + for u, v in edges: + adj[u].append(v) + adj[v].append(u) + distances = compute_distances(n, adj) + covered = [ False ] * n + result = [] + uncovered_count = n + while uncovered_count > 0: + max_count = -1 + best_op = (-1, -1) + for u in range(n): + for d in range(n): + if distances[u][d]: + count = 0 + for v in distances[u][d]: + if not covered[v]: + count += 1 + if count > max_count: + max_count = count + best_op = (u, d) + if max_count > 0: + u, d = best_op + result.append( (u + 1, d) ) + for v in distances[u][d]: + if not covered[v]: + covered[v] = True + uncovered_count -= 1 + else: + break + return len(result), result + +def main(): + input = sys.stdin.read().splitlines() + t = int(input[0]) + idx = 1 + for _ in range(t): + n = int(input[idx]) + idx += 1 + edges = [] + for _ in range(n-1): + u, v = map(int, input[idx].split()) + edges.append( (u-1, v-1) ) + idx += 1 + op_count, ops = solve_test_case(n, edges) + print(op_count) + for u, d in ops: + print(u, d) + +if __name__ == '__main__': + main() diff --git a/new_data/test/1943_C_1.py b/new_data/test/1943_C_1.py new file mode 100644 index 0000000..0f13e89 --- /dev/null +++ b/new_data/test/1943_C_1.py @@ -0,0 +1,75 @@ + +import sys +from collections import deque + +def compute_distances(n, adj): + # Compute distances from each vertex to all other vertices + distances = [ [ [] for _ in range(n) ] for _ in range(n) ] + for u in range(n): + q = deque() + q.append(u) + dist = [ -1 ] * n + dist[u] = 0 + distances[u][0].append(u) + while q: + current = q.popleft() + for neighbor in adj[current]: + if dist[neighbor] == -1: + dist[neighbor] = dist[current] + 1 + if dist[neighbor] < n: + distances[u][dist[neighbor]].append(neighbor) + q.append(neighbor) + return distances + +def solve_test_case(n, edges): + adj = [[] for _ in range(n)] + for u, v in edges: + adj[u].append(v) + adj[v].append(u) + distances = compute_distances(n, adj) + covered = [ False ] * n + result = [] + uncovered_count = n + while uncovered_count > 0: + max_count = -1 + best_op = (-1, -1) + for u in range(n): + for d in range(n): + if distances[u][d]: + count = 0 + for v in distances[u][d]: + if not covered[v]: + count += 1 + if count > max_count: + max_count = count + best_op = (u, d) + if max_count > 0: + u, d = best_op + result.append( (u + 1, d) ) + for v in distances[u][d]: + if not covered[v]: + covered[v] = True + uncovered_count -= 1 + else: + break + return len(result), result + +def main(): + input = sys.stdin.read().splitlines() + t = int(input[0]) + idx = 1 + for _ in range(t): + n = int(input[idx]) + idx += 1 + edges = [] + for _ in range(n-1): + u, v = map(int, input[idx].split()) + edges.append( (u-1, v-1) ) + idx += 1 + op_count, ops = solve_test_case(n, edges) + print(op_count) + for u, d in ops: + print(u, d) + +if __name__ == '__main__': + main() diff --git a/new_data/test/1944_A.jsonl b/new_data/test/1944_A.jsonl new file mode 100644 index 0000000..9be08ee --- /dev/null +++ b/new_data/test/1944_A.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n2 0\n2 1\n4 1\n5 10\n5 3\n4 4", "output": "2\n1\n4\n1\n5\n1"} +{"input": "1\n1 0", "output": "1"} +{"input": "1\n100 4950", "output": "1"} +{"input": "1\n2 1", "output": "1"} +{"input": "1\n100 0", "output": "100"} +{"input": "1\n4 5", "output": "1"} +{"input": "1\n5 7", "output": "1"} +{"input": "10\n3 3\n5 9\n6 4\n10 20\n7 21\n8 27\n9 36\n10 0\n99 4851\n100 2450", "output": "1\n1\n6\n1\n1\n1\n1\n10\n1\n1"} +{"input": "1\n8 0", "output": "8"} +{"input": "1\n3 0", "output": "3"} +{"input": "1\n50 1225", "output": "1"} diff --git a/new_data/test/1944_A.py b/new_data/test/1944_A.py new file mode 100644 index 0000000..3dccc4e --- /dev/null +++ b/new_data/test/1944_A.py @@ -0,0 +1,20 @@ +for _ in range(int(input())): + n, k = map(int, input().split()) + + max_edges = (n * (n - 1)) // 2 + x = n - 1 + if k < x: + print(n) + elif k == x: + print(n - 1) + elif k == max_edges: + print(1) + else: + cnt = 0 + while True: + if k > x: + cnt += 1 + k -= n - 1 + x -= 1 + else:break + print(cnt) \ No newline at end of file diff --git a/new_data/test/1944_A_1.py b/new_data/test/1944_A_1.py new file mode 100644 index 0000000..8dd3a50 --- /dev/null +++ b/new_data/test/1944_A_1.py @@ -0,0 +1,14 @@ +t = int(input()) +for _ in range(t): + n, k = map(int, input().split()) + if k == 0: + print(n) + elif k == n: + print(1) + elif k == ((n) * (n - 1)) // 2: + print(1) + else: + while k >= n - 1: + k -= (n - 1) + n -= 1 + print(n) diff --git a/new_data/test/1945_A.jsonl b/new_data/test/1945_A.jsonl new file mode 100644 index 0000000..2047e95 --- /dev/null +++ b/new_data/test/1945_A.jsonl @@ -0,0 +1,11 @@ +{"input": "10\n1 2 3\n1 4 1\n1 4 2\n1 1 1\n1 3 2\n19 7 18\n0 0 0\n7 0 0\n0 24 0\n1000000000 1000000000 1000000000", "output": "3\n-1\n3\n-1\n3\n28\n0\n7\n8\n1666666667"} +{"input": "1\n0 0 1", "output": "1"} +{"input": "1\n0 1 0", "output": "-1"} +{"input": "1\n1 1 0", "output": "-1"} +{"input": "1\n0 0 2", "output": "1"} +{"input": "1\n1000000000 0 0", "output": "1000000000"} +{"input": "1\n0 1000000000 0", "output": "-1"} +{"input": "1\n0 0 1000000000", "output": "333333334"} +{"input": "1\n333333333 333333333 333333334", "output": "555555556"} +{"input": "1\n5 15 9", "output": "13"} +{"input": "1\n1 2 3", "output": "3"} diff --git a/new_data/test/1945_A.py b/new_data/test/1945_A.py new file mode 100644 index 0000000..8a0e29a --- /dev/null +++ b/new_data/test/1945_A.py @@ -0,0 +1,18 @@ +for i in range(int(input())): + a , b ,c = map(int,input().split()) + leu = a + dung = True + while b % 3 != 0: + b = b + 1 + c = c - 1 + if c == 0 and b % 3 != 0: + print(-1) + dung = False + break + leu += (b // 3) + if c % 3 == 0: + leu += (c // 3) + else: + leu += (c // 3 + 1) + if dung: + print(leu) \ No newline at end of file diff --git a/new_data/test/1945_A_1.py b/new_data/test/1945_A_1.py new file mode 100644 index 0000000..1aca9b9 --- /dev/null +++ b/new_data/test/1945_A_1.py @@ -0,0 +1,31 @@ +def make_space(a,b,c): + result=a + if b%3!=0: + remaining=b-((b//3)*3) + if remaining>c: + result=-1 + else: + if remaining+c<3: + result=-1 + else: + result+=(b//3) + 1 + c-=(3-remaining) + if c%3==0: + result+=c//3 + else: + result+=(c//3)+1 + else: + result+=b//3 + if c%3==0: + result+=c//3 + else: + result+=(c//3)+1 + return result + + +amount=int(input()) +while amount>0: + a,b,c = map(int, input().split()) + result=make_space(a,b,c) + print(result) + amount-=1 \ No newline at end of file diff --git a/new_data/test/1945_B.jsonl b/new_data/test/1945_B.jsonl new file mode 100644 index 0000000..d3e181e --- /dev/null +++ b/new_data/test/1945_B.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n6 7 4\n3 4 10\n7 8 56\n5 6 78123459896\n1 1 1\n1 1 1000000000000000000", "output": "2\n7\n17\n28645268630\n4\n2000000000000000002"} +{"input": "1\n5 11 5", "output": "3"} +{"input": "3\n4 6 2\n5 5 100\n10 10 9", "output": "2\n42\n2"} +{"input": "1\n12 15 1", "output": "2"} +{"input": "2\n9 10 0\n100000 200000 50000", "output": "2\n2"} +{"input": "1\n99999998 99999999 99999997", "output": "2"} +{"input": "1\n1 1000000000000000000 0", "output": "2"} +{"input": "2\n8 16 3\n6 9 8", "output": "2\n3"} +{"input": "1\n123456789012345 98765432109876 1234567890", "output": "2"} +{"input": "4\n2 3 1000000\n5 10 15\n7 14 21\n9 18 5", "output": "833335\n6\n6\n2"} +{"input": "1\n270 360 180", "output": "2"} diff --git a/new_data/test/1945_B.py b/new_data/test/1945_B.py new file mode 100644 index 0000000..e7fbee8 --- /dev/null +++ b/new_data/test/1945_B.py @@ -0,0 +1,6 @@ +import math + +t = int(input()) +for _ in range(t): + a, b, m = map(int, input().split()) + print(math.floor(m / a) + math.floor(m / b) + 2) \ No newline at end of file diff --git a/new_data/test/1945_B_1.py b/new_data/test/1945_B_1.py new file mode 100644 index 0000000..65d7dcd --- /dev/null +++ b/new_data/test/1945_B_1.py @@ -0,0 +1,8 @@ +t=int(input()) +A=[] +for i in range(t): + a,b,m=map(int, input().split()) + sum=2+int(m/a)+int(m/b) + A.append(sum) +for i in A: + print(i) \ No newline at end of file diff --git a/new_data/test/1945_C.jsonl b/new_data/test/1945_C.jsonl new file mode 100644 index 0000000..84ed5ef --- /dev/null +++ b/new_data/test/1945_C.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n3\n101\n6\n010111\n6\n011001\n3\n000\n3\n110\n3\n001\n4\n1100", "output": "2\n3\n2\n3\n0\n1\n0"} +{"input": "1\n3\n010", "output": "1"} +{"input": "1\n5\n11010", "output": "0"} +{"input": "2\n6\n111111\n5\n00001", "output": "0\n3"} +{"input": "1\n4\n1001", "output": "2"} +{"input": "1\n8\n00001111", "output": "4"} +{"input": "3\n7\n1010101\n6\n001011\n5\n10000", "output": "4\n3\n5"} +{"input": "1\n9\n111000111", "output": "6"} +{"input": "2\n4\n0110\n5\n11111", "output": "2\n0"} +{"input": "1\n10\n0101010101", "output": "5"} +{"input": "1\n6\n010101", "output": "3"} diff --git a/new_data/test/1945_C.py b/new_data/test/1945_C.py new file mode 100644 index 0000000..fbf8d4a --- /dev/null +++ b/new_data/test/1945_C.py @@ -0,0 +1,32 @@ +import math +from decimal import Decimal + +t = int(input()) +while t: + n=int(input()) + input_string = input() + arr = [int(ch) for ch in input_string] + z = arr.count(0) + o = arr.count(1) + z_r = z + o_r = o + z_l=0 + o_l=0 + dist,ans,pos=abs(n/2),0,0 + if o_r>=(z_r+o_r)/2: + b_d=dist + else: + b_d=30001 + for i in arr: + pos+=1 + if i==0: + z_l+=1 + z_r-=1 + else: + o_l+=1 + o_r-=1 + if o_r>=((z_r+o_r)/2) and z_l>=((z_l+o_l)/2) and b_d > abs(n/2-pos): + ans=pos + b_d = abs(n/2-pos) + print(ans) + t -= 1 \ No newline at end of file diff --git a/new_data/test/1945_C_1.py b/new_data/test/1945_C_1.py new file mode 100644 index 0000000..3bfda72 --- /dev/null +++ b/new_data/test/1945_C_1.py @@ -0,0 +1,57 @@ +t = int(input()) +for jk in range(t): + n = int(input()) + a = input() + if a == '0100': + print(4) + elif n == 300000: + print(161662) + else: + x = [0] * (len(a) + 1) + y = [0] * (len(a) + 1) + for i in range(len(a)): + if a[i] == '0': + x[i] = x[i - 1] + 1 + else: + x[i] = x[i - 1] + if a[len(a) - i - 1] == '1': + y[len(a) - i - 1] = y[len(a) - i] + 1 + else: + y[len(a) - i - 1] = y[len(a) - i] + x.insert(0, 0) + y.insert(0, 0) + flag = 0 + ans = [] + for i in range(1, len(x)): + l = max(x[:i]) + r = max(y[i:]) + if (i) // 2 <= l and (n - i + 1) // 2 <= r: + if (n - i + 1) % 2 == 1: + if r < (n - i + 1) // 2 + 1: + continue + if i == 2 and (l == 0 or r == 0): + continue + if i == n and r == 0: + continue + if n % 2 == 0: + ans.append([abs((n) // 2 - i + 1), i - 1]) + else: + ans.append([max(abs((n + 1) // 2 - i + 1), 1), i - 1]) + flag += 1 + if flag == 0: + print(-1) + else: + ans.sort() + ''' for i in ans: + print(i)''' + if len(ans) > 1: + if ans[1][0] == ans[0][0]: + if ans[1][1] < ans[0][1]: + print(ans[1][1]) + else: + print(ans[0][1]) + else: + print(ans[0][1]) + else: + + print(ans[0][1]) \ No newline at end of file diff --git a/new_data/test/1945_D.jsonl b/new_data/test/1945_D.jsonl new file mode 100644 index 0000000..48eba38 --- /dev/null +++ b/new_data/test/1945_D.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n4 2\n7 3 6 9\n4 3 8 5\n6 2\n6 9 7 1 8 3\n5 8 8 1 4 1\n7 7\n7 2 9 2 6 5 9\n9 1 10 7 1 4 9\n2 1\n2 3\n1 1", "output": "14\n22\n9\n3"} +{"input": "1\n1 1\n1000000000\n1000000000", "output": "1000000000"} +{"input": "1\n2 2\n1 10\n10 1", "output": "2"} +{"input": "1\n2 1\n1 1\n1 1", "output": "2"} +{"input": "1\n3 2\n2 4 6\n1 1 1", "output": "4"} +{"input": "1\n3 2\n1 1 1\n1000000000 1000000000 1000000000", "output": "2"} +{"input": "1\n5 3\n10 9 8 7 6\n1 1 1 1 1", "output": "10"} +{"input": "1\n6 3\n1 2 4 8 16 32\n32 16 8 4 2 1", "output": "11"} +{"input": "1\n4 3\n2 2 2 2\n3 3 3 3", "output": "4"} +{"input": "1\n4 2\n10 5 10 5\n5 10 5 10", "output": "15"} +{"input": "1\n10 5\n1 2 3 4 5 6 7 8 9 10\n10 9 8 7 6 5 4 3 2 1", "output": "20"} diff --git a/new_data/test/1945_D.py b/new_data/test/1945_D.py new file mode 100644 index 0000000..7ea417c --- /dev/null +++ b/new_data/test/1945_D.py @@ -0,0 +1,205 @@ +# JlI MlTl DI +##### binary and decimal ##### +# way to convert number to binary -------> bin(Number)[2:] +# way to convert binary to number -------> int(n,2) +######################### +# to get permutations of a string +from itertools import permutations + + +def allPermutations(str): + permList = permutations(str) + return permList + + +####################### +# TO GET FlCTORS OF l NUMBER: +def factors(x): + result = [] + i = 1 + while i * i <= x: + if x % i == 0: + result.append(i) + if x // i != i: + result.append(x // i) + i += 1 + return result + + +##################################### +def fast_expo(val, power): + result = pow(val, power // 2) + result = result * result + + if power % 2 != 0: + result = result * val + return result + + +###################################### +# xeck if prime or not +def is_prime(n): + if n < 2: + return False + i = 2 + while i * i <= n: + if n % i == 0: + return False + i += 1 + return True + + +######################################## +def transpose(l1, l2): + for i in range(len(l1[0])): + # print(i) + row = [] + for item in l1: + row.append(item[i]) + l2.append(row) + return l2 + + +###################################### +def primeFactor(x): + l = [] + while x % 2 == 0: + l.append(2) + x = x // 2 + for i in range(3, int(math.sqrt(x) + 1), 2): + while x % i == 0: + l.append(i) + x = x / i + if x > 2: + l.append(x) + return l + + +################################################ +from math import gcd as bltin_gcd + + +def coprime2(a, b): + return bltin_gcd(a, b) == 1 + + +##################################################### + +# Sieve of Eratosthenes to precompute primes up to a certain limit, +# and then check if a number is prime using the precomputed list. + +def sieve_of_eratosthenes(limit): + primes = [True] * (limit + 1) + primes[0] = primes[1] = False + for i in range(2, int(limit ** 0.5) + 1): + if primes[i]: + for j in range(i * i, limit + 1, i): + primes[j] = False + return primes + + +################################################################################# +# MEX FINDER +def find_mex(arr): + return min(set(range(len(arr) + 1)) - set(arr)) + + +################################################################################ +# KADANES ALGORITHM +# helps to find the subarray with the largest sum + +def kadanes(nums): + maxSum = nums[0] + curSum = 0 + + for n in nums: + curSum = max(curSum, 0) + curSum += n + maxSum = max(maxSum, curSum) + return maxSum + + +################################################################################ + +# ONE COUNTER IN BINARY REPRESENTATION + +def count_ones(n): + count = 0 + while n: + n &= n - 1 + count += 1 + return count + + +########################################################################### + + +################################################################################ +## IMPORTSSS ## + +import math +from collections import * +from itertools import groupby +import heapq + +##NOTES NOTES NOTES NOTES NOTES!!!!!! +## +# 1) To find maximum element and its index efficiently use heapq like this========> +# max_heap = [(-value, index) for index, value in enumerate(arr)] +# heapq.heapify(max_heap) +# val, a = heapq.heappop(max_heap) + + +# 2) if you see a question that invovle parentheses checking pattern use STACKS. + +# 3) if question gives cost of something and ask max number kitne le skte ya bna skte +# like hamburger ques or magic powder use BINARY SEARCH + +# 4) GOLDEN RATIO +# int(round((golden_ratio ** n)/ 5 ** 0.5)) +# gives any particular element of fibonacci series + + +################################################################################################################# +for _ in range(int(input())): + n, m = map(int, input().split()) + a = list(map(int, input().split())) + b = list(map(int, input().split())) + ans = 10 ** 14 + res = 0 + for i in range(n - 1, -1, -1): + if i < m: + ans = min(ans, a[i] + res) + res += min(a[i], b[i]) + print(ans) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/new_data/test/1945_D_1.py b/new_data/test/1945_D_1.py new file mode 100644 index 0000000..c61fd53 --- /dev/null +++ b/new_data/test/1945_D_1.py @@ -0,0 +1,36 @@ +cases = int(input()) + +for c in range(cases): + na_frente, pos_final = map(int, input().split()) + custo_pra_trocar_a = list(map(int, input().split())) + custo_pra_passar_b = list(map(int, input().split())) + + na_frente -= 1 + pos_final -= 1 + + total = 0 + best = 10 ** 12 + for v in range(na_frente, -1, -1): + if (v <= pos_final): + if (best > total + custo_pra_trocar_a[v]): + best = total + custo_pra_trocar_a[v] + + if (custo_pra_trocar_a[v] < custo_pra_passar_b[v]): + total += custo_pra_trocar_a[v] + else: + total += custo_pra_passar_b[v] + else: + if (custo_pra_trocar_a[v] < custo_pra_passar_b[v]): + total += custo_pra_trocar_a[v] + else: + total += custo_pra_passar_b[v] + + print(best) + + + + + + + + diff --git a/new_data/test/1945_F.jsonl b/new_data/test/1945_F.jsonl new file mode 100644 index 0000000..ad5fbd5 --- /dev/null +++ b/new_data/test/1945_F.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n3\n9 8 14\n3 2 1\n5\n1 2 3 4 5\n1 2 3 4 5\n6\n1 2 3 4 5 6\n6 5 4 3 2 1\n5\n1 4 6 10 10\n2 1 4 5 3\n4\n2 2 5 5\n4 2 3 1\n5\n1 2 9 10 10\n1 4 2 3 5", "output": "16 2\n9 3\n8 2\n20 2\n5 1\n20 2"} +{"input": "1\n1\n1\n1", "output": "1 1"} +{"input": "1\n5\n5 5 5 5 5\n5 4 3 2 1", "output": "15 3"} +{"input": "1\n3\n1000000 999999 999998\n3 2 1", "output": "1999998 2"} +{"input": "1\n6\n1 2 3 4 5 6\n1 2 3 4 5 6", "output": "12 3"} +{"input": "1\n7\n10 9 8 7 6 5 4\n7 6 5 4 3 2 1", "output": "28 4"} +{"input": "1\n4\n1 4 2 3\n4 3 2 1", "output": "4 1"} +{"input": "1\n8\n9 1 8 1 7 1 6 1\n8 7 6 5 4 3 2 1", "output": "21 3"} +{"input": "1\n2\n10 10\n1 2", "output": "10 1"} +{"input": "1\n5\n1 1000000000 1 1000000000 1\n5 4 3 2 1", "output": "2000000000 2"} +{"input": "1\n10\n1 2 3 4 5 6 7 8 9 10\n10 1 9 2 8 3 7 4 6 5", "output": "21 3"} diff --git a/new_data/test/1945_F.py b/new_data/test/1945_F.py new file mode 100644 index 0000000..19a8b85 --- /dev/null +++ b/new_data/test/1945_F.py @@ -0,0 +1,121 @@ +import sys +import math + + +class Fenw: + def __init__(self, n): + self.n = n + self.tree = [0] * (n + 1) + + def update(self, i, delta): + # i: índice 0-based + i += 1 + while i <= self.n: + self.tree[i] += delta + i += i & -i + + def query(self, i): + # Suma de [0, i] (i 0-based) + s = 0 + i += 1 + while i: + s += self.tree[i] + i -= i & -i + return s + + def query_range(self, l, r): + return self.query(r) - (self.query(l - 1) if l > 0 else 0) + + def find_kth(self, k): + """Encuentra el índice mínimo i tal que query(i) >= k""" + idx = 0 + bit_mask = 1 << (self.n.bit_length() - 1) + while bit_mask: + t = idx + bit_mask + if t <= self.n and self.tree[t] < k: + k -= self.tree[t] + idx = t + bit_mask //= 2 + return idx # idx es 0-based + + +def solve(): + data = sys.stdin.read().split() + ptr = 0 + t = int(data[ptr]) + ptr += 1 + out_lines = [] + + for _ in range(t): + n = int(data[ptr]) + ptr += 1 + v = list(map(int, data[ptr:ptr + n])) + ptr += n + p = list(map(int, data[ptr:ptr + n])) + ptr += n + # Ajustar a 0-indexed + p = [x - 1 for x in p] + + # Precalcular el "umbral" para cada seta. + # zero_at_k[i] es el mayor k para el cual la seta i está activa (disponible) + # Se inicializa con n+2 y se actualiza para k>=2 usando p. + zero_at_k = [n + 2] * n + for k in range(2, n + 1): + # Para la seta con índice p[k-2], se anula a partir de k, + # es decir, está activa solo hasta k-1. + zero_at_k[p[k - 2]] = k - 1 + + # Armar una lista de setas: (magia, umbral) + mushrooms = [(v[i], zero_at_k[i]) for i in range(n)] + # Ordenar por magia decreciente; en caso de empate, por índice (no relevante aquí) + sorted_mushrooms = sorted(mushrooms, key=lambda x: -x[0]) + + # Preparar BIT: cada posición representa una seta en sorted_mushrooms. + BIT = Fenw(n) + for i in range(n): + BIT.update(i, 1) + + # Para actualizar el BIT según el umbral, + # preparamos una lista de (umbral, pos) donde pos es la posición de la seta + # en sorted_mushrooms. + removal = [] + for pos, (magic, thresh) in enumerate(sorted_mushrooms): + removal.append((thresh, pos)) + removal.sort(key=lambda x: x[0]) # en orden ascendente por umbral + + max_strength = 0 + best_k = 0 + limit = min(n, 2000) + rem_ptr = 0 + # Para k = 1 a limit, actualizamos BIT removiendo las setas que dejan de estar disponibles. + for k in range(1, limit + 1): + # Remover todas las setas cuyo umbral < k + while rem_ptr < n and removal[rem_ptr][0] < k: + pos_to_remove = removal[rem_ptr][1] + BIT.update(pos_to_remove, -1) + rem_ptr += 1 + + available = BIT.query(n - 1) + if available < k: + continue + # Encontrar el k-ésimo disponible (0-based: find_kth(k) devuelve índice) + pos_k = BIT.find_kth(k) + # En sorted_mushrooms, pos_k corresponde a la seta con la k-ésima mayor magia entre las disponibles + kth_magic = sorted_mushrooms[pos_k][0] + strength = k * kth_magic + if strength > max_strength or (strength == max_strength and k < best_k): + max_strength = strength + best_k = k + + # Verificación adicional para k=1: la seta más poderosa sola + if sorted_mushrooms[0][0] > max_strength: + max_strength = sorted_mushrooms[0][0] + best_k = 1 + + out_lines.append(f"{max_strength} {best_k}") + + sys.stdout.write("\n".join(out_lines)) + + +if __name__ == "__main__": + solve() diff --git a/new_data/test/1945_F_1.py b/new_data/test/1945_F_1.py new file mode 100644 index 0000000..4878583 --- /dev/null +++ b/new_data/test/1945_F_1.py @@ -0,0 +1,154 @@ +""" +The "sorted list" data-structure, with amortized O(n^(1/3)) cost per insert and pop. + +Example: + +A = SortedList() +A.insert(30) +A.insert(50) +A.insert(20) +A.insert(30) +A.insert(30) + +print(A) # prints [20, 30, 30, 30, 50] + +print(A.lower_bound(30), A.upper_bound(30)) # prints 1 4 + +print(A[-1]) # prints 50 +print(A.pop(1)) # prints 30 + +print(A) # prints [20, 30, 30, 50] +print(A.count(30)) # prints 2 + +""" + +from bisect import bisect_left as lower_bound +from bisect import bisect_right as upper_bound + + +class FenwickTree: + def __init__(self, x): + bit = self.bit = list(x) + size = self.size = len(bit) + for i in range(size): + j = i | (i + 1) + if j < size: + bit[j] += bit[i] + + def update(self, idx, x): + """updates bit[idx] += x""" + while idx < self.size: + self.bit[idx] += x + idx |= idx + 1 + + def __call__(self, end): + """calc sum(bit[:end])""" + x = 0 + while end: + x += self.bit[end - 1] + end &= end - 1 + return x + + def find_kth(self, k): + """Find largest idx such that sum(bit[:idx]) <= k""" + idx = -1 + for d in reversed(range(self.size.bit_length())): + right_idx = idx + (1 << d) + if right_idx < self.size and self.bit[right_idx] <= k: + idx = right_idx + k -= self.bit[idx] + return idx + 1, k + + +class SortedList: + block_size = 700 + + def __init__(self, iterable=()): + self.macro = [] + self.micros = [[]] + self.micro_size = [0] + self.fenwick = FenwickTree([0]) + self.size = 0 + for item in iterable: + self.insert(item) + + def insert(self, x): + i = lower_bound(self.macro, x) + j = upper_bound(self.micros[i], x) + self.micros[i].insert(j, x) + self.size += 1 + self.micro_size[i] += 1 + self.fenwick.update(i, 1) + if len(self.micros[i]) >= self.block_size: + self.micros[i:i + 1] = self.micros[i][:self.block_size >> 1], self.micros[i][self.block_size >> 1:] + self.micro_size[i:i + 1] = self.block_size >> 1, self.block_size >> 1 + self.fenwick = FenwickTree(self.micro_size) + self.macro.insert(i, self.micros[i + 1][0]) + def remove(self, x): + i = lower_bound(self.macro, x) + j = lower_bound(self.micros[i], x) + if j < len(self.micros[i]) and self.micros[i][j] == x: + self.micros[i].pop(j) + self.size -= 1 + self.micro_size[i] -= 1 + self.fenwick.update(i, -1) + + def pop(self, k=-1): + i, j = self._find_kth(k) + self.size -= 1 + self.micro_size[i] -= 1 + self.fenwick.update(i, -1) + return self.micros[i].pop(j) + + def __getitem__(self, k): + i, j = self._find_kth(k) + return self.micros[i][j] + + def count(self, x): + return self.upper_bound(x) - self.lower_bound(x) + + def __contains__(self, x): + return self.count(x) > 0 + + def lower_bound(self, x): + i = lower_bound(self.macro, x) + return self.fenwick(i) + lower_bound(self.micros[i], x) + + def upper_bound(self, x): + i = upper_bound(self.macro, x) + return self.fenwick(i) + upper_bound(self.micros[i], x) + + def _find_kth(self, k): + return self.fenwick.find_kth(k + self.size if k < 0 else k) + + def __len__(self): + return self.size + + def __iter__(self): + return (x for micro in self.micros for x in micro) + + def __repr__(self): + return str(list(self)) + + +t = int(input()) +for _ in range(t): + n = int(input()) + v = list(map(int,input().split())) + p = list(map(int,input().split())) + r = SortedList() + a = [] + for i in range(n): + a.append([v[i],p[i]]) + r.insert(a[-1]) + ans = r[-1][0] + idx = 1 + for i in range(1,n): + if r.__len__()ans: + ans = x[0] * i + idx = i + r.remove(a[a[i-1][1]-1]) + print(ans,idx) \ No newline at end of file diff --git a/new_data/test/1946_A.jsonl b/new_data/test/1946_A.jsonl new file mode 100644 index 0000000..5f1c8b2 --- /dev/null +++ b/new_data/test/1946_A.jsonl @@ -0,0 +1,11 @@ +{"input": "8\n3\n2 2 8\n4\n7 3 3 1\n1\n1000000000\n5\n5 5 5 4 5\n6\n2 1 2 3 1 4\n2\n1 2\n2\n1 1\n4\n5 5 5 5", "output": "1\n2\n1\n3\n2\n1\n2\n3"} +{"input": "1\n1\n1", "output": "1"} +{"input": "1\n5\n3 3 3 3 3", "output": "3"} +{"input": "1\n2\n1 1000000000", "output": "1"} +{"input": "1\n6\n5 5 5 5 5 5", "output": "4"} +{"input": "1\n4\n1 2 3 10", "output": "1"} +{"input": "1\n5\n10 9 8 7 6", "output": "1"} +{"input": "1\n7\n4 4 4 4 4 4 6", "output": "3"} +{"input": "1\n9\n2 2 2 2 2 3 3 3 3", "output": "1"} +{"input": "1\n8\n3 4 5 6 7 8 9 10", "output": "1"} +{"input": "1\n10\n1 1 1 2 2 2 2 2 2 9", "output": "5"} diff --git a/new_data/test/1946_A.py b/new_data/test/1946_A.py new file mode 100644 index 0000000..e45850f --- /dev/null +++ b/new_data/test/1946_A.py @@ -0,0 +1,27 @@ +num = int(input()) + +for i in range(0, num): + num2 = int(input()) + case = input() + op = 0 + if num2 > 10000: + print(1) + print(16668) + break + else: + + a = [int(i) for i in case.split() if i.isdigit()] + b = sorted(a) + if num2 % 2 == 0: + ma = int(num2 / 2) - 1 + else: + ma = int(num2 / 2) + median = b[ma] + new_median = median + + while new_median <= median: + b[ma] += 1 + op += 1 + b = sorted(b) + new_median = b[ma] + print(op) diff --git a/new_data/test/1946_A_1.py b/new_data/test/1946_A_1.py new file mode 100644 index 0000000..b4bcd00 --- /dev/null +++ b/new_data/test/1946_A_1.py @@ -0,0 +1,26 @@ +num = int(input()) + +for i in range(0, num): + num2 = int(input()) + case = input() + op = 0 + if num2 > 10000: + print(1) + print(16668) + else: + + a = [int(i) for i in case.split() if i.isdigit()] + b = sorted(a) + if num2 % 2 == 0: + ma = int(num2 / 2) - 1 + else: + ma = int(num2 / 2) + median = b[ma] + new_median = median + + while new_median <= median: + b[ma] += 1 + op += 1 + b = sorted(b) + new_median = b[ma] + print(op) diff --git a/new_data/test/1946_B.jsonl b/new_data/test/1946_B.jsonl new file mode 100644 index 0000000..1aa409d --- /dev/null +++ b/new_data/test/1946_B.jsonl @@ -0,0 +1,11 @@ +{"input": "12\n2 2\n-4 -7\n3 3\n2 2 8\n1 7\n7\n5 1\n4 -2 8 -12 9\n7 4\n8 14 -9 6 0 -1 3\n7 100\n5 3 -8 12 -5 -9 3\n6 1000\n-1000000000 -1000000000 -1000000000 -1000000000 -1000000000 -1000000000\n2 1\n1000000000 8\n5 4\n0 0 0 0 0\n6 10\n48973 757292 58277 -38574 27475 999984\n7 1\n-1000 1000 -1000 1000 -1000 1000 -1000\n10 10050\n408293874 -3498597 7374783 295774930 -48574034 26623784 498754833 -294875830 283045804 85938045", "output": "999999996\n96\n896\n17\n351\n716455332\n42\n2\n0\n897909241\n0\n416571966"} +{"input": "1\n1 1\n10", "output": "20"} +{"input": "1\n2 1\n-10 10", "output": "10"} +{"input": "2\n3 2\n1 -1 1\n4 3\n-5 -5 -5 -5", "output": "4\n999999987"} +{"input": "1\n5 5\n4 4 4 4 4", "output": "640"} +{"input": "1\n6 6\n1000000000 -999999999 500000000 -500000000 200000000 -200000000", "output": "999999567"} +{"input": "1\n4 100\n0 0 0 0", "output": "0"} +{"input": "1\n10 5\n1 2 3 4 5 6 7 8 9 10", "output": "1760"} +{"input": "1\n1 100000\n-1000000000", "output": "7"} +{"input": "3\n3 1\n100 200 300\n4 2\n150 -50 50 150\n2 2\n1000000 2000000", "output": "1200\n1200\n12000000"} +{"input": "2\n5 3\n0 -1 0 1 0\n7 7\n5 0 -5 5 0 -5 5", "output": "7\n640"} diff --git a/new_data/test/1946_B.py b/new_data/test/1946_B.py new file mode 100644 index 0000000..cc659eb --- /dev/null +++ b/new_data/test/1946_B.py @@ -0,0 +1,37 @@ +t=int(input()) +for j in range(t): + b=input().split() + n=int(b[0]) + k=int(b[1]) + l=list(map(int, input().split())) + suf=[] + suf.append(0) + for i in range(n): + suf.append(suf[i]+l[i]) + smin=[0] + for i in range(n): + if suf[i+1]sm or sm==-111: + sm=suf[i]-smin[i] + # min=100 + # max=-111 + # for i in suf: + # if min==100 or min>i: + # min=i + # if max==-111 or max= 0 else y - (abs(v) % y) + + print(v) + + + + + diff --git a/new_data/test/1946_C.jsonl b/new_data/test/1946_C.jsonl new file mode 100644 index 0000000..65b3916 --- /dev/null +++ b/new_data/test/1946_C.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n5 1\n1 2\n1 3\n3 4\n3 5\n2 1\n1 2\n6 1\n1 2\n2 3\n3 4\n4 5\n5 6\n3 1\n1 2\n1 3\n8 2\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7\n3 8\n6 2\n1 2\n2 3\n1 4\n4 5\n5 6", "output": "2\n1\n3\n1\n1\n2"} +{"input": "1\n2 1\n1 2", "output": "1"} +{"input": "2\n3 1\n1 2\n2 3\n3 1\n1 2\n1 3", "output": "1\n1"} +{"input": "1\n6 1\n1 2\n2 3\n3 4\n4 5\n5 6", "output": "3"} +{"input": "1\n5 2\n1 2\n1 3\n1 4\n1 5", "output": "1"} +{"input": "2\n4 1\n1 2\n2 3\n2 4\n4 2\n1 2\n2 3\n3 4", "output": "1\n1"} +{"input": "1\n7 3\n1 2\n1 3\n2 4\n2 5\n3 6\n5 7", "output": "1"} +{"input": "2\n5 1\n1 2\n1 3\n3 4\n3 5\n5 1\n1 2\n1 3\n1 4\n1 5", "output": "2\n1"} +{"input": "3\n6 2\n1 2\n2 3\n3 4\n4 5\n5 6\n6 1\n1 2\n1 3\n1 4\n1 5\n1 6\n6 4\n1 2\n1 3\n2 4\n2 5\n3 6", "output": "2\n1\n1"} +{"input": "1\n10 1\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10", "output": "5"} +{"input": "3\n4 1\n1 2\n2 3\n2 4\n5 4\n1 2\n1 3\n1 4\n1 5\n6 5\n1 2\n1 3\n1 4\n1 5\n1 6", "output": "1\n1\n1"} diff --git a/new_data/test/1946_C.py b/new_data/test/1946_C.py new file mode 100644 index 0000000..6adfeef --- /dev/null +++ b/new_data/test/1946_C.py @@ -0,0 +1,77 @@ +from collections import deque +for _ in range(int(input())): + n,k=map(int,input().split()) + d=[[] for _ in range(n+1)] + for i in range(n-1): + x,y=map(int,input().split()) + d[x].append(y) + d[y].append(x) + node=[] + for i in range(1,n+1): + if len(d[i])==1: + node.append(i) + def fun(mid): + vis=[-1 for _ in range(n+1)] + cnt=[1 for _ in range(n+1)] + attach=[0 for _ in range(n+1)] + q=deque() + for j in node: + vis[j]=1 + q.append(j) + rem=0 + a=False + while len(q)!=0: + x=q.popleft() + if cnt[x]>=mid : + rem+=1 + if len(q)==0: + a=True + for o in d[x]: + if vis[o]==-1: + if len(d[o])==2: + vis[o]=1 + q.append(o) + else: + if attach[o]==len(d[o])-2: + vis[o]=1 + q.append(o) + else: + attach[o]+=1 + elif cnt[x]k: + return True + if rem=mid: + return True + return False + low=1 + high=n//(k+1) + while(low<=high): + mid=(low+high)//2 + if fun(mid): + low=mid+1 + else: + high=mid-1 + print(high) \ No newline at end of file diff --git a/new_data/test/1946_C_1.py b/new_data/test/1946_C_1.py new file mode 100644 index 0000000..6bd5c5a --- /dev/null +++ b/new_data/test/1946_C_1.py @@ -0,0 +1,56 @@ +def load_data(): + with open('problem_4/1.in') as f: + t = int(f.readline().strip()) + n, k = map(int, f.readline().strip().split()) + edges = [] + for i in range(n - 1): + u, v = map(int, f.readline().strip().split()) + edges.append((u, v)) + return t, n, k, edges + + +def check(tree, mid, node, visited): + # count: 能额外切分出几个子树,remain: 切分后连到父节点还剩多少节点 + remain, count = 1, 0 + for v in tree[node]: + if v not in visited: + visited.add(v) + _remain, _count = check(tree, mid, v, visited) + if _remain >= mid: + count += 1 + else: + remain += _remain + count += _count + return remain, count + + +def main(): + # t, n, k, edges = load_data() + t = int(input()) + for _ in range(t): + try: + n, k = map(int, input().strip().split()) + tree = {i: [] for i in range(1, n + 1)} + for i in range(n - 1): + u, v = map(int, input().strip().split()) + # u, v = edges[i] + tree[u].append(v) + tree[v].append(u) + + min_, max_ = 1, n // (k + 1) + 1 + while max_ - min_ > 1: + mid = (min_ + max_) // 2 + visited = {n // 2, } + remain, count = check(tree, mid, n // 2, visited) + if remain >= mid: + count += 1 + if count >= k + 1: + min_ = mid + else: + max_ = mid + print(min_) + except Exception as e: + print(e) + + +main() diff --git a/new_data/test/1946_D.jsonl b/new_data/test/1946_D.jsonl new file mode 100644 index 0000000..0e4ba42 --- /dev/null +++ b/new_data/test/1946_D.jsonl @@ -0,0 +1,11 @@ +{"input": "8\n3 1\n1 2 3\n2 2\n1 1\n2 2\n1 3\n2 3\n0 0\n3 2\n0 0 1\n4 2\n1 3 3 7\n2 2\n2 3\n5 0\n0 1 2 2 1", "output": "2\n2\n1\n2\n3\n-1\n1\n2"} +{"input": "1\n6 2\n3 1 2 0 0 1", "output": "4"} +{"input": "2\n3 2\n4 5 6\n4 3\n3 1 7 2", "output": "-1\n-1"} +{"input": "1\n1 0\n0", "output": "1"} +{"input": "3\n5 15\n5 5 5 5 5\n4 4\n1 2 3 4\n3 7\n7 0 7", "output": "5\n2\n3"} +{"input": "1\n4 8\n1 2 4 8", "output": "-1"} +{"input": "2\n3 5\n1 4 2\n5 0\n2 3 6 7 8", "output": "-1\n-1"} +{"input": "1\n10 255\n128 64 32 16 8 4 2 1 255 254", "output": "10"} +{"input": "3\n2 1\n0 1\n3 6\n6 2 3\n5 20\n5 5 10 10 5", "output": "2\n-1\n5"} +{"input": "1\n7 3\n0 1 0 1 0 1 0", "output": "7"} +{"input": "1\n9 7\n1 1 1 1 1 1 1 1 1", "output": "9"} diff --git a/new_data/test/1946_D.py b/new_data/test/1946_D.py new file mode 100644 index 0000000..fa95965 --- /dev/null +++ b/new_data/test/1946_D.py @@ -0,0 +1,77 @@ +t_num = int(input()) +r = [] + +mod = 10 ** 9 + 7 + + +def solve(): + # n, q = list(map(int, input().split())) + n, x = list(map(int, input().split())) + arr = list(map(int, input().split())) + st = 0 + for i in arr: + st ^= i + + if st > x: + return -1 + + cx = x + goal = [] + for i in range(30): + goal.append(cx & 1) + cx >>= 1 + goal.reverse() + + use = [] + nst = st + for i in range(30): + use.append(st & 1) + st >>= 1 + use.reverse() + + re = 1 + + for i in range(30): + if use[i] > goal[i]: + return re + + if use[i] == goal[i] and goal[i]: + for j in range(n): + arr[j] |= (1 << (29 - i)) + continue + + if use[i] < goal[i]: + narr = [j >> (29 - i) for j in arr] + nx = nst >> (29 - i) + st = 0 + cur = 0 + for j in narr: + st ^= j + if st <= nx: + st = 0 + cur += 1 + re = max(cur, re) + + for j in range(n): + arr[j] |= (1 << (29 - i)) + nst |= (1 << (29 - i)) + + narr = arr + st = 0 + cur = 0 + for j in narr: + st ^= j + if st <= x: + st = 0 + cur += 1 + + re = max(cur, re) + + return re + + +for _ in range(t_num): + r.append(solve()) + +for i in r: + print(i) \ No newline at end of file diff --git a/new_data/test/1946_D_1.py b/new_data/test/1946_D_1.py new file mode 100644 index 0000000..c65aebf --- /dev/null +++ b/new_data/test/1946_D_1.py @@ -0,0 +1,39 @@ +import sys + + +def main(): + input = sys.stdin.read().split() + ptr = 0 + t = int(input[ptr]) + ptr += 1 + for _ in range(t): + n, x = int(input[ptr]), int(input[ptr + 1]) + ptr += 2 + a = list(map(int, input[ptr:ptr + n])) + ptr += n + + current_or = 0 + current_xor = 0 + k = 0 + for num in a: + current_xor ^= num + if (current_or | current_xor) <= x: + k += 1 + current_or |= current_xor + current_xor = 0 + + if current_xor == 0 and k >= 1: + print(k) + else: + # Check if the entire array's XOR is <=x + total_xor = 0 + for num in a: + total_xor ^= num + if total_xor <= x: + print(1) + else: + print(-1) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/new_data/test/1946_E.jsonl b/new_data/test/1946_E.jsonl new file mode 100644 index 0000000..551f261 --- /dev/null +++ b/new_data/test/1946_E.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n1 1 1\n1\n1\n4 2 3\n1 2\n2 3 4\n3 3 1\n1 2 3\n3\n5 3 4\n1 2 3\n2 3 4 5\n20 5 4\n1 2 3 4 12\n12 13 18 20\n6 2 3\n1 3\n3 4 6", "output": "1\n3\n1\n0\n317580808\n10"} +{"input": "1\n1 1 1\n1\n1", "output": "1"} +{"input": "1\n10 5 5\n1 2 3 4 5\n6 7 8 9 10", "output": "0"} +{"input": "1\n6 2 2\n1 4\n3 6", "output": "0"} +{"input": "1\n3 2 2\n1 3\n1 3", "output": "0"} +{"input": "1\n8 4 3\n1 3 5 7\n4 6 8", "output": "0"} +{"input": "1\n7 3 4\n2 4 7\n4 5 6 7", "output": "0"} +{"input": "1\n4 4 4\n1 2 3 4\n1 2 3 4", "output": "0"} +{"input": "1\n9 1 3\n1\n4 6 9", "output": "0"} +{"input": "1\n10 2 2\n1 10\n1 10", "output": "0"} +{"input": "1\n5 1 4\n5\n2 3 4 5", "output": "0"} diff --git a/new_data/test/1946_E.py b/new_data/test/1946_E.py new file mode 100644 index 0000000..b116d36 --- /dev/null +++ b/new_data/test/1946_E.py @@ -0,0 +1,51 @@ +t = int(input()) +mod = 10 ** 9 + 7 + + +def count(k, m): + res = 1 + for i in range(k): + res *= m + res %= mod + m -= 1 + return res + + +def debug(func): + def wrapper(*args, **kwargs): + res = func(*args, **kwargs) + print(args, res) + return res + + return wrapper + + +for i in range(t): + n, m1, m2 = map(int, input().split()) + a1 = list(map(int, input().split())) + a2 = list(map(int, input().split())) + + if a1[-1] != a2[0]: + print(0) + continue + + + def dp(i, j): + # print return value before return + if i == -1 and j == m2: + return 1 + if i < 0: + if j >= m2: + return 1 + return (count(a2[j] - a2[j - 1] - 1, a1[i + 1] - 1 + (n - a2[j - 1]) - 1) * dp(i, j + 1)) % mod + + if j >= m2: + if i < 0: + return 1 + return (count(a1[i + 1] - a1[i] - 1, a1[i + 1] - 1 + (n - a2[j - 1]) - 1) * dp(i - 1, j)) % mod + + return (count(a1[i + 1] - a1[i] - 1, a1[i + 1] - 1 + (n - a2[j - 1]) - 1) * dp(i - 1, j) + count( + a2[j] - a2[j - 1] - 1, a1[i + 1] - 1 + (n - a2[j - 1]) - 1) * dp(i, j + 1)) % mod + + + print(dp(m1 - 2, 1)) \ No newline at end of file diff --git a/new_data/test/1946_E_1.py b/new_data/test/1946_E_1.py new file mode 100644 index 0000000..ae64916 --- /dev/null +++ b/new_data/test/1946_E_1.py @@ -0,0 +1,77 @@ +import math + +T = int(input()) +s = [] +p = [] +facs = [] + + +def extended_euclidean_algorithm(a, b): + if b == 0: + return a, 1, 0 + gcd, x1, y1 = extended_euclidean_algorithm(b, a % b) + x = y1 + y = x1 - (a // b) * y1 + return gcd, x, y + + +def find_inverse_element(a, m): + gcd, x, y = extended_euclidean_algorithm(a, m) + if gcd != 1: + return None # обратный элемент не существует + return (x % m + m) % m + + +def division_mod_p(dividend, divisor, prime): + # Находим обратный элемент по модулю prime + inv_divisor = find_inverse_element(divisor, prime) + + # Выполняем целочисленное деление с остатком по модулю prime + return (dividend * inv_divisor) % prime + + +def fact(n): + global facs + if n == 0: + return 1 + return facs[n] + + +def c_n_k(k, n): + return (math.factorial(n) // math.factorial(k) // math.factorial(n - k)) % 1000000007 + + +def loc(num, n): + global p + if num == -1: + return 1 + pos = p[num] + return ((c_n_k(n - pos - 1, n - 1) * fact(n - pos - 1) % 1000000007) * loc(num - 1, pos)) % 1000000007 + + +for t in range(T): + n, m1, m2 = map(int, input().split()) + p = list(map(int, input().split())) + s = list(map(int, input().split())) + facs = [1] + for i in range(1, n + 1): + facs.append((facs[-1] * i) % 1000000007) + if p[-1] != s[0]: + print(0) + continue + for i in range(m1): + p[i] -= 1 + for i in range(m2): + s[i] -= 1 + res = c_n_k(p[-1], n - 1) * loc(m1 - 2, p[-1]) + res = res % 1000000007 + p = [n - 1 - i for i in s] + p = p[::-1] + res *= loc(m2 - 2, p[-1]) + res = res % 1000000007 + print(res) + + + + + diff --git a/new_data/test/1948_B.jsonl b/new_data/test/1948_B.jsonl new file mode 100644 index 0000000..6f52cfe --- /dev/null +++ b/new_data/test/1948_B.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n4\n12 3 45 67\n3\n12 28 5\n2\n0 0", "output": "YES\nNO\nYES"} +{"input": "1\n4\n9 12 23 34", "output": "YES"} +{"input": "1\n5\n90 21 3 45 9", "output": "NO"} +{"input": "1\n3\n29 19 10", "output": "NO"} +{"input": "1\n6\n99 98 97 2 1 0", "output": "NO"} +{"input": "1\n2\n56 65", "output": "YES"} +{"input": "1\n7\n1 1 1 1 1 1 1", "output": "YES"} +{"input": "1\n8\n15 26 37 48 59 70 81 92", "output": "YES"} +{"input": "1\n4\n10 11 12 13", "output": "YES"} +{"input": "1\n3\n77 8 32", "output": "YES"} +{"input": "1\n5\n0 0 0 0 0", "output": "YES"} diff --git a/new_data/test/1948_B.py b/new_data/test/1948_B.py new file mode 100644 index 0000000..9e0d308 --- /dev/null +++ b/new_data/test/1948_B.py @@ -0,0 +1,66 @@ +import sys +from typing import List + + +def is_sorted(nums: List[int]): + for i in range(len(nums) - 1): + if nums[i] > nums[i + 1]: + return False + return True + + +def get_unsorted_idx(nums: List[int]): + unsorted_idx = [] + for i in range(len(nums) - 1): + if nums[i] > nums[i + 1]: + unsorted_idx.append(i) + + return unsorted_idx + + +def fix(nums: List[int], idx: int): + num_to_fix = nums.pop(idx) + split_nums = [int(x) for x in str(num_to_fix)] + # [nums.insert(idx, num) for num in split_nums] + split_nums.reverse() + for num in split_nums: + nums.insert(idx, num) + + return len(split_nums) - 1 + + +lines = [] +line_idx = 0 +for line in sys.stdin: + if line_idx % 2 == 0: + lines.append(line) + line_idx += 1 + if line_idx == (1 + 2 * 7) and len(line.split()) > 15: + print(line) + +lines.pop(0) + +for test in lines: + nums = [int(x) for x in test.strip().split()] + if is_sorted(nums): + print("yes") + continue + + became_sorted = False + continue_sorting = True + while continue_sorting: + unsorted_idx = get_unsorted_idx(nums) + nums_inserted = 0 + for idx in unsorted_idx: + if nums[idx] < 10: + continue_sorting = False # unsortable + nums_inserted += fix(nums, idx + nums_inserted) + if is_sorted(nums): + became_sorted = True + continue_sorting = False + break + + if became_sorted: + print("yes") + continue + print("no") diff --git a/new_data/test/1948_B_1.py b/new_data/test/1948_B_1.py new file mode 100644 index 0000000..6d6ef55 --- /dev/null +++ b/new_data/test/1948_B_1.py @@ -0,0 +1,66 @@ +def lstIn(dataType=int, itType=list): + return itType(map(dataType, input().split())) + + +def mapIn(dataType=int): + return map(dataType, input().split()) + + +def mtrxIn(row, col, dataType=int, itType=list): + mat = [] + for _ in range(row): + colo = lstIn(dataType, itType) + mat.append(colo) + return mat + + +def split(arr, dtaType, itType=list): + temp = str(arr) + res = [dtaType(i) for i in temp] + return itType(res) + + +def solve(): + n = int(input()) + nums = lstIn() + + ans = [] + + def merge(left, right): + if left[-1] > right[0] and left[-1] // 10 > 0: + sus = str(left.pop()) + left.append(int(sus[0])) + left.append(int(sus[1:])) + + res = [] + res.extend(left) + res.extend(right) + + ans.extend(res) + return res + + def split(l, r, arr): + if l == r: + return [arr[l]] + + mid = (l + r) // 2 + + left = split(l, mid, arr) + right = split(mid + 1, r, arr) + + return merge(left, right) + + ans = split(0, n - 1, nums) + rans = split(0, len(ans) - 1, ans) + + # print(rans) + if sorted(rans) == rans: + print("YES") + else: + print("NO") + + +testcase = 1 +T = int(input()) if testcase else 1 +for _ in range(T): + solve() \ No newline at end of file diff --git a/new_data/test/1948_C.jsonl b/new_data/test/1948_C.jsonl new file mode 100644 index 0000000..3cb9b83 --- /dev/null +++ b/new_data/test/1948_C.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n4\n>><<\n>>><\n2\n><\n><\n4\n>>><\n>><<\n6\n>><<><\n><>>><", "output": "YES\nYES\nNO\nYES"} +{"input": "1\n2\n<>\n><", "output": "Yes"} +{"input": "1\n2\n><\n<>", "output": "No"} +{"input": "1\n4\n>>>>\n<><>", "output": "Yes"} +{"input": "1\n4\n<><>\n>>>>", "output": "Yes"} +{"input": "1\n6\n<<<<<<\n>>>>>>", "output": "Yes"} +{"input": "1\n6\n>>>><<\n>>>><<", "output": "No"} +{"input": "1\n8\n<><><><>\n<><><><>", "output": "Yes"} +{"input": "1\n8\n<<<<<<<>\n>>>>>>>>", "output": "Yes"} +{"input": "1\n10\n><><><><><\n><><><><><", "output": "Yes"} +{"input": "1\n10\n<><><><><<\n<><><><><>", "output": "No"} diff --git a/new_data/test/1948_C.py b/new_data/test/1948_C.py new file mode 100644 index 0000000..e585982 --- /dev/null +++ b/new_data/test/1948_C.py @@ -0,0 +1,43 @@ +def sol(L, n): + d = {} + + def helper(i, j): + try: + if i < 0 or i > 1 or j < 0 or j >= n: + return False + if i == 0 and j == 0: + return True + if (i == 0 and j % 2 != 0) or (i == 1 and j % 2 == 0): + return False + if (i, j) in d: + return d[(i, j)] + + y = False + if j > 0 and L[i][j - 1] == '>': + y = (j >= 2 and helper(i, j - 2)) or helper(i - 1, j - 1) or helper(i + 1, j - 1) + + d[(i, j)] = y + return y + except IndexError as e: + print(f"IndexError: i={i}, j={j}, error={e}") + return False + except Exception as e: + print(f"Error: i={i}, j={j}, error={e}") + return False + + z = helper(1, n - 1) + if z: + print('YES') + else: + print('NO') + + +t = int(input()) +for _ in range(t): + n = int(input()) + s1 = input().strip() + s2 = input().strip() + L1 = list(s1) + L2 = list(s2) + L = [L1, L2] + sol(L, n) diff --git a/new_data/test/1948_C_1.py b/new_data/test/1948_C_1.py new file mode 100644 index 0000000..f050be4 --- /dev/null +++ b/new_data/test/1948_C_1.py @@ -0,0 +1,39 @@ +def BFS(): + return + + +def solve(n, row, arr): + des = (1, n - 1) + queue = [] + for i in range(len(row)): + for j in range(len(row[i])): + if row[i][j] == ">": + queue.append((i, j)) + ok = [des] + status = 0 + # print(queue) + while (ok != []): + x, y = ok.pop(0) + # print(x,y) + if (x, y) == (0, 0) or (x, y) == (1, 2): + return "YES" + if (x, y - 1) in queue: + status = 1 + ok.append((x, y - 1)) + if (x - 1, y) in queue: + status = 1 + ok.append((x - 1, y)) + if status == 0: + return "NO" + # print(ok) + return "NO" + + +n = int(input()) +for _ in range(n): + arrow = int(input()) + tam = [[False] * arrow, [False] * arrow] + row = [] + row.append([i for i in input()]) + row.append([i for i in input()]) + print(solve(arrow, row, tam)) diff --git a/new_data/test/1948_D.jsonl b/new_data/test/1948_D.jsonl new file mode 100644 index 0000000..a08a615 --- /dev/null +++ b/new_data/test/1948_D.jsonl @@ -0,0 +1,11 @@ +{"input": "1\n?", "output": "0"} +{"input": "1\na", "output": "0"} +{"input": "1\n?", "output": "0"} +{"input": "2\naa\nab?", "output": "2\n2"} +{"input": "2\n????\nabab", "output": "4\n4"} +{"input": "3\nabc\nzzz??zzz\n?????", "output": "0\n8\n4"} +{"input": "1\n?????abc??", "output": "10"} +{"input": "3\nzxz??zxz\naaaaaa\nab?ab?", "output": "6\n6\n6"} +{"input": "2\ncodeforces\ncode?????s", "output": "0\n10"} +{"input": "1\nzaabaabz", "output": "6"} +{"input": "2\nabcabc\n??????", "output": "6\n6"} diff --git a/new_data/test/1948_D.py b/new_data/test/1948_D.py new file mode 100644 index 0000000..128dff1 --- /dev/null +++ b/new_data/test/1948_D.py @@ -0,0 +1,25 @@ +def checkSym(str): + n=len(str) + if len(str)%2==1: + return False + for i in range(len(str)//2): + if (not str[i]==str[n//2+i]) and (not str[i]=="?") and (not str[n//2+i]=="?"): + return False + return True + +t=int(input()) +if t==1: + print(24) +else: + for tests in range(t): + test = input() + n = len(test) + max_len = 0 + for i in range(n-1): + for j in range(n-1, i, -1): + substring = test[i:j+1] + if checkSym(substring): + max_len=max(len(substring),max_len) + break + if not t==1: + print(max_len) \ No newline at end of file diff --git a/new_data/test/1948_D_1.py b/new_data/test/1948_D_1.py new file mode 100644 index 0000000..f5880ce --- /dev/null +++ b/new_data/test/1948_D_1.py @@ -0,0 +1,18 @@ +t = int(input()) + +for i in range(t): + s = input().strip() + n = len(s) + for j in range(n // 2, 0, -1): + count = 0 + for k in range(0, n - j): + if s[k] == '?' or s[k + j] == '?' or s[k] == s[k + j]: + count += 1 + else: + count = 0 + if count == j: + break + if count == j: + break + + print(count * 2) diff --git a/new_data/test/1949_I.jsonl b/new_data/test/1949_I.jsonl new file mode 100644 index 0000000..5bc5af5 --- /dev/null +++ b/new_data/test/1949_I.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n0 2 1\n0 0 1\n4 -3 4\n11 0 3\n11 5 2", "output": "YES\nInput\n4\n2 2 2\n7 2 3\n7 7 2\n2 7 3\nOutput\nNO"} +{"input": "1\n0 0 1000000000", "output": "YES"} +{"input": "2\n0 0 1000000000\n2000000000 0 1000000000", "output": "NO"} +{"input": "3\n0 0 1\n2 0 2\n5 0 3", "output": "YES"} +{"input": "3\n0 0 1000000000\n2000000000 0 999999999\n3000000000 0 999999998", "output": "YES"} +{"input": "4\n0 0 1\n2 0 1\n0 2 1\n2 2 1", "output": "NO"} +{"input": "2\n0 0 10\n30 0 20", "output": "NO"} +{"input": "6\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n2 0 1\n3 1 1", "output": "YES"} +{"input": "5\n-1000000000 -1000000000 100000000\n0 0 10000\n10000 0 10000\n0 10000 10000\n-10000 -10000 10000", "output": "YES"} +{"input": "5\n0 0 1\n2 0 1\n0 3 1\n2 3 1\n1 1 2", "output": "YES"} +{"input": "4\n1 1 1\n4 1 1\n1 4 1\n4 4 1", "output": "YES"} diff --git a/new_data/test/1949_I.py b/new_data/test/1949_I.py new file mode 100644 index 0000000..f6cee5f --- /dev/null +++ b/new_data/test/1949_I.py @@ -0,0 +1,62 @@ +from collections import deque + +def sol(): + n = int(input()) + + rad = [] + cn = [] + for _ in range(n): + x, y, r = map(int, input().split()) + cn.append((x, y)) + rad.append(r) + + g = [[] for _ in range(n)] + for i in range(n): + for j in range(i): + dx = cn[i][0] - cn[j][0] + dy = cn[i][1] - cn[j][1] + dt = dx * dx + dy * dy + dr = rad[i] + rad[j] + if dr * dr == dt: + g[i].append(j) + g[j].append(i) + + vis = [False] * n + + for i in range(n): + if vis[i]: + continue + + vis[i] = True + q = deque([(i, 0)]) + od, ev = set(), set() + ev.add(i) + pos = True + + while q and pos: + c, p = q.popleft() + p = 1 - p + for ch in g[c]: + if vis[ch]: + if p: + if ch in ev: + pos = False + else: + if ch in od: + pos = False + continue + vis[ch] = True + if p: + od.add(ch) + else: + ev.add(ch) + q.append((ch, p)) + + if pos: + if len(od) != len(ev): + print("YES") + return + + print("NO") + +sol() diff --git a/new_data/test/1949_I_1.py b/new_data/test/1949_I_1.py new file mode 100644 index 0000000..9aa0d4f --- /dev/null +++ b/new_data/test/1949_I_1.py @@ -0,0 +1,43 @@ +def main(): + n = int(input()) + x = [None] * n + y = [None] * n + r = [None] * n + visited = [False] * n + coef0 = [None] * n + coef1 = [None] * n + nodes = [] + for i in range(n): + x[i], y[i], r[i] = map(int, input().split()) + + def dfs(i): + if not visited[i]: + visited[i] = True + nodes.append(i) + for j in range(n): + dx = x[i] - x[j] + dy = y[i] - y[j] + if not visited[j] and (r[i] + r[j]) ** 2 == dx ** 2 + dy ** 2: + coef0[j] = r[i] + r[j] - coef0[i] + coef1[j] = -coef1[i] + dfs(j) + + ok = False + for i in range(n): + if not visited[i]: + coef0[i] = 0 + coef1[i] = 1 + nodes = [] + dfs(i) + c0 = 0 + c1 = 0 + for j in nodes: + c0 += coef0[j] + c1 += coef1[j] + ok = ok or c1 != 0; + if ok: + print("YES") + else: + print("NO") + +main() diff --git a/new_data/test/1950_A.jsonl b/new_data/test/1950_A.jsonl new file mode 100644 index 0000000..96026dc --- /dev/null +++ b/new_data/test/1950_A.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n1 2 3\n3 2 1\n1 5 3\n3 4 1\n0 0 0\n4 1 7\n4 5 7", "output": "STAIR\nNONE\nPEAK\nPEAK\nNONE\nNONE\nSTAIR"} +{"input": "3\n1 2 3\n3 2 1\n2 2 2", "output": "STAIR\nNONE\nNONE"} +{"input": "1\n0 0 0", "output": "NONE"} +{"input": "2\n1 9 5\n5 9 1", "output": "PEAK\nPEAK"} +{"input": "4\n4 5 4\n5 4 5\n2 2 1\n3 4 3", "output": "PEAK\nNONE\nNONE\nPEAK"} +{"input": "1\n7 8 9", "output": "STAIR"} +{"input": "3\n0 5 10\n6 4 3\n8 9 8", "output": "STAIR\nNONE\nPEAK"} +{"input": "5\n9 8 9\n3 3 4\n4 4 3\n0 1 2\n7 6 5", "output": "NONE\nNONE\nNONE\nSTAIR\nNONE"} +{"input": "2\n0 1 0\n5 6 7", "output": "PEAK\nSTAIR"} +{"input": "2\n2 7 2\n9 5 3", "output": "PEAK\nNONE"} +{"input": "10\n6 7 8\n8 7 6\n1 3 2\n2 2 3\n5 3 8\n0 0 2\n4 5 6\n6 5 4\n7 5 5\n9 1 9", "output": "STAIR\nNONE\nPEAK\nNONE\nNONE\nNONE\nSTAIR\nNONE\nNONE\nNONE"} diff --git a/new_data/test/1950_A.py b/new_data/test/1950_A.py new file mode 100644 index 0000000..8bd5b43 --- /dev/null +++ b/new_data/test/1950_A.py @@ -0,0 +1,13 @@ +n = int(input()) + +for _ in range(n): + arr = list(map(int, input().split())) + + if arr[0] > arr[1]: + print('NONE') + elif arr[1] > arr[2]: + print('PEAK') + elif arr[1] < arr[2]: + print('STAIR') + else: + print('NONE') \ No newline at end of file diff --git a/new_data/test/1950_A_1.py b/new_data/test/1950_A_1.py new file mode 100644 index 0000000..6109834 --- /dev/null +++ b/new_data/test/1950_A_1.py @@ -0,0 +1,10 @@ +n = int(input()) +for _ in range(n): + a,b,c = map(int,input().split()) + if a < b: + if b < c: + print("STAIR") + else: + print("PEAK") + else: + print("NONE") \ No newline at end of file diff --git a/new_data/test/1950_C.jsonl b/new_data/test/1950_C.jsonl new file mode 100644 index 0000000..413a581 --- /dev/null +++ b/new_data/test/1950_C.jsonl @@ -0,0 +1,11 @@ +{"input": "11\n09:41\n18:06\n12:14\n00:59\n00:00\n14:34\n01:01\n19:07\n11:59\n12:00\n21:37", "output": "09:41 AM\n06:06 PM\n12:14 PM\n12:59 AM\n12:00 AM\n02:34 PM\n01:01 AM\n07:07 PM\n11:59 AM\n12:00 PM\n09:37 PM"} +{"input": "1\n00:00", "output": "12:00 AM"} +{"input": "1\n12:00", "output": "12:00 PM"} +{"input": "1\n23:59", "output": "11:59 PM"} +{"input": "1\n13:00", "output": "01:00 PM"} +{"input": "1\n01:01", "output": "01:01 AM"} +{"input": "1\n11:59", "output": "11:59 AM"} +{"input": "1\n05:00", "output": "05:00 AM"} +{"input": "1\n19:30", "output": "07:30 PM"} +{"input": "1\n22:15", "output": "10:15 PM"} +{"input": "1\n10:10", "output": "10:10 AM"} diff --git a/new_data/test/1950_C.py b/new_data/test/1950_C.py new file mode 100644 index 0000000..8814d07 --- /dev/null +++ b/new_data/test/1950_C.py @@ -0,0 +1,23 @@ +lista = [] +t = int(input()) +for i in range(t): + hora = input().split(':') + hora_int = int(hora[0]) + if hora_int == 0: + completa = f"{12}:{hora[1]} AM" + lista.append(completa) + elif hora_int > 0 and hora_int < 12: + if hora_int > 9: + completa = f"{hora_int}:{hora[1]} AM" + else: + completa = f"0{hora_int}:{hora[1]} AM" + lista.append(completa) + elif hora_int == 12: + completa = f"{hora_int}:{hora[1]} PM" + lista.append(completa) + else: + completa = f"0{hora_int - 12}:{hora[1]} PM" + lista.append(completa) + +for a in range(len(lista)): + print(lista[a]) diff --git a/new_data/test/1950_C_1.py b/new_data/test/1950_C_1.py new file mode 100644 index 0000000..569dab7 --- /dev/null +++ b/new_data/test/1950_C_1.py @@ -0,0 +1,23 @@ +lista = [] +t = int(input()) +for i in range(t): + hora = input().split(':') + hora_int = int(hora[0]) + if hora_int == 0: + completa = f"{12}:{hora[1]} AM" + lista.append(completa) + elif hora_int > 0 and hora_int < 12: + if hora_int > 9: + completa = f"{hora_int}:{hora[1]} AM" + else: + completa = f"0{hora_int}:{hora[1]} AM" + lista.append(completa) + elif hora_int >= 12 and hora_int < 13: + completa = f"{hora_int}:{hora[1]} PM" + lista.append(completa) + else: + completa = f"0{hora_int - 12}:{hora[1]} PM" + lista.append(completa) + +for a in range(len(lista)): + print(lista[a]) diff --git a/new_data/test/1951_A.jsonl b/new_data/test/1951_A.jsonl new file mode 100644 index 0000000..b26c092 --- /dev/null +++ b/new_data/test/1951_A.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n10\n1101010110\n10\n1001001110\n6\n000000\n1\n1\n12\n111111111111", "output": "YES\nNO\nYES\nNO\nYES"} +{"input": "3\n10\n0000000000\n10\n0101010101\n10\n1010101010", "output": "YES\nNO\nNO"} +{"input": "2\n5\n10001\n5\n11001", "output": "YES\nNO"} +{"input": "2\n8\n11101110\n8\n00010000", "output": "YES\nNO"} +{"input": "5\n50\n11111111111111111111111111111111111111111111111111\n15\n101010101010101\n20\n01010101010101010101\n12\n001010101010\n13\n0001100000000", "output": "YES\nYES\nYES\nNO\nNO"} +{"input": "1\n2\n01", "output": "NO"} +{"input": "4\n6\n000001\n6\n111111\n8\n00000000\n9\n111111111", "output": "NO\nYES\nYES\nNO"} +{"input": "3\n7\n1011101\n7\n1000000\n7\n0000001", "output": "NO\nNO\nNO"} +{"input": "2\n5\n00100\n5\n11011", "output": "NO\nYES"} +{"input": "3\n15\n101011101010111\n15\n010101010101010\n15\n111000111000111", "output": "YES\nNO\nNO"} +{"input": "1\n1\n0", "output": "YES"} diff --git a/new_data/test/1951_A.py b/new_data/test/1951_A.py new file mode 100644 index 0000000..1d41062 --- /dev/null +++ b/new_data/test/1951_A.py @@ -0,0 +1,14 @@ +import sys +input = sys.stdin.readline + +t = int(input()) +for _ in range(t): + n = int(input()) + a = input() + x=a.count('1') + # print(x) + if not x&1 or x==0: + print("Yes") + else: + print("No") + diff --git a/new_data/test/1951_A_1.py b/new_data/test/1951_A_1.py new file mode 100644 index 0000000..c669cbc --- /dev/null +++ b/new_data/test/1951_A_1.py @@ -0,0 +1,10 @@ +t = int(input()) +for i in range(t): + n = int(input()) + s = input() + count_ones = s.count('1') + + if count_ones % 2 == 1: + print("NO") + else: + print("YES") diff --git a/new_data/test/1951_B.jsonl b/new_data/test/1951_B.jsonl new file mode 100644 index 0000000..9b06aae --- /dev/null +++ b/new_data/test/1951_B.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n6 1\n12 10 14 11 8 3\n6 5\n7 2 727 10 12 13\n2 2\n1000000000 1", "output": "1\n2\n0"} +{"input": "1\n2 1\n2 1", "output": "1"} +{"input": "1\n3 3\n3 1 2", "output": "1"} +{"input": "1\n5 5\n1 3 5 2 4", "output": "2"} +{"input": "1\n4 2\n10 20 30 40", "output": "1"} +{"input": "1\n7 4\n15 5 25 35 45 55 65", "output": "3"} +{"input": "1\n6 3\n10000000 9999999 3 2 1 4", "output": "0"} +{"input": "1\n8 6\n3 6 8 20 14 16 10 12", "output": "2"} +{"input": "1\n10 9\n25 30 10 15 20 35 40 45 5 50", "output": "0"} +{"input": "1\n9 1\n1000000000 1 999999998 999999997 999999996 999999995 999999994 999999993 999999992", "output": "8"} +{"input": "1\n5 2\n9 5 6 7 8", "output": "0"} diff --git a/new_data/test/1951_B.py b/new_data/test/1951_B.py new file mode 100644 index 0000000..1f42787 --- /dev/null +++ b/new_data/test/1951_B.py @@ -0,0 +1,45 @@ +def position_wins( + n, # number of cows + k, # cow position + v # cow value +): + curr_wins = 0 + if k > 0 and k < n - 1: + curr_wins += 1 if a[k - 1] < v else 0 + curr_wins += 1 if a[k + 1] < v else 0 + elif k == 0: + curr_wins += 1 if a[k + 1] < v else 0 + elif k == n: + curr_wins += 1 if a[k - 1] < v else 0 + return curr_wins + + +t = int(input()) + +for _ in range(t): + test_case = input().split(" ") + n = int(test_case[0]) + k = int(test_case[1]) - 1 + a = list(map(int, input().split(" "))) + + curr_pos = 0 + wins = 0 + + curr_wins = position_wins(n, k, a[k]) + greater_cows = list(filter(lambda x: x > a[k], a)) + pos_first_g_c = a.index(greater_cows[0]) if greater_cows else n - 1 + g_n_wins = position_wins(n, pos_first_g_c, a[k]) if pos_first_g_c < k else 0 + candidate_cows_curr = list(filter(lambda x: a.index(x) < pos_first_g_c, a)) + + a[pos_first_g_c], a[k] = a[k], a[pos_first_g_c] + greater_cows = list(filter(lambda x: x > a[pos_first_g_c], a)) + before_pos_first_g_c = pos_first_g_c + pos_first_g_c = a.index(greater_cows[0]) if greater_cows else n - 1 + candidate_cows_with_change = list( + filter(lambda x: a.index(x) < pos_first_g_c and a.index(x) > before_pos_first_g_c, a)) + + change_pos_wins = (len(candidate_cows_with_change) or 1) + g_n_wins - 1 + curr_pos_wins = (len(candidate_cows_curr) or 1) - 1 + (curr_wins - 1) + wins = max(curr_pos_wins, change_pos_wins, curr_wins, g_n_wins) + + print(wins) \ No newline at end of file diff --git a/new_data/test/1951_B_1.py b/new_data/test/1951_B_1.py new file mode 100644 index 0000000..4593bb6 --- /dev/null +++ b/new_data/test/1951_B_1.py @@ -0,0 +1,50 @@ +from sys import stdin + +res = [] +i = 0 +l = "" + +for ligne in stdin: + + if i == 0: + nb_test = int(ligne) + + elif i % 2 == 1: + l = ligne.split() + + else: + vaches = ligne.split() + for j in range(len(vaches)): + vaches[j] = int(vaches[j]) + + k = int(l[1]) + val_vache = vaches[k - 1] + inversion = False + i_sup_vache = None + + for j in range(len(vaches)): + if vaches[j] > val_vache: + i_sup_vache = j + if i_sup_vache < (k - 1): + inversion = True + break + + if inversion: + vaches[k - 1], vaches[i_sup_vache] = vaches[i_sup_vache], vaches[k - 1] + k = i_sup_vache + 1 + + res = 0 + + if k > 1: + if vaches[k - 1] > vaches[k - 2]: + res += 1 + + for j in range(k - 1, len(vaches) - 1): + if vaches[j] > vaches[j + 1]: + res += 1 + else: + break + + print(res) + + i += 1 \ No newline at end of file diff --git a/new_data/test/1951_C.jsonl b/new_data/test/1951_C.jsonl new file mode 100644 index 0000000..d10e1c0 --- /dev/null +++ b/new_data/test/1951_C.jsonl @@ -0,0 +1,11 @@ +{"input": "1\n5 1 5\n10 9 8 7 6", "output": "50"} +{"input": "1\n1 1 1\n10", "output": "10"} +{"input": "1\n2 1 2\n1 2", "output": "4"} +{"input": "2\n3 2 2\n1 3 8\n3 2 4\n3 1 4", "output": "2\n12"} +{"input": "2\n2 5 5\n2 2\n2 5 8\n1 999999999", "output": "10\n3000000017"} +{"input": "2\n5 100 1\n10000 1 100 10 1000\n6 3 9\n5 5 5 5 5 5", "output": "1\n72"} +{"input": "3\n3 3 3\n100 100 100\n3 1 3\n1 2 3\n3 1 2\n3 3 3", "output": "300\n9\n7"} +{"input": "2\n5 1 1\n1 2 3 4 5\n5 1 5\n5 4 3 2 1", "output": "1\n25"} +{"input": "2\n3 5 15\n1 1 1\n3 5 14\n2 2 2", "output": "90\n93"} +{"input": "3\n4 2 4\n8 4 8 4\n3 3 8\n1 9 1\n3 3 9\n5 5 5", "output": "20\n45\n72"} +{"input": "2\n3 10 10\n999999999 999999999 999999999\n3 10 30\n100 100 100", "output": "9999999990\n3300"} diff --git a/new_data/test/1951_C.py b/new_data/test/1951_C.py new file mode 100644 index 0000000..416caf8 --- /dev/null +++ b/new_data/test/1951_C.py @@ -0,0 +1,42 @@ +t = int(input()) + +for _ in range(t): + n, m, k = map(int, input().split()) + a = list(map(int, input().split())) + k_cpy = k + + a_original = a + + a.sort() + dic = {} + fac = 0 + + for ele in a: + # if ele in dic: + # fac+=1 + # ele=ele+dic[ele]*fac + # else: + # fac=0 + if k >= m: + dic[ele] = m + k = k - m + else: + dic[ele] = k + k = k - k + if k == 0: + break + + x, price = 0, 0 + for elem in a_original: + if x >= k_cpy: + break + if elem not in dic: + continue + else: + val = elem + x + x += dic[elem] + + mapvalue = dic[elem] + price += val * mapvalue + + print(price) \ No newline at end of file diff --git a/new_data/test/1951_C_1.py b/new_data/test/1951_C_1.py new file mode 100644 index 0000000..89c286f --- /dev/null +++ b/new_data/test/1951_C_1.py @@ -0,0 +1,42 @@ +from math import ceil +n= int(input()) +for i in range(n): + n,m,k = map(int, input().split()) + a=list(map(int, input().split())) + if k<=m: + print(min(a)*k) + else: + if k%m==0: + s=set(sorted(a)[:k//m]) + b=[] + leng=0 + for i in range(n): + if a[i] in s and leng bit_count: + if n >= k: + x = n - k + 1 + if x <= n // 2: + print("NO") + else: + print("YES") + print(2) + print(x, 1) + else: + print("NO") + else: + bits = [] + for i in reversed(range(n.bit_length())): + if (n >> i) & 1: + bits.append(i) + mer = bit_count - k + 1 + fir = 0 + for i in range(mer): + fir += (1 << bits[i]) + ans = [fir] + [(1 << b) for b in bits[mer:]] + print("YES") + print(len(ans)) + print(' '.join(map(str, ans))) + +if __name__ == "__main__": + solve() \ No newline at end of file diff --git a/new_data/test/1951_D_1.py b/new_data/test/1951_D_1.py new file mode 100644 index 0000000..e58cee9 --- /dev/null +++ b/new_data/test/1951_D_1.py @@ -0,0 +1,75 @@ +import sys + +def solve(): + t = int(sys.stdin.readline()) + for _ in range(t): + n, k = map(int, sys.stdin.readline().split()) + if k > n: + print("NO") + continue + if k == 0: + print("NO") + continue + if k == n: + print("YES") + print(1) + print(1) + continue + if k == 1: + print("YES") + print(1) + print(n) + continue + if k <= 60: + p = [] + remaining = n + sum_q = 0 + possible = True + for i in range(k): + if remaining <= 0: + break + p_i = (remaining + 1) // 2 + q_i = remaining // p_i + sum_q += q_i + if sum_q > k: + possible = False + break + p.append(p_i) + remaining = remaining % p_i + if possible and sum_q == k: + print("YES") + print(len(p)) + print(' '.join(map(str, p))) + else: + found = False + low = (n // (k + 1)) + 1 + high = n // k + if low <= high: + p_candidate = high + if p_candidate > 0 and (n // p_candidate) == k: + print("YES") + print(1) + print(p_candidate) + found = True + if not found: + print("NO") + else: + low = (n // (k + 1)) + 1 + high = n // k + if low > high: + print("NO") + else: + p_candidate = high + if p_candidate <= 0: + print("NO") + continue + q_candidate = n // p_candidate + if q_candidate == k: + print("YES") + print(1) + print(p_candidate) + else: + print("NO") + +if __name__ == "__main__": + solve() diff --git a/new_data/test/1955_A.jsonl b/new_data/test/1955_A.jsonl new file mode 100644 index 0000000..27ac4f9 --- /dev/null +++ b/new_data/test/1955_A.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n2 5 9\n3 5 9\n3 5 11\n4 5 11", "output": "9\n14\n15\n20"} +{"input": "1\n1 1 2", "output": "1"} +{"input": "1\n99 1 2", "output": "99"} +{"input": "1\n100 30 30", "output": "1500"} +{"input": "1\n1 15 1", "output": "15"} +{"input": "1\n4 10 30", "output": "40"} +{"input": "1\n2 7 14", "output": "14"} +{"input": "1\n3 10 15", "output": "25"} +{"input": "1\n6 3 5", "output": "15"} +{"input": "1\n10 5 8", "output": "40"} +{"input": "1\n50 1 50", "output": "50"} diff --git a/new_data/test/1955_A.py b/new_data/test/1955_A.py new file mode 100644 index 0000000..f599ff8 --- /dev/null +++ b/new_data/test/1955_A.py @@ -0,0 +1,8 @@ +for i in range(int(input())): + n, a, b = list(map(int, input().split())) + + if a * 2 >= b: + cost = b*n//2 + a*n%2 + else: cost = a*n + + print(cost) \ No newline at end of file diff --git a/new_data/test/1955_A_1.py b/new_data/test/1955_A_1.py new file mode 100644 index 0000000..11770a6 --- /dev/null +++ b/new_data/test/1955_A_1.py @@ -0,0 +1,18 @@ +t = int(input()) +for i in range(t): + n,a,b = map(int, input().split()) + if n == a == b: + print(a) + elif n < a > b: + print(a) + elif a*2 > b: + o = 0 + k_op = n//2 + o += b + if n%2 == 0: + o = o + else: + o += a + print(o) + else: + print(n*a) \ No newline at end of file diff --git a/new_data/test/1955_B.jsonl b/new_data/test/1955_B.jsonl new file mode 100644 index 0000000..6df0ad8 --- /dev/null +++ b/new_data/test/1955_B.jsonl @@ -0,0 +1,10 @@ +{"input": "1\n2 2 2\n1 2 3 4", "output": "no"} +{"input": "1\n3 3 3\n3 9 15 6 12 18 9 15 21", "output": "no"} +{"input": "1\n4 5 5\n5 10 15 20 10 15 20 25 15 20 25 30 20 25 30 35", "output": "yes"} +{"input": "1\n5 1000000 1000000\n1000000 2000000 3000000 4000000 5000000 2000000 3000000 4000000 5000000 6000000 3000000 4000000 5000000 6000000 7000000 4000000 5000000 6000000 7000000 8000000 5000000 6000000 7000000 8000000 9000000", "output": "yes"} +{"input": "2\n3 1 2\n1 3 2 4 5 6 7 8 9\n2 4 10\n1 12 14 9", "output": "no\nno"} +{"input": "3\n3 5 5\n15 25 35 25 35 45 35 45 55\n4 10 10\n10 20 30 40 20 30 40 50 30 40 50 60 40 50 60 70\n2 1 1\n1 3 3 5", "output": "no\nyes\nno"} +{"input": "1\n2 999999 999999\n1999999 2999998 2999998 3999997", "output": "yes"} +{"input": "3\n3 2 2\n2 4 6 4 6 8 6 8 10\n2 7 3\n7 10 14 13\n4 6 4\n30 40 35 45 40 50 45 55 35 45 40 50 25 35 30 40", "output": "yes\nno\nno"} +{"input": "1\n3 1 1\n1 2 3 2 3 4 3 4 5", "output": "yes"} +{"input": "2\n5 5 5\n5 10 15 20 25 10 15 20 25 30 15 20 25 30 35 20 25 30 35 40 25 30 35 40 45\n3 2 6\n8 20 32 26 44 38 50 62 74", "output": "yes\nno"} diff --git a/new_data/test/1955_B.py b/new_data/test/1955_B.py new file mode 100644 index 0000000..1b080af --- /dev/null +++ b/new_data/test/1955_B.py @@ -0,0 +1,28 @@ +u = int(input()) +for _ in range(u): + n1 = list(map(int, input().split())) + l = list(map(int, input().split())) + m=l.copy() + n=n1[0] + c=n1[1] + d=n1[2] + i=min(l) + a=0 + if n>400: + print('YES') + else: + while a= M[0]: + print(1) + else: + print(0) + continue + if len(list(set(M))) == 1: + if k >= M[0] * n: + print(n) + else: + if k >= M[0] * 2: + a = (k // (M[0] * 2)) * 2 + if k % M[0] != k - 1: + print(a) + else: + print(a + 1) + elif k == M[0] * 2 - 1: + print(1) + else: + print(0) + continue + count = 0 + while k > 0 and len(M) > 0: + if len(M) > 1: + q = min(M[0], M[-1]) + if 2 * q <= k: + k -= 2 * q + if M[0] == M[-1]: + count += 2 + else: + count += 1 + M[0] -= q + M[-1] -= q + elif 2 * q - 1 == k: + if M[0] <= M[-1]: + k -= 2 * q - 1 + count += 1 + break + else: + break + else: + break + if M[0] == 0: + M.pop(0) + if M[-1] == 0: + M.pop() + else: + if M[0] <= k: + count += 1 + break + print(count) + continue + + + + diff --git a/new_data/test/1955_C_1.py b/new_data/test/1955_C_1.py new file mode 100644 index 0000000..e478276 --- /dev/null +++ b/new_data/test/1955_C_1.py @@ -0,0 +1,24 @@ +u = int(input()) +for _ in range(u): + n1 = list(map(int, input().split())) + l = list(map(int, input().split())) + n=n1[0] + k=n1[1] + if k>sum(l): + ans=n + elif n>1000 and l[0]+l[-1]>k: + ans=0 + else: + i=1 + while i<=k: + if i%2==1: + l[0]=l[0]-1 + if l[0]==0: + l.pop(0) + else: + l[-1]=l[-1]-1 + if l[-1]==0: + l.pop() + i+=1 + ans=n-len(l) + print(ans) \ No newline at end of file diff --git a/new_data/test/1955_D.jsonl b/new_data/test/1955_D.jsonl new file mode 100644 index 0000000..b6f15a6 --- /dev/null +++ b/new_data/test/1955_D.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n7 4 2\n4 1 2 3 4 5 6\n1 2 3 4\n7 4 3\n4 1 2 3 4 5 6\n1 2 3 4\n7 4 4\n4 1 2 3 4 5 6\n1 2 3 4\n11 5 3\n9 9 2 2 10 9 7 6 3 6 3\n6 9 7 8 10\n4 1 1\n4 1 5 6\n6", "output": "4\n3\n2\n4\n1"} +{"input": "1\n5 2 1\n5 6 5 6 7\n5 7", "output": "4"} +{"input": "1\n10 5 3\n4 4 4 4 4 4 4 4 4 4\n4 3 4 1 4", "output": "6"} +{"input": "1\n6 3 3\n1 2 3 4 5 6\n1 2 3", "output": "1"} +{"input": "1\n8 4 2\n3 3 3 3 3 3 3 3\n3 4 5 6", "output": "0"} +{"input": "1\n4 4 3\n1000000 999999 999998 999997\n1000000 999999 999998 999997", "output": "1"} +{"input": "1\n9 3 1\n10 9 8 9 10 8 7 6 5\n7 8 9", "output": "7"} +{"input": "1\n10 5 5\n1 1 1 1 1 1 1 1 1 1\n1 1 1 1 1", "output": "6"} +{"input": "1\n6 3 2\n4 5 6 4 5 6\n5 6 7", "output": "4"} +{"input": "1\n12 4 3\n7 8 9 10 11 12 13 14 15 16 17 18\n8 9 10 11", "output": "3"} +{"input": "1\n15 6 3\n3 3 3 3 3 3 3 3 3 4 4 4 4 4 4\n4 3 3 3 4 4", "output": "10"} diff --git a/new_data/test/1955_D.py b/new_data/test/1955_D.py new file mode 100644 index 0000000..7489ba8 --- /dev/null +++ b/new_data/test/1955_D.py @@ -0,0 +1,36 @@ +import time +from collections import defaultdict + + +def h(x): + x += int(time.time()) + x += 0x9e3779b97f4a7c15 + x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9 + x = (x ^ (x >> 27)) * 0x94d049bb133111eb + return x ^ (x >> 31) + + +for _ in range(int(input())): + n, m, k = map(int, input().split()) + a = list(map(int, input().split())) + b = list(map(int, input().split())) + + a_map = defaultdict(int) + b_map = defaultdict(int) + for x in b: + b_map[h(x)] += 1 + + good = 0 + count = 0 + for i in range(n): + if i >= m: + a_map[h(a[i - m])] -= 1 + if a_map.get(h(a[i - m]), 0) < b_map.get(h(a[i - m]), 0): + count -= 1 + if a_map.get(h(a[i]), 0) < b_map.get(h(a[i]), 0): + count += 1 + a_map[h(a[i])] += 1 + if i >= m - 1 and count >= k: + good += 1 + + print(good) diff --git a/new_data/test/1955_D_1.py b/new_data/test/1955_D_1.py new file mode 100644 index 0000000..c38a4c6 --- /dev/null +++ b/new_data/test/1955_D_1.py @@ -0,0 +1,53 @@ +for i in range(int(input())): + n,m,k=map(int,input().split()) + A=list(map(int,input().split())) + B=list(map(int,input().split())) + U=[False for j in range(n)] + S=dict() + for j in range(m): + if B[j] in S: + S[B[j]]+=1 + else: + S[B[j]]=1 + size=m + D=dict() + for j in range(m): + if A[j] in S: + if S[A[j]]: + S[A[j]]-=1 + size-=1 + U[j]=True + else: + if A[j] in D: + D[A[j]].append(j) + else: + D[A[j]]=[j] + else: + if A[j] in D: + D[A[j]].append(j) + else: + D[A[j]]=[j] + ans=int(size<=m-k) + for j in range(1,n-m+1): + if U[j-1]: + U[j-1]=False + S[A[j-1]]+=1 + size+=1 + if A[j-1] in D: + if D[A[j-1]]: + U[D[A[j-1]].pop()]=True + size-=1 + S[A[j-1]]-=1 + if A[j+m-1] in S: + if S[A[j+m-1]]: + S[A[j+m-1]]-=1 + size-=1 + U[j+m-1]=True + else: + if A[j+m-1] in D: + D[A[j+m-1]].append(j+m-1) + else: + D[A[j+m-1]]=[j+m-1] + if size<=m-k: + ans+=1 + print(ans) \ No newline at end of file diff --git a/new_data/test/1955_F.jsonl b/new_data/test/1955_F.jsonl new file mode 100644 index 0000000..c962b1e --- /dev/null +++ b/new_data/test/1955_F.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n1 1 1 0\n1 0 1 2\n2 2 2 0\n3 3 2 0\n0 9 9 9", "output": "1\n1\n3\n3\n12"} +{"input": "1\n0 0 0 0", "output": "0"} +{"input": "1\n1 0 0 0", "output": "0"} +{"input": "1\n0 1 0 0", "output": "0"} +{"input": "1\n0 0 1 0", "output": "0"} +{"input": "1\n0 0 0 1", "output": "0"} +{"input": "1\n1 1 1 1", "output": "1"} +{"input": "1\n2 2 2 2", "output": "4"} +{"input": "1\n199 0 0 0", "output": "99"} +{"input": "1\n0 199 0 0", "output": "99"} +{"input": "1\n0 0 199 0", "output": "99"} diff --git a/new_data/test/1955_F.py b/new_data/test/1955_F.py new file mode 100644 index 0000000..52dc47f --- /dev/null +++ b/new_data/test/1955_F.py @@ -0,0 +1,26 @@ +import sys + +def main(): + t = int(sys.stdin.readline()) + for _ in range(t): + a, b, c, d = map(int, sys.stdin.readline().split()) + # Calculate parities of each count + p1 = a % 2 + p2 = b % 2 + p3 = c % 2 + p4 = d % 2 + # Compute the initial XOR based on parities + initial_xor = p1 * 1 ^ p2 * 2 ^ p3 * 3 ^ p4 * 4 + # Calculate sum of floor division by 2 for each count + s = (a // 2) + (b // 2) + (c // 2) + (d // 2) + # Determine the answer based on initial XOR and s + if initial_xor == 0: + if s == 0: + print(1) + else: + print(s) + else: + print(s) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/new_data/test/1955_F_1.py b/new_data/test/1955_F_1.py new file mode 100644 index 0000000..3dbf836 --- /dev/null +++ b/new_data/test/1955_F_1.py @@ -0,0 +1,7 @@ +t = int(input()) +for i in range(0, t): + ones, twos, threes, fours = map(int, input().split()) + tot = ones // 2 + twos // 2 + threes // 2 + fours // 2 + if ones % 2 == 1 and twos % 2 == 1 and threes % 2 == 1: + tot += (fours // 2) + 1 + print(tot) \ No newline at end of file diff --git a/new_data/test/1956_B.jsonl b/new_data/test/1956_B.jsonl new file mode 100644 index 0000000..6efa47f --- /dev/null +++ b/new_data/test/1956_B.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n4\n1 1 2 3\n8\n7 4 1 2 8 8 5 5\n8\n7 1 4 5 3 4 2 6\n3\n1 2 3\n1\n1", "output": "1\n2\n1\n0\n0"} +{"input": "1\n1\n1", "output": "0"} +{"input": "1\n3\n1 2 3", "output": "0"} +{"input": "1\n4\n1 1 2 3", "output": "1"} +{"input": "1\n4\n2 2 3 4", "output": "1"} +{"input": "1\n5\n1 1 2 5 5", "output": "2"} +{"input": "2\n3\n1 1 2\n3\n1 2 2", "output": "1\n1"} +{"input": "3\n4\n1 2 3 4\n4\n1 1 3 3\n4\n2 3 4 4", "output": "0\n2\n1"} +{"input": "2\n6\n1 2 2 3 6 6\n6\n1 1 2 4 5 5", "output": "2\n2"} +{"input": "2\n5\n2 3 3 4 5\n7\n2 2 3 6 6 7 1", "output": "1\n2"} +{"input": "3\n5\n1 2 2 3 4\n5\n5 5 4 3 3\n5\n1 1 2 5 3", "output": "1\n2\n1"} diff --git a/new_data/test/1956_B.py b/new_data/test/1956_B.py new file mode 100644 index 0000000..0e3af12 --- /dev/null +++ b/new_data/test/1956_B.py @@ -0,0 +1,12 @@ +from collections import Counter + + +t = int(input()) +for _ in range(t): + n = int(input()) + a = (int(i) for i in input().split()) + cnt = Counter(a) + bth = sum(v == 2 for v in cnt.values()) + one = len(cnt) - bth + res = n if bth > one else bth + print(res) diff --git a/new_data/test/1956_B_1.py b/new_data/test/1956_B_1.py new file mode 100644 index 0000000..37ac55e --- /dev/null +++ b/new_data/test/1956_B_1.py @@ -0,0 +1,11 @@ +t=int(input("")) +for _ in range(t): + n=input("") + ans=0 + x=list(map(int,input("").split())) + for y in x: + x.remove(y) + if y in x: + ans+=1 + x.remove(y) + print(ans) diff --git a/new_data/test/1956_D.jsonl b/new_data/test/1956_D.jsonl new file mode 100644 index 0000000..35b65ad --- /dev/null +++ b/new_data/test/1956_D.jsonl @@ -0,0 +1,11 @@ +{"input": "2\n0 1", "output": "4 1\n1 2\nInput\n3\n1 3 9\nOutput\n13 0\nInput\n4\n1 100 2 1\nOutput\n105 2\n3 3\n3 4\nInput\n1\n0\nOutput\n1 1\n1 1"} +{"input": "1\n0", "output": "1 1\n1 1"} +{"input": "2\n7 7", "output": "14 0"} +{"input": "3\n10 9 8", "output": "27 0"} +{"input": "4\n0 1 2 3", "output": "16 1\n1 4"} +{"input": "5\n5 0 0 5 5", "output": "25 32\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5"} +{"input": "6\n3 1 4 1 5 9", "output": "36 62\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6"} +{"input": "7\n1 1 1 0 0 1 1", "output": "49 126\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7"} +{"input": "8\n9 8 7 6 5 4 3 2", "output": "64 256\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8"} +{"input": "9\n0 0 0 0 0 0 0 0 0", "output": "81 511\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 9\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 9"} +{"input": "10\n1 3 2 4 5 2 1 0 6 7", "output": "100 1020\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 9\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 10\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 9\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 8\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 7\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 6\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 5\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 4\n1 1\n1 2\n1 1\n1 3\n1 1\n1 2\n1 1\n1 10"} diff --git a/new_data/test/1956_D.py b/new_data/test/1956_D.py new file mode 100644 index 0000000..7dde374 --- /dev/null +++ b/new_data/test/1956_D.py @@ -0,0 +1,51 @@ +def getMaxable(lst): + r = l = 0 + over_sum = sum(lst) + for i in range(len(lst)): + for j in range(i + 1, len(lst)): + sm = sum(lst[:i]) + sum(lst[j+1:]) + (j - i + 1) ** 2 + if sm > over_sum: + r, l = [i, j] + over_sum = sm + return r, l + + +def addOps(r, l, ops: list): + if r == l: + ops.append([r + 1, l + 1]) + return + addOps(r, l - 1, ops) + ops.append([r + 1, l + 1]) + addOps(r, l - 1, ops) + + +def doOps(r, l, lst: list, ops: list): + ops.append([r + 1, l + 1]) + if min(lst[r:l + 1]) == 0: + ops.append([r + 1, l + 1]) + ops.append([r + 1, r + 1]) + addOps(r, l, ops) + ops.append([r + 1, l + 1]) + n = l - r + 1 + lst[r:l + 1] = [n for _ in range(n)] + return lst + + +input() +lst = list(map(int, input().split())) + +ops = [] +r, l = getMaxable(lst) +while r != l: + lst = doOps(r, l, lst, ops) + r, l = getMaxable(lst) +try: + while True: + i = lst.index(0) + 1 + lst[i - 1] = 1 + ops.append([i, i]) +except ValueError: + pass +print(sum(lst), len(ops)) +for r in ops: + print(*r) \ No newline at end of file diff --git a/new_data/test/1956_D_1.py b/new_data/test/1956_D_1.py new file mode 100644 index 0000000..82d21cf --- /dev/null +++ b/new_data/test/1956_D_1.py @@ -0,0 +1,95 @@ +# import sys +# sys.stdin = open("input.txt", "r") +# sys.stdout = open("output.txt", "w") +# code starts below +###### +###### +##### + +arr = [] +flag = [] +ops = [] + + +def main(): + n = int(input()) + for i in input().split(): + arr.append(int(i)) + flag.append(False) + + # mark every element possible for improvement + for i in range(n): + for j in range(i, n): + k = j - i + 1 + if sum(arr[i:j + 1]) < k * k: + for idx in range(i, j + 1): + flag[idx] = True + + # lets get the connected compoenents in array + on = False + l, r = -1, -1 + for idx, i in enumerate(flag): + if not on and i: + on = True + l = idx + if on and not i: + r = idx - 1 + on = False + # process l...r + mex_max(l, r) + l, r = -1, -1 + # if end with on , process everything left + if on: + mex_max(l, n - 1) + print(sum(arr), len(ops)) + for l, r in ops: + print(l + 1, r + 1) + + +def mex_seq(l, r): + """converts the subarray arr[l:r+1] to 0,1,...k-1""" + # base case k=1 + k = r - l + 1 + if k == 1: + if arr[l] != 0: + ops.append((l, l)) + arr[l] = 0 + return + + # if k >= 2 + mex_max(l + 1, r) + mex_seq(l, r - 1) + + +def mex_max(l, r): + """converts the subarray arr[l:r+1] to k,k,k,..""" + + # base case where k = 1 + k = r - l + 1 + if k == 1: + mex_seq(l, l) + mex_op(l, l) + return + + # if k >= 2 + mex_max(l + 1, r) + mex_seq(l, r - 1) + mex_op(l, r) + + +def mex_op(l, r): + ops.append((l, r)) + s = set(arr[l:r + 1]) + mex = -1 + for i in range(100): + if i not in s: + mex = i + break + + for i in range(l, r + 1): + arr[i] = mex + return arr + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/new_data/test/1965_A.jsonl b/new_data/test/1965_A.jsonl new file mode 100644 index 0000000..f90f101 --- /dev/null +++ b/new_data/test/1965_A.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n5\n3 3 3 3 3\n2\n1 7\n7\n1 3 9 7 4 2 100\n3\n1 2 3\n6\n2 1 3 4 2 4\n8\n5 7 2 9 6 3 3 2\n1\n1000000000", "output": "Alice\nBob\nAlice\nAlice\nBob\nAlice\nAlice"} +{"input": "1\n1\n999999999", "output": "Alice"} +{"input": "1\n2\n1000000000 1", "output": "Bob"} +{"input": "2\n3\n5 5 5\n2\n2 3", "output": "Alice\nAlice"} +{"input": "1\n5\n8 8 8 8 8", "output": "Alice"} +{"input": "1\n6\n1 1 1 1 1 1", "output": "Alice"} +{"input": "1\n4\n1 3 5 7", "output": "Bob"} +{"input": "1\n6\n10 20 30 40 50 60", "output": "Alice"} +{"input": "1\n3\n300000000 300000000 299999999", "output": "Alice"} +{"input": "1\n1\n2", "output": "Alice"} +{"input": "1\n10\n1 1 1 1 1 1 1 1 1 10", "output": "Bob"} diff --git a/new_data/test/1965_A.py b/new_data/test/1965_A.py new file mode 100644 index 0000000..b4978ff --- /dev/null +++ b/new_data/test/1965_A.py @@ -0,0 +1,33 @@ +for _ in range(int(input())): + n=int(input()) + lis=list(map(int,input().split())) + lis.sort() + for i in range(n-1,0,-1): + lis[i]-=lis[i-1] + s=1 + i=n-1 + while i>=0 and lis[i]==0: + i-=1 + if i==-1: + print('Alice') + continue + if i==0: + if lis[0]==1: + print('Bob') + else: + print('Alice') + continue + for j in range(i-1,0,-1): + if lis[j]==0: + continue + if lis[j]==1: + s=1-s + else: + continue + if s==1: + if lis[0]>1: + print('Alice') + else: + print('Bob') + else: + print('Alice') \ No newline at end of file diff --git a/new_data/test/1965_A_1.py b/new_data/test/1965_A_1.py new file mode 100644 index 0000000..933cfaf --- /dev/null +++ b/new_data/test/1965_A_1.py @@ -0,0 +1,21 @@ +A = int(input()) +for t in range(A): + n = input() + arr = list(map(int, input().split())) + arr = [x for x in set(arr)] + arr.sort() + ans = 1 + if arr[0] == 1: + for t in range(1, len(arr)): + if arr[t] == arr[t - 1] + 1: + ans += 1 + if ans == len(arr) and len(arr) % 2 == 0: + print("Bob") + elif ans == len(arr): + print("Alice") + elif ans % 2 == 0: + print("Alice") + else: + print("Bob") + else: + print("Alice") diff --git a/new_data/test/1966_B.jsonl b/new_data/test/1966_B.jsonl new file mode 100644 index 0000000..4155255 --- /dev/null +++ b/new_data/test/1966_B.jsonl @@ -0,0 +1,11 @@ +{"input": "8\n2 1\nW\nB\n6 6\nWWWWBW\nWBWWWW\nBBBWWW\nBWWWBB\nWWBWBB\nBBBWBW\n1 1\nW\n2 2\nBB\nBB\n3 4\nBWBW\nWBWB\nBWBW\n4 2\nBB\nBB\nWW\nWW\n4 4\nWWBW\nBBWB\nWWBB\nBBBB\n1 5\nWBBWB", "output": "NO\nYES\nYES\nYES\nYES\nNO\nYES\nNO"} +{"input": "1\n3 3\nWBW\nWBW\nWBW", "output": "YES"} +{"input": "1\n4 4\nWWWW\nWWWW\nWWWW\nWWBB", "output": "YES"} +{"input": "1\n2 3\nBBB\nBWW", "output": "YES"} +{"input": "1\n5 5\nWBWBW\nBWBWB\nWBWBW\nBWBWB\nWBWBW", "output": "YES"} +{"input": "1\n6 1\nB\nB\nW\nB\nW\nB", "output": "YES"} +{"input": "1\n3 3\nBBW\nBWW\nBBB", "output": "YES"} +{"input": "1\n4 4\nBBBB\nWBWB\nWBWB\nBBBB", "output": "YES"} +{"input": "1\n7 7\nWWWWWWW\nWWWWWWW\nWWWWWWW\nWWWWWWW\nWWWWBBB\nWWBBWWW\nWBBBWWW", "output": "YES"} +{"input": "1\n2 5\nWWWWW\nBBBBW", "output": "YES"} +{"input": "1\n5 3\nBBW\nBBW\nBBW\nBBW\nBBW", "output": "NO"} diff --git a/new_data/test/1966_C.jsonl b/new_data/test/1966_C.jsonl new file mode 100644 index 0000000..fdd0861 --- /dev/null +++ b/new_data/test/1966_C.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n5\n3 3 3 3 3\n2\n1 7\n7\n1 3 9 7 4 2 100\n3\n1 2 3\n6\n2 1 3 4 2 4\n8\n5 7 2 9 6 3 3 2\n1\n1000000000", "output": "Alice\nBob\nAlice\nAlice\nBob\nAlice\nAlice"} +{"input": "1\n2\n1 1", "output": "Alice"} +{"input": "1\n4\n10 10 10 10", "output": "Alice"} +{"input": "1\n1\n100", "output": "Alice"} +{"input": "1\n5\n5 5 5 5 5", "output": "Alice"} +{"input": "1\n3\n1 2 1", "output": "Bob"} +{"input": "1\n6\n5 7 5 7 5 7", "output": "Alice"} +{"input": "1\n3\n3 2 1", "output": "Alice"} +{"input": "1\n2\n1000000000 1", "output": "Bob"} +{"input": "1\n8\n1 1 1 1 1 1 1 1", "output": "Alice"} +{"input": "1\n10\n9 8 7 6 5 4 3 2 1 1", "output": "Alice"} diff --git a/new_data/test/1967_B1.jsonl b/new_data/test/1967_B1.jsonl new file mode 100644 index 0000000..8639fa1 --- /dev/null +++ b/new_data/test/1967_B1.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n1 1\n2 3\n3 5\n10 8\n100 1233\n1000000 1145141", "output": "1\n3\n4\n14\n153\n1643498"} +{"input": "1\n1 1", "output": "1"} +{"input": "1\n2 2", "output": "3"} +{"input": "1\n2 8", "output": "3"} +{"input": "2\n3 3\n4 4", "output": "4\n5"} +{"input": "3\n100 1\n1 100\n100 100", "output": "100\n1\n153"} +{"input": "1\n999983 999979", "output": "1643469"} +{"input": "1\n2000000 2000000", "output": "3287832"} +{"input": "1\n1 2000000", "output": "1"} +{"input": "1\n2000000 1", "output": "2000000"} +{"input": "3\n10 20\n1000 500\n123456 654321", "output": "14\n1603\n202570"} diff --git a/new_data/test/1968_B.jsonl b/new_data/test/1968_B.jsonl new file mode 100644 index 0000000..aad2128 --- /dev/null +++ b/new_data/test/1968_B.jsonl @@ -0,0 +1,10 @@ +{"input": "1\n1 1\n0\n0", "output": "1"} +{"input": "1\n5 5\n11111\n11111", "output": "5"} +{"input": "1\n4 10\n1010\n1101010010", "output": "4"} +{"input": "1\n7 4\n1110000\n1100", "output": "2"} +{"input": "1\n6 6\n100100\n001001", "output": "4"} +{"input": "1\n8 12\n11001100\n101100110010", "output": "8"} +{"input": "1\n3 7\n111\n0000000", "output": "0"} +{"input": "1\n2 6\n11\n101010", "output": "2"} +{"input": "1\n5 3\n11111\n011", "output": "2"} +{"input": "1\n4 6\n1011\n111000", "output": "2"} diff --git a/new_data/test/1968_F.jsonl b/new_data/test/1968_F.jsonl new file mode 100644 index 0000000..afa958e --- /dev/null +++ b/new_data/test/1968_F.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n5 5\n1 1 2 3 0\n1 5\n2 4\n3 5\n1 3\n3 4\n5 5\n1 2 3 4 5\n1 5\n2 4\n3 5\n1 3\n2 3\n7 4\n12 9 10 9 10 11 9\n1 5\n1 7\n2 6\n2 7\n11 4\n0 0 1 0 0 1 0 1 1 0 1\n1 2\n2 5\n6 9\n7 11", "output": "YES\nYES\nNO\nNO\nNO\nYES\nNO\nNO\nYES\nNO\nNO\nNO\nNO\nNO\nYES\nNO\nYES\nYES"} +{"input": "1\n2 1\n0 0\n1 2", "output": "Yes"} +{"input": "1\n3 1\n1 1 1\n1 3", "output": "Yes"} +{"input": "1\n4 2\n4 4 4 4\n1 4\n2 4", "output": "Yes\nYes"} +{"input": "1\n5 1\n8 8 8 8 8\n1 5", "output": "Yes"} +{"input": "1\n6 2\n3 9 9 3 3 3\n1 6\n2 5", "output": "Yes\nYes"} +{"input": "1\n7 3\n10 5 10 5 10 5 10\n1 7\n3 7\n2 6", "output": "Yes\nYes\nYes"} +{"input": "1\n8 1\n14 14 14 14 14 0 0 0\n1 8", "output": "Yes"} +{"input": "1\n10 2\n7 0 7 0 7 0 7 0 7 0\n1 10\n5 10", "output": "Yes\nYes"} +{"input": "1\n10 2\n5 5 5 5 5 5 5 5 5 5\n1 10\n3 7", "output": "Yes\nYes"} +{"input": "1\n9 3\n1 2 3 4 5 6 7 8 9\n1 9\n1 5\n5 9", "output": "Yes\nYes\nNo"} diff --git a/new_data/test/1969_B.jsonl b/new_data/test/1969_B.jsonl new file mode 100644 index 0000000..ad5cd5c --- /dev/null +++ b/new_data/test/1969_B.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n10\n0000\n11000\n101011\n01101001", "output": "2\n0\n9\n5\n11"} +{"input": "1\n01", "output": "0"} +{"input": "1\n10", "output": "2"} +{"input": "1\n111111", "output": "0"} +{"input": "1\n000111", "output": "0"} +{"input": "1\n111000", "output": "12"} +{"input": "1\n101010", "output": "9"} +{"input": "1\n110101", "output": "7"} +{"input": "1\n1100110011", "output": "16"} +{"input": "1\n1111000011110000", "output": "56"} +{"input": "1\n0000111110000", "output": "24"} diff --git a/new_data/test/1969_D.jsonl b/new_data/test/1969_D.jsonl new file mode 100644 index 0000000..1b43833 --- /dev/null +++ b/new_data/test/1969_D.jsonl @@ -0,0 +1,11 @@ +{"input": "4\n2 0\n2 1\n1 2\n4 1\n1 2 1 4\n3 3 2 3\n4 2\n2 1 1 1\n4 2 3 2\n6 2\n1 3 4 9 1 3\n7 6 8 10 6 8", "output": "1\n1\n0\n7"} +{"input": "1\n3 2\n5 5 5\n7 3 6", "output": "0"} +{"input": "1\n4 0\n1 2 3 4\n4 3 2 1", "output": "4"} +{"input": "1\n5 5\n1 1 1 1 1\n2 2 2 2 2", "output": "0"} +{"input": "1\n6 3\n10 5 15 20 10 5\n5 20 10 5 15 10", "output": "0"} +{"input": "1\n7 3\n10 15 25 30 35 45 50\n55 60 45 40 35 30 25", "output": "0"} +{"input": "1\n8 0\n1 1 1 1 1 1 1 1\n10 9 8 7 6 5 4 3", "output": "44"} +{"input": "1\n3 3\n10000 10000 10000\n9999 9998 9997", "output": "0"} +{"input": "1\n2 1\n1 1000000000\n1000000000 1", "output": "0"} +{"input": "1\n5 2\n100 200 300 400 500\n150 250 350 450 550", "output": "0"} +{"input": "1\n10 5\n5 15 25 10 20 30 40 10 20 5\n30 10 20 15 25 35 45 20 30 5", "output": "0"} diff --git a/new_data/test/1970_A1.jsonl b/new_data/test/1970_A1.jsonl new file mode 100644 index 0000000..ba374ac --- /dev/null +++ b/new_data/test/1970_A1.jsonl @@ -0,0 +1,11 @@ +{"input": "(()(()))", "output": "()(()())"} +{"input": "()", "output": "()"} +{"input": "((()))", "output": "()()()"} +{"input": "(()())", "output": "()(())"} +{"input": "((()()))", "output": "()()(())"} +{"input": "(()(()))", "output": "()(()())"} +{"input": "((((((()))))))", "output": "()()()()()()()"} +{"input": "()(())(())", "output": "((()()()))"} +{"input": "((())())(())((()))(())", "output": "(((()()()()(())()))())"} +{"input": "(()()(()()))", "output": "()((()(())))"} +{"input": "((((()))))()()", "output": "((()))()()()()"} diff --git a/new_data/test/1970_C2.jsonl b/new_data/test/1970_C2.jsonl new file mode 100644 index 0000000..9bd9ff3 --- /dev/null +++ b/new_data/test/1970_C2.jsonl @@ -0,0 +1,11 @@ +{"input": "5 1\n1 2\n1 3\n3 4\n3 5\n1", "output": "Ron"} +{"input": "2 1\n1 2\n1", "output": "Ron"} +{"input": "3 1\n1 2\n1 3\n2", "output": "Hermione"} +{"input": "4 1\n1 2\n1 3\n2 4\n3", "output": "Ron"} +{"input": "6 1\n1 2\n1 3\n3 4\n3 5\n5 6\n1", "output": "Ron"} +{"input": "7 1\n1 2\n1 3\n1 4\n4 5\n4 6\n6 7\n4", "output": "Ron"} +{"input": "5 1\n1 2\n1 3\n3 4\n4 5\n5", "output": "Hermione"} +{"input": "9 1\n1 2\n1 3\n1 4\n3 5\n3 6\n5 7\n6 8\n8 9\n5", "output": "Ron"} +{"input": "10 1\n1 2\n1 3\n1 4\n2 5\n4 6\n5 7\n7 8\n7 9\n9 10\n6", "output": "Ron"} +{"input": "8 1\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n5 8\n3", "output": "Ron"} +{"input": "11 1\n1 2\n2 3\n2 4\n3 5\n5 6\n5 7\n4 8\n8 9\n9 10\n9 11\n7", "output": "Hermione"} diff --git a/new_data/test/1970_F1.jsonl b/new_data/test/1970_F1.jsonl new file mode 100644 index 0000000..a2313bf --- /dev/null +++ b/new_data/test/1970_F1.jsonl @@ -0,0 +1,11 @@ +{"input": "5 5\n.. R1 .. B1 ..\nRG .. .. .. BG\nRG R0 .Q B0 BG\nRG .. .. .. BG\n.. R2 .. B2 ..\n13\nB2 U\nB2 U\nB2 L\nB2 C .Q\nB2 L\nB2 L\nB2 T\nR0 R\nR0 C .Q\nR0 D\nR0 R\nR0 R\nR0 T", "output": "6 BLUE GOAL\n12 RED GOAL\nFINAL SCORE: 1 1\nInput\n3 5\n.. .. R0 .. ..\nRG .. .Q .. BG\n.. .. B0 .. ..\n12\nR0 D\nR0 C .Q\nR0 R\nR0 T\nR0 D\nB0 R\nB0 U\nB0 C .Q\nB0 L\nB0 L\nB0 L\nB0 T\nOutput\n11 BLUE GOAL\nFINAL SCORE: 0 1\nInput\n3 5\n.. .. R0 .. ..\nRG .. .Q .. BG\n.. .. B0 .. ..\n5\nR0 D\nR0 C .Q\nR0 L\nR0 L\nR0 T\nOutput\n4 BLUE GOAL\nFINAL SCORE: 0 1"} +{"input": "3 3\nRG .. ..\n.. .Q ..\nB0 .. BG\n5\nB0 U\nB0 C .Q\nB0 L\nB0 L\nB0 T", "output": "FINAL SCORE: 0 0"} +{"input": "5 5\nR1 .. .. B1 ..\nRG .. .. .. BG\nRG R0 .Q B0 BG\nRG .. .. .. BG\n.. R2 .. B2 ..\n9\nR0 D\nR0 C .Q\nR0 R\nR0 T\nB1 L\nB1 C .Q\nB1 L\nB1 L\nB1 T", "output": "FINAL SCORE: 0 0"} +{"input": "7 5\n.. .. R3 .. ..\nBG RG .. .. RG\n.R .. .. BG ..\n.. .. .. .Q ..\nBG R4 .. .. BG\n.. .. B0 .. ..\nR2 .. .. B1 ..\n10\nR3 L\nR3 D\nR3 C .Q\nR3 L\nR3 T\nB0 D\nB0 C .Q\nB0 U\nB0 L\nB0 T", "output": "4 RED GOAL\nFINAL SCORE: 1 0"} +{"input": "3 5\n.. R1 B0 R3 ..\nRG .Q .. .. BG\n.. B1 .. .. ..\n0", "output": "FINAL SCORE: 0 0"} +{"input": "5 3\nRG .. ..\n.. .. ..\nR0 .Q B0\n.. .. ..\nBG .. ..\n6\nR0 U\nR0 C .Q\nR0 D\nR0 T\nB0 U\nB0 C .Q", "output": "FINAL SCORE: 0 0"} +{"input": "5 5\nR0 .. B1 RG ..\nBG .Q .. .. B0\nBG .. .. R3 ..\nRG .. B2 .. ..\n.. R4 .. .. ..\n8\nR4 L\nR4 U\nR4 C .Q\nR4 R\nR4 T\nB1 L\nB1 C .Q\nB1 T", "output": "FINAL SCORE: 0 0"} +{"input": "3 3\n.. R0 BG\nB0 .Q ..\nRG .. ..\n6\nR0 D\nR0 C .Q\nR0 R\nR0 T\nB0 D\nB0 C .Q", "output": "FINAL SCORE: 0 0"} +{"input": "5 7\n.. .. R0 .. .. .. ..\n.. .. .Q .. .. .. ..\nBG .. .. .. R1 .. BG\n.. .. .. .. B0 .. ..\n.. .. .. .. .. .. ..\n14\nB0 U\nB0 C .Q\nB0 R\nB0 R\nB0 R\nB0 T\nR0 D\nR0 D\nR0 C .Q\nR0 U\nR0 L\nR0 T\nR1 L\nR1 C .Q", "output": "FINAL SCORE: 0 0"} +{"input": "3 7\n.. .. .. B0 .. .. ..\nRG .. .. .. .Q .. RG\n.. .. .. R0 .. .. ..\n5\nB0 L\nB0 L\nB0 C .Q\nB0 R\nB0 T", "output": "FINAL SCORE: 0 0"} +{"input": "3 5\n.. R0 .. .. ..\nRG .Q .. RG BG\n.. .. B0 .. ..\n5\nB0 L\nB0 C .Q\nB0 R\nB0 T\nR0 D", "output": "FINAL SCORE: 0 0"} diff --git a/new_data/test/1970_F2.jsonl b/new_data/test/1970_F2.jsonl new file mode 100644 index 0000000..2b314a6 --- /dev/null +++ b/new_data/test/1970_F2.jsonl @@ -0,0 +1,11 @@ +{"input": "3 5\n.. .. R0 .. ..\nRG .. .Q .. BG\n.. .. B0 .. ..\n12\nR0 D\nR0 C .Q\nR0 R\nR0 T\nR0 D\nB0 R\nB0 U\nB0 C .Q\nB0 L\nB0 L\nB0 L\nB0 T", "output": "11 BLUE GOAL\nFINAL SCORE: 0 1"} +{"input": "3 3\nRG .. ..\n.. .Q BG\nR0 .. B0\n0", "output": "FINAL SCORE: 0 0"} +{"input": "3 3\nRG .. R0\n.Q .. ..\n.. .. BG\n1\nR0 C .Q", "output": "FINAL SCORE: 0 0"} +{"input": "5 5\nRG .. .. .. RG\n.. R0 .B B1 ..\n.. .Q .. .. ..\n.. B0 .. R1 ..\nBG .. .. .. BG\n5\nR0 R\nR0 C .Q\n.B D\nB1 L\nB1 C .B", "output": "0 R0 ELIMINATED\nFINAL SCORE: 0 0"} +{"input": "3 5\nRG .. R0 .. RG\n.Q R0 .. B0 BG\nR1 .. .. .. ..\n5\nR0 L\nR0 L\nR0 C .Q\nR0 T\nB0 L", "output": "FINAL SCORE: 0 0"} +{"input": "3 5\nR0 .B BG .. ..\n.. .Q .. .. ..\nRG .. B0 .. ..\n2\nR0 R\nB0 U", "output": "0 R0 ELIMINATED\nFINAL SCORE: 0 0"} +{"input": "7 3\nRG .. ..\nR0 B0 .B\n.Q R1 B1\n.. .. ..\n.. .. ..\n.. .. ..\nBG .. ..\n6\nR0 R\nB0 R\nR1 L\nR1 C .Q\nR1 R\n.B U", "output": "1 B0 ELIMINATED\nFINAL SCORE: 0 0"} +{"input": "5 3\nRG .. BG\n.. R0 ..\n.Q .B ..\n.. B0 ..\nRG .. BG\n0", "output": "FINAL SCORE: 0 0"} +{"input": "5 5\nRG .. .. .. RG\nR0 .. B1 .B ..\n.. .Q .. .. ..\n.. B0 R1 .. ..\nBG .. .. .. BG\n10\nR0 R\nR0 R\nR0 C .Q\nR0 D\nR0 R\nR0 T\nB1 U\nB1 L\nB1 C .Q\nB1 D", "output": "FINAL SCORE: 0 0"} +{"input": "3 7\nRG .. R0 .. .Q .. RG\n.. .. .. .B .. .. ..\nBG .. B0 .. .. .. BG\n4\nR0 R\nR0 C .Q\n.B L\nB0 L", "output": "FINAL SCORE: 0 0"} +{"input": "9 3\nRG .. ..\nR0 .. B0\n.. .. ..\nBG .Q ..\n.. .B ..\nRG .. ..\nB1 .. R1\n.. .. ..\nBG .. RG\n0", "output": "FINAL SCORE: 0 0"} diff --git a/new_data/test/1971_D.jsonl b/new_data/test/1971_D.jsonl new file mode 100644 index 0000000..0f97268 --- /dev/null +++ b/new_data/test/1971_D.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n11010\n00000000\n1\n10\n0001111\n0110", "output": "3\n1\n1\n2\n1\n2"} +{"input": "1\n0", "output": "1"} +{"input": "1\n1", "output": "1"} +{"input": "1\n010101", "output": "5"} +{"input": "1\n111000", "output": "2"} +{"input": "1\n000111000111", "output": "3"} +{"input": "2\n10\n111000", "output": "2\n2"} +{"input": "1\n1100011", "output": "2"} +{"input": "1\n00001111", "output": "1"} +{"input": "1\n11111111", "output": "1"} +{"input": "1\n00000000", "output": "1"} diff --git a/new_data/test/1971_E.jsonl b/new_data/test/1971_E.jsonl new file mode 100644 index 0000000..ddc8a66 --- /dev/null +++ b/new_data/test/1971_E.jsonl @@ -0,0 +1,10 @@ +{"input": "1\n100 10 5\n10 20 30 40 50 60 70 80 90 100\n1 2 3 4 5 6 7 8 9 10\n0\n15\n45\n75\n100", "output": "0 1 4 7 10"} +{"input": "3\n50 5 3\n5 15 25 35 50\n5 10 20 35 60\n0\n25\n50\n10 3 4\n3 6 10\n1 3 7\n2\n4\n8\n10\n100 2 2\n50 100\n10 30\n25\n75", "output": "0 20 60 \n0 1 5 7 \n5 20"} +{"input": "2\n20 4 2\n5 10 15 20\n2 5 8 10\n10\n20\n30 3 3\n10 20 30\n10 20 30\n5\n15\n25", "output": "5 10 \n5 15 25"} +{"input": "1\n15 5 5\n3 7 11 13 15\n2 5 9 12 16\n2\n6\n9\n14\n15", "output": "1 4 7 14 16"} +{"input": "2\n200 3 4\n50 100 200\n30 70 130\n0\n50\n150\n200\n20 2 3\n10 20\n15 25\n5\n10\n15", "output": "0 30 100 130 \n7 15 20"} +{"input": "4\n1000 1 1\n1000\n100\n500\n150 5 3\n30 60 90 120 150\n10 20 30 45 60\n60\n90\n120\n80 4 2\n20 40 60 80\n5 15 35 55\n70\n80\n100 2 5\n50 100\n25 75\n10\n30\n50\n70\n100", "output": "50 \n20 30 45 \n45 55 \n5 15 25 45 75"} +{"input": "1\n8 2 6\n3 8\n4 9\n0\n2\n3\n5\n7\n8", "output": "0 2 4 6 8 9"} +{"input": "1\n40 6 5\n5 10 15 20 25 40\n3 7 12 19 27 42\n1\n10\n22\n30\n40", "output": "0 7 22 32 42"} +{"input": "3\n25 4 4\n5 10 20 25\n3 8 18 24\n0\n5\n10\n20\n10 2 3\n4 10\n6 12\n3\n8\n10\n50 3 2\n20 40 50\n15 25 35\n30\n50", "output": "0 3 8 18 \n4 10 12 \n20 35"} +{"input": "2\n60 5 3\n10 20 30 50 60\n5 10 15 25 30\n15\n35\n55\n25 3 3\n10 15 25\n5 12 20\n0\n12\n25", "output": "7 17 27 \n0 7 20"} diff --git a/new_data/test/1972_B.jsonl b/new_data/test/1972_B.jsonl new file mode 100644 index 0000000..e340403 --- /dev/null +++ b/new_data/test/1972_B.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n5\nUUDUD\n5\nUDDUD\n2\nUU", "output": "YES\nNO\nNO"} +{"input": "1\n1\nU", "output": "YES"} +{"input": "1\n1\nD", "output": "NO"} +{"input": "1\n2\nUU", "output": "NO"} +{"input": "1\n2\nUD", "output": "YES"} +{"input": "3\n3\nUUU\n4\nUDUD\n4\nDDDD", "output": "YES\nNO\nNO"} +{"input": "3\n5\nUUDUD\n5\nUDDUD\n2\nUU", "output": "YES\nNO\nNO"} +{"input": "2\n6\nUUUUUU\n6\nUDUDUD", "output": "NO\nYES"} +{"input": "2\n7\nUUDUUDU\n7\nDUUDUDU", "output": "YES\nNO"} +{"input": "3\n5\nDUDDD\n5\nDDDDU\n5\nDDDDD", "output": "YES\nYES\nNO"} +{"input": "5\n3\nUDU\n4\nDUDU\n5\nUDDUU\n6\nDUUDUD\n7\nDDDUUDU", "output": "NO\nNO\nYES\nYES\nYES"} diff --git a/new_data/test/1972_D2.jsonl b/new_data/test/1972_D2.jsonl new file mode 100644 index 0000000..7f0c4a8 --- /dev/null +++ b/new_data/test/1972_D2.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n1 1\n2 3\n3 5\n10 8\n100 1233\n1000000 1145141", "output": "0\n1\n1\n6\n423\n5933961"} +{"input": "1\n1 1", "output": "0"} +{"input": "1\n2 2", "output": "1"} +{"input": "1\n1 2", "output": "0"} +{"input": "1\n2 1", "output": "0"} +{"input": "1\n999999 999999", "output": "5548403"} +{"input": "1\n2000000 2000000", "output": "11680996"} +{"input": "1\n1 2000000", "output": "0"} +{"input": "1\n2000000 1", "output": "0"} +{"input": "1\n1234567 7654321", "output": "14647274"} +{"input": "1\n678 987", "output": "2022"} diff --git a/new_data/test/1973_A.jsonl b/new_data/test/1973_A.jsonl new file mode 100644 index 0000000..0c0db80 --- /dev/null +++ b/new_data/test/1973_A.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n0 0 0\n0 1 1\n1 1 1\n1 1 2\n3 3 3\n3 4 5\n1 1 10", "output": "0\n1\n-1\n2\n-1\n6\n2"} +{"input": "5\n0 0 0\n0 0 1\n0 1 2\n1 1 1\n2 2 2", "output": "0\n-1\n-1\n-1\n3"} +{"input": "5\n1 2 3\n2 3 5\n4 4 6\n5 6 12\n3 4 4", "output": "3\n5\n7\n-1\n-1"} +{"input": "5\n0 0 30\n1 1 30\n2 2 25\n0 1 3\n0 5 10", "output": "0\n2\n-1\n1\n-1"} +{"input": "5\n30 30 30\n29 29 30\n28 28 30\n27 27 28\n26 26 26", "output": "45\n44\n43\n41\n39"} +{"input": "5\n10 10 10\n11 11 12\n12 12 14\n0 0 15\n15 15 15", "output": "15\n17\n19\n-1\n-1"} +{"input": "5\n0 15 15\n0 15 30\n15 15 30\n20 25 27\n24 26 30", "output": "15\n-1\n30\n36\n40"} +{"input": "5\n1 5 10\n5 5 10\n7 8 9\n12 15 15\n10 10 12", "output": "6\n10\n12\n21\n16"} +{"input": "5\n1 29 30\n10 20 29\n9 19 20\n5 5 15\n10 10 20", "output": "30\n-1\n24\n-1\n20"} +{"input": "5\n0 10 20\n1 11 21\n1 5 8\n8 9 10\n15 15 17", "output": "10\n-1\n6\n-1\n-1"} +{"input": "5\n7 7 14 \n3 3 4\n5 5 7\n6 6 6\n0 2 2", "output": "14\n5\n-1\n9\n2"} diff --git a/new_data/test/1974_A.jsonl b/new_data/test/1974_A.jsonl new file mode 100644 index 0000000..828cfdd --- /dev/null +++ b/new_data/test/1974_A.jsonl @@ -0,0 +1,11 @@ +{"input": "11\n1 1\n7 2\n12 4\n0 3\n1 0\n8 1\n0 0\n2 0\n15 0\n8 2\n0 9", "output": "1\n1\n2\n2\n1\n1\n0\n1\n1\n2\n5"} +{"input": "1\n15 4", "output": "3"} +{"input": "1\n0 0", "output": "0"} +{"input": "1\n99 99", "output": "50"} +{"input": "1\n3 0", "output": "1"} +{"input": "1\n12 6", "output": "3"} +{"input": "1\n20 3", "output": "3"} +{"input": "1\n5 5", "output": "3"} +{"input": "1\n50 0", "output": "4"} +{"input": "1\n0 10", "output": "5"} +{"input": "1\n25 25", "output": "13"} diff --git a/new_data/test/1974_B.jsonl b/new_data/test/1974_B.jsonl new file mode 100644 index 0000000..563cd03 --- /dev/null +++ b/new_data/test/1974_B.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n10\nserofedsoc\n3\nttf\n9\ntlrhgmaoi\n1\nw\n15\nhnndledmnhlttin", "output": "codeforces\nfft\nalgorithm\nw\nmeetinthemiddle"} +{"input": "1\n1\na", "output": "a"} +{"input": "1\n3\nzaz", "output": "aza"} +{"input": "2\n5\nabcde\n5\nzyxwv", "output": "edcba\nvwxyz"} +{"input": "3\n6\nabcdef\n4\ndbca\n4\nabcd", "output": "fedcba\nacbd\ndcba"} +{"input": "1\n8\nzoyaazoz", "output": "ayozzaya"} +{"input": "1\n26\nabcdefghijklmnopqrstuvwxyz", "output": "zyxwvutsrqponmlkjihgfedcba"} +{"input": "1\n12\nlmkonmnoonmm", "output": "nmoklmlkklmm"} +{"input": "1\n13\nedomentoralg", "output": "orelogaedtmn"} +{"input": "1\n10\ntwtstwtwtw", "output": "tstwtststs"} +{"input": "1\n15\nnbddtfobborlliy", "output": "lyttdriyyifnnob"} diff --git a/new_data/test/1975_A.jsonl b/new_data/test/1975_A.jsonl new file mode 100644 index 0000000..be854bf --- /dev/null +++ b/new_data/test/1975_A.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n6\n1 1 4 5 1 4\n5\n7 9 2 2 3\n3\n1 2 3", "output": "No\nYes\nYes"} +{"input": "1\n2\n2 1", "output": "YES"} +{"input": "1\n4\n3 2 1 4", "output": "NO"} +{"input": "2\n3\n2 2 2\n5\n5 4 3 2 1", "output": "YES\nNO"} +{"input": "1\n6\n1 9 8 7 6 5", "output": "NO"} +{"input": "1\n7\n10 1 1 1 1 1 1", "output": "YES"} +{"input": "3\n3\n3 3 3\n4\n4 5 6 7\n5\n5 5 5 5 1", "output": "YES\nYES\nYES"} +{"input": "1\n5\n1 3 5 3 1", "output": "NO"} +{"input": "2\n2\n5 6\n6\n6 5 4 3 2 1", "output": "YES\nNO"} +{"input": "1\n4\n1 3 1 3", "output": "NO"} +{"input": "1\n8\n2 3 4 4 4 4 3 2", "output": "NO"} diff --git a/new_data/test/1975_C.jsonl b/new_data/test/1975_C.jsonl new file mode 100644 index 0000000..79f281a --- /dev/null +++ b/new_data/test/1975_C.jsonl @@ -0,0 +1,11 @@ +{"input": "2\n2\n1 2\n5\n1 2 3 4 5", "output": "1\n4"} +{"input": "1\n2\n2 1", "output": "1"} +{"input": "1\n5\n5 4 3 2 1", "output": "4"} +{"input": "1\n4\n1 1 1 1", "output": "1"} +{"input": "1\n3\n1 1000000000 1", "output": "1"} +{"input": "1\n6\n10 10 10 20 20 20", "output": "20"} +{"input": "1\n4\n5 6 7 8", "output": "7"} +{"input": "1\n7\n1 2 1 2 1 2 1", "output": "2"} +{"input": "1\n10\n1 2 3 4 5 6 7 8 9 10", "output": "9"} +{"input": "1\n3\n3 5 3", "output": "3"} +{"input": "1\n5\n1000000000 999999999 1000000000 999999999 1000000000", "output": "1000000000"} diff --git a/new_data/test/1976_A.jsonl b/new_data/test/1976_A.jsonl new file mode 100644 index 0000000..0b75bcb --- /dev/null +++ b/new_data/test/1976_A.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n4\n12ac\n5\n123wa\n9\nallllmost\n5\nac123\n6\n011679", "output": "YES\nNO\nYES\nNO\nYES"} +{"input": "2\n3\nabc\n3\n123", "output": "YES\nYES"} +{"input": "1\n5\n1a1a1", "output": "NO"} +{"input": "1\n4\n9999", "output": "YES"} +{"input": "1\n8\nabcdefgh", "output": "YES"} +{"input": "2\n6\ncba321\n6\n123abc", "output": "NO\nYES"} +{"input": "3\n4\nacbd\n6\n112233\n9\naaabbbccc", "output": "NO\nYES\nYES"} +{"input": "2\n7\nabacus1\n4\nab12", "output": "NO\nNO"} +{"input": "1\n10\n0987654321", "output": "NO"} +{"input": "1\n2\nba", "output": "NO"} +{"input": "3\n1\na\n1\nz\n1\n0", "output": "YES\nYES\nYES"} diff --git a/new_data/test/1977_A.jsonl b/new_data/test/1977_A.jsonl new file mode 100644 index 0000000..cd07f90 --- /dev/null +++ b/new_data/test/1977_A.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n3 3\n2 4\n5 3", "output": "Yes\nNo\nYes"} +{"input": "1\n1 0", "output": "No"} +{"input": "1\n1 1", "output": "Yes"} +{"input": "1\n2 0", "output": "Yes"} +{"input": "1\n2 1", "output": "No"} +{"input": "1\n2 2", "output": "Yes"} +{"input": "1\n100 50", "output": "Yes"} +{"input": "1\n100 100", "output": "Yes"} +{"input": "1\n100 99", "output": "No"} +{"input": "10\n10 10\n5 5\n4 3\n3 2\n2 1\n1 0\n0 0\n100 100\n100 99\n100 51", "output": "Yes\nYes\nNo\nNo\nNo\nNo\nYes\nYes\nNo\nNo"} +{"input": "2\n99 1\n99 98", "output": "Yes\nNo"} diff --git a/new_data/test/1977_B.jsonl b/new_data/test/1977_B.jsonl new file mode 100644 index 0000000..52e863e --- /dev/null +++ b/new_data/test/1977_B.jsonl @@ -0,0 +1,11 @@ +{"input": "7\n1\n14\n24\n15\n27\n11\n19", "output": "1\n1\n5\n0 -1 0 0 1\n6\n0 0 0 -1 0 1\n5\n-1 0 0 0 1\n6\n-1 0 -1 0 0 1\n5\n-1 0 -1 0 1\n5\n-1 0 1 0 1"} +{"input": "1\n1", "output": "30\n1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"} +{"input": "1\n1073741823", "output": "31\n-1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1"} +{"input": "1\n16", "output": "30\n0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"} +{"input": "1\n1024", "output": "30\n0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"} +{"input": "1\n3", "output": "30\n-1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"} +{"input": "1\n7", "output": "30\n-1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"} +{"input": "1\n255", "output": "30\n-1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"} +{"input": "1\n4096", "output": "30\n0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"} +{"input": "1\n123456789", "output": "30\n1 0 1 0 1 0 0 0 1 0 -1 0 1 0 -1 0 0 0 -1 0 0 -1 0 -1 0 0 0 1 0 0"} +{"input": "1\n987654321", "output": "31\n1 0 0 0 -1 0 -1 0 1 0 0 1 0 -1 0 1 0 -1 0 0 0 -1 0 0 -1 0 -1 0 0 0 1"} diff --git a/new_data/test/1978_A.jsonl b/new_data/test/1978_A.jsonl new file mode 100644 index 0000000..3b145ff --- /dev/null +++ b/new_data/test/1978_A.jsonl @@ -0,0 +1,11 @@ +{"input": "5\n2\n1 1\n4\n2 3 3 1\n5\n2 2 3 2 2\n2\n10 3\n3\n1 2 3", "output": "2\n4\n5\n13\n5"} +{"input": "1\n2\n1 1000000000", "output": "1000000001"} +{"input": "2\n3\n4 5 6\n5\n1 1 1 1 1", "output": "11\n2"} +{"input": "1\n4\n10 9 8 7", "output": "17"} +{"input": "1\n5\n1 2 100 3 4", "output": "104"} +{"input": "3\n2\n100 99\n2\n5 10\n3\n6 5 6", "output": "199\n15\n12"} +{"input": "1\n6\n5 5 5 5 5 5", "output": "10"} +{"input": "1\n7\n1 1 1 1 1000000000 1 1", "output": "1000000001"} +{"input": "1\n8\n2 3 1 4 8 7 6 5", "output": "13"} +{"input": "1\n10\n1 2 3 4 5 6 7 8 9 10", "output": "19"} +{"input": "2\n3\n10 20 30\n4\n4 9 2 8", "output": "50\n17"} diff --git a/new_data/test/1978_B.jsonl b/new_data/test/1978_B.jsonl new file mode 100644 index 0000000..3e7ece1 --- /dev/null +++ b/new_data/test/1978_B.jsonl @@ -0,0 +1,10 @@ +{"input": "1\n1 1 1", "output": "1"} +{"input": "1\n10 15 3", "output": "150"} +{"input": "2\n6 7 7\n9 3 8", "output": "42\n42"} +{"input": "3\n1000000000 1 500\n100 100 1000\n50 100 50", "output": "1000124750\n95050\n5000"} +{"input": "2\n7 7 1\n9 9 18", "output": "49\n126"} +{"input": "1\n10 5 10", "output": "65"} +{"input": "2\n3 50 1\n8 8 8", "output": "150\n64"} +{"input": "3\n5 5 5\n7 10 20\n1000000 1000 2", "output": "25\n119\n1000000000"} +{"input": "2\n2 10 2\n1 100 50", "output": "20\n100"} +{"input": "1\n1000000000 999999999 999999998", "output": "999999999000000000"} diff --git a/new_data/test/1978_C.jsonl b/new_data/test/1978_C.jsonl new file mode 100644 index 0000000..94f5529 --- /dev/null +++ b/new_data/test/1978_C.jsonl @@ -0,0 +1,11 @@ +{"input": "8\n3 4\n4 5\n7 0\n1 1000000000000\n8 14\n112 777\n5 12\n5 2", "output": "Yes\n3 1 2\nNo\nYes\n1 2 3 4 5 6 7\nNo\nYes\n8 2 3 4 5 6 1 7\nNo\nYes\n5 4 3 1 2\nYes\n2 1 3 4 5"} +{"input": "1\n1 0", "output": "YES\n1"} +{"input": "3\n4 6\n5 10\n6 0", "output": "YES\n4 2 3 1 \nYES\n5 2 4 3 1 \nYES\n1 2 3 4 5 6"} +{"input": "2\n3 3\n3 2", "output": "NO\nYES\n1 3 2"} +{"input": "1\n10 0", "output": "YES\n1 2 3 4 5 6 7 8 9 10"} +{"input": "1\n2 1", "output": "NO"} +{"input": "2\n5 5\n5 15", "output": "NO\nNO"} +{"input": "1\n10 45", "output": "NO"} +{"input": "1\n7 11", "output": "NO"} +{"input": "4\n11 5\n11 20\n11 50\n11 0", "output": "NO\nYES\n11 2 3 4 5 6 7 8 9 10 1 \nYES\n11 10 9 4 5 6 8 7 3 2 1 \nYES\n1 2 3 4 5 6 7 8 9 10 11"} +{"input": "1\n1000 500500", "output": "NO"} diff --git a/new_data/test/1979_C.jsonl b/new_data/test/1979_C.jsonl new file mode 100644 index 0000000..effd571 --- /dev/null +++ b/new_data/test/1979_C.jsonl @@ -0,0 +1,11 @@ +{"input": "6\n3\n3 2 7\n2\n3 3\n5\n5 5 5 5 5\n6\n7 9 3 17 9 13\n3\n6 3 2\n5\n9 4 6 8 3", "output": "27 41 12 \n1 1 \n-1\n1989 1547 4641 819 1547 1071 \n-1\n8 18 12 9 24"} +{"input": "1\n1\n2", "output": "1"} +{"input": "1\n2\n20 20", "output": "1 1"} +{"input": "1\n2\n2 19", "output": "19 2"} +{"input": "1\n4\n3 2 2 20", "output": "-1"} +{"input": "1\n5\n4 5 6 3 7", "output": "-1"} +{"input": "1\n3\n5 5 5", "output": "1 1 1"} +{"input": "1\n6\n6 4 3 2 5 5", "output": "-1"} +{"input": "1\n7\n10 2 10 3 10 4 10", "output": "-1"} +{"input": "1\n50\n20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20", "output": "-1"} +{"input": "1\n6\n12 14 16 18 20 2", "output": "420 360 315 280 252 2520"} \ No newline at end of file diff --git a/new_data/test/1980_A.jsonl b/new_data/test/1980_A.jsonl new file mode 100644 index 0000000..f25b7f2 --- /dev/null +++ b/new_data/test/1980_A.jsonl @@ -0,0 +1,11 @@ +{"input": "3\n10 1\nBGECDCBDED\n10 2\nBGECDCBDED\n9 1\nBBCDEFFGG", "output": "2\n5\n1"} +{"input": "1\n7 1\nABCDEFG", "output": "0"} +{"input": "1\n7 1\nAAAAAAA", "output": "6"} +{"input": "1\n10 1\nBCDEFGBCDE", "output": "1"} +{"input": "1\n7 1\nABCDEFG", "output": "0"} +{"input": "1\n50 5\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "output": "30"} +{"input": "1\n50 5\nBCDEFGBCDEFGBCDEFGBCDEFGBCDEFGBCDEFGBCDEFGBCDEFGBC", "output": "5"} +{"input": "2\n10 2\nABCDEFGABC\n7 1\nABCDEFG", "output": "4\n0"} +{"input": "2\n12 1\nCDEFGABCDEFA\n14 4\nGGGGGGGGGGGGGG", "output": "0\n24"} +{"input": "1\n10 3\nABCDEABCDE", "output": "11"} +{"input": "1\n5 1\nACDFG", "output": "2"} diff --git a/src/main_test.py b/src/main_test.py new file mode 100644 index 0000000..f6a999f --- /dev/null +++ b/src/main_test.py @@ -0,0 +1,250 @@ +import ast +from datetime import datetime +from math import sqrt +import csv +import os +import argparse +import shutil +import subprocess +from pathlib import Path +from hoareprompt import compute_postcondition, check_entailment, extract_precondition, compute_postcondition_naive, \ + assess +from importlib.metadata import version +import importlib.util +from src.file_io import load_json +from src.logger_setup import logger_setup +from src.preprocessing import replace_function_name, count_function_defs + +import json + + +# Writes the provided content to a specified file +def save_to_file(content, file_path): + with open(file_path, 'w') as file: + #if content i boolean, convert it to string + content = str(content) + file.write(content) + + +# Calculates the Matthews Correlation Coefficient for evaluating binary classification results +def calculate_mcc(tp, tn, fp, fn): + numerator = tp * tn - fp * fn + denominator = sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) + if denominator == 0: + return 0 + return numerator / denominator + + +def main(data: dict, config: dict, logger, model, run_number, datafile): + # These variables are used for tracking the number of tasks and accuracy + total = 0 + correct = 0 + + # These counters are used for calculating MCC + tp, tn, fp, fn = 0, 0, 0, 0 + + # Failed tasks list to store failure details + failed_tasks = [] + columns = [ + "Task ID", "unique_id", "Dataset", "model_created", "model_run", "description", "Code", "run_number", "original correctness", + "naive_test"] + if not os.path.exists(logger.csv_file): + with open(logger.csv_file, mode='w', newline='') as file: + writer = csv.DictWriter(file, fieldnames=columns) + writer.writeheader() + config["annotated"] = False + config["fsl"] = False + config_annotated = config.copy() + config_annotated["assessment-mode"] = "naive-test" + # This is the main loop where the work is done, it tterates over each task in the provided data + #for loop to include the index and the task in the data + for index, task_data in enumerate(data): + print(f"Running task {index} out of {len(data)}") + task_id = task_data["task_id"] + task_id = task_id.replace("/", "_") + model_created = task_data["model"] + dataset = task_data["dataset"] + code = task_data["generated_code"] + description = task_data["description"] + unique_id = task_data["unique_id"] + original_correctness = task_data["correct"] + + # Here we replace the function name to avoid conflicts in parsing + replaced_code = replace_function_name(code) + logger.debug(f"Start Task {task_id}") + + try: + # if you connot parse the code in ast , skip this task + parsed_code = ast.parse(replaced_code).body + except Exception as e: + logger.debug(f"Task {task_id} skip due to parse error: {e}\n\n\n") + # Add this task to a failed tasks list with the fail reason being parse error + failed_tasks.append({ + "task_id": task_id, + "model_created": model_created, + "dataset": dataset, + "model_run": model, + "code": code, + "fail_reason": f"Parse error: {e}", + "type_of_run": "parse_error" + }) + # continue + detail_log_directory = logger.log_dir / unique_id / model_created + detail_log_directory.mkdir(parents=True, exist_ok=True) + # pre_directory = detail_log_directory / "extract-precondition" + # post_directory = detail_log_directory / "compute-postconditon" + # check_directory = detail_log_directory / "check-entailment" + # naive_directory = detail_log_directory / "naive" + # pre_directory.mkdir(parents=True, exist_ok=True) + # post_directory.mkdir(parents=True, exist_ok=True) + # check_directory.mkdir(parents=True, exist_ok=True) + # naive_directory.mkdir(parents=True, exist_ok=True) + try: + total += 1 + print(f"Running task {task_id} with log directory {detail_log_directory}") + result = assess(description, code, task_id, config_annotated, detail_log_directory, None) + + save_to_file(description, detail_log_directory / "description.txt") + save_to_file(code, detail_log_directory / "program.py") + save_to_file(result, detail_log_directory / "naive.txt") + + # write to logger + logger.debug(f"Dataset: {dataset}") + logger.debug(f"model_created: {model_created}") + logger.debug(f"model_run: {model}") + logger.debug(f"description: {description}") + logger.debug(f"Correctness: {result}") + + # # Write task result to CSV logger + + result = { + "Task ID": task_id, + "unique_id": unique_id, + "Dataset": dataset, + "model_created": model_created, + "model_run": model, + "description": description, + "Code": code, + "run_number": run_number, + "original correctness": original_correctness, + "naive_test": result + } + + with open(logger.csv_file, mode='a', newline='') as file: + writer = csv.DictWriter(file, fieldnames=columns) + writer.writerow(result) + + # result = check_entailment(description, post, code, task_id, config, check_directory) + except Exception as e: + # Handle any errors like API issues and log them also add the task to the failed tasks list + failed_tasks.append({ + "task_id": task_id, + "unique_id": unique_id, + "model_created": model_created, + "dataset": dataset, + "model_run": model, + "code": code, + "fail_reason": f"Error: {e}", + "type_of_run": "hoareprompt" + }) + + logger.error(f"Error: {e}") + # break + + # Only save the failed tasks if there are any + if failed_tasks: + failed_tasks_file = logger.log_dir / 'failed_tasks.csv' + + # Define the headers for the CSV file + failed_tasks_headers = ['task_id', 'unique_id', 'model_created', 'dataset', 'model_run', 'code', 'fail_reason', + 'type_of_run'] + + # Write the failed tasks to a CSV file + with open(failed_tasks_file, 'w', newline='') as file: + writer = csv.DictWriter(file, fieldnames=failed_tasks_headers) + writer.writeheader() + for task in failed_tasks: + writer.writerow(task) + + +if __name__ == "__main__": + # Initialize the argument parser with descriptions for expected command-line arguments + parser = argparse.ArgumentParser(description="HoarePrompt Experiment") + parser.add_argument('--config', type=str, help="Path to custom configuration file") + parser.add_argument('--data', type=str, help="Path to read data") + parser.add_argument('--log', type=str, help="Directory to save detailed logs") + + #add another argument but make it optional + parser.add_argument('--run_number', type=str, help="which repetition of the run this is", default=1) + args = parser.parse_args() + + if args.config: + config_file = Path(args.config) + else: + config_file = Path("default_config.json") + config = load_json(config_file) + + if args.data: + data_file = Path(args.data) + else: + raise ValueError("Cannot find data file.") + data = load_json(data_file) + + if args.log: + log_directory = Path(args.log) + else: + log_directory = Path("Results") + + # if log_directory does not end with underscore and the run_number then add that to the final name in the path + if not str(log_directory).endswith("_" + str(args.run_number)): + log_directory = Path(str(log_directory) + f"_{args.run_number}") + print(f"Log directory: {log_directory}") + #if the log directory does not exist, create it + log_directory.mkdir(parents=True, exist_ok=True) + + base = datetime.now().strftime("%Y%m%d-%H%M%S") + + logger = logger_setup(log_directory, base) + + # copy config to log dir + shutil.copy(config_file, logger.log_dir / config_file.name) + + # save hoareprompt version to log dir + hoareprompt_version = version("hoareprompt") + spec = importlib.util.find_spec("hoareprompt") + # Get the directory where Hoareprompt is installed + if spec is not None: + # this is the python script path + hoareprompt_path = spec.origin + # this is the source dir + hoareprompt_dir = os.path.dirname(hoareprompt_path) + # this is the git repo + repo_path = os.path.abspath(os.path.join(hoareprompt_dir, "..")) + #print(f"HoarePrompt is installed at: {repo_path}") + else: + print("HoarePrompt is not installed.") + #Check if it's a Git repository + if os.path.exists(os.path.join(repo_path, ".git")): + try: + # Run git command to get the latest commit hash + commit_hash_hoare = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=repo_path + ).strip().decode('utf-8') + except subprocess.CalledProcessError: + print("Failed to get the current commit hash.") + else: + print(f"{repo_path} is not a Git repository.") + #keep the file name form the data_file path string, the name is the last file in the path + data_file_name = os.path.basename(data_file) + # find the commit of the git repo we are in + commit_hash_exp = subprocess.check_output(["git", "rev-parse", "HEAD"]).strip().decode() + model = config['model'] + version_file = logger.log_dir / "VERSIONS" + with open(version_file, 'w') as f: + f.write(f"hoareprompt version: {hoareprompt_version}\n") + f.write(f"HoarePrompt commit hash: {commit_hash_hoare}\n") + f.write(f"HoarePrompt experiments commit hash: {commit_hash_exp}\n") + f.write(f"model version: {config['model']}\n") + f.write(f"data file: {data_file_name}\n") + + main(data, config, logger, model, args.run_number, datafile=data_file_name)