diff --git "a/data/py/test.jsonl" "b/data/py/test.jsonl" deleted file mode 100644--- "a/data/py/test.jsonl" +++ /dev/null @@ -1,200 +0,0 @@ -{"contest_id":"1286","problem_id":"C1","statement":"C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the string, and the following line should contain the string ss.ExampleInputCopy4\n\na\naa\na\n\ncb\nb\nc\n\ncOutputCopy? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc","tags":["brute force","constructive algorithms","interactive","math"],"code":"import sys, os\n\ninput = sys.stdin.buffer.readline\n\n\n\nn = int(input())\n\na, b = \"?\".encode(), \"!\".encode()\n\nif n == 1:\n\n os.write(1, b\"%s %d %d\\n\" % (a, 1, 1))\n\n s = input().rstrip().decode()\n\n ans = (\"! \" + s).encode()\n\n os.write(1, b\"%s\\n\" % ans)\n\n exit()\n\ncnt1 = [[0] * 26 for _ in range(n + 1)]\n\nos.write(1, b\"%s %d %d\\n\" % (a, 1, n))\n\nfor _ in range(n * (n + 1) \/\/ 2):\n\n s = list(input().rstrip())\n\n c = cnt1[len(s)]\n\n for i in s:\n\n c[i - 97] += 1\n\ncnt2 = [[0] * 26 for _ in range(n + 1)]\n\nos.write(1, b\"%s %d %d\\n\" % (a, 1, n - 1))\n\nfor _ in range(n * (n - 1) \/\/ 2):\n\n s = list(input().rstrip())\n\n c = cnt2[len(s)]\n\n for i in s:\n\n c[i - 97] += 1\n\nans = [-1] * n\n\nc1, c2 = cnt1[n], cnt2[n - 1]\n\nfor i in range(26):\n\n if c1[i] ^ c2[i]:\n\n ans[-1] = i\n\n break\n\nfor i in range(2, (n + 1) \/\/ 2 + 1):\n\n x = [min(j + 1, n - j, i) for j in range(n)]\n\n c = cnt1[i]\n\n for j in range(n):\n\n if ans[j] ^ -1:\n\n c[ans[j]] -= x[j]\n\n for j in range(26):\n\n if c[j] % i:\n\n ans[i - 2] = j\n\n break\n\n x = [min(j + 1, n - 1 - j, i) for j in range(n - 1)]\n\n c = cnt2[i]\n\n for j in range(n - 1):\n\n if ans[j] ^ -1:\n\n c[ans[j]] -= x[j]\n\n for j in range(26):\n\n if c[j] % i:\n\n ans[-i] = j\n\n break\n\nif not n % 2:\n\n c = cnt1[n]\n\n for i in ans:\n\n if i ^ -1:\n\n c[i] -= 1\n\n for i in range(26):\n\n if c[i]:\n\n ans[n \/\/ 2 - 1] = i\n\n break\n\nans = (\"! \" + \"\".join(chr(i + 97) for i in ans)).encode()\n\nos.write(1, b\"%s\\n\" % ans)\n\nexit()","language":"py"} -{"contest_id":"1324","problem_id":"E","statement":"E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai\u22121ai\u22121 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r dp[j]:\n\n dp[j] = dp[j - 1]\n\n if l <= (pres - j) % h <= r:\n\n dp[j] += 1\n\n\n\n print(max(dp))\n\n\n\n\n\nsolve()","language":"py"} -{"contest_id":"1324","problem_id":"A","statement":"A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2\u00d712\u00d71 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2\u00d712\u00d71 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai\u22121ai\u22121. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.ExampleInputCopy4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\nOutputCopyYES\nNO\nYES\nYES\nNoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.","tags":["implementation","number theory"],"code":"import os\n\nos.system(\"cls\") # clear screen\n\n\n\nt = int(input())\n\nfor T in range(t):\n\n n = int(input())\n\n arr = list(map(int, input().split()))\n\n parity = arr[0] % 2\n\n answer = \"YES\"\n\n for x in arr:\n\n if x % 2 != parity:\n\n answer = \"NO\"\n\n break\n\n print(answer)\n\n","language":"py"} -{"contest_id":"1304","problem_id":"F1","statement":"F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1\u2264n\u2264501\u2264n\u226450, 1\u2264m\u22642\u22c51041\u2264m\u22642\u22c5104, 1\u2264k\u2264min(m,20)1\u2264k\u2264min(m,20)) \u2013 the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer \u2013 the maximum number of animals that can be observed.ExamplesInputCopy4 5 2\n0 2 1 1 0\n0 0 3 1 2\n1 0 4 3 1\n3 3 0 0 4\nOutputCopy25\nInputCopy3 3 1\n1 2 3\n4 5 6\n7 8 9\nOutputCopy31\nInputCopy3 3 2\n1 2 3\n4 5 6\n7 8 9\nOutputCopy44\nInputCopy3 3 3\n1 2 3\n4 5 6\n7 8 9\nOutputCopy45\nNoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: ","tags":["data structures","dp"],"code":"import sys, os, io\n\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\ndef sparse_table(a):\n\n table = []\n\n s0, l = a, 1\n\n table.append(s0)\n\n while 2 * l <= len(a):\n\n s = [max(s0[i], s0[i + l]) for i in range(len(s0) - l)]\n\n table.append(list(s))\n\n s0 = s\n\n l *= 2\n\n return table\n\n\n\ndef get_max(l, r, table):\n\n d = len(bin(r - l + 1)) - 3\n\n ans = max(table[d][l], table[d][r - pow2[d] + 1])\n\n return ans\n\n\n\nn, m, k = map(int, input().split())\n\ns = []\n\nfor _ in range(n):\n\n s0 = list(map(int, input().split()))\n\n u = [0]\n\n for i in s0:\n\n u.append(u[-1] + i)\n\n s.append(u)\n\ns.append([0] * (m + 1))\n\nl = m - k + 1\n\ndp0 = [0] * l\n\ns0, s1 = s[0], s[1]\n\nfor i in range(l):\n\n dp0[i] = s0[i + k] + s1[i + k] - s0[i] - s1[i]\n\ns0 = s[1]\n\npow2 = [1]\n\nfor _ in range(20):\n\n pow2.append(2 * pow2[-1])\n\nfor i in range(1, n):\n\n s1 = s[i + 1]\n\n dp = [0] * l\n\n table = sparse_table(dp0)\n\n for j in range(l):\n\n c = s0[j + k] + s1[j + k] - s0[j] - s1[j]\n\n dpj = 0\n\n for u in range(max(0, j - k + 1), min(l, j + k)):\n\n x, y = max(j, u), min(j, u) + k\n\n dpj = max(dpj, dp0[u] + c - s0[y] + s0[x])\n\n if j - k >= 0:\n\n dpj = max(dpj, get_max(0, j - k, table) + c)\n\n if j + k <= l - 1:\n\n dpj = max(dpj, get_max(j + k, l - 1, table) + c)\n\n dp[j] = dpj\n\n dp0 = dp\n\n s0 = s1\n\nans = max(dp0)\n\nprint(ans)","language":"py"} -{"contest_id":"1311","problem_id":"E","statement":"E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The only line of each test case contains two integers nn and dd (2\u2264n,d\u226450002\u2264n,d\u22645000) \u2014 the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (\u2211n\u22645000,\u2211d\u22645000\u2211n\u22645000,\u2211d\u22645000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print \"NO\" (without quotes) in the first line. Otherwise, print \"{YES}\" in the first line. Then print n\u22121n\u22121 integers p2,p3,\u2026,pnp2,p3,\u2026,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3\n5 7\n10 19\n10 18\nOutputCopyYES\n1 2 1 3 \nYES\n1 2 3 3 9 9 2 1 6 \nNO\nNotePictures corresponding to the first and the second test cases of the example:","tags":["brute force","constructive algorithms","trees"],"code":"for _ in range(int(input())):\n\n n, d = map(int, input().split())\n\n ld, rd = 0, n * (n - 1) \/\/ 2\n\n tn = n\n\n cd = 0\n\n mvl = 1\n\n while tn:\n\n vl = min(tn, mvl)\n\n ld += cd * vl\n\n cd += 1\n\n tn -= vl\n\n mvl *= 2\n\n if not (ld <= d <= rd):\n\n print('NO')\n\n continue\n\n parent = [i-1 for i in range(n)]\n\n bad = [False] * n\n\n deep = [i for i in range(n)]\n\n child = [1] * n\n\n child[-1] = 0\n\n cur = rd\n\n while cur > d:\n\n v = None\n\n for i in range(n):\n\n if not bad[i] and not child[i] and (v is None or deep[i] < deep[v]):\n\n v = i\n\n p = None\n\n for i in range(n):\n\n if child[i] < 2 and deep[i] < deep[v] - 1 and (p is None or deep[i] > deep[p]):\n\n p = i\n\n if p is None:\n\n bad[v] = True\n\n else:\n\n child[parent[v]] -= 1\n\n deep[v] -= 1\n\n child[p] += 1\n\n parent[v] = p\n\n cur -= 1\n\n print('YES')\n\n print(*map(lambda x: x + 1, parent[1:]))\n\n","language":"py"} -{"contest_id":"1304","problem_id":"C","statement":"C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi \u2014 the time (in minutes) when the ii-th customer visits the restaurant, lili \u2014 the lower bound of their preferred temperature range, and hihi \u2014 the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1\u2264q\u22645001\u2264q\u2264500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1\u2264n\u22641001\u2264n\u2264100, \u2212109\u2264m\u2264109\u2212109\u2264m\u2264109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1\u2264ti\u22641091\u2264ti\u2264109, \u2212109\u2264li\u2264hi\u2264109\u2212109\u2264li\u2264hi\u2264109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print \"YES\" if it is possible to satisfy all customers. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0\nOutputCopyYES\nNO\nYES\nNO\nNoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.","tags":["dp","greedy","implementation","sortings","two pointers"],"code":"T = int (input()) \n\nfor test in range (T):\n\n n,m = map (int, input().split(' '))\n\n repost = list() \n\n time = dict () \n\n scad = list()\n\n for reservation in range (n):\n\n t,l,r= map(int ,input().split(' ')) \n\n if t in time.keys():\n\n old = repost[time[t]]\n\n l = max (old[0],l)\n\n r= min (old[1],r) \n\n repost.append([l,r])\n\n ind = int (len(repost)-1)\n\n time.update({t:ind})\n\n else:\n\n repost.append([l,r])\n\n ind = int (len(repost)-1)\n\n time.update({t:ind})\n\n scad.append(t) \n\n scad.sort()\n\n past_time= 0 \n\n past_range = [m,m] \n\n ok = True \n\n for t in scad :\n\n nowRang= [past_range[0]- abs (t-past_time),past_range[1] +abs (t-past_time) ]\n\n thistine = repost[time[t]]\n\n now =[max (nowRang[0],thistine[0]), min (nowRang[1],thistine[1])]\n\n ok &= now[1]>=now[0]\n\n past_range = now\n\n past_time =t \n\n print (\"YES\") if ok else print (\"NO\")","language":"py"} -{"contest_id":"1296","problem_id":"C","statement":"C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x\u22121,y)(x\u22121,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y\u22121)(x,y\u22121). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of \"LURLLR\" are \"LU\", \"LR\", \"LURLLR\", \"URL\", but not \"RR\" and \"UL\".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' \u2014 the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211n\u22642\u22c5105\u2211n\u22642\u22c5105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n \u2014 endpoints of the substring you remove. The value r\u2212l+1r\u2212l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4\n4\nLRUD\n4\nLURD\n5\nRRUDU\n5\nLLDDR\nOutputCopy1 2\n1 4\n3 4\n-1\n","tags":["data structures","implementation"],"code":"for _ in range(int(input())):\n\n n = int((input()))\n\n s = input()\n\n cur = (0, 0) \n\n dic = {(0, 0): 0}\n\n l, r = -1, n\n\n for i, a in enumerate(s): \n\n f, s = cur\n\n if a == 'L': \n\n cur = (f - 1, s)\n\n if a == 'R':\n\n cur = (f + 1, s)\n\n if a == 'U':\n\n cur = (f, s + 1)\n\n if a == 'D':\n\n cur = (f, s - 1) \n\n if cur in dic: \n\n if i - dic[cur] + 1 < r - l + 1: \n\n l, r = dic[cur], i \n\n dic[cur] = i + 1 \n\n if l == -1:\n\n print(-1)\n\n else:\n\n print(l + 1, r + 1)\n\n ","language":"py"} -{"contest_id":"1293","problem_id":"B","statement":"B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show \"1 vs. nn\"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0\u2264t\u2264s0\u2264t\u2264s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s\u2212ts\u2212t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10\u2212410\u22124. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a\u2212b|max(1,b)\u226410\u22124|a\u2212b|max(1,b)\u226410\u22124.ExamplesInputCopy1\nOutputCopy1.000000000000\nInputCopy2\nOutputCopy1.500000000000\nNoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.","tags":["combinatorics","greedy","math"],"code":"print(sum([1\/i for i in range(1,int(input())+1)]))\n\t\t\t\t\t\t \t \t \t \t \t \t \t\t","language":"py"} -{"contest_id":"1284","problem_id":"C","statement":"C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n. This indicates the subsegment where l\u22121l\u22121 elements from the beginning and n\u2212rn\u2212r elements from the end are deleted from the sequence.For a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212lmax{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1\u2264n\u22642500001\u2264n\u2264250000, 108\u2264m\u2264109108\u2264m\u2264109, mm is prime).OutputPrint rr (0\u2264r= M: ans -= M\n return ans\n\ntoks = sys.stdin.read().split()\nN = int(toks[0])\nM = int(toks[1])\nprint(solve2(N, M))\n","language":"py"} -{"contest_id":"1301","problem_id":"D","statement":"D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm\u22122n\u22122m)(4nm\u22122n\u22122m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i\u22121,j)(i\u22121,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j\u22121)(i,j\u22121); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1\u2264n,m\u22645001\u2264n,m\u2264500, 1\u2264k\u22641091\u2264k\u2264109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print \"NO\" (without quotes), otherwise print \"YES\" (without quotes) in the first line.If the answer is \"YES\", on the second line print an integer aa (1\u2264a\u226430001\u2264a\u22643000)\u00a0\u2014 the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1\u2264f\u22641091\u2264f\u2264109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4\nOutputCopyYES\n2\n2 R\n2 L\nInputCopy3 3 1000000000\nOutputCopyNO\nInputCopy3 3 8\nOutputCopyYES\n3\n2 R\n2 D\n1 LLRR\nInputCopy4 4 9\nOutputCopyYES\n1\n3 RLD\nInputCopy3 4 16\nOutputCopyYES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D\nNoteThe moves Bashar is going to move in the first example are: \"RRLL\".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: \"RRDDLLRR\".The moves Bashar is going to move in the fifth example are: \"RRRLLLDRRRDULLLD\". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):","tags":["constructive algorithms","graphs","implementation"],"code":"import sys\ninput = sys.stdin.readline\nimport math\nimport copy\nimport collections\nfrom collections import deque\n\ndef solve(ans):\n print(len(ans))\n for ele in ans:\n print(ele[0],ele[1])\n\nn,m,k = map(int,input().split())\ncount = 0\nans = []\nif 4*n*m-2*n-2*m=k:\n ans.append([k,'R'])\n solve(ans)\n quit()\n else:\n ans.append([m-1,'R'])\n k-=m-1\n ans.append([k,'L'])\n solve(ans)\nelif m==1:\n print(\"YES\")\n if n-1>=k:\n ans.append([k,'D'])\n solve(ans)\n quit()\n else:\n ans.append([n-1,'D'])\n k-=n-1\n ans.append([k,'U'])\n solve(ans)\nelse:\n print(\"YES\")\n if n-1>=k:\n ans.append([k,'D'])\n solve(ans)\n quit()\n else:\n k-=n-1\n count+=1\n ans.append([n-1,'D'])\n row = n-1\n while row>0:\n if m-1>=k:\n ans.append([k,'R'])\n solve(ans)\n quit()\n else:\n k-=m-1\n count+=1\n ans.append([m-1,'R'])\n if m-1>=k:\n ans.append([k,'L'])\n solve(ans)\n quit()\n else:\n k-=m-1\n count+=1\n ans.append([m-1,'L'])\n count+=1\n ans.append([1,'U'])\n k-=1\n if k==0:\n solve(ans)\n quit()\n row-=1\n col = 0\n while col=k:\n ans.append([k,'D'])\n solve(ans)\n quit()\n else:\n count+=1\n k-=n-1\n ans.append([n-1,'D'])\n if n-1>=k:\n ans.append([k,'U'])\n solve(ans)\n quit()\n else:\n count+=1\n k-=n-1\n ans.append([n-1,'U'])\n count+=1\n ans.append([k,'L'])\n solve(ans)\n\n","language":"py"} -{"contest_id":"1296","problem_id":"A","statement":"A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1\u2264i,j\u2264n1\u2264i,j\u2264n such that i\u2260ji\u2260j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226420001\u2264t\u22642000) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u226420001\u2264n\u22642000) \u2014 the number of elements in aa. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226420001\u2264ai\u22642000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (\u2211n\u22642000\u2211n\u22642000).OutputFor each test case, print the answer on it \u2014 \"YES\" (without quotes) if it is possible to obtain the array with an odd sum of elements, and \"NO\" otherwise.ExampleInputCopy5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1\nOutputCopyYES\nNO\nYES\nNO\nNO\n","tags":["math"],"code":"t = int(input())\n\n\n\nfor i in range(t):\n\n n = int(input())\n\n number = (input().split())\n\n ans = 0\n\n for x in number:\n\n if int(x) % 2 == 0:\n\n ans += 1\n\n if (ans == n) or (ans == 0 and n % 2 == 0):\n\n print(\"NO\")\n\n else:\n\n print(\"YES\")\n\n","language":"py"} -{"contest_id":"1315","problem_id":"A","statement":"A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a\u00d7ba\u00d7b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0\u2264x2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers\u00a0\u2014 the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6\n8 8 0 0\n1 10 0 3\n17 31 10 4\n2 1 0 0\n5 10 3 9\n10 10 4 8\nOutputCopy56\n6\n442\n1\n45\n80\nNoteIn the first test case; the screen resolution is 8\u00d788\u00d78, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. ","tags":["implementation"],"code":"import sys\n\nimport math\n\nimport bisect\n\nimport heapq\n\nimport string\n\nfrom collections import defaultdict,Counter,deque\n\n \n\ndef I():\n\n return input()\n\n \n\ndef II():\n\n return int(input())\n\n \n\ndef MII():\n\n return map(int, input().split())\n\n \n\ndef LI():\n\n return list(input().split())\n\n \n\ndef LII():\n\n return list(map(int, input().split()))\n\n \n\ndef GMI():\n\n return map(lambda x: int(x) - 1, input().split())\n\n \n\ndef LGMI():\n\n return list(map(lambda x: int(x) - 1, input().split()))\n\n \n\ndef WRITE(out):\n\n return print('\\n'.join(map(str, out)))\n\n \n\ndef WS(out):\n\n return print(' '.join(map(str, out)))\n\n \n\ndef WNS(out):\n\n return print(''.join(map(str, out)))\n\n\n\n'''\n\nb > a\n\ngcd(b,a) == 1\n\n\n\nn = 1000\n\nb => (2,n+1)\n\n a = n-b\n\n if gcd(a,b) == 1:\n\n cnt += 1\n\nprint(cnt)\n\n\n\n6\n\n1 5\n\n2 4 x\n\n\n\nx x x x x\n\nx x x x x\n\nx x x x x\n\nx x x x x\n\nx x x x x\n\nx x x x x\n\nx x x x x\n\nx x x x x\n\nx x ! x x\n\nx x x x x\n\n'''\n\n\n\n# sys.stdin = open(\"backforth.in\", \"r\")\n\n# sys.stdout = open(\"backforth.out\", \"w\")\n\ninput = sys.stdin.readline\n\n\n\ndirections = [[-1,-1],[-1,1],[1,-1],[1,1]]\n\n\n\ndef isCross(i,j,grid):\n\n for di, dj in directions:\n\n if grid[i+di][j+dj] != 'X':\n\n return False\n\n return True\n\n\n\ndef solve():\n\n t = II()\n\n for _ in range(t):\n\n a,b,x,y = MII()\n\n all_rows = max(b * x, b * (a - x - 1))\n\n all_cols = max(a * y, a * (b - y - 1))\n\n print(max(all_rows, all_cols))\n\n\n\nsolve() ","language":"py"} -{"contest_id":"1286","problem_id":"C1","statement":"C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the string, and the following line should contain the string ss.ExampleInputCopy4\n\na\naa\na\n\ncb\nb\nc\n\ncOutputCopy? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc","tags":["brute force","constructive algorithms","interactive","math"],"code":"import sys\n\ninput = sys.stdin.buffer.readline \n\n\n\n\n\ndef convert(s):\n\n answer = [0 for i in range(26)]\n\n for c in s:\n\n answer[ord(c)-ord('a')]+=1\n\n return answer\n\n\n\ndef string_apply(t1, t2, f):\n\n answer = [f(t1[i], t2[i]) for i in range(26)]\n\n return answer\n\n \n\ndef convert2(t):\n\n if max(t)==1 and min(t)==0 and sum(t)==1:\n\n for i in range(26):\n\n if t[i]==1:\n\n return chr(i+ord('a'))\n\n return -1 \n\n\n\ndef process(n):\n\n L = []\n\n sys.stdout.write(f'? 1 {n}\\n')\n\n sys.stdout.flush()\n\n for i in range(n*(n+1)\/\/2):\n\n substring = input().decode().strip()\n\n L.append([convert(substring), 1])\n\n if n >= 2:\n\n sys.stdout.write(f'? 2 {n}\\n')\n\n sys.stdout.flush()\n\n for i in range(n*(n-1)\/\/2):\n\n substring = input().decode().strip()\n\n L.append([convert(substring), 2])\n\n L.sort()\n\n curr = [L[0][0], 0, 0]\n\n L2 = []\n\n for i in range(len(L)):\n\n if curr[0] < L[i][0]:\n\n L2.append(curr)\n\n curr = [L[i][0], 0, 0]\n\n t = L[i][1]\n\n curr[t]+=1\n\n L2.append(curr)\n\n final = []\n\n for x in L2:\n\n if x[1] > x[2]:\n\n final.append(x[0])\n\n answer = [None for i in range(n)]\n\n answer[0] = convert2(final[0])\n\n for i in range(1, n):\n\n X = string_apply(final[i], final[i-1], lambda a, b: a-b)\n\n answer[i] = convert2(X)\n\n answer = ''.join(answer)\n\n sys.stdout.write(f'! {answer}\\n')\n\n sys.stdout.flush()\n\n \n\nn = int(input())\n\nprocess(n)","language":"py"} -{"contest_id":"1299","problem_id":"B","statement":"B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)\u2212\u2192\u2212\u2212(x,y)\u2192. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB\u2212\u2192\u2212=(x,y)\u2212\u2192\u2212\u2212AB\u2192=(x,y)\u2192. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3\u2264n\u22641053\u2264n\u2264105)\u00a0\u2014 the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|\u2264109|xi|,|yi|\u2264109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput \"YES\" in a separate line, if PP and TT are similar. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4\n1 0\n4 1\n3 4\n0 3\nOutputCopyYESInputCopy3\n100 86\n50 0\n150 0\nOutputCopynOInputCopy8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3\nOutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.","tags":["geometry"],"code":"def d(a, b):\n\n return 1000000 * ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) + (abs(a[0] - b[0]) + abs(a[1] - b[1]))\n\nn = int(input())\n\na = []\n\nb = []\n\nfor i in range(n):\n\n b.append([int(x) for x in input().split()])\n\nfor i in range(n - 1):\n\n a.append(d(b[i], b[i + 1]))\n\na.append(d(b[0], b[-1]))\n\nif n % 2:\n\n print('NO')\n\n quit()\n\nfor i in range(n \/\/ 2):\n\n if a[i] != a[i + n \/\/ 2]:\n\n print('NO')\n\n quit()\n\nprint('YES')\n\n\n\n","language":"py"} -{"contest_id":"1284","problem_id":"B","statement":"B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,\u2026,al]a=[a1,a2,\u2026,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1\u2264i 2):\n\n counter[n] += 1;\n\n \n\n return counter;\n\n\n\n\n\n\n\n\n\n\n\n\n\nn = int(input())\n\n\n\n\n\narrays = []\n\n\n\ngenCnt = 0;\n\n\n\ncount = 0;\n\n\n\n\n\nmaxes, mins = [], []\n\nfor _ in range(n):\n\n array = list(map(int, input().split()))\n\n \n\n array = array[1:]\n\n \n\n if array != sorted(array, reverse = True):\n\n continue\n\n else:\n\n maxes.append(max(array));\n\n mins.append(min(array))\n\n \n\n\n\n\n\n\n\nmins.sort()\n\nmaxes.sort()\n\n\n\n\n\n\n\ndef bisectLeft(val):\n\n leftPointer, rightPointer = 0, len(maxes) - 1\n\n \n\n ans = -1\n\n while(rightPointer >= leftPointer):\n\n middlePointer = (rightPointer + leftPointer) \/\/ 2\n\n if maxes[middlePointer] <= val:\n\n ans = middlePointer;\n\n leftPointer = middlePointer + 1\n\n else:\n\n rightPointer = middlePointer - 1\n\n \n\n return ans; \n\n\n\n\n\nfor num in mins:\n\n count += bisectLeft(num) + 1\n\n\n\nprint((n * n) - count) ","language":"py"} -{"contest_id":"1294","problem_id":"D","statement":"D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai\u2212xai:=ai\u2212x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,\u2026,yj][y1,y2,\u2026,yj].InputThe first line of the input contains two integers q,xq,x (1\u2264q,x\u22644\u22c51051\u2264q,x\u22644\u22c5105) \u2014 the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0\u2264yj\u22641090\u2264yj\u2264109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query \u2014 for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3\n0\n1\n2\n2\n0\n0\n10\nOutputCopy1\n2\n3\n3\n4\n4\n7\nInputCopy4 3\n1\n2\n1\n2\nOutputCopy0\n0\n0\n0\nNoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]\u22123=10\u22123=7a[6]:=a[6]\u22123=10\u22123=7, a[6]:=a[6]\u22123=7\u22123=4a[6]:=a[6]\u22123=7\u22123=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77. ","tags":["data structures","greedy","implementation","math"],"code":"q,x=map(int,input().split())\n\na,m,s=[0]*(x+1),0,\"\"\n\nwhile q>0:\n\n\tq-=1\n\n\ta[int(input())%x]+=1\n\n\twhile a[m%x]>0:\n\n\t\ta[m%x]-=1\n\n\t\tm+=1\n\n\ts+=(str(m)+\"\\n\")\n\nprint(s)","language":"py"} -{"contest_id":"1284","problem_id":"C","statement":"C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n. This indicates the subsegment where l\u22121l\u22121 elements from the beginning and n\u2212rn\u2212r elements from the end are deleted from the sequence.For a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212lmax{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1\u2264n\u22642500001\u2264n\u2264250000, 108\u2264m\u2264109108\u2264m\u2264109, mm is prime).OutputPrint rr (0\u2264r lp[i] or i * p >= MAX:\n\n\t\t\tbreak\n\n\t\tlp[i * p] = p\n\n\n\nn = int(input())\n\na = list(map(int, input().split()))\n\n\n\ng = [[] for _ in range(len(pid))]\n\ne = set()\n\nfor x in a:\n\n\tf = []\n\n\twhile x > 1:\n\n\t\tp, c = lp[x], 0\n\n\t\twhile lp[x] == p:\n\n\t\t\tx \/\/= p\n\n\t\t\tc ^= 1\n\n\t\tif c:\n\n\t\t\tf.append(p)\n\n\tif not f:\n\n\t\tprint(1)\n\n\t\tsys.exit(0)\n\n\tf += [1] * (2 - len(f))\n\n\tu, v = pid[f[0]], pid[f[1]]\n\n\tif (u, v) in e or (v, u) in e:\n\n\t\tprint(2)\n\n\t\tsys.exit(0)\n\n\tg[u].append(v)\n\n\tg[v].append(u)\n\n\n\ndef bfs(s):\n\n\td = [-1] * len(pid)\n\n\td[s] = 0\n\n\tq = [(s, -1)]\n\n\twhile q:\n\n\t\tq2 = []\n\n\t\tfor u, p in q:\n\n\t\t\tfor v in g[u]:\n\n\t\t\t\tif d[v] != -1:\n\n\t\t\t\t\tif v != p:\n\n\t\t\t\t\t\treturn d[u] + d[v] + 1\n\n\t\t\t\telse:\n\n\t\t\t\t\td[v] = d[u] + 1\n\n\t\t\t\t\tq2.append((v, u))\n\n\t\tq = q2\n\n\n\nans = n + 1\n\nfor i in range(len(pid)):\n\n\tif i > 0 and pr[i - 1] ** 2 >= MAX:\n\n\t\tbreak\n\n\tans = min(ans, bfs(i) or ans)\n\nprint(ans if ans <= n else -1)\n\n","language":"py"} -{"contest_id":"1325","problem_id":"A","statement":"A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1\u2264t\u2264100)(1\u2264t\u2264100) \u00a0\u2014 the number of testcases.Each testcase consists of one line containing a single integer, xx (2\u2264x\u2264109)(2\u2264x\u2264109).OutputFor each testcase, output a pair of positive integers aa and bb (1\u2264a,b\u2264109)1\u2264a,b\u2264109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2\n2\n14\nOutputCopy1 1\n6 4\nNoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.","tags":["constructive algorithms","greedy","number theory"],"code":"n = int(input())\n\nfor i in range(n):\n\n x = int(input())\n\n print(1,x-1, sep=\" \")","language":"py"} -{"contest_id":"1284","problem_id":"C","statement":"C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n. This indicates the subsegment where l\u22121l\u22121 elements from the beginning and n\u2212rn\u2212r elements from the end are deleted from the sequence.For a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212lmax{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1\u2264n\u22642500001\u2264n\u2264250000, 108\u2264m\u2264109108\u2264m\u2264109, mm is prime).OutputPrint rr (0\u2264r=2:\n\n return (2,(1,2))\n\n else:\n\n return -1\n\n else:\n\n return (1,(res.index(0)+1,))\n\n \n\nfor i in range(t):\n\n n=int(input())\n\n L=[int(x)for x in input().split()]\n\n M.append(fonction(L,n))\n\nfor k in M:\n\n if k==-1:\n\n print(k)\n\n else:\n\n print(k[0])\n\n print(\" \".join([str(x) for x in k[1]]))","language":"py"} -{"contest_id":"1284","problem_id":"B","statement":"B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,\u2026,al]a=[a1,a2,\u2026,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1\u2264i=0):\n\n print(-1)\n\n return()\n\n tot=-tot\n\n mi=10**21\n\n for i in range(n):\n\n ans=(i+1)+((((H+pref[i])\/\/tot)+min((H+pref[i])%tot,1))*n)\n\n mi=min(mi,ans)\n\n print(mi)\n\n \n\n \n\nmain()\n\n","language":"py"} -{"contest_id":"1324","problem_id":"E","statement":"E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai\u22121ai\u22121 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264raiai 1:\n\n checker = 0\n\n for letter in 'zyxwvutsrqponmlkjihgfedcb':\n\n # print(letter, end='')\n\n if letter in s:\n\n for i in range(0, len(s)):\n\n a = i-1\n\n b = i+1\n\n neighbours = []\n\n if a >= 0:\n\n neighbours.append(s[a])\n\n if b < len(s):\n\n neighbours.append(s[b])\n\n\n\n if s[i] == letter and chr(ord(s[i])-1) in neighbours:\n\n s = s[:i] + s[i+1:]\n\n checker = 1\n\n break\n\n \n\n if checker == 1:\n\n break\n\n # print()\n\n if checker == 0:\n\n # print(s)\n\n break\n\nprint(n-len(s))\n\n ","language":"py"} -{"contest_id":"1325","problem_id":"C","statement":"C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n\u22122n\u22122 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2\u2264n\u22641052\u2264n\u2264105)\u00a0\u2014 the number of nodes in the tree.Each of the next n\u22121n\u22121 lines contains two space-separated integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n\u22121n\u22121 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3\n1 2\n1 3\nOutputCopy0\n1\nInputCopy6\n1 2\n1 3\n2 4\n2 5\n5 6\nOutputCopy0\n3\n2\n4\n1NoteThe tree from the second sample:","tags":["constructive algorithms","dfs and similar","greedy","trees"],"code":"n = int(input())\ng = [0]*(n+1)\nl = []\nfor i in range(n-1):\n\ta,b = map(int,input().split())\n\ta -= 1\n\tb -= 1\n\tg[a] += 1\n\tg[b] += 1\n\tl.append([a,b])\ncnt = 0\nmex = n-2\nfor a,b in l:\n\tif g[a] == 1 or g[b] == 1:\n\t\tprint(cnt)\n\t\tcnt += 1\n\telse:\n\t\tprint(mex)\n\t\tmex -= 1\n\t \t\t \t\t \t\t\t\t \t\t \t \t \t","language":"py"} -{"contest_id":"1320","problem_id":"C","statement":"C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1\u2264n,m,p\u22642\u22c51051\u2264n,m,p\u22642\u22c5105)\u00a0\u2014 the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1\u2264ai\u22641061\u2264ai\u2264106, 1\u2264cai\u22641091\u2264cai\u2264109)\u00a0\u2014 the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1\u2264bj\u22641061\u2264bj\u2264106, 1\u2264cbj\u22641091\u2264cbj\u2264109)\u00a0\u2014 the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1\u2264xk,yk\u22641061\u2264xk,yk\u2264106, 1\u2264zk\u22641031\u2264zk\u2264103)\u00a0\u2014 defense, attack and the number of coins of the monster kk.OutputPrint a single integer\u00a0\u2014 the maximum profit of the grind.ExampleInputCopy2 3 3\n2 3\n4 7\n2 4\n3 2\n5 11\n1 2 4\n2 1 6\n3 4 6\nOutputCopy1\n","tags":["brute force","data structures","sortings"],"code":"from sys import stdin, stdout\n\nfrom bisect import bisect_left, bisect_right\n\n\n\ndp = []\n\nadd = []\n\nam = []\n\n\n\ndef build(pos, l,r):\n\n global dp\n\n global am\n\n if l == r - 1:\n\n dp[pos] = -am[l][1]\n\n return\n\n mid = int((l+r)\/2)\n\n build (pos*2+1,l,mid)\n\n build (pos*2+2,mid,r)\n\n dp[pos] = max(dp[pos*2+1],dp[pos*2+2])\n\n \n\ndef push(pos, l,r):\n\n global dp\n\n global add\n\n if add[pos] != 0:\n\n if r- l > 1:\n\n add[pos*2+1] += add[pos]\n\n dp[pos*2+1] += add[pos]\n\n add[pos*2+2] += add[pos]\n\n dp[pos*2+2] += add[pos]\n\n add[pos] = 0\n\n \n\ndef update(pos, l,r,L,R, val):\n\n global dp\n\n global add\n\n if L>=R:\n\n return\n\n if l == L and r == R:\n\n add[pos] += val\n\n dp[pos] += val\n\n push(pos, l,r)\n\n return\n\n push(pos, l,r)\n\n mid = int((l+r)\/2)\n\n update(pos*2+1, l, mid, L, min(R,mid), val)\n\n update(pos*2+2, mid, r, max(L,mid), R, val)\n\n dp[pos] = max(dp[pos*2+1],dp[pos*2+2])\n\n \n\ndef main():\n\n global dp\n\n global am\n\n global add\n\n n,m,k = list(map(int, stdin.readline().split()))\n\n AMT = 1000002\n\n dp = [0] * (m *4 + 2)\n\n add = [0] * (m *4 + 2)\n\n WP = [-1] * AMT\n\n AM = [-1] * AMT\n\n am2 = []\n\n PWN = [[] for _ in range(AMT)]\n\n max_atk = -1\n\n for _ in range(n):\n\n power, cost = list(map(int, stdin.readline().split()))\n\n if WP[power] == -1 or (WP[power] != -1 and WP[power] > cost):\n\n WP[power] = cost\n\n if power > max_atk:\n\n max_atk = power\n\n \n\n for _ in range(m):\n\n power, cost = list(map(int, stdin.readline().split()))\n\n if AM[power] == -1 or (AM[power] != -1 and AM[power] > cost):\n\n AM[power] = cost\n\n \n\n for _ in range(k):\n\n atk, df, gold = list(map(int, stdin.readline().split()))\n\n PWN[atk+1].append((df, gold))\n\n for i in range(AMT):\n\n if AM[i] != -1:\n\n am.append((i, AM[i]))\n\n am2.append(i)\n\n m = len(am)\n\n\n\n build(0,0,m)\n\n mx = -999999999999\n\n for i in range(AMT):\n\n if i > max_atk:\n\n break\n\n for a,b in PWN[i]:\n\n right = bisect_right(am2, a)\n\n update(0, 0, m, right, m, b)\n\n if WP[i] == -1:\n\n continue\n\n temp = dp[0]\n\n if temp - WP[i] > mx:\n\n mx = temp - WP[i]\n\n stdout.write(str(mx))\n\n\n\nmain()","language":"py"} -{"contest_id":"1325","problem_id":"E","statement":"E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the length of aa.The second line contains nn integers a1a1, a2a2, \u2026\u2026, anan (1\u2264ai\u22641061\u2264ai\u2264106)\u00a0\u2014 the elements of the array aa.OutputOutput the length of the shortest non-empty subsequence of aa product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print \"-1\".ExamplesInputCopy3\n1 4 6\nOutputCopy1InputCopy4\n2 3 6 6\nOutputCopy2InputCopy3\n6 15 10\nOutputCopy3InputCopy4\n2 3 5 7\nOutputCopy-1NoteIn the first sample; you can choose a subsequence [1][1].In the second sample, you can choose a subsequence [6,6][6,6].In the third sample, you can choose a subsequence [6,15,10][6,15,10].In the fourth sample, there is no such subsequence.","tags":["brute force","dfs and similar","graphs","number theory","shortest paths"],"code":"import collections\nimport math\n\n\ndef prime_range(n):\n sieve = [0] * n\n pid = {1: 0}\n for i in range(2, n):\n if not sieve[i]:\n sieve[i] = i\n pid[i] = len(pid)\n for j in range(i * i, n, i):\n if not sieve[j]:\n sieve[j] = i\n return sieve, pid\n\n\ndef odd_prime_factors(a, min_p_factor):\n f = collections.Counter()\n while a > 1:\n x = min_p_factor[a]\n f[x] ^= 1\n a \/\/= x\n return [x for x in f if f[x]]\n\n\ndef shortest_cycle(root, g):\n if not g[root]:\n return math.inf\n # -1 is faster than None (PyPy 3.6.9)\n depth = [-1] * len(g)\n depth[root] = 0\n queue = collections.deque([(root, None)])\n while queue:\n u, parent = queue.popleft()\n for v in g[u]:\n if depth[v] is -1:\n depth[v] = depth[u] + 1\n queue.append((v, u))\n elif v != parent:\n return depth[u] + depth[v] + 1\n return math.inf\n\n\nmin_p_factor, pid = prime_range(10**6 + 1)\ninput()\ng = [[] for _ in range(len(pid))]\nfor x in map(int, input().split()):\n f = odd_prime_factors(x, min_p_factor)\n if not f:\n print(1)\n exit()\n f.append(1)\n u, v = pid[f[0]], pid[f[1]]\n g[u].append(v)\n g[v].append(u)\nshortest = min(shortest_cycle(i, g) for i in range(169)) # pid[1009] == 169\nprint(shortest if math.isfinite(shortest) else -1)\n","language":"py"} -{"contest_id":"1313","problem_id":"B","statement":"B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round\u00a0\u2014 yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100)\u00a0\u2014 the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1\u2264n\u22641091\u2264n\u2264109, 1\u2264x,y\u2264n1\u2264x,y\u2264n)\u00a0\u2014 the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers\u00a0\u2014 the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second\u00a0\u2014 third place.","tags":["constructive algorithms","greedy","implementation","math"],"code":"t=int(input())\n\n \n\nfor k in range(t):\n\n nit,x,y=map(int,input().split())\n\n print(max(1,min(nit,x+y-nit+1)),min(x+y-1,nit))\n\n","language":"py"} -{"contest_id":"1288","problem_id":"D","statement":"D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k\u2208[1,m]k\u2208[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105, 1\u2264m\u226481\u2264m\u22648) \u2014 the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0\u2264ax,y\u22641090\u2264ax,y\u2264109).OutputPrint two integers ii and jj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j) \u2014 the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5\n5 0 3 1 2\n1 8 9 1 3\n1 2 3 4 5\n9 1 0 3 7\n2 3 0 6 3\n6 4 1 7 0\nOutputCopy1 5\n","tags":["binary search","bitmasks","dp"],"code":"n,m=map(int,input().split())\n\narr=[]\n\nfor _ in range(n):\n\n arr.append(list(map(int,input().split())))\n\nl=0\n\na1=0\n\na2=0\n\nr=10**10\n\ndef check(x):\n\n d=[-1 for _ in range(1<x:\n\n curr|=(1<0:\n\n \n\n \n\n if vector[contor][0]==bloc[0]:\n\n left=max(vector[contor][1],bloc[1])\n\n right=min(vector[contor][2],bloc[2])\n\n if left>right:\n\n partial=0\n\n else:\n\n vector[contor][1]=left\n\n vector[contor][2]=right\n\n else:\n\n vector.append(bloc)\n\n contor+=1\n\n else:\n\n vector.append(bloc)\n\n contor+=1\n\n \n\n \n\n \n\n if partial==0:\n\n print(\"NO\")\n\n else:\n\n # print(vector)\n\n for pp in vector:\n\n posibil=0\n\n ti,li,hi=pp\n\n # print(ti,li,hi)\n\n \n\n durata=ti-timpul_initial\n\n timpul_initial=ti\n\n \n\n max_left=max_left-durata\n\n max_right=max_right+durata\n\n \n\n if (li>=max_left and li<=max_right) or (hi>=max_left and hi<=max_right) or (li<=max_left and hi>=max_right):\n\n posibil=1\n\n max_left=min(max(li,max_left),max_right)\n\n max_right=max(min(hi,max_right),max_left)\n\n if posibil==0:\n\n posibil_total=\"NO\"\n\n break\n\n \n\n \n\n print(posibil_total)\n\n ","language":"py"} -{"contest_id":"1311","problem_id":"C","statement":"C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s=\"abca\" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1\u2264pi0:\n\n c[i]-=1\n\n else :\n\n while i<60 and c[i]==0:\n\n i+=1\n\n res+=1\n\n c[i]-=1\n\n continue\n\n c[i+1]+=c[i]\/\/2\n\n i+=1\n\n print(res)","language":"py"} -{"contest_id":"1307","problem_id":"B","statement":"B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,\u2026,ana1,a2,\u2026,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi\u2212xj)2+(yi\u2212yj)2\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u2212\u221a(xi\u2212xj)2+(yi\u2212yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) \u2192\u2192 (2,\u22125\u2013\u221a)(2,\u22125) \u2192\u2192 (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 the number of test cases. Next 2t2t lines contain test cases \u2014 two lines per test case.The first line of each test case contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, 1\u2264x\u22641091\u2264x\u2264109) \u00a0\u2014 the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109) \u00a0\u2014 Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer\u00a0\u2014 the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2\n3\n1\n2\nNoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5\u2013\u221a)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) \u2192\u2192 (4,0)(4,0) \u2192\u2192 (8,0)(8,0) \u2192\u2192 (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) \u2192\u2192 (5,102\u2013\u221a)(5,102) \u2192\u2192 (10,0)(10,0).","tags":["geometry","greedy","math"],"code":"for _ in range(int(input())):\n\n n, x = [int(x) for x in input().split()]\n\n a = [int(x) for x in input().split()]\n\n f = max(a)\n\n if f < x:\n\n print((x + f - 1) \/\/ f)\n\n elif x in a:\n\n print(1)\n\n else:\n\n print(2)\n\n","language":"py"} -{"contest_id":"1288","problem_id":"B","statement":"B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Each test case contains two integers AA and BB (1\u2264A,B\u2264109)(1\u2264A,B\u2264109).OutputPrint one integer \u2014 the number of pairs (a,b)(a,b) such that 1\u2264a\u2264A1\u2264a\u2264A, 1\u2264b\u2264B1\u2264b\u2264B, and the equation a\u22c5b+a+b=conc(a,b)a\u22c5b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1\n0\n1337\nNoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1\u22c59=191+9+1\u22c59=19).","tags":["math"],"code":"import sys\n\nfrom math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm\n\nfrom collections import deque, Counter, OrderedDict, defaultdict\n\nfrom heapq import heapify, heappush, heappop\n\n#from sortedcontainers import SortedList\n\n#sys.setrecursionlimit(10**5)\n\nfrom functools import lru_cache\n\n#@lru_cache(None)\n\n\n\n#======================================================#\n\ninput = lambda: sys.stdin.readline()\n\nI = lambda: int(input().strip())\n\nS = lambda: input().strip()\n\nM = lambda: map(int,input().strip().split())\n\nL = lambda: list(map(int,input().strip().split()))\n\n#======================================================#\n\n\n\ndef bs(arr,x):\n\n low,high = 0,len(arr)-1\n\n ans = len(arr)\n\n while low<=high:\n\n mid = (low+high)\/\/2\n\n #if arr[mid]==x:\n\n # return x\n\n if arr[mid]n:\n\n return 0\n\n return ((nfactorial[n]*finverse[k]%mod)*finverse[n-k])%mod\n\n#======================================================#\n\ndef primelist():\n\n L = [False for i in range((10**10)+1)]\n\n primes = [False for i in range((10**10)+1)]\n\n for i in range(2,(10**10)+1):\n\n if not L[i]:\n\n primes[i]=True\n\n for j in range(i,(10**10)+1,i):\n\n L[j]=True\n\n return primes\n\ndef isPrime(n):\n\n p = primelist()\n\n return p[n]\n\n#======================================================#\n\ndef bst(arr,x):\n\n low,high = 0,len(arr)-1\n\n ans = -1\n\n while low<=high:\n\n mid = (low+high)\/\/2\n\n if arr[mid]==x:\n\n return x\n\n if arr[mid] p\n\n\n\n\n\n\n\nfor _ in range(int(input())):\n\n a, b, p = map(int, input().split())\n\n s = input()\n\n l = -1\n\n r = len(s)\n\n# print(a, \"LOL\")\n\n while r - l > 1:\n\n m = (r + l) \/\/ 2\n\n# print(l, r, m)\n\n if check(s, m, a, b, p):\n\n l = m\n\n else:\n\n r = m\n\n print(r + 1)","language":"py"} -{"contest_id":"1316","problem_id":"C","statement":"C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+\u22ef+an\u22121xn\u22121f(x)=a0+a1x+\u22ef+an\u22121xn\u22121 and g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1. Let h(x)=f(x)\u22c5g(x)h(x)=f(x)\u22c5g(x). Suppose that h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1\u2264n,m\u2264106,2\u2264p\u22641091\u2264n,m\u2264106,2\u2264p\u2264109), \u00a0\u2014 nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,\u2026,an\u22121a0,a1,\u2026,an\u22121 (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,\u2026,bm\u22121b0,b1,\u2026,bm\u22121 (1\u2264bi\u22641091\u2264bi\u2264109) \u00a0\u2014 bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0\u2264t\u2264n+m\u221220\u2264t\u2264n+m\u22122) \u00a0\u2014 the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2\n1 1 2\n2 1\nOutputCopy1\nInputCopy2 2 999999937\n2 1\n3 1\nOutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.","tags":["constructive algorithms","math","ternary search"],"code":"import sys\n\nimport random\n\ninput = sys.stdin.readline\n\nn, m, p = [int(xx) for xx in input().split()]\n\na = [int(xx) for xx in input().split()]\n\nb = [int(Xx) for Xx in input().split()]\n\nfor i in range(n):\n\n a[i] %= p\n\nfor i in range(m):\n\n b[i] %= p\n\npr1 = [0]\n\npr2 = [0]\n\nfor i in range(n):\n\n pr1.append(pr1[-1] + a[i])\n\nfor i in range(m):\n\n pr2.append(pr2[-1] + b[i])\n\nfor i in range(n):\n\n if pr1[i]:\n\n break\n\nfor j in range(m):\n\n if pr2[j]:\n\n break\n\nfor x in range(max(0, i + j - 2), 101010101101010101):\n\n ans = 0\n\n for i in range(min(x + 1, n)):\n\n if x - i < m:\n\n ans += a[i] * b[x - i]\n\n if ans % p:\n\n print(x)\n\n quit()\n\n","language":"py"} -{"contest_id":"1305","problem_id":"E","statement":"E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the \"Proof by AC\" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,\u2026,ana1,a2,\u2026,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1\u2264a1 m:\n\n break\n\n curr_balance+=new_balance;\n\n ans.append(i);\n\n\n\nif curr_balanceb[i]:\n\n rt+=1\n\n else:\n\n bt+=1\n\nif rt>bt:\n\n print('1')\n\nelse:\n\n if rt==0:\n\n print('-1')\n\n else:\n\n if bt%rt==0:\n\n print(bt\/\/rt + 1)\n\n else:\n\n print((bt+(rt-bt%rt))\/\/rt)\n\n\n\n","language":"py"} -{"contest_id":"1311","problem_id":"D","statement":"D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a\u2264b\u2264ca\u2264b\u2264c.In one move, you can add +1+1 or \u22121\u22121 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1\u2264a\u2264b\u2264c\u22641041\u2264a\u2264b\u2264c\u2264104).OutputFor each test case, print the answer. In the first line print resres \u2014 the minimum number of operations you have to perform to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46\nOutputCopy1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48\n","tags":["brute force","math"],"code":"import sys\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\n\\r\")\n\nimport math\n\n\n\ndef solve(): \n\n a, b, c = list(map(int, input().split()))\n\n ans = math.inf\n\n lst = [0, 0, 0] \n\n for i in range(1, 10001):\n\n for j in factors[i]:\n\n p = j * (c \/\/ j)\n\n q = j * (c \/\/ j + 1)\n\n k = None\n\n z = None\n\n if abs(c - p) < abs(c - q):\n\n k = p\n\n z = abs(c - p)\n\n else:\n\n k = q\n\n z = abs(c - q)\n\n y = abs(b - j)\n\n x = abs(a - i)\n\n \n\n if x + y + z < ans:\n\n \n\n ans = x + y + z\n\n lst = [i, j, k]\n\n print(ans)\n\n print(*lst)\n\n\n\nfactors = [[] for i in range(10001)]\n\nfor i in range(1, 10001):\n\n x = i\n\n ind = 1\n\n while True:\n\n val = x * ind\n\n if val > 20001:\n\n break\n\n factors[i].append(val)\n\n ind += 1\n\nfor _ in range(int(input())):\n\n solve()\n\n\n\n\n\n ","language":"py"} -{"contest_id":"1296","problem_id":"D","statement":"D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1\u2264n\u22642\u22c5105,1\u2264a,b,k\u22641091\u2264n\u22642\u22c5105,1\u2264a,b,k\u2264109) \u2014 the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,\u2026,hnh1,h2,\u2026,hn (1\u2264hi\u22641091\u2264hi\u2264109), where hihi is the health points of the ii-th monster.OutputPrint one integer \u2014 the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3\n7 10 50 12 1 8\nOutputCopy5\nInputCopy1 1 100 99\n100\nOutputCopy1\nInputCopy7 4 2 1\n1 3 5 4 2 7 6\nOutputCopy6\n","tags":["greedy","sortings"],"code":"import math\n\n[n,a,b,k]=list(map(int,input().split(\" \")))\n\nnew=list(map(int,input().split(\" \")))\n\nnew=[(i-a)%(a+b) for i in new]\n\narr=[]\n\nans=0\n\nfor i in new:\n\n # print(i)\n\n if i>b:\n\n ans+=1\n\n else:\n\n arr.append(i)\n\narr.sort()\n\ni=0\n\n# print(arr)\n\nwhile(i0):\n\n k-=math.ceil(arr[i]\/a)\n\n # print(k)\n\n if k>=0:\n\n ans+=1\n\n i+=1\n\n # print(ans)\n\nprint(ans)","language":"py"} -{"contest_id":"1304","problem_id":"D","statement":"D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog\u2061n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n\u22121n\u22121, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n\u22121n\u22121.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2\u22c51052\u22c5105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3\n3 <<\n7 >><>><\n5 >>><\nOutputCopy1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3\nNoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.","tags":["constructive algorithms","graphs","greedy","two pointers"],"code":"import sys\n\nimport math\n\nimport collections\n\nimport heapq\n\nimport decimal\n\ninput=sys.stdin.readline\n\nt=int(input())\n\nfor w in range(t):\n\n n,s=(i for i in input().split())\n\n n=int(n)\n\n s=list(s)\n\n ans1=[0]*n\n\n ans2=[0]*n\n\n k=n\n\n prev=-1\n\n for i in range(n):\n\n if(i==n-1 or s[i]=='>'):\n\n for j in range(i,prev,-1):\n\n ans1[j]=k\n\n k-=1\n\n prev=i\n\n k=1\n\n prev=-1\n\n for i in range(n):\n\n if(i==n-1 or s[i]=='<'):\n\n for j in range(i,prev,-1):\n\n ans2[j]=k\n\n k+=1\n\n prev=i\n\n print(*ans1)\n\n print(*ans2)","language":"py"} -{"contest_id":"1316","problem_id":"B","statement":"B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1\u2264k\u2264n1\u2264k\u2264n). For ii from 11 to n\u2212k+1n\u2212k+1, reverse the substring s[i:i+k\u22121]s[i:i+k\u22121] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a\u2260ba\u2260b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u226450001\u2264t\u22645000). The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u226450001\u2264n\u22645000)\u00a0\u2014 the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s\u2032s\u2032 achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1\u2264k\u2264n1\u2264k\u2264n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6\n4\nabab\n6\nqwerty\n5\naaaaa\n6\nalaska\n9\nlfpbavjsm\n1\np\nOutputCopyabab\n1\nertyqw\n3\naaaaa\n1\naksala\n6\navjsmbpfl\n5\np\n1\nNoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11. ","tags":["brute force","constructive algorithms","implementation","sortings","strings"],"code":"def solve():\n\n n = int(input())\n\n seq = input()\n\n\n\n ans = [(seq, 1)]\n\n\n\n def check(k):\n\n if k == 1:\n\n ans[0] = (seq, 1)\n\n return\n\n\n\n seq_copy = list(seq)\n\n seq_copy = seq[k-1:]\n\n if (n-k) % 2 == 0:\n\n seq_copy += seq[:k-1][::-1]\n\n else:\n\n seq_copy += seq[:k-1]\n\n \n\n ans[0] = min(ans[0], (''.join(seq_copy), k))\n\n\n\n\n\n\n\n indices = []\n\n cmin = min(seq)\n\n for i, e in enumerate(seq):\n\n if e == cmin:\n\n indices.append(i+1)\n\n\n\n for idx in indices:\n\n check(idx)\n\n \n\n return ans[0]\n\n\n\n\n\ndef main():\n\n t = int(input())\n\n output = []\n\n for _ in range(t):\n\n ans0, ans1 = solve()\n\n output.append(ans0)\n\n output.append(ans1)\n\n\n\n print_lines(output)\n\n\n\n\n\ndef input(): return next(test).strip()\n\ndef read_ints(): return [int(c) for c in input().split()]\n\ndef print_lines(lst): print('\\n'.join(map(str, lst)))\n\n\n\n\n\nif __name__ == \"__main__\":\n\n import sys\n\n from os import environ as env\n\n if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']:\n\n sys.stdout = open('out.txt', 'w')\n\n sys.stdin = open('in.txt', 'r')\n\n\n\n test = iter(sys.stdin.readlines())\n\n\n\n main()\n\n","language":"py"} -{"contest_id":"1311","problem_id":"B","statement":"B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,\u2026,pmp1,p2,\u2026,pm, where 1\u2264pi=m +1 :res = \"No\" ;break\n\n if p[pos-1] != y-1:res = \"No\" ;break\n\n print(res)\n\n","language":"py"} -{"contest_id":"1287","problem_id":"B","statement":"B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game \"Set\" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature \u2014 color, number, shape, and shading \u2014 the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called \"Hyperset\". In her game, there are nn cards with kk features, each feature has three possible values: \"S\", \"E\", or \"T\". The original \"Set\" game can be viewed as \"Hyperset\" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1\u2264n\u226415001\u2264n\u22641500, 1\u2264k\u2264301\u2264k\u226430)\u00a0\u2014 number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters \"S\", \"E\", \"T\". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer\u00a0\u2014 the number of ways to choose three cards that form a set.ExamplesInputCopy3 3\nSET\nETS\nTSE\nOutputCopy1InputCopy3 4\nSETE\nETSE\nTSES\nOutputCopy0InputCopy5 4\nSETT\nTEST\nEEET\nESTE\nSTES\nOutputCopy2NoteIn the third example test; these two triples of cards are sets: \"SETT\"; \"TEST\"; \"EEET\" \"TEST\"; \"ESTE\", \"STES\" ","tags":["brute force","data structures","implementation"],"code":"import os,sys\n\nfrom io import BytesIO, IOBase\n\n\n\ndef main():\n\n n,k = map(int,input().split())\n\n arr = [input().strip() for _ in range(n)]\n\n se = {arr[i]:i for i in range(n)}\n\n ans = 0\n\n for i in range(n):\n\n for j in range(i+1,n):\n\n req = []\n\n for z in range(k):\n\n if arr[i][z] == arr[j][z]:\n\n req.append(arr[i][z])\n\n else:\n\n xx = [\"S\",\"E\",\"T\"]\n\n xx.remove(arr[i][z])\n\n xx.remove(arr[j][z])\n\n req.append(xx[0])\n\n if se.get(''.join(req),-1) > j:\n\n ans += 1\n\n print(ans)\n\n\n\n# Fast IO Region\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\nif __name__ == \"__main__\":\n\n main()","language":"py"} -{"contest_id":"1296","problem_id":"E1","statement":"E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1\u2264n\u22642001\u2264n\u2264200) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print \"NO\" (without quotes) in the first line.Otherwise, print \"YES\" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9\nabacbecfd\nOutputCopyYES\n001010101\nInputCopy8\naaabbcbb\nOutputCopyYES\n01011011\nInputCopy7\nabcdedc\nOutputCopyNO\nInputCopy5\nabcde\nOutputCopyYES\n00000\n","tags":["constructive algorithms","dp","graphs","greedy","sortings"],"code":"from collections import deque, defaultdict, Counter\n\nfrom heapq import heappush, heappop, heapify\n\nfrom math import inf, sqrt, ceil\n\nfrom functools import lru_cache\n\nfrom itertools import accumulate, combinations, permutations, product\n\nfrom typing import List\n\nfrom bisect import bisect_left, bisect_right\n\nimport sys\n\ninput=lambda:sys.stdin.readline().strip('\\n')\n\nmis=lambda:map(int,input().split())\n\nii=lambda:int(input())\n\n#sys.setrecursionlimit(10 ** 7)\n\n\n\nN = ii()\n\nS = input()\n\n\n\nedges = defaultdict(list)\n\ncolor = [-1] * N\n\n\n\ndef dfs(i, node_color):\n\n if color[i] == node_color:\n\n return \n\n elif color[i] != -1 and color[i] ^ node_color:\n\n print(\"NO\")\n\n exit(0)\n\n color[i] = node_color \n\n for nei in edges[i]:\n\n dfs(nei, 1-node_color)\n\n\n\nfor i, c in enumerate(S):\n\n for j in range(i):\n\n if S[j] > c:\n\n edges[i].append(j)\n\n edges[j].append(i)\n\n\n\nfor i in range(N):\n\n if color[i] == -1:\n\n dfs(i, 0)\n\n\n\nprint(\"YES\")\n\nprint(\"\".join(map(str,color)))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n","language":"py"} -{"contest_id":"1299","problem_id":"B","statement":"B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)\u2212\u2192\u2212\u2212(x,y)\u2192. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB\u2212\u2192\u2212=(x,y)\u2212\u2192\u2212\u2212AB\u2192=(x,y)\u2192. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3\u2264n\u22641053\u2264n\u2264105)\u00a0\u2014 the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|\u2264109|xi|,|yi|\u2264109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput \"YES\" in a separate line, if PP and TT are similar. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4\n1 0\n4 1\n3 4\n0 3\nOutputCopyYESInputCopy3\n100 86\n50 0\n150 0\nOutputCopynOInputCopy8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3\nOutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.","tags":["geometry"],"code":"import sys; import math; \nCASE=0; rla=''\n\n\n\ndef solve() : \n n=int(rla)\n if n&1 : \n for i in range(n) : a, b=map(int, input().split())\n print(\"NO\"); return\n else : \n x=[]; y=[]\n for i in range(n>>1) : \n a, b=map(int, input().split())\n x.append(a); y.append(b)\n flag=0\n a, b=map(int, input().split())\n for i in range(1, (n>>1)) : \n c, d=map(int, input().split())\n if c-a!=x[i-1]-x[i] or d-b!=y[i-1]-y[i] : flag=1\n a=c; b=d\n print(\"NO\" if flag==1 else \"YES\")\n\nwhile True : \n rla=sys.stdin.readline()\n cases=1\n if not rla: break\n if (rla=='\\n')|(rla=='') : continue\n if CASE==1 : cases=int(rla)\n for cas in range(cases) : \n \n solve()\n \n\n\n\t\t \t \t \t\t \t \t\t\t\t \t\t\t \t","language":"py"} -{"contest_id":"1322","problem_id":"A","statement":"A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting \"+\" and \"1\" you can get a well-formed mathematical expression from it. For example; sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not.The teacher gave Dmitry's class a very strange task\u00a0\u2014 she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word \"correct\" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for \"))((\" he can choose the substring \")(\" and do reorder \")()(\" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 the length of Dima's sequence.The second line contains string of length nn, consisting of characters \"(\" and \")\" only.OutputPrint a single integer\u00a0\u2014 the minimum number of nanoseconds to make the sequence correct or \"-1\" if it is impossible to do so.ExamplesInputCopy8\n))((())(\nOutputCopy6\nInputCopy3\n(()\nOutputCopy-1\nNoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with \"()()\"; the whole sequence will be \"()()())(\". And then reorder the segment from the seventh to eighth character; replacing it with \"()\". In the end the sequence will be \"()()()()\"; while the total time spent is 4+2=64+2=6 nanoseconds.","tags":["greedy"],"code":"n=int(input())\n\ns=input()\n\nc=0\n\nfor i in s:\n\n c+=1 if i==\"(\" else 0\n\nif c!=n\/2:\n\n print(-1)\n\n exit()\n\nans=0\n\ndir=0\n\nc=0\n\nl=0\n\nfor i in s:\n\n if c==0:\n\n if dir==-1:\n\n ans+=l\n\n l=0\n\n dir =1 if i==\"(\" else -1\n\n if i==\"(\":\n\n c+=1\n\n l+=1\n\n else:\n\n c-=1\n\n l+=1\n\nif c==0:\n\n if dir==-1:\n\n ans+=l\n\nprint(ans)\n\n ","language":"py"} -{"contest_id":"1316","problem_id":"C","statement":"C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+\u22ef+an\u22121xn\u22121f(x)=a0+a1x+\u22ef+an\u22121xn\u22121 and g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1. Let h(x)=f(x)\u22c5g(x)h(x)=f(x)\u22c5g(x). Suppose that h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1\u2264n,m\u2264106,2\u2264p\u22641091\u2264n,m\u2264106,2\u2264p\u2264109), \u00a0\u2014 nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,\u2026,an\u22121a0,a1,\u2026,an\u22121 (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,\u2026,bm\u22121b0,b1,\u2026,bm\u22121 (1\u2264bi\u22641091\u2264bi\u2264109) \u00a0\u2014 bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0\u2264t\u2264n+m\u221220\u2264t\u2264n+m\u22122) \u00a0\u2014 the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2\n1 1 2\n2 1\nOutputCopy1\nInputCopy2 2 999999937\n2 1\n3 1\nOutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.","tags":["constructive algorithms","math","ternary search"],"code":"import sys\n\ninput=sys.stdin.buffer.readline\n\nn,m,p=map(int,input().split())\n\na=list(map(int,input().split()))\n\nb=list(map(int,input().split()))\n\nidx1=-1\n\nidx2=-1\n\nfor i in range(n):\n\n if a[i]%p!=0:\n\n idx1=i\n\n break\n\nfor i in range(m):\n\n if b[i]%p!=0:\n\n idx2=i\n\n break\n\nprint(idx1+idx2)","language":"py"} -{"contest_id":"1313","problem_id":"B","statement":"B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round\u00a0\u2014 yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100)\u00a0\u2014 the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1\u2264n\u22641091\u2264n\u2264109, 1\u2264x,y\u2264n1\u2264x,y\u2264n)\u00a0\u2014 the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers\u00a0\u2014 the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second\u00a0\u2014 third place.","tags":["constructive algorithms","greedy","implementation","math"],"code":"import sys, threading\n\nimport math\n\nfrom os import path\n\nfrom collections import deque, defaultdict, Counter\n\nfrom bisect import *\n\nfrom string import ascii_lowercase\n\nfrom functools import cmp_to_key\n\nfrom random import randint\n\nimport heapq\n\n \n\n \n\ndef readInts():\n\n x = list(map(int, (sys.stdin.readline().rstrip().split())))\n\n return x[0] if len(x) == 1 else x\n\n \n\n \n\ndef readList(type=int):\n\n x = sys.stdin.readline()\n\n x = list(map(type, x.rstrip('\\n\\r').split()))\n\n return x\n\n \n\n \n\ndef readStr():\n\n x = sys.stdin.readline().rstrip('\\r\\n')\n\n return x\n\n \n\n \n\nwrite = sys.stdout.write\n\nread = sys.stdin.readline\n\n \n\n \n\nMAXN = 1123456\n\n\n\n\n\nclass mydict:\n\n def __init__(self, func=lambda: 0):\n\n self.random = randint(0, 1 << 32)\n\n self.default = func\n\n self.dict = {}\n\n \n\n def __getitem__(self, key):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n self.dict[mykey] = self.default()\n\n return self.dict[mykey]\n\n \n\n def get(self, key, default):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n return default\n\n return self.dict[mykey]\n\n \n\n def __setitem__(self, key, item):\n\n mykey = self.random ^ key\n\n self.dict[mykey] = item\n\n \n\n def getkeys(self):\n\n return [self.random ^ i for i in self.dict]\n\n \n\n def __str__(self):\n\n return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'\n\n\n\n \n\ndef lcm(a, b):\n\n return (a*b)\/\/(math.gcd(a,b))\n\n \n\n \n\ndef mod(n):\n\n return n%(1000000007) \n\n\n\n\n\ndef solve(t):\n\n # print(f'Case #{t}: ', end = '')\n\n n, x, y = readInts()\n\n sm = x+y\n\n print(min(n, max(1, sm+1-n)), min(n, sm-1))\n\n\n\n\n\ndef main():\n\n t = 1\n\n if path.exists(\"F:\/Comp Programming\/input.txt\"):\n\n sys.stdin = open(\"F:\/Comp Programming\/input.txt\", 'r')\n\n sys.stdout = open(\"F:\/Comp Programming\/output1.txt\", 'w')\n\n # sys.setrecursionlimit(100000) \n\n t = readInts()\n\n for i in range(t):\n\n solve(i+1)\n\n \n\n \n\nif __name__ == '__main__':\n\n main() ","language":"py"} -{"contest_id":"1307","problem_id":"D","statement":"D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105, n\u22121\u2264m\u22642\u22c5105n\u22121\u2264m\u22642\u22c5105, 2\u2264k\u2264n2\u2264k\u2264n) \u00a0\u2014 the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n) \u00a0\u2014 the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4\nOutputCopy3\nInputCopy5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5\nOutputCopy3\nNoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. ","tags":["binary search","data structures","dfs and similar","graphs","greedy","shortest paths","sortings"],"code":"import sys\n\nimport collections\n\ninput = sys.stdin.readline\n\n\n\nints = lambda: list(map(int, input().split()))\n\n \n\nn, m, k = ints()\n\nspecial = ints()\n\ngraph = [[] for _ in range(n + 1)]\n\nfor _ in range(m):\n\n x, y = ints()\n\n graph[x].append(y)\n\n graph[y].append(x)\n\n\n\nd1 = [-1 for _ in range(n + 1)]\n\nq = collections.deque([1])\n\ndepth = 1\n\nd1[1] = 0\n\nwhile q:\n\n for _ in range(len(q)):\n\n node = q.popleft()\n\n \n\n for nb in graph[node]:\n\n if d1[nb] == -1:\n\n q.append(nb)\n\n d1[nb] = depth\n\n depth += 1\n\n\n\nd2 = [-1 for _ in range(n + 1)]\n\nq = collections.deque([n])\n\ndepth = 1\n\nd2[n] = 0\n\nwhile q:\n\n for _ in range(len(q)):\n\n node = q.popleft()\n\n \n\n for nb in graph[node]:\n\n if d2[nb] == -1:\n\n q.append(nb)\n\n d2[nb] = depth\n\n depth += 1\n\n\n\nans = d2[1]\n\ns_distances = [(d1[i], d2[i]) for i in special]\n\ns_distances.sort(key=lambda x: x[1], reverse=True)\n\nmx = 0\n\nfor i in range(len(s_distances) - 1):\n\n l = s_distances[i + 1][1] + 1 + s_distances[i][0]\n\n mx = max(mx, l)\n\nprint(min(ans, mx))\n\n ","language":"py"} -{"contest_id":"1315","problem_id":"B","statement":"B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,\u2026,j\u22121i,i+1,\u2026,j\u22121 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i\u2264t p and i < len(s):\n\n if s[i] == 'A' and j == 1:\n\n c = c - b\n\n j = 0\n\n elif s[i] == 'B' and j == 0:\n\n c = c - a\n\n j = 1\n\n i = i + 1\n\n\n\n print(i)\n\n\n\n\n\n\n\n","language":"py"} -{"contest_id":"1295","problem_id":"E","statement":"E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets \u2014 prefix and suffix. More formally, the first set contains elements p1,p2,\u2026,pkp1,p2,\u2026,pk, the second \u2014 pk+1,pk+2,\u2026,pnpk+1,pk+2,\u2026,pn, where 1\u2264kmid:\n\n c+=a[i]\n\n left[i]=c\n\n \n\n right=[0]*n\n\n c=0\n\n for i in range(n-1,-1,-1):\n\n if p[i]<=mid:\n\n c+=a[i]\n\n right[i]=c\n\n \n\n res=10**18\n\n for i in range(n-1):\n\n res=min(res,left[i]+right[i+1])\n\n return res \n\n \n\ndef ternary_search(L,R):\n\n # \u6e96\u4e0b\u51f8\u95a2\u6570\u306e\u6700\u5c0f\u5024\n\n while L+21:\n\n p=mf[a]\n\n e=0\n\n while p==mf[a]:\n\n a\/\/=p\n\n e^=1\n\n if e:pp.append(p)\n\n if len(pp)==0:ext(1)\n\n elif len(pp)==1:pp.append(1)\n\n u,v=ptoi[pp[0]],ptoi[pp[1]]\n\n to[u].append(v)\n\n to[v].append(u)\n\n if pp[0]**2<=mxa:ss.add(u)\n\n if pp[1]**2<=mxa:ss.add(v)\n\n return to,ss\n\n\n\ndef ext(ans):\n\n print(ans)\n\n exit()\n\n\n\ndef solve():\n\n ans=inf\n\n for u in ss:\n\n ans=bfs(u,ans)\n\n if ans==inf:ans=-1\n\n return ans\n\n\n\ndef bfs(u,ans):\n\n dist=[-1]*pn\n\n q=deque()\n\n q.append((u,0,-1))\n\n dist[u]=0\n\n while q:\n\n u,d,pu=q.popleft()\n\n if d*2>=ans:break\n\n for v in to[u]:\n\n if v==pu:continue\n\n if dist[v]!=-1:ans=min(ans,d+dist[v]+1)\n\n dist[v]=d+1\n\n q.append((v,d+1,u))\n\n return ans\n\n\n\ninf=10**9\n\nn=int(input())\n\naa=list(map(int,input().split()))\n\nmxa=max(aa)\n\nmf,ptoi,pn=make_mf()\n\nto,ss=make_to()\n\nprint(solve())\n\n","language":"py"} -{"contest_id":"1288","problem_id":"D","statement":"D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k\u2208[1,m]k\u2208[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105, 1\u2264m\u226481\u2264m\u22648) \u2014 the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0\u2264ax,y\u22641090\u2264ax,y\u2264109).OutputPrint two integers ii and jj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j) \u2014 the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5\n5 0 3 1 2\n1 8 9 1 3\n1 2 3 4 5\n9 1 0 3 7\n2 3 0 6 3\n6 4 1 7 0\nOutputCopy1 5\n","tags":["binary search","bitmasks","dp"],"code":"n,m = [int(i) for i in input().strip().split()]\n\na = [[int(i) for i in input().strip().split()] for j in range(n)]\n\nlo = float('inf')\n\nhi = -float('inf')\n\nval = (2**m)-1\n\nans = [None,None]\n\nfor i in range(n):\n\n lo = min(lo,min(a[i]))\n\n hi = max(hi,max(a[i]))\n\nwhile lo<=hi:\n\n x = (lo+hi)\/\/2\n\n already = set()\n\n masks = []\n\n for i in range(n):\n\n mask = int(''.join(['1' if a[i][k]>=x else '0' for k in range(m)]),2)\n\n if mask in already:\n\n continue\n\n else:\n\n already.add(mask)\n\n masks.append([mask,i])\n\n N = len(masks)\n\n check = False\n\n for i in range(N):\n\n for j in range(i,N):\n\n if masks[i][0]|masks[j][0]==val:\n\n check = True\n\n ans = [masks[i][1],masks[j][1]]\n\n break\n\n if check:\n\n break\n\n if check:\n\n lo = x+1\n\n else:\n\n hi = x-1\n\nprint(ans[0]+1,ans[1]+1)","language":"py"} -{"contest_id":"1323","problem_id":"B","statement":"B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n\u00d7mn\u00d7m formed by following rule: ci,j=ai\u22c5bjci,j=ai\u22c5bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1\u2264x1\u2264x2\u2264n1\u2264x1\u2264x2\u2264n, 1\u2264y1\u2264y2\u2264m1\u2264y1\u2264y2\u2264m) a subrectangle c[x1\u2026x2][y1\u2026y2]c[x1\u2026x2][y1\u2026y2] is an intersection of the rows x1,x1+1,x1+2,\u2026,x2x1,x1+1,x1+2,\u2026,x2 and the columns y1,y1+1,y1+2,\u2026,y2y1,y1+1,y1+2,\u2026,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1\u2264n,m\u226440000,1\u2264k\u2264n\u22c5m1\u2264n,m\u226440000,1\u2264k\u2264n\u22c5m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410\u2264ai\u22641), elements of aa.The third line contains mm integers b1,b2,\u2026,bmb1,b2,\u2026,bm (0\u2264bi\u226410\u2264bi\u22641), elements of bb.OutputOutput single integer\u00a0\u2014 the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2\n1 0 1\n1 1 1\nOutputCopy4\nInputCopy3 5 4\n1 1 1\n1 1 1 1 1\nOutputCopy14\nNoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: ","tags":["binary search","greedy","implementation"],"code":"[a,a,area]=list(map(int,input().split(\" \")))\n\na=[len(i)for i in input().replace(' ','').split('0')if len(i)>0]\n\nb=[len(i)for i in input().replace(' ','').split('0')if len(i)>0]\n\nans=0\n\n\n\nfac=[]\n\nk=1\n\nwhile(k*k<=area):\n\n if area%k==0:\n\n fac.append((k,area\/\/k))\n\n k+=1\n\nfac+=[(j,i)for i,j in fac if i!=j]\n\nfor x,y in fac:\n\n ans+=sum(i-x+1 for i in a if x<=i)*sum(j-y+1 for j in b if y<=j)\n\nprint(ans)","language":"py"} -{"contest_id":"1305","problem_id":"F","statement":"F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u00a0\u2014 the number of elements in the array.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an. (1\u2264ai\u226410121\u2264ai\u22641012) \u00a0\u2014 the elements of the array.OutputPrint a single integer \u00a0\u2014 the minimum number of operations required to make the array good.ExamplesInputCopy3\n6 2 4\nOutputCopy0\nInputCopy5\n9 8 7 3 1\nOutputCopy4\nNoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.","tags":["math","number theory","probabilities"],"code":"import random\n\n\n\n# Sieve\n\nsieve_primes = []\n\nPRIME_LIMIT = int(1e6)\n\nsieve = [False for i in range(0,PRIME_LIMIT)]\n\nfor i in range(2,PRIME_LIMIT):\n\n if not sieve[i]:\n\n sieve_primes.append(i)\n\n for j in range(i*i, PRIME_LIMIT, i):\n\n sieve[j]=True\n\n\n\n# Input\n\nn = int(input())\n\narr=list(map(int, input().split()))\n\n\n\n# Construct search space Primes \n\nprimes = set()\n\ndef addPrime(num):\n\n for sieve_prime in sieve_primes:\n\n if num%sieve_prime == 0:\n\n primes.add(sieve_prime)\n\n while num%sieve_prime == 0:\n\n num\/\/=sieve_prime\n\n if num>1:\n\n primes.add(num)\n\n\n\n# (Could use probability calculations here to reduce search space)\n\nrandom.shuffle(arr)\n\n\n\nfor num in arr[:8]:\n\n if num > 1:\n\n addPrime(num)\n\n addPrime(num+1)\n\n if num > 2:\n\n addPrime(num-1)\n\n\n\n# Find answer\n\nans = n\n\n\n\n# Function to find answer based on input prime\n\ndef findAns(prime):\n\n global ans\n\n curr_ans = 0\n\n for num in arr:\n\n if num= ans:\n\n return\n\n ans = min(curr_ans, ans)\n\n\n\nfor prime in primes:\n\n findAns(prime)\n\n if ans == 0: break\n\n\n\nprint(ans)","language":"py"} -{"contest_id":"1316","problem_id":"A","statement":"A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0\u2264ai\u2264m0\u2264ai\u2264m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22642001\u2264t\u2264200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1\u2264n\u22641031\u2264n\u2264103, 1\u2264m\u22641051\u2264m\u2264105) \u00a0\u2014 the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u2264m0\u2264ai\u2264m) \u00a0\u2014 scores of the students.OutputFor each testcase, output one integer \u00a0\u2014 the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2\n4 10\n1 2 3 4\n4 5\n1 2 3 4\nOutputCopy10\n5\nNoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0\u2264ai\u226450\u2264ai\u22645. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0\u2264ai\u2264m0\u2264ai\u2264m.","tags":["implementation"],"code":"for i in range(int(input())):\n\n\tn,m = map(int,input().split())\n\n\tarr = map(int,input().split())\n\n\tprint(min(m,sum(arr)))","language":"py"} -{"contest_id":"1304","problem_id":"D","statement":"D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog\u2061n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n\u22121n\u22121, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n\u22121n\u22121.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2\u22c51052\u22c5105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3\n3 <<\n7 >><>><\n5 >>><\nOutputCopy1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3\nNoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.","tags":["constructive algorithms","graphs","greedy","two pointers"],"code":"def reverse(arr,i,j):\n\n while i':\n\n j+=1\n\n reverse(maxLIS,i,j)\n\n # print(i,j)\n\n i=j+1\n\n allans.append(maxLIS)\n\n \n\n multiLineArrayOfArraysPrint(allans)\n\n \n\n \n\n return\n\n \n\n# import sys\n\n# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)\n\nimport sys\n\ninput=lambda: sys.stdin.readline().rstrip(\"\\r\\n\") #FOR READING STRING\/TEXT INPUTS.\n\n \n\ndef oneLineArrayPrint(arr):\n\n print(' '.join([str(x) for x in arr]))\n\ndef multiLineArrayPrint(arr):\n\n print('\\n'.join([str(x) for x in arr]))\n\ndef multiLineArrayOfArraysPrint(arr):\n\n print('\\n'.join([' '.join([str(x) for x in y]) for y in arr]))\n\n \n\ndef readIntArr():\n\n return [int(x) for x in input().split()]\n\n# def readFloatArr():\n\n# return [float(x) for x in input().split()]\n\n \n\ndef makeArr(*args):\n\n \"\"\"\n\n *args : (default value, dimension 1, dimension 2,...)\n\n \n\n Returns : arr[dim1][dim2]... filled with default value\n\n \"\"\"\n\n assert len(args) >= 2, \"makeArr args should be (default value, dimension 1, dimension 2,...\"\n\n if len(args) == 2:\n\n return [args[0] for _ in range(args[1])]\n\n else:\n\n return [makeArr(args[0],*args[2:]) for _ in range(args[1])]\n\n \n\ndef queryInteractive(x,y):\n\n print('? {} {}'.format(x,y))\n\n sys.stdout.flush()\n\n return int(input())\n\n \n\ndef answerInteractive(ans):\n\n print('! {}'.format(ans))\n\n sys.stdout.flush()\n\n \n\ninf=float('inf')\n\nMOD=10**9+7\n\n \n\nfor _abc in range(1):\n\n main()","language":"py"} -{"contest_id":"1293","problem_id":"B","statement":"B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show \"1 vs. nn\"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0\u2264t\u2264s0\u2264t\u2264s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s\u2212ts\u2212t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10\u2212410\u22124. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a\u2212b|max(1,b)\u226410\u22124|a\u2212b|max(1,b)\u226410\u22124.ExamplesInputCopy1\nOutputCopy1.000000000000\nInputCopy2\nOutputCopy1.500000000000\nNoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.","tags":["combinatorics","greedy","math"],"code":"import math\n\n\n\n\n\n# -------- info --------\n\n\n\n# https:\/\/codeforces.com\/profile\/Wolxy\n\n\n\n# -------- solve --------\n\n\n\ndef solve() -> None:\n\n n = int(input())\n\n print(sum(1 \/ i for i in range(1, n + 1)))\n\n\n\n# -------- main --------\n\n\n\n\n\nT = 1\n\n# T = int(input())\n\nfor _ in range(T):\n\n solve()\n\n","language":"py"} -{"contest_id":"13","problem_id":"C","statement":"C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1\u2009\u2264\u2009N\u2009\u2264\u20095000) \u2014 the length of the initial sequence. The following N lines contain one integer each \u2014 elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer \u2014 minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1","tags":["dp","sortings"],"code":"N=int(input())\n\nA=list(map(int,input().split()))\n\n\n\nS=sorted(set(A))\n\nDP=[0]*len(S)\n\n\n\nfor a in A:\n\n NDP=[0]*len(S)\n\n\n\n MIN=1<<60\n\n\n\n for i in range(len(S)):\n\n MIN=min(MIN,DP[i])\n\n x=S[i]\n\n\n\n NDP[i]=abs(a-x)+MIN\n\n\n\n DP=NDP\n\n\n\nprint(min(DP))\n\n","language":"py"} -{"contest_id":"1288","problem_id":"E","statement":"E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,\u2026,n1,2,\u2026,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1\u2264n,m\u22643\u22c51051\u2264n,m\u22643\u22c5105) \u2014 the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,\u2026,ama1,a2,\u2026,am (1\u2264ai\u2264n1\u2264ai\u2264n) \u2014 the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4\n3 5 1 4\nOutputCopy1 3\n2 5\n1 4\n1 5\n1 5\nInputCopy4 3\n1 2 4\nOutputCopy1 3\n1 2\n3 4\n1 4\nNoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] ","tags":["data structures"],"code":"import sys\n\ninput=sys.stdin.readline\n\ndef binary_index(ar,n):\n\n for idx in range(1,n):\n\n idx2=idx+(idx&(-idx))\n\n if (idx2dis[p[i]]-1:\n\n\t\t\tmx+=1;mn+=1\n\n\t\telse:\n\n\t\t\tc=0\n\n\t\t\tfor j in f[p[i]]:\n\n\t\t\t\tif dis[j]==dis[p[i]]-1:\n\n\t\t\t\t\tc+=1\n\n\t\t\tif \tc>1:\n\n\t\t\t\tmx+=1\n\n\tprint(mn,mx)\n\n\tpass\n\n\n\nmain()\n\n#threading.Thread(target=main).start()\n\n","language":"py"} -{"contest_id":"1311","problem_id":"D","statement":"D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a\u2264b\u2264ca\u2264b\u2264c.In one move, you can add +1+1 or \u22121\u22121 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1\u2264a\u2264b\u2264c\u22641041\u2264a\u2264b\u2264c\u2264104).OutputFor each test case, print the answer. In the first line print resres \u2014 the minimum number of operations you have to perform to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46\nOutputCopy1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48\n","tags":["brute force","math"],"code":"import random, sys, os, math, gc\n\nfrom collections import Counter, defaultdict, deque\n\nfrom functools import lru_cache, reduce, cmp_to_key\n\nfrom itertools import accumulate, combinations, permutations, product\n\nfrom heapq import nsmallest, nlargest, heapify, heappop, heappush\n\nfrom io import BytesIO, IOBase\n\nfrom copy import deepcopy\n\nfrom bisect import bisect_left, bisect_right\n\nfrom math import factorial, gcd\n\nfrom operator import mul, xor\n\nfrom types import GeneratorType\n\n# if \"PyPy\" in sys.version:\n\n# import pypyjit; pypyjit.set_param('max_unroll_recursion=-1')\n\n# sys.setrecursionlimit(2*10**5)\n\nBUFSIZE = 8192\n\nMOD = 10**9 + 7\n\nMODD = 998244353\n\nINF = float('inf')\n\nD4 = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\nD8 = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]\n\n\n\nN = 2*10**4+10\n\n\n\n# \u5bf9\u6b63\u6574\u6570n\uff0c\u6b27\u62c9\u51fd\u6570\u662f\u5c0f\u4e8en\u7684\u6b63\u6574\u6570\u4e2d\u4e0en\u4e92\u8d28\u7684\u6570\u7684\u6570\u76ee\n\n# x = d\u2223x \u2211 \u03c6(d)\n\nphi = [0] * N\n\nphi[1] = 1\n\npfact = [0] * N\n\nfact = [[] for _ in range(N)]\n\nprimes = []\n\n\n\n# 1\uff09\u83ab\u6bd4\u4e4c\u65af\u51fd\u6570\u03bc(n)\u7684\u5b9a\u4e49\u57df\u662fN\uff1b\n\n# 2\uff09\u03bc(1)=1\uff1b\n\n# 3\uff09\u5f53n\u5b58\u5728\u5e73\u65b9\u56e0\u5b50\u65f6\uff0c\u03bc(n)=0\uff1b\n\n# 4\uff09\u5f53n\u662f\u7d20\u6570\u6216\u5947\u6570\u4e2a\u4e0d\u540c\u7d20\u6570\u4e4b\u79ef\u65f6\uff0c\u03bc(n)=-1\uff1b\n\n# 5\uff09\u5f53n\u662f\u5076\u6570\u4e2a\u4e0d\u540c\u7d20\u6570\u4e4b\u79ef\u65f6\uff0c\u03bc(n)=1\u3002\n\n# d\u2223n \u2211 \u03bc(d) = [n == 1]\n\n\n\n# d\u2223n \u2211 \u03bc(d) * (n \/ d) = \u03c6(n)\n\n\n\n# g(n) = d\u2223n \u2211 f(d) <---> f(n) = d\u2223n \u2211 \u03bc(d) g(n\/d)\n\n# g(n) = d\u2223n \u2211 f(n) <---> f(n) = d\u2223n \u2211 \u03bc(n\/d) g(n)\n\n# mobious = [0] * N\n\n# mobious[1] = 1\n\n\n\nfor i in range(1, N):\n\n if not phi[i]:\n\n primes.append(i)\n\n phi[i] = i-1\n\n # mobious[i] = -1\n\n for j in range(1, N):\n\n if i * j >= N:\n\n break\n\n pfact[i*j] = i\n\n for j in primes:\n\n if i * j >= N:\n\n break\n\n if i % j == 0:\n\n phi[i*j] = phi[i] * j\n\n # mobious[i*j] = 0\n\n break\n\n phi[i*j] = phi[i] * (j-1)\n\n # mobious[i*j] = mobious[i] * mobious[j]\n\n \n\n for j in range(i, N, i):\n\n fact[j].append(i)\n\n\n\ndef getfact(x):\n\n res = defaultdict(int)\n\n while x != 1:\n\n res[pfact[x]] += 1\n\n x \/\/= pfact[x]\n\n return res\n\n\n\ndef factlist(x):\n\n res = [1]\n\n while x != 1:\n\n k = pfact[x]\n\n c = 0\n\n while x % k == 0:\n\n c += 1\n\n x \/\/= k\n\n tmp = []\n\n for i in res:\n\n for j in range(1, c+1):\n\n tmp.append(i * pow(k, j))\n\n res += tmp\n\n return res\n\n\n\ndef solve():\n\n a, b, c = LII()\n\n ans = INF\n\n ansl = [0, 0, 0]\n\n for i in range(1, N):\n\n res = abs(b - i)\n\n t = INF\n\n aa = 0\n\n for j in fact[i]:\n\n if t > abs(a - j):\n\n t = abs(a - j)\n\n aa = j\n\n res += t\n\n t = INF\n\n cc = 0\n\n for j in range(i, N, i):\n\n if t > abs(c - j):\n\n t = abs(c - j)\n\n cc = j\n\n res += t\n\n if res < ans:\n\n ans = res\n\n ansl = [aa, i, cc]\n\n print(ans)\n\n print(*ansl)\n\n \n\n\n\ndef main():\n\n t = 1\n\n t = II()\n\n for _ in range(t):\n\n solve()\n\n\n\ndef bootstrap(f, stack=[]):\n\n def wrappedfunc(*args, **kwargs):\n\n if stack:\n\n return f(*args, **kwargs)\n\n else:\n\n to = f(*args, **kwargs)\n\n while True:\n\n if type(to) is GeneratorType:\n\n stack.append(to)\n\n to = next(to)\n\n else:\n\n stack.pop()\n\n if not stack:\n\n break\n\n to = stack[-1].send(to)\n\n return to\n\n return wrappedfunc\n\n\n\ndef bitcnt(n):\n\n c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)\n\n c = (c & 0x3333333333333333) + ((c >> 2) & 0x3333333333333333)\n\n c = (c & 0x0F0F0F0F0F0F0F0F) + ((c >> 4) & 0x0F0F0F0F0F0F0F0F)\n\n c = (c & 0x00FF00FF00FF00FF) + ((c >> 8) & 0x00FF00FF00FF00FF)\n\n c = (c & 0x0000FFFF0000FFFF) + ((c >> 16) & 0x0000FFFF0000FFFF)\n\n c = (c & 0x00000000FFFFFFFF) + ((c >> 32) & 0x00000000FFFFFFFF)\n\n return c\n\n\n\ndef lcm(x, y):\n\n return x * y \/\/ gcd(x, y)\n\n\n\ndef lowbit(x):\n\n return x & -x\n\n\n\ndef perm(n, r):\n\n return factorial(n) \/\/ factorial(n - r) if n >= r else 0\n\n \n\ndef comb(n, r):\n\n return factorial(n) \/\/ (factorial(r) * factorial(n - r)) if n >= r else 0\n\n\n\ndef probabilityMod(x, y, mod):\n\n return x * pow(y, mod-2, mod) % mod\n\n\n\nclass SortedList:\n\n def __init__(self, iterable=[], _load=200):\n\n \"\"\"Initialize sorted list instance.\"\"\"\n\n values = sorted(iterable)\n\n self._len = _len = len(values)\n\n self._load = _load\n\n self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]\n\n self._list_lens = [len(_list) for _list in _lists]\n\n self._mins = [_list[0] for _list in _lists]\n\n self._fen_tree = []\n\n self._rebuild = True\n\n \n\n def _fen_build(self):\n\n \"\"\"Build a fenwick tree instance.\"\"\"\n\n self._fen_tree[:] = self._list_lens\n\n _fen_tree = self._fen_tree\n\n for i in range(len(_fen_tree)):\n\n if i | i + 1 < len(_fen_tree):\n\n _fen_tree[i | i + 1] += _fen_tree[i]\n\n self._rebuild = False\n\n \n\n def _fen_update(self, index, value):\n\n \"\"\"Update `fen_tree[index] += value`.\"\"\"\n\n if not self._rebuild:\n\n _fen_tree = self._fen_tree\n\n while index < len(_fen_tree):\n\n _fen_tree[index] += value\n\n index |= index + 1\n\n \n\n def _fen_query(self, end):\n\n \"\"\"Return `sum(_fen_tree[:end])`.\"\"\"\n\n if self._rebuild:\n\n self._fen_build()\n\n \n\n _fen_tree = self._fen_tree\n\n x = 0\n\n while end:\n\n x += _fen_tree[end - 1]\n\n end &= end - 1\n\n return x\n\n \n\n def _fen_findkth(self, k):\n\n \"\"\"Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).\"\"\"\n\n _list_lens = self._list_lens\n\n if k < _list_lens[0]:\n\n return 0, k\n\n if k >= self._len - _list_lens[-1]:\n\n return len(_list_lens) - 1, k + _list_lens[-1] - self._len\n\n if self._rebuild:\n\n self._fen_build()\n\n \n\n _fen_tree = self._fen_tree\n\n idx = -1\n\n for d in reversed(range(len(_fen_tree).bit_length())):\n\n right_idx = idx + (1 << d)\n\n if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:\n\n idx = right_idx\n\n k -= _fen_tree[idx]\n\n return idx + 1, k\n\n \n\n def _delete(self, pos, idx):\n\n \"\"\"Delete value at the given `(pos, idx)`.\"\"\"\n\n _lists = self._lists\n\n _mins = self._mins\n\n _list_lens = self._list_lens\n\n \n\n self._len -= 1\n\n self._fen_update(pos, -1)\n\n del _lists[pos][idx]\n\n _list_lens[pos] -= 1\n\n \n\n if _list_lens[pos]:\n\n _mins[pos] = _lists[pos][0]\n\n else:\n\n del _lists[pos]\n\n del _list_lens[pos]\n\n del _mins[pos]\n\n self._rebuild = True\n\n \n\n def _loc_left(self, value):\n\n \"\"\"Return an index pair that corresponds to the first position of `value` in the sorted list.\"\"\"\n\n if not self._len:\n\n return 0, 0\n\n \n\n _lists = self._lists\n\n _mins = self._mins\n\n \n\n lo, pos = -1, len(_lists) - 1\n\n while lo + 1 < pos:\n\n mi = (lo + pos) >> 1\n\n if value <= _mins[mi]:\n\n pos = mi\n\n else:\n\n lo = mi\n\n \n\n if pos and value <= _lists[pos - 1][-1]:\n\n pos -= 1\n\n \n\n _list = _lists[pos]\n\n lo, idx = -1, len(_list)\n\n while lo + 1 < idx:\n\n mi = (lo + idx) >> 1\n\n if value <= _list[mi]:\n\n idx = mi\n\n else:\n\n lo = mi\n\n \n\n return pos, idx\n\n \n\n def _loc_right(self, value):\n\n \"\"\"Return an index pair that corresponds to the last position of `value` in the sorted list.\"\"\"\n\n if not self._len:\n\n return 0, 0\n\n \n\n _lists = self._lists\n\n _mins = self._mins\n\n \n\n pos, hi = 0, len(_lists)\n\n while pos + 1 < hi:\n\n mi = (pos + hi) >> 1\n\n if value < _mins[mi]:\n\n hi = mi\n\n else:\n\n pos = mi\n\n \n\n _list = _lists[pos]\n\n lo, idx = -1, len(_list)\n\n while lo + 1 < idx:\n\n mi = (lo + idx) >> 1\n\n if value < _list[mi]:\n\n idx = mi\n\n else:\n\n lo = mi\n\n \n\n return pos, idx\n\n \n\n def add(self, value):\n\n \"\"\"Add `value` to sorted list.\"\"\"\n\n _load = self._load\n\n _lists = self._lists\n\n _mins = self._mins\n\n _list_lens = self._list_lens\n\n \n\n self._len += 1\n\n if _lists:\n\n pos, idx = self._loc_right(value)\n\n self._fen_update(pos, 1)\n\n _list = _lists[pos]\n\n _list.insert(idx, value)\n\n _list_lens[pos] += 1\n\n _mins[pos] = _list[0]\n\n if _load + _load < len(_list):\n\n _lists.insert(pos + 1, _list[_load:])\n\n _list_lens.insert(pos + 1, len(_list) - _load)\n\n _mins.insert(pos + 1, _list[_load])\n\n _list_lens[pos] = _load\n\n del _list[_load:]\n\n self._rebuild = True\n\n else:\n\n _lists.append([value])\n\n _mins.append(value)\n\n _list_lens.append(1)\n\n self._rebuild = True\n\n \n\n def discard(self, value):\n\n \"\"\"Remove `value` from sorted list if it is a member.\"\"\"\n\n _lists = self._lists\n\n if _lists:\n\n pos, idx = self._loc_right(value)\n\n if idx and _lists[pos][idx - 1] == value:\n\n self._delete(pos, idx - 1)\n\n \n\n def remove(self, value):\n\n \"\"\"Remove `value` from sorted list; `value` must be a member.\"\"\"\n\n _len = self._len\n\n self.discard(value)\n\n if _len == self._len:\n\n raise ValueError('{0!r} not in list'.format(value))\n\n \n\n def pop(self, index=-1):\n\n \"\"\"Remove and return value at `index` in sorted list.\"\"\"\n\n pos, idx = self._fen_findkth(self._len + index if index < 0 else index)\n\n value = self._lists[pos][idx]\n\n self._delete(pos, idx)\n\n return value\n\n \n\n def bisect_left(self, value):\n\n \"\"\"Return the first index to insert `value` in the sorted list.\"\"\"\n\n pos, idx = self._loc_left(value)\n\n return self._fen_query(pos) + idx\n\n \n\n def bisect_right(self, value):\n\n \"\"\"Return the last index to insert `value` in the sorted list.\"\"\"\n\n pos, idx = self._loc_right(value)\n\n return self._fen_query(pos) + idx\n\n \n\n def count(self, value):\n\n \"\"\"Return number of occurrences of `value` in the sorted list.\"\"\"\n\n return self.bisect_right(value) - self.bisect_left(value)\n\n \n\n def __len__(self):\n\n \"\"\"Return the size of the sorted list.\"\"\"\n\n return self._len\n\n \n\n def __getitem__(self, index):\n\n \"\"\"Lookup value at `index` in sorted list.\"\"\"\n\n pos, idx = self._fen_findkth(self._len + index if index < 0 else index)\n\n return self._lists[pos][idx]\n\n \n\n def __delitem__(self, index):\n\n \"\"\"Remove value at `index` from sorted list.\"\"\"\n\n pos, idx = self._fen_findkth(self._len + index if index < 0 else index)\n\n self._delete(pos, idx)\n\n \n\n def __contains__(self, value):\n\n \"\"\"Return true if `value` is an element of the sorted list.\"\"\"\n\n _lists = self._lists\n\n if _lists:\n\n pos, idx = self._loc_left(value)\n\n return idx < len(_lists[pos]) and _lists[pos][idx] == value\n\n return False\n\n \n\n def __iter__(self):\n\n \"\"\"Return an iterator over the sorted list.\"\"\"\n\n return (value for _list in self._lists for value in _list)\n\n \n\n def __reversed__(self):\n\n \"\"\"Return a reverse iterator over the sorted list.\"\"\"\n\n return (value for _list in reversed(self._lists) for value in reversed(_list))\n\n \n\n def __repr__(self):\n\n \"\"\"Return string representation of sorted list.\"\"\"\n\n return 'SortedList({0})'.format(list(self))\n\n\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\n\n\nsys.stdin = IOWrapper(sys.stdin)\n\n# sys.stdout = IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\ndef I():\n\n return input()\n\n\n\ndef II():\n\n return int(input())\n\n\n\ndef MI():\n\n return map(int, input().split())\n\n\n\ndef LI():\n\n return list(input().split())\n\n\n\ndef LII():\n\n return list(map(int, input().split()))\n\n\n\ndef GMI():\n\n return map(lambda x: int(x) - 1, input().split())\n\n\n\ndef LGMI():\n\n return list(map(lambda x: int(x) - 1, input().split()))\n\n\n\ndef getGraph(n, m, directed=False):\n\n d = [[] for _ in range(n)]\n\n for _ in range(m):\n\n u, v = LGMI()\n\n d[u].append(v)\n\n if not directed:\n\n d[v].append(u)\n\n return d\n\n\n\ndef getWeightedGraph(n, m, directed=False):\n\n d = [[] for _ in range(n)]\n\n for _ in range(m):\n\n u, v, w = LII()\n\n u -= 1; v -= 1\n\n d[u].append((v, w))\n\n if not directed:\n\n d[v].append((u, w))\n\n return d\n\n\n\nif __name__ == \"__main__\":\n\n main()","language":"py"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"n=int(input())\n\nf=[[[n,n]for _ in range(n+1)]for _ in range(n+1)]\n\nf[0][0]=[0,0]\n\nfor i,v in enumerate(map(int,input().split())):\n\n\tfor j in range(i+2):\n\n\t\tif v==0 or v%2:f[i+1][j][1]=min(f[i][j][0]+1,f[i][j][1])\n\n\t\tif v%2==0:f[i+1][j][0]=min(f[i][j-1][0],f[i][j-1][1]+1)\n\nprint(min(f[n][n\/\/2]))","language":"py"} -{"contest_id":"1312","problem_id":"D","statement":"D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that ajaj+1aj>aj+1, if j\u2265ij\u2265i). InputThe first line contains two integers nn and mm (2\u2264n\u2264m\u22642\u22c51052\u2264n\u2264m\u22642\u22c5105).OutputPrint one integer \u2014 the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4\nOutputCopy6\nInputCopy3 5\nOutputCopy10\nInputCopy42 1337\nOutputCopy806066790\nInputCopy100000 200000\nOutputCopy707899035\nNoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. ","tags":["combinatorics","math"],"code":"import bisect\n\nimport collections\n\nimport heapq\n\nimport io\n\nimport math\n\nimport os\n\nimport random\n\nimport sys\n\n\n\nLO = 'abcdefghijklmnopqrstuvwxyz'\n\n# Mod = 1000000007\n\nMod = 998244353\n\n\n\ndef gcd(x, y):\n\n while y:\n\n x, y = y, x % y\n\n return x\n\n\n\n# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()\n\n_input = lambda: sys.stdin.buffer.readline().strip().decode()\n\n\n\nT = 1\n\n# T = int(_input())\n\nfor _ in range(T):\n\n n, m = map(int, _input().split())\n\n if n > 2:\n\n p = 1\n\n for i in range(n, m + 1):\n\n p = p * i % Mod\n\n q = 1\n\n for i in range(1, m - (n - 1) + 1):\n\n q = q * i % Mod\n\n print(p * pow(q, Mod - 2, Mod) % Mod * pow(2, n - 3, Mod) * (n - 2) % Mod)\n\n else:\n\n print(0)","language":"py"} -{"contest_id":"1141","problem_id":"B","statement":"B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day \u2014 it is a sequence a1,a2,\u2026,ana1,a2,\u2026,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 number of hours per day.The second line contains nn integer numbers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410\u2264ai\u22641), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5\n1 0 1 0 1\nOutputCopy2\nInputCopy6\n0 1 0 1 1 0\nOutputCopy2\nInputCopy7\n1 0 1 1 1 0 1\nOutputCopy3\nInputCopy3\n0 0 0\nOutputCopy0\nNoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.","tags":["implementation"],"code":"n=int(input())\n\nlst=list(map(int,input().split()))\n\nm=0\n\ntemp=0\n\nfor i in range(n):\n\n if (lst[i] ==1 and temp==0) or lst[i]==1 and lst[i-1]==1:\n\n temp+=1\n\n else:\n\n m=max(temp,m)\n\n temp=0\n\nfirst=0\n\nfor ele in lst:\n\n if ele==0:\n\n break\n\n else:\n\n first+=1\n\nsecond=0\n\nfor i in range(n-1,-1,-1):\n\n if lst[i]==0:\n\n break\n\n else:\n\n second+=1\n\ntot=first+second\n\nprint(max(m,tot))","language":"py"} -{"contest_id":"1295","problem_id":"B","statement":"B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss\u2026t=ssss\u2026 For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q\u2212cnt1,qcnt0,q\u2212cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".InputThe first line contains the single integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.Next 2T2T lines contain descriptions of test cases \u2014 two lines per test case. The first line contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, \u2212109\u2264x\u2264109\u2212109\u2264x\u2264109) \u2014 the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si\u2208{0,1}si\u2208{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers \u2014 one per test case. For each test case print the number of prefixes or \u22121\u22121 if there is an infinite number of such prefixes.ExampleInputCopy4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01\nOutputCopy3\n0\n1\n-1\nNoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.","tags":["math","strings"],"code":"# If you win, you live. You cannot win unless you fight.\nfrom math import sin\nfrom sys import stdin,setrecursionlimit\ninput=stdin.readline\nimport heapq\nrd=lambda: map(lambda s: int(s), input().strip().split())\nri=lambda: int(input())\nrs=lambda :input().strip()\nfrom collections import defaultdict as unsafedict,deque,Counter as unsafeCounter\nfrom bisect import bisect_left as bl, bisect_right as br\nfrom random import randint\nrandom = randint(1, 10 ** 9)\nmod=998244353\ndef ceil(a,b):\n return (a+b-1)\/\/b\nclass myDict:\n def __init__(self,func):\n self.RANDOM = randint(0,1<<32)\n self.default=func\n self.dict={}\n def __getitem__(self,key):\n myKey=self.RANDOM^key\n if myKey not in self.dict:\n self.dict[myKey]=self.default()\n return self.dict[myKey]\n def get(self,key,default):\n myKey=self.RANDOM^key\n if myKey not in self.dict:\n return default\n return self.dict[myKey]\n def __setitem__(self,key,item):\n myKey=self.RANDOM^key\n self.dict[myKey]=item\n def getKeys(self):\n return [self.RANDOM^i for i in self.dict]\n def __str__(self):\n return f'{[(self.RANDOM^i,self.dict[i]) for i in self.dict]}'\nfrom math import prod\n'''\nx*ts+y==m\n(m-y)%ts==0\ntype 2\nx*ts-x==m\n\n'''\ndef samepar(a,b):\n return (a>=0 and b>=0) or (a<=0 and b<=0)\nfor _ in range(ri()):\n n,m=rd()\n s=rs()\n ts=s.count(\"0\")-s.count(\"1\")\n if ts==0:\n x=0\n ans=0\n for i in s:\n if i==\"0\":\n x+=1\n else:\n x-=1\n if x==m:\n ans+=1\n if ans:\n print(-1)\n else:\n print(0)\n continue\n ans=0\n y=0\n st=set()\n if (m%ts)==0 and samepar(m,ts) :\n # print(\"here \",m ,ts)\n st.add((m\/\/ts,n-1))\n for i in range(n-1):\n if s[i]==\"1\":\n y-=1\n else:\n y+=1\n if (m-y)%ts==0:\n if (m-y)\/\/ts>=0:\n # print(m - y, y, (m - y) \/\/ ts)\n st.add(((m-y)\/\/ts,i))\n ans+=1\n # print(st)\n print(len(st))\n\n \t\t\t\t \t \t\t\t\t \t\t\t \t","language":"py"} -{"contest_id":"1320","problem_id":"A","statement":"A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck\u22121ck>ck\u22121. So, the sequence of visited cities [c1,c2,\u2026,ck][c1,c2,\u2026,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1\u2212ci=bci+1\u2212bcici+1\u2212ci=bci+1\u2212bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1\u2264bi\u22644\u22c51051\u2264bi\u22644\u22c5105), where bibi is the beauty value of the ii-th city.OutputPrint one integer \u2014 the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6\n10 7 1 9 10 15\nOutputCopy26\nInputCopy1\n400000\nOutputCopy400000\nInputCopy7\n8 9 26 11 12 29 14\nOutputCopy55\nNoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].","tags":["data structures","dp","greedy","math","sortings"],"code":"#import io, os\n\n#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\nn = int(input())\n\n\n\nlis = list(map(int,input().split()))\n\n\n\nconnections = {}\n\n\n\nfor i in range(len(lis)):\n\n\n\n if str(lis[i] - i) in connections:\n\n a = connections[str(lis[i] - i)]\n\n a.append(lis[i])\n\n connections[str(lis[i] - i)] = a\n\n\n\n else:\n\n\n\n connections[str(lis[i] - i)] = [lis[i]]\n\n\n\nmaxi = 0\n\n\n\nfor i in connections:\n\n\n\n b = sum(connections[i])\n\n maxi = max(maxi,b)\n\n\n\nprint(maxi)","language":"py"} -{"contest_id":"1323","problem_id":"A","statement":"A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1\u2264t\u22641001\u2264t\u2264100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100), length of array aa.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output \u22121\u22121 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1\u2264pi\u2264n1\u2264pi\u2264n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3\n3\n1 4 3\n1\n15\n2\n3 5\nOutputCopy1\n2\n-1\n2\n1 2\nNoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.","tags":["brute force","dp","greedy","implementation"],"code":"for t in range(int(input())):\n\n n = int(input())\n\n\n\n a = list(map(int, input().split()))\n\n\n\n if n == 1:\n\n if a[0] % 2 == 0:\n\n print(1)\n\n print(1)\n\n else:\n\n print(-1)\n\n\n\n else:\n\n j = 0\n\n\n\n for i in range(n):\n\n if a[i] % 2 == 0:\n\n j = i+1\n\n break\n\n if j > 0:\n\n print(1)\n\n print(j)\n\n else:\n\n print(2)\n\n print(1, 2)","language":"py"} -{"contest_id":"1316","problem_id":"E","statement":"E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him\u00a0\u2014 the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j \u00a0\u2014 the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2\u2264n\u2264105,1\u2264p\u22647,1\u2264k,p+k\u2264n2\u2264n\u2264105,1\u2264p\u22647,1\u2264k,p+k\u2264n).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an. (1\u2264ai\u22641091\u2264ai\u2264109).The ii-th of the next nn lines contains pp integers si,1,si,2,\u2026,si,psi,1,si,2,\u2026,si,p. (1\u2264si,j\u22641091\u2264si,j\u2264109)OutputPrint a single integer resres \u00a0\u2014 the maximum possible strength of the club.ExamplesInputCopy4 1 2\n1 16 10 3\n18\n19\n13\n15\nOutputCopy44\nInputCopy6 2 3\n78 93 9 17 13 78\n80 97\n30 52\n26 17\n56 68\n60 36\n84 55\nOutputCopy377\nInputCopy3 2 1\n500 498 564\n100002 3\n422332 2\n232323 1\nOutputCopy422899\nNoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.","tags":["bitmasks","dp","greedy","sortings"],"code":"import sys\nfrom array import array # noqa: F401\nfrom typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401\n\n\ndef input():\n return sys.stdin.buffer.readline().decode('utf-8')\n\n\nclass UnionFind(object):\n __slots__ = ['nodes']\n\n def __init__(self, n: int):\n self.nodes = [-1] * n\n\n def find(self, x: int) -> int:\n if self.nodes[x] < 0:\n return x\n else:\n self.nodes[x] = self.find(self.nodes[x])\n return self.nodes[x]\n\n def unite(self, x: int, y: int) -> bool:\n root_x, root_y, nodes = self.find(x), self.find(y), self.nodes\n\n if root_x != root_y:\n if nodes[root_x] > nodes[root_y]:\n root_x, root_y = root_y, root_x\n nodes[root_x] += nodes[root_y]\n nodes[root_y] = root_x\n\n return root_x != root_y\n\n def size(self, x: int) -> int:\n return -self.nodes[self.find(x)]\n\n\nborder = 1 << 30\nmask = border - 1\n\n\ndef add(x1, y1, x2, y2):\n x, y = x1 + x2, y1 + y2\n if y >= border:\n x += 1\n y &= mask\n return x, y\n\n\ndef main():\n n, p, k = map(int, input().split())\n a = list(map(int, input().split()))\n matrix = [list(map(int, input().split())) for _ in range(n)]\n m = 1 << p\n popcnt = [bin(bit).count('1') for bit in range(m)]\n dests = [[i for i in range(p) if ((1 << i) & bit) == 0] for bit in range(m)]\n minf = -10**9\n\n dp_up = array('i', [0] + [minf] * (m - 1))\n dp_lo = array('i', [0] + [minf] * (m - 1))\n for cnt, i in enumerate(sorted(range(n), key=lambda i: -a[i])):\n ndp_up = dp_up[:]\n ndp_lo = dp_lo[:]\n\n for bit in range(m):\n if cnt - popcnt[bit] < k:\n up, lo = add(dp_up[bit], dp_lo[bit], 0, a[i])\n if ndp_up[bit] < up or ndp_up[bit] == up and ndp_lo[bit] < lo:\n ndp_up[bit], ndp_lo[bit] = up, lo\n for j in dests[bit]:\n up, lo = add(dp_up[bit], dp_lo[bit], 0, matrix[i][j])\n if ndp_up[bit | (1 << j)] < up or ndp_up[bit | (1 << j)] == up and ndp_lo[bit | (1 << j)] < lo:\n ndp_up[bit | (1 << j)], ndp_lo[bit | (1 << j)] = up, lo\n\n dp_up, dp_lo = ndp_up, ndp_lo\n\n print(dp_up[-1] * border + dp_lo[-1])\n\n\nif __name__ == '__main__':\n main()\n","language":"py"} -{"contest_id":"1141","problem_id":"D","statement":"D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1\u2264n\u22641500001\u2264n\u2264150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk \u2014 the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1\u2264aj,bj\u2264n1\u2264aj,bj\u2264n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10\ncodeforces\ndodivthree\nOutputCopy5\n7 8\n4 9\n2 2\n9 10\n3 1\nInputCopy7\nabaca?b\nzabbbcc\nOutputCopy5\n6 5\n2 3\n4 6\n7 4\n1 2\nInputCopy9\nbambarbia\nhellocode\nOutputCopy0\nInputCopy10\ncode??????\n??????test\nOutputCopy10\n6 2\n1 6\n7 3\n3 5\n4 8\n9 7\n5 1\n2 4\n10 9\n8 10\n","tags":["greedy","implementation"],"code":"import os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\nfrom math import *\n\nfrom collections import defaultdict\n\ndef solve():\n\n n=int(input())\n\n a=input()\n\n b=input()\n\n dl=defaultdict(list)\n\n dr=defaultdict(list)\n\n left=[]\n\n right=[]\n\n ans=[]\n\n for i in range(n):\n\n dl[a[i]].append(i+1)\n\n dr[b[i]].append(i+1)\n\n for i in range(97,123):\n\n char=chr(i)\n\n for j in range(min(len(dl[char]),len(dr[char]))):\n\n ans.append([dl[char][-1],dr[char][-1]])\n\n dl[char].pop()\n\n dr[char].pop()\n\n if len(dl[char])>0:\n\n for j in dl[char]:\n\n left.append(j)\n\n else:\n\n for j in dr[char]:\n\n right.append(j)\n\n for j in range(min(len(left),len(dr['?']))):\n\n ans.append([left[-1],dr['?'][-1]])\n\n left.pop()\n\n dr['?'].pop()\n\n for j in range(min(len(right),len(dl['?']))):\n\n ans.append([dl['?'][-1],right[-1]])\n\n right.pop()\n\n dl['?'].pop()\n\n char='?'\n\n for i in range(min(len(dl[char]),len(dr[char]))):\n\n ans.append([dl[char][-1],dr[char][-1]])\n\n dl[char].pop()\n\n dr[char].pop()\n\n print(len(ans))\n\n for x,y in ans:\n\n print(x,y)\n\nfor _ in range(1):\n\n solve()","language":"py"} -{"contest_id":"1310","problem_id":"A","statement":"A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A\/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn\u00a0\u2014 the number of news categories (1\u2264n\u22642000001\u2264n\u2264200000).The second line of input consists of nn integers aiai\u00a0\u2014 the number of publications of ii-th category selected by the batch algorithm (1\u2264ai\u22641091\u2264ai\u2264109).The third line of input consists of nn integers titi\u00a0\u2014 time it takes for targeted algorithm to find one new publication of category ii (1\u2264ti\u2264105)1\u2264ti\u2264105).OutputPrint one integer\u00a0\u2014 the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5\n3 7 9 7 8\n5 2 5 7 5\nOutputCopy6\nInputCopy5\n1 2 3 4 5\n1 1 1 1 1\nOutputCopy0\nNoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.","tags":["data structures","greedy","sortings"],"code":"import functools\n\nimport math\n\nimport random\n\nfrom collections import defaultdict,deque\n\nfrom heapq import heapify,heappop,heappush\n\nimport bisect\n\nfrom collections import Counter\n\nimport collections\n\nfrom functools import lru_cache\n\nimport time\n\nfrom typing import List\n\nfrom math import log\n\nfrom random import randint,seed\n\nfrom time import time\n\nimport os,sys\n\nfrom io import BytesIO, IOBase\n\n\n\n# Fast IO Region\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\nn,a,t=int(input()),list(map(int,input().split())),list(map(int,input().split()))\n\n# n,a,t=5,[3,7,9,7,8],[5,2,5,7,5]\n\ndt=defaultdict(list)\n\nfor i in range(n):\n\n dt[a[i]].append(t[i])\n\n\n\ndata=sorted(dt.items(),key=lambda x:x[0])\n\n# print(data)\n\nans,cur,sum,n=0,[],0,len(data)\n\nfor i,(x,lst) in enumerate(data):\n\n for cost in lst:\n\n heappush(cur,-cost)\n\n sum+=cost\n\n top=heappop(cur)\n\n sum-=-top\n\n x+=1\n\n while i r:\n\n ans += 1\n\n else:\n\n r -= 1\n\n l -= 1\n\n i += 1\n\n if i == n:\n\n break\n\n if (l!=0) or (r != 0):\n\n return -1\n\n else:\n\n return 2*ans\n\n# print(checker(8,\"))((())(\"))\n\nn = int(input())\n\ns = str(input())\n\nprint(checker(n,s))\n\n ","language":"py"} -{"contest_id":"1293","problem_id":"A","statement":"A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin \"ConneR\" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1\u2264t\u226410001\u2264t\u22641000)\u00a0\u2014 the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2\u2264n\u22641092\u2264n\u2264109, 1\u2264s\u2264n1\u2264s\u2264n, 1\u2264k\u2264min(n\u22121,1000)1\u2264k\u2264min(n\u22121,1000))\u00a0\u2014 respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n)\u00a0\u2014 the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer\u00a0\u2014 the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77\nOutputCopy2\n0\n4\n0\n2\nNoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.","tags":["binary search","brute force","implementation"],"code":"def solve():\n\n n, s, k = map(int, input().split())\n\n a = list(map(int, input().split()))\n\n\n\n for i in range(0, k + 1):\n\n if s - i >= 1 and not s - i in a:\n\n print(i);\n\n break\n\n if s + i <= n and not s + i in a:\n\n print(i);\n\n break\n\n else:\n\n assert False\n\n\n\n\n\nfor _ in range(int(input())):\n\n solve()\n\n","language":"py"} -{"contest_id":"1300","problem_id":"B","statement":"B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,\u2026,a2k+1][a1,a2,\u2026,a2k+1] of odd number of elements is defined as follows: let [b1,b2,\u2026,b2k+1][b1,b2,\u2026,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104). The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the number of students halved.The second line of each test case contains 2n2n integers a1,a2,\u2026,a2na1,a2,\u2026,a2n (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3\n1\n1 1\n3\n6 5 4 1 2 3\n5\n13 4 20 13 2 5 8 3 17 16\nOutputCopy0\n1\n5\nNoteIn the first test; there is only one way to partition students\u00a0\u2014 one in each class. The absolute difference of the skill levels will be |1\u22121|=0|1\u22121|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4\u22123|=1|4\u22123|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.","tags":["greedy","implementation","sortings"],"code":"I=input\n\nfor _ in[0]*int(I()):n=int(I());a=sorted(map(int,I().split()));print(a[n]-a[n-1])","language":"py"} -{"contest_id":"1325","problem_id":"F","statement":"F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309 vertices. find a simple cycle of length at least \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5\u2264n\u22641055\u2264n\u2264105, n\u22121\u2264m\u22642\u22c5105n\u22121\u2264m\u22642\u22c5105)\u00a0\u2014 the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print \"1\", followed by a line containing \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309 distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print \"2\", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\nOutputCopy1\n1 6 4InputCopy6 8\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\n1 4\n2 5\nOutputCopy2\n4\n1 5 2 4InputCopy5 4\n1 2\n1 3\n2 4\n2 5\nOutputCopy1\n3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2\u22124\u22123\u22121\u22125\u221262\u22124\u22123\u22121\u22125\u22126 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2\u22125\u221262\u22125\u22126, for example, is acceptable.In the third sample:","tags":["constructive algorithms","dfs and similar","graphs","greedy"],"code":"#coding:utf8\nimport math\n\nn, m, = [int(x) for x in input().split()]\ncons = math.ceil(pow(n, 0.5))\n\nadj_mat = [[] for x in range(n + 1)]\npre_node, cur_deepth = [0] * (n + 1), [0] * (n + 1)\n\nfor i in range(m):\n node1, node2 = [int(x) for x in input().split()]\n adj_mat[node1].append(node2)\n adj_mat[node2].append(node1)\n\ntmp_rec, deep_path = [node1], []\n\nwhile tmp_rec != []:\n n1 = tmp_rec.pop()\n if cur_deepth[n1] > 0:\n continue\n deep_path.append(n1)\n cur_deepth[n1] = cur_deepth[pre_node[n1]] + 1\n for n2 in adj_mat[n1]:\n if not cur_deepth[n2]:\n pre_node[n2] = n1\n tmp_rec.append(n2)\n elif cur_deepth[n1] - cur_deepth[n2] + 1 >= cons:\n circle = []\n while n1 != pre_node[n2]:\n circle.append(n1)\n n1 = pre_node[n1]\n if len(circle) >= cons:\n print(\"2\")\n print(len(circle))\n print(\" \".join([str(x) for x in circle]))\n exit(0)\n\n\ncur_deepth = [0] * (n + 1)\ntmp_arr = []\nwhile deep_path != []:\n n1 = deep_path.pop()\n if not cur_deepth[n1]:\n tmp_arr.append(n1)\n for n2 in adj_mat[n1]:\n cur_deepth[n2] = 1\nprint(\"1\")\nprint(\" \".join([str(x) for x in tmp_arr[:cons]]))\n\n \n\n \t \t \t \t\t \t\t \t\t \t \t \t","language":"py"} -{"contest_id":"1296","problem_id":"E1","statement":"E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1\u2264n\u22642001\u2264n\u2264200) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print \"NO\" (without quotes) in the first line.Otherwise, print \"YES\" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9\nabacbecfd\nOutputCopyYES\n001010101\nInputCopy8\naaabbcbb\nOutputCopyYES\n01011011\nInputCopy7\nabcdedc\nOutputCopyNO\nInputCopy5\nabcde\nOutputCopyYES\n00000\n","tags":["constructive algorithms","dp","graphs","greedy","sortings"],"code":"from sys import stdin\n\ninput=lambda :stdin.readline()[:-1]\n\n\n\nn=int(input())\n\ns=[ord(i)-97 for i in input()]\n\nc=[-1]*27\n\nans=[]\n\nfor i in s:\n\n mx=max(c[i+1:])\n\n c[i]=mx+1\n\n ans.append(mx+1)\n\nif max(ans)<=1:\n\n print('YES')\n\n print(*ans,sep='')\n\nelse:\n\n print('NO')","language":"py"} -{"contest_id":"1322","problem_id":"B","statement":"B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one\u00a0\u2014 xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)Here x\u2295yx\u2295y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https:\/\/en.wikipedia.org\/wiki\/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2\u2264n\u22644000002\u2264n\u2264400000)\u00a0\u2014 the number of integers in the array.The second line contains integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641071\u2264ai\u2264107).OutputPrint a single integer\u00a0\u2014 xor of all pairwise sums of integers in the given array.ExamplesInputCopy2\n1 2\nOutputCopy3InputCopy3\n1 2 3\nOutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112\u22951002\u22951012=01020112\u22951002\u22951012=0102, thus the answer is 2.\u2295\u2295 is the bitwise xor operation. To define x\u2295yx\u2295y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012\u229500112=0110201012\u229500112=01102.","tags":["binary search","bitmasks","constructive algorithms","data structures","math","sortings"],"code":"import sys\n\ninput = sys.stdin.buffer.readline\n\n \n\nfrom collections import deque\n\ndef countingSort(arr, exp1): \n\n n = len(arr)\n\n output = [0] * (n)\n\n count = [0] * (10)\n\n for i in range(0, n):\n\n index = arr[i] \/\/ exp1\n\n count[index % 10] += 1\n\n for i in range(1, 10):\n\n count[i] += count[i - 1]\n\n i = n - 1\n\n while i >= 0:\n\n index = arr[i] \/\/ exp1\n\n output[count[index % 10] - 1] = arr[i]\n\n count[index % 10] -= 1\n\n i -= 1\n\n i = 0\n\n for i in range(0, len(arr)):\n\n arr[i] = output[i]\n\n\n\ndef radixSort(arr):\n\n max1 = max(arr)\n\n exp = 1\n\n while max1 \/ exp >= 1:\n\n countingSort(arr, exp)\n\n exp *= 10\n\n\n\nN = int(input())\n\na = list(map(int, input().split()))\n\n \n\n \n\nres = 0\n\nradixSort(a)\n\nfor k in range(max(a).bit_length(), -1, -1):\n\n z = 1 << k\n\n c = 0\n\n \n\n j = jj = jjj = N - 1\n\n for i in range(N):\n\n while j >= 0 and a[i] + a[j] >= z: j -= 1\n\n while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1\n\n while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1\n\n \n\n c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj)\n\n \n\n res += z * (c & 1)\n\n for i in range(N): a[i] = min(a[i] ^ z, a[i])\n\n a.sort()\n\n #print(res, a, c)\n\nprint(res)","language":"py"} -{"contest_id":"1310","problem_id":"A","statement":"A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A\/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn\u00a0\u2014 the number of news categories (1\u2264n\u22642000001\u2264n\u2264200000).The second line of input consists of nn integers aiai\u00a0\u2014 the number of publications of ii-th category selected by the batch algorithm (1\u2264ai\u22641091\u2264ai\u2264109).The third line of input consists of nn integers titi\u00a0\u2014 time it takes for targeted algorithm to find one new publication of category ii (1\u2264ti\u2264105)1\u2264ti\u2264105).OutputPrint one integer\u00a0\u2014 the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5\n3 7 9 7 8\n5 2 5 7 5\nOutputCopy6\nInputCopy5\n1 2 3 4 5\n1 1 1 1 1\nOutputCopy0\nNoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.","tags":["data structures","greedy","sortings"],"code":"inf=float('inf')\n\nfrom heapq import heapify,heappop,heappush\n\nfrom collections import defaultdict\n\nif __name__=='__main__':\n\n n=int(input())\n\n lst=list(map(int,input().split(' ')))\n\n tm=list(map(int,input().split(' ')))\n\n l=[]\n\n for i in range(n):\n\n l.append([lst[i],tm[i]])\n\n l.sort()\n\n l.append((10**12,0))\n\n cnt = 0\n\n prev=0\n\n now = []\n\n for x in l:\n\n a,t = x\n\n for ai in range(prev,a):\n\n if not now:\n\n break\n\n tm,am = heappop(now)\n\n tm = 10**5-tm\n\n cnt += (ai-am) * tm\n\n heappush(now,(10**5-t,a))\n\n prev=a\n\n print(cnt)","language":"py"} -{"contest_id":"1296","problem_id":"C","statement":"C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x\u22121,y)(x\u22121,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y\u22121)(x,y\u22121). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of \"LURLLR\" are \"LU\", \"LR\", \"LURLLR\", \"URL\", but not \"RR\" and \"UL\".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' \u2014 the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211n\u22642\u22c5105\u2211n\u22642\u22c5105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n \u2014 endpoints of the substring you remove. The value r\u2212l+1r\u2212l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4\n4\nLRUD\n4\nLURD\n5\nRRUDU\n5\nLLDDR\nOutputCopy1 2\n1 4\n3 4\n-1\n","tags":["data structures","implementation"],"code":"import math\n\nimport sys\n\ninput = sys.stdin.readline\n\n\n\n############ ---- Input Functions ---- ############\n\ndef inp():\n\n return(int(input()))\n\ndef inlt():\n\n return(list(map(int,input().split())))\n\ndef insr():\n\n s = input()\n\n return(list(s[:len(s) - 1]))\n\ndef invr():\n\n return(map(int,input().split()))\n\n\n\n\n\n\n\n\n\n\n\nfor _ in range(inp()):\n\n n = inp()\n\n s = insr()\n\n coord = {(0,0):0}\n\n left = 0\n\n up = 0\n\n maxer = 999999999999999\n\n coords = None\n\n for i in range(n):\n\n if s[i] == 'L':\n\n left -= 1\n\n elif s[i] == 'R':\n\n left += 1\n\n elif s[i] == 'U':\n\n up += 1\n\n else:\n\n up -= 1\n\n if (left, up) in coord:\n\n if i+1 - coord[(left, up)] < maxer:\n\n maxer = i+1 - coord[(left, up)]\n\n coords = (coord[(left, up)], i+1)\n\n coord[(left, up)] = i+1\n\n if maxer == 999999999999999:\n\n print(-1)\n\n else:\n\n print(coords[0]+1, coords[1])\n\n","language":"py"} -{"contest_id":"1285","problem_id":"D","statement":"D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,\u2026,ana1,a2,\u2026,an and challenged him to choose an integer XX such that the value max1\u2264i\u2264n(ai\u2295X)max1\u2264i\u2264n(ai\u2295X) is minimum possible, where \u2295\u2295 denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1\u2264i\u2264n(ai\u2295X)max1\u2264i\u2264n(ai\u2295X).InputThe first line contains integer nn (1\u2264n\u22641051\u2264n\u2264105).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u2264230\u221210\u2264ai\u2264230\u22121).OutputPrint one integer \u2014 the minimum possible value of max1\u2264i\u2264n(ai\u2295X)max1\u2264i\u2264n(ai\u2295X).ExamplesInputCopy3\n1 2 3\nOutputCopy2\nInputCopy2\n1 5\nOutputCopy4\nNoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.","tags":["bitmasks","brute force","dfs and similar","divide and conquer","dp","greedy","strings","trees"],"code":"# import time\n# start = time.time()\n\n\ndef checkBits(integers, bit):\n if bit < 0:\n return 0\n\n left = []\n right = []\n\n for i in integers:\n if ((i >> bit) & 1) == 0:\n left.append(i)\n else:\n right.append(i)\n if len(left) == 0:\n return checkBits(right, bit -1)\n if len(right) == 0:\n return checkBits(left, bit - 1)\n return min(checkBits(left, bit - 1), checkBits(right, bit - 1)) + (1 << bit)\n\nif __name__ == '__main__':\n _ = input()\n integers = list(map(int, input().split()))\n\n print(checkBits(integers, 30))\n # print(f'end1 {time.time() - start}')\n \t \t\t\t \t \t\t \t\t \t \t \t \t \t","language":"py"} -{"contest_id":"1324","problem_id":"A","statement":"A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2\u00d712\u00d71 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2\u00d712\u00d71 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai\u22121ai\u22121. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.ExampleInputCopy4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\nOutputCopyYES\nNO\nYES\nYES\nNoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.","tags":["implementation","number theory"],"code":"def gcd(a,b):\n\n if(b==0):\n\n return a \n\n else:\n\n return gcd(b,a%b) \n\n \n\n \n\nfrom collections import Counter \n\nimport math\n\nfor _ in range(int(input())):\n\n n = int(input())\n\n #n,m = map(int,input().split())\n\n l = list(map(int,input().split()))\n\n x = []\n\n for i in range(n):\n\n x.append(l[i]%2) \n\n \n\n if(len(set(x))==1):\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")","language":"py"} -{"contest_id":"1304","problem_id":"B","statement":"B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings \"pop\", \"noon\", \"x\", and \"kkkkkk\" are palindromes, while strings \"moon\", \"tv\", and \"abab\" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1\u2264n\u22641001\u2264n\u2264100, 1\u2264m\u2264501\u2264m\u226450) \u2014 the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3\ntab\none\nbat\nOutputCopy6\ntabbat\nInputCopy4 2\noo\nox\nxo\nxx\nOutputCopy6\noxxxxo\nInputCopy3 5\nhello\ncodef\norces\nOutputCopy0\n\nInputCopy9 4\nabab\nbaba\nabcd\nbcde\ncdef\ndefg\nwxyz\nzyxw\nijji\nOutputCopy20\nababwxyzijjizyxwbaba\nNoteIn the first example; \"battab\" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.","tags":["brute force","constructive algorithms","greedy","implementation","strings"],"code":"def solve():\n\n n,m = list(map(int,input().split()))\n\n arr, pairs, single = [],[],[]\n\n ans = ''\n\n for i in range(n):\n\n arr.append(input())\n\n while arr:\n\n a = arr.pop()\n\n if a[::-1] in arr: # can be optimized with dict lookup\n\n pairs.append(a)\n\n else:\n\n single.append(a)\n\n while single:\n\n b = single.pop()\n\n if b[::-1] == b:\n\n ans = b\n\n break\n\n for i in pairs:\n\n ans = i + ans + i[::-1]\n\n print(len(ans))\n\n return ans\n\nprint(solve())","language":"py"} -{"contest_id":"1141","problem_id":"D","statement":"D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1\u2264n\u22641500001\u2264n\u2264150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk \u2014 the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1\u2264aj,bj\u2264n1\u2264aj,bj\u2264n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10\ncodeforces\ndodivthree\nOutputCopy5\n7 8\n4 9\n2 2\n9 10\n3 1\nInputCopy7\nabaca?b\nzabbbcc\nOutputCopy5\n6 5\n2 3\n4 6\n7 4\n1 2\nInputCopy9\nbambarbia\nhellocode\nOutputCopy0\nInputCopy10\ncode??????\n??????test\nOutputCopy10\n6 2\n1 6\n7 3\n3 5\n4 8\n9 7\n5 1\n2 4\n10 9\n8 10\n","tags":["greedy","implementation"],"code":"import sys\n\n\n\n\n\ndef II(): return int(sys.stdin.readline())\n\ndef LI(): return [int(num) for num in sys.stdin.readline().split()]\n\ndef SI(): return sys.stdin.readline().rstrip()\n\n\n\nfrom collections import defaultdict\n\n\n\nk = II()\n\nl = defaultdict(list)\n\nr = defaultdict(list)\n\n\n\nfor ind, char in enumerate(zip(SI(), SI())):\n\n l[char[0]].append(ind + 1)\n\n r[char[1]].append(ind + 1)\n\n\n\n# print(l)\n\n# print(r)\n\n\n\npairs = []\n\ndef func(seek_from, where, flag):\n\n for char in seek_from:\n\n if char != '?' and char in where:\n\n while seek_from[char] and where[char]:\n\n if flag:\n\n pairs.append([seek_from[char].pop(), where[char].pop()])\n\n else:\n\n pairs.append([where[char].pop(), seek_from[char].pop()])\n\n if not where[char]:\n\n del where[char]\n\n\n\n# print(l)\n\n# print(r)\n\n\n\nfunc(l, r, 1)\n\nfunc(r, l, 0)\n\n\n\n# print(pairs)\n\n\n\ndef func2(where, seek_from, flag):\n\n for char in seek_from:\n\n if char != '?':\n\n while where['?'] and seek_from[char]:\n\n if flag:\n\n pairs.append([where['?'].pop(), seek_from[char].pop()])\n\n else:\n\n pairs.append([seek_from[char].pop(), where['?'].pop()])\n\n\n\n# print(l)\n\n# print(r)\n\nfunc2(l, r, 1)\n\nfunc2(r, l, 0)\n\n\n\n# print(pairs)\n\n\n\n# print(l)\n\n# print(r)\n\nwhile l['?'] and r['?']:\n\n pairs.append([l['?'].pop(), r['?'].pop()])\n\n\n\nprint(len(pairs))\n\nfor pair in pairs:\n\n print(*pair)\n\n\n\n # for char in seek_from:\n\n # if char == '?' and char in where:\n\n # while seek_from[char] and where[char]:\n\n # pairs.append([seek_from[char].pop(), where[char].pop()])\n\n # if not where[char]:\n\n # del where[char]\n\n\n\n#\n\n# pairs = []\n\n# for char in l:\n\n# if char != '?' and char in r:\n\n# nexus = min(l[char], r[char])\n\n# pairs += nexus\n\n# l[char] -= nexus\n\n# r[char] -= nexus\n\n# if not r[char]:\n\n# del r[char]\n\n#\n\n#\n\n# def func(where, from_counter):\n\n# global pairs\n\n# if '?' in where:\n\n# for char in from_counter:\n\n# if char != '?' and where['?']:\n\n# nexus = min(from_counter[char], where['?'])\n\n# pairs += nexus\n\n# where['?'] -= nexus\n\n#\n\n","language":"py"} -{"contest_id":"1286","problem_id":"C1","statement":"C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the string, and the following line should contain the string ss.ExampleInputCopy4\n\na\naa\na\n\ncb\nb\nc\n\ncOutputCopy? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc","tags":["brute force","constructive algorithms","interactive","math"],"code":"import sys\n\nlatin = \"abcdefghijklmnopqrstuvwxyz\"\n\nn = int(input())\n\nif n == 1:\n\n print(\"?\", 1, n)\n\n sys.stdout.flush()\n\n a = input()\n\n print(\"!\", a)\n\nelse:\n\n print(\"?\",1,n)\n\n sys.stdout.flush()\n\n d1 = {}\n\n for i in range(1,n+1):\n\n d1[i] = []\n\n for i in range((n+1)*n\/\/2):\n\n s = input()\n\n dick = []\n\n for i in latin:\n\n dick.append(s.count(i))\n\n d1[len(s)].append(dick)\n\n print(\"?\",2,n)\n\n sys.stdout.flush()\n\n d2 = {}\n\n for i in range(1,n):\n\n d2[i] = []\n\n for i in range((n-1)*n\/\/2):\n\n s = input()\n\n dick = []\n\n for i in latin:\n\n dick.append(s.count(i))\n\n d2[len(s)].append(dick)\n\n odp = [0] * n\n\n for i in range(1,n+1):\n\n d1[i].sort()\n\n if i < n:\n\n d2[i].sort()\n\n lewe = {}\n\n for i in range(1, n):\n\n kandydat = d1[i][-1]\n\n for j in range(len(d2[i])):\n\n if d1[i][j] != d2[i][j]:\n\n kandydat = d1[i][j]\n\n break\n\n lewe[i] = kandydat\n\n lewe[n] = d1[n][0]\n\n for i in range(26):\n\n if lewe[1][i] !=0:\n\n odp[0] = chr(97+i)\n\n for i in range(2, n+1):\n\n for j in range(26):\n\n if lewe[i][j] > lewe[i-1][j]:\n\n odp[i-1] = chr(97 + j)\n\n print(\"!\",\"\".join(odp))","language":"py"} -{"contest_id":"1287","problem_id":"A","statement":"A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters \"A\" and \"P\": \"A\" corresponds to an angry student \"P\" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt\u00a0\u2014 the number of groups of students (1\u2264t\u22641001\u2264t\u2264100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1\u2264ki\u22641001\u2264ki\u2264100)\u00a0\u2014 the number of students in the group, followed by a string sisi, consisting of kiki letters \"A\" and \"P\", which describes the ii-th group of students.OutputFor every group output single integer\u00a0\u2014 the last moment a student becomes angry.ExamplesInputCopy1\n4\nPPAP\nOutputCopy1\nInputCopy3\n12\nAPPAPPPAPPPP\n3\nAAP\n3\nPPA\nOutputCopy4\n1\n0\nNoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute\u00a0\u2014 AAPAAPPAAPPP after 22 minutes\u00a0\u2014 AAAAAAPAAAPP after 33 minutes\u00a0\u2014 AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.","tags":["greedy","implementation"],"code":"n = int(input())\n\nfor i in range(n):\n\n size = int(input())\n\n s = input()\n\n cnt = 0\n\n temp = s.replace('AP','AA')\n\n while(temp != s):\n\n cnt += 1 \n\n s= temp\n\n temp = s.replace('AP','AA')\n\n print(cnt)","language":"py"} -{"contest_id":"1285","problem_id":"B","statement":"B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1\u2264l\u2264r\u2264n)(1\u2264l\u2264r\u2264n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,\u2026,rl,l+1,\u2026,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,\u22121][7,4,\u22121]. Yasser will buy all of them, the total tastiness will be 7+4\u22121=107+4\u22121=10. Adel can choose segments [7],[4],[\u22121],[7,4][7],[4],[\u22121],[7,4] or [4,\u22121][4,\u22121], their total tastinesses are 7,4,\u22121,117,4,\u22121,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104). The description of the test cases follows.The first line of each test case contains nn (2\u2264n\u22641052\u2264n\u2264105).The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (\u2212109\u2264ai\u2264109\u2212109\u2264ai\u2264109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print \"YES\", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print \"NO\".ExampleInputCopy3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5\nOutputCopyYES\nNO\nNO\nNoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.","tags":["dp","greedy","implementation"],"code":"import itertools\n\n\n\nfor t in range(int(input())):\n\n n = int(input())\n\n\n\n a = list(itertools.accumulate(map(int, input().split())))\n\n\n\n if min(a[:-1]) <= 0 or max(a[:-1]) >= a[-1]:\n\n print('NO')\n\n else:\n\n print('YES')\n\n","language":"py"} -{"contest_id":"1311","problem_id":"A","statement":"A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a\u2212ya\u2212y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1\u2264a,b\u22641091\u2264a,b\u2264109).OutputFor each test case, print the answer \u2014 the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5\n2 3\n10 10\n2 4\n7 4\n9 3\nOutputCopy1\n0\n2\n2\n1\nNoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.","tags":["greedy","implementation","math"],"code":"def main():\n\n t = int(input())\n\n # Loop through each test case and compute\n\n for _ in range(t):\n\n a, b = [int(i) for i in input().split()]\n\n if a == b:\n\n print(0)\n\n continue\n\n diff = abs(a-b)\n\n if diff % 2:\n\n if a < b:\n\n print(1)\n\n else:\n\n print(2)\n\n else:\n\n if a < b:\n\n print(2)\n\n else:\n\n print(1)\n\n \n\n\n\nif __name__ == \"__main__\":\n\n main()","language":"py"} -{"contest_id":"1305","problem_id":"F","statement":"F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u00a0\u2014 the number of elements in the array.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an. (1\u2264ai\u226410121\u2264ai\u22641012) \u00a0\u2014 the elements of the array.OutputPrint a single integer \u00a0\u2014 the minimum number of operations required to make the array good.ExamplesInputCopy3\n6 2 4\nOutputCopy0\nInputCopy5\n9 8 7 3 1\nOutputCopy4\nNoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.","tags":["math","number theory","probabilities"],"code":"import random\n\n \n\nn = int(input())\n\na = list(map(int, input().split()))\n\n \n\nlimit = min(8, n)\n\niterations = [x for x in range(n)]\n\nrandom.shuffle(iterations)\n\niterations = iterations[:limit]\n\n \n\ndef factorization(x):\n\n\tprimes = []\n\n\ti = 2\n\n\twhile i * i <= x:\n\n\t\tif x % i == 0:\n\n\t\t\tprimes.append(i)\n\n\t\t\twhile x % i == 0: x \/\/= i\n\n\t\ti = i + 1\n\n\tif x > 1: primes.append(x)\n\n\treturn primes\n\n \n\ndef solve_with_fixed_gcd(arr, gcd):\n\n\tresult = 0\n\n\tfor x in arr:\n\n\t\tif x < gcd: result += (gcd - x)\n\n\t\telse:\n\n\t\t\tremainder = x % gcd\n\n\t\t\tresult += min(remainder, gcd - remainder)\n\n\treturn result\n\n \n\nanswer = float(\"inf\")\n\nprime_list = set()\n\nfor index in iterations:\n\n\tfor x in range(-1, 2):\n\n\t\ttmp = factorization(a[index]-x)\n\n\t\tfor z in tmp: prime_list.add(z)\n\n \n\nfor prime in prime_list:\n\n\tanswer = min(answer, solve_with_fixed_gcd(a, prime))\n\n\tif answer == 0: break\n\n \n\nprint(answer)","language":"py"} -{"contest_id":"1286","problem_id":"C1","statement":"C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the string, and the following line should contain the string ss.ExampleInputCopy4\n\na\naa\na\n\ncb\nb\nc\n\ncOutputCopy? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc","tags":["brute force","constructive algorithms","interactive","math"],"code":"from collections import Counter\n\nDEBUG = False\n\n\n\nN = int(input())\n\nif N == 1:\n\n print('? 1 {}'.format(N), flush = True)\n\n print('! ' + input(), flush = True)\n\nelse:\n\n LC = [Counter() for _ in range(N+1)]\n\n if not DEBUG:\n\n print('? 1 {}'.format(N), flush = True)\n\n for _ in range(N*(N+1)\/\/2):\n\n K = list(map(lambda x: ord(x)-97, input().strip()))\n\n l = len(K)\n\n for k in K:\n\n LC[l][k] += 1\n\n else:\n\n for i in range(1, N+1):\n\n for j in range(i):\n\n K = list(map(lambda x: ord(x)-97, S[j:i]))\n\n l = len(K)\n\n for k in K:\n\n LC[l][k] += 1\n\n \n\n comp = [Counter() for _ in range(N+1)]\n\n pre = Counter()\n\n for k in range(26):\n\n comp[N][k] += LC[N][k]\n\n pre[k] += LC[N][k]\n\n for x in range(N-1, 0, -1):\n\n if N+1-x > x:\n\n break\n\n for k in range(26):\n\n comp[x][k] = LC[x][k] - pre[k]\n\n pre[k] += comp[x][k]\n\n \n\n LC2 = [Counter() for _ in range(N)]\n\n Ar = [None] * (N+1)\n\n if not DEBUG:\n\n print('? 1 {}'.format(N-1), flush = True)\n\n for _ in range((N-1)*N\/\/2):\n\n K = list(map(lambda x: ord(x)-97, input().strip()))\n\n l = len(K)\n\n for k in K:\n\n LC2[l][k] += 1\n\n else:\n\n for i in range(1, N):\n\n for j in range(i):\n\n K = list(map(lambda x: ord(x)-97, S[j:i]))\n\n l = len(K)\n\n for k in K:\n\n LC2[l][k] += 1\n\n \n\n comp2 = [Counter() for _ in range(N+1)]\n\n pre = Counter()\n\n for k in range(26):\n\n comp2[N-1][k] += LC2[N-1][k]\n\n pre[k] += LC2[N-1][k]\n\n for x in range(N-2, 0, -1):\n\n if N-x > x:\n\n break\n\n for k in range(26):\n\n comp2[x][k] = LC2[x][k] - pre[k]\n\n pre[k] += comp2[x][k]\n\n\n\n for i in range(N-1, -1, -1):\n\n if comp2[i] == Counter():\n\n break\n\n for st in range(26):\n\n if comp[i][st] != comp2[i][st]:\n\n Ar[N-i] = st\n\n for i in range(1, N):\n\n if comp[N+1-i] == Counter():\n\n break\n\n for st in range(26):\n\n if comp[N+1-i][st] != comp2[N-i][st]:\n\n Ar[N+1-i] = st\n\n \n\n print('! ' + ''.join(map(lambda x:chr(x+97), Ar[1:])), flush = True)\n\n ","language":"py"} -{"contest_id":"1313","problem_id":"C2","statement":"C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n\u2264500000n\u2264500000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiai= a[i]):\n\n left[s.pop()] = i\n\n\n\n s.append(i)\n\n\n\n\n\n right , s = [n for i in range(n)] , []\n\n for i in range(n):\n\n\n\n while(len(s) and a[s[-1]] >= a[i]):\n\n right[s.pop()] = i\n\n\n\n s.append(i)\n\n\n\n \n\n sumval = [0 for i in range(n + 1)]\n\n for i in range(n):\n\n sumval[i + 1] = sumval[i] + a[i]\n\n\n\n prefix = [0 for i in range(n + 1)]\n\n for i in range(n):\n\n sval = sumval[i] - sumval[left[i] + 1]\n\n prefix[i + 1] = prefix[left[i] + 1] + sval - (i - left[i] - 1) * a[i]\n\n\n\n\n\n suffix = [0 for i in range(n + 1)]\n\n for i in range(n - 1 , -1 , -1):\n\n sval = sumval[right[i]] - sumval[i + 1]\n\n suffix[i] = suffix[right[i]] + sval - (right[i] - i - 1) * a[i]\n\n\n\n best = float('inf')\n\n for i in range(n):\n\n value = prefix[i + 1] + suffix[i]\n\n\n\n if(best > value):\n\n best = value\n\n peak = i\n\n \n\n\n\n for i in range(peak - 1 , -1 , -1):\n\n if(a[i] > a[i + 1]):\n\n a[i] = a[i + 1]\n\n\n\n for i in range(peak + 1 , n):\n\n if(a[i] > a[i - 1]):\n\n a[i] = a[i - 1]\n\n\n\n\n\n return a\n\n \n\n\n\nfor T in range(1):\n\n\n\n n = int(input())\n\n a = inp()\n\n\n\n print(*answer())\n\n","language":"py"} -{"contest_id":"1285","problem_id":"C","statement":"C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1\u2264X\u226410121\u2264X\u22641012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2\nOutputCopy1 2\nInputCopy6\nOutputCopy2 3\nInputCopy4\nOutputCopy1 4\nInputCopy1\nOutputCopy1 1\n","tags":["brute force","math","number theory"],"code":"from math import lcm, ceil\n\n \n\n# primes = []\n\n \n\n# def seive(lim):\n\n# lim = ceil(lim ** 0.5) + 10\n\n# p = [True] * lim\n\n# p[0] = p[1] = False\n\n# i = 2\n\n# while i < lim:\n\n# if p[i]:\n\n# primes.append(i)\n\n# j = i*i\n\n# while j < lim:\n\n# p[j] = False\n\n# j += i\n\n# i += 1\n\n \n\nmin = n = int(input())\n\nsq = ceil(n ** 0.5) + 100\n\n# seive(n)\n\nx = 1\n\nwhile x <= sq:\n\n if n % x == 0:\n\n y = n \/\/ x\n\n if lcm(x, y) != n:\n\n x += 1\n\n continue\n\n m = max(x, y)\n\n if m < min:\n\n min = m\n\n x += 1\n\n \n\na, b = sorted([min, n \/\/ min])\n\nprint(a, b)","language":"py"} -{"contest_id":"1325","problem_id":"D","statement":"D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0\u2264u,v\u22641018)(0\u2264u,v\u22641018).OutputIf there's no array that satisfies the condition, print \"-1\". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4\nOutputCopy2\n3 1InputCopy1 3\nOutputCopy3\n1 1 1InputCopy8 5\nOutputCopy-1InputCopy0 0\nOutputCopy0NoteIn the first sample; 3\u22951=23\u22951=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.","tags":["bitmasks","constructive algorithms","greedy","number theory"],"code":"import sys\n\n\n\ninput = sys.stdin.readline\n\n\n\n\n\ndef inp():\n\n\treturn (int(input()))\n\n\n\n\n\ndef inlt():\n\n\treturn (list(map(int, input().split())))\n\n\n\n\n\ndef insr():\n\n\ts = input()\n\n\treturn (list(s[:len(s) - 1]))\n\n\n\n\n\ndef invr():\n\n\treturn (map(int, input().split()))\n\n\n\nn,k=invr()\n\nif(k n:\n\n ans += pri_q[-1] - n\n\n pri_q.pop()\n\n insort(pri_q, n)\n\n insort(pri_q, n)\n\n return ans\n\n\n\nif __name__ == '__main__':\n\n N = input()\n\n arr = list(map(int, input().split(' ')))\n\n print(min_steps_N(arr))\n\n","language":"py"} -{"contest_id":"1324","problem_id":"A","statement":"A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2\u00d712\u00d71 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2\u00d712\u00d71 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai\u22121ai\u22121. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.ExampleInputCopy4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\nOutputCopyYES\nNO\nYES\nYES\nNoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.","tags":["implementation","number theory"],"code":"\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n odd = 0\n even = 0\n for i in a:\n if i%2 == 0:\n even += 1\n else:\n odd += 1\n if odd == 0 or even == 0:\n print(\"YES\")\n else:\n print(\"NO\")\n\n\n \t \t\t\t \t\t\t \t\t\t\t\t \t \t \t","language":"py"} -{"contest_id":"1316","problem_id":"C","statement":"C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+\u22ef+an\u22121xn\u22121f(x)=a0+a1x+\u22ef+an\u22121xn\u22121 and g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1. Let h(x)=f(x)\u22c5g(x)h(x)=f(x)\u22c5g(x). Suppose that h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1\u2264n,m\u2264106,2\u2264p\u22641091\u2264n,m\u2264106,2\u2264p\u2264109), \u00a0\u2014 nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,\u2026,an\u22121a0,a1,\u2026,an\u22121 (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,\u2026,bm\u22121b0,b1,\u2026,bm\u22121 (1\u2264bi\u22641091\u2264bi\u2264109) \u00a0\u2014 bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0\u2264t\u2264n+m\u221220\u2264t\u2264n+m\u22122) \u00a0\u2014 the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2\n1 1 2\n2 1\nOutputCopy1\nInputCopy2 2 999999937\n2 1\n3 1\nOutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.","tags":["constructive algorithms","math","ternary search"],"code":"from collections import deque, defaultdict, Counter\n\nfrom heapq import heappush, heappop, heapify\n\nfrom math import inf, sqrt, ceil, log2\n\nfrom functools import lru_cache\n\nfrom itertools import accumulate, combinations, permutations, product\n\nfrom typing import List\n\nfrom bisect import bisect_left, bisect_right\n\nimport sys\n\nimport string\n\ninput=lambda:sys.stdin.buffer.readline()\n\nmis=lambda:map(int,input().split())\n\nii=lambda:int(input())\n\n#sys.setrecursionlimit(5*(10 ** 3))\n\n\n\nN, M, P = mis()\n\nA = list(mis())\n\nB = list(mis())\n\n\n\npi = None\n\npj = None\n\nfor i in range(N):\n\n if A[i] % P != 0:\n\n pi = i\n\n break\n\nfor j in range(M):\n\n if B[j] % P != 0:\n\n pj = j\n\n break\n\nprint(pi + pj)\n\n\n\n\n\n","language":"py"} -{"contest_id":"1141","problem_id":"F2","statement":"F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],\u2026,a[n].a[1],a[2],\u2026,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],\u2026,a[r]a[l],a[l+1],\u2026,a[r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),\u2026,(lk,rk)(l1,r1),(l2,r2),\u2026,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i\u2260ji\u2260j either rikk\u2032>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1\u2264n\u226415001\u2264n\u22641500) \u2014 the length of the given array. The second line contains the sequence of elements a[1],a[2],\u2026,a[n]a[1],a[2],\u2026,a[n] (\u2212105\u2264ai\u2264105\u2212105\u2264ai\u2264105).OutputIn the first line print the integer kk (1\u2264k\u2264n1\u2264k\u2264n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1\u2264li\u2264ri\u2264n1\u2264li\u2264ri\u2264n) \u2014 the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7\n4 1 2 2 1 5 3\nOutputCopy3\n7 7\n2 3\n4 5\nInputCopy11\n-5 -4 -3 -2 -1 0 1 2 3 4 5\nOutputCopy2\n3 4\n1 1\nInputCopy4\n1 1 1 1\nOutputCopy4\n4 4\n1 1\n2 2\n3 3\n","tags":["data structures","greedy"],"code":"import io, os, sys, atexit\n\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\ninputs =lambda: input().decode().strip()\n\nstdout = io.BytesIO()\n\nsys.stdout.write = lambda s: stdout.write(s.encode())\n\natexit.register(lambda: os.write(1, stdout.getvalue()))\n\n\n\n\n\n## code start\n\nfrom collections import defaultdict\n\nfrom itertools import accumulate\n\nn=int(input())\n\na=[*map(int,input().split())]\n\npresum=list(accumulate(a,initial=0)) # \u524d\u7f00\u548c\n\n\n\ndata=defaultdict(list) \n\nfor h in range(n):\n\n for t in range(h+1,n+1):\n\n data[presum[t]-presum[h]].append((h+1,t)) # \u4ee5\u533a\u95f4\u548c\u4e3a\u952e\u503c, \u5efa\u7acb\u5b57\u5178, \u8bb0\u5f55\u6240\u6709\u533a\u95f4\u548c\u4e3a\u8be5\u952e\u503c\u7684\u8d77\u7ec8\u70b9\n\n\n\nmaxcnt,res=0,[]\n\nfor key in data: # \u679a\u4e3e\u533a\u95f4\u548c\n\n data[key].sort(key=lambda x:x[1]) # \u6240\u6709\u533a\u95f4\u6309\u7ec8\u70b9\u6392\u5e8f\n\n cnt,prev=0,-1 \n\n for a,b in data[key]:\n\n if a>prev: # \u5982\u679c\u8d77\u70b9\u5927\u4e8e\u4e0a\u4e00\u6bb5\u7ec8\u70b9, \u8d2a\u5fc3\u52a0\u5165\n\n cnt+=1 # \u8ba1\u6570\u52a01\n\n prev=b # \u7ec8\u70b9\u53d8\u6210\u672c\u533a\u95f4\u7ec8\u70b9\n\n if cnt>maxcnt:\n\n maxcnt=cnt\n\n res=key\n\n \n\n \n\nprint(maxcnt)\n\nprev=-1\n\nfor a,b in data[res]:\n\n if a>prev:\n\n print(a,b)\n\n prev=b\n\n\n\n \n\n","language":"py"} -{"contest_id":"1292","problem_id":"B","statement":"B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIV\u039b - \u6f02\u6d41 KIV\u039b & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by)(ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x\u22121,y)(x\u22121,y), (x+1,y)(x+1,y), (x,y\u22121)(x,y\u22121) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1\u2264x0,y0\u226410161\u2264x0,y0\u22641016, 2\u2264ax,ay\u22641002\u2264ax,ay\u2264100, 0\u2264bx,by\u226410160\u2264bx,by\u22641016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1\u2264xs,ys,t\u226410161\u2264xs,ys,t\u22641016)\u00a0\u2013 the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer\u00a0\u2014 the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0\n2 4 20\nOutputCopy3InputCopy1 1 2 3 1 0\n15 27 26\nOutputCopy2InputCopy1 1 2 3 1 0\n2 2 1\nOutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3\u22122|+|3\u22124|=2|3\u22122|+|3\u22124|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1\u22123|+|1\u22123|=4|1\u22123|+|1\u22123|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7\u22121|+|9\u22121|=14|7\u22121|+|9\u22121|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15\u22127|+|27\u22129|=26|15\u22127|+|27\u22129|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.","tags":["brute force","constructive algorithms","geometry","greedy","implementation"],"code":"import sys\n\ninput=lambda:sys.stdin.readline().rstrip()\n\ndef dist(a,b):\n\n return sum([abs(a[i]-b[i]) for i in range(2)])\n\ntemp=list(map(int,input().split()))\n\npoints=[temp[0:2]]\n\na=temp[2:4]\n\nb=temp[4:6]\n\nstart=[0,0]\n\n*start,t=map(int,input().split())\n\nwhile points[-1][0]-start[0]<=t:\n\n\tpoints.append([points[-1][i]*a[i]+b[i] for i in range(2)])\n\nfor i in range(len(points)-1,-1,-1):\n\n\tfor j in range(len(points)-i):\n\n\t\tif dist(points[j],points[j+i])+min(dist(start,points[j]),dist(start,points[j+i]))<=t:\n\n\t\t\tprint(i+1)\n\n\t\t\tsys.exit()\n\nprint(0)","language":"py"} -{"contest_id":"1293","problem_id":"A","statement":"A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin \"ConneR\" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1\u2264t\u226410001\u2264t\u22641000)\u00a0\u2014 the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2\u2264n\u22641092\u2264n\u2264109, 1\u2264s\u2264n1\u2264s\u2264n, 1\u2264k\u2264min(n\u22121,1000)1\u2264k\u2264min(n\u22121,1000))\u00a0\u2014 respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n)\u00a0\u2014 the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer\u00a0\u2014 the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77\nOutputCopy2\n0\n4\n0\n2\nNoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.","tags":["binary search","brute force","implementation"],"code":"t = int(input())\n\n\n\nfor _ in range(t):\n\n n, s, k = map(int, input().split())\n\n a = set(map(int, input().split()))\n\n ans = 0\n\n\n\n for i in range(k+1):\n\n if (s-i >= 1 and not s-i in a) or (s+i <= n and not s+i in a):\n\n ans = i\n\n break\n\n\n\n print(ans)\n\n \n\n","language":"py"} -{"contest_id":"1141","problem_id":"F1","statement":"F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],\u2026,a[n].a[1],a[2],\u2026,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],\u2026,a[r]a[l],a[l+1],\u2026,a[r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),\u2026,(lk,rk)(l1,r1),(l2,r2),\u2026,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i\u2260ji\u2260j either rikk\u2032>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1\u2264n\u2264501\u2264n\u226450) \u2014 the length of the given array. The second line contains the sequence of elements a[1],a[2],\u2026,a[n]a[1],a[2],\u2026,a[n] (\u2212105\u2264ai\u2264105\u2212105\u2264ai\u2264105).OutputIn the first line print the integer kk (1\u2264k\u2264n1\u2264k\u2264n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1\u2264li\u2264ri\u2264n1\u2264li\u2264ri\u2264n) \u2014 the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7\n4 1 2 2 1 5 3\nOutputCopy3\n7 7\n2 3\n4 5\nInputCopy11\n-5 -4 -3 -2 -1 0 1 2 3 4 5\nOutputCopy2\n3 4\n1 1\nInputCopy4\n1 1 1 1\nOutputCopy4\n4 4\n1 1\n2 2\n3 3\n","tags":["greedy"],"code":"# Thank God that I'm not you.\n\n\n\nimport bisect\n\nfrom collections import Counter, deque\n\nimport heapq\n\nimport itertools\n\nimport math\n\nimport random\n\nimport sys\n\nfrom types import GeneratorType;\n\n\n\ndef bootstrap(f, stack=[]):\n\n def wrappedfunc(*args, **kwargs):\n\n if stack:\n\n return f(*args, **kwargs)\n\n else:\n\n to = f(*args, **kwargs)\n\n while True:\n\n if type(to) is GeneratorType:\n\n stack.append(to)\n\n to = next(to)\n\n else:\n\n stack.pop()\n\n if not stack:\n\n break\n\n to = stack[-1].send(to)\n\n return to\n\n \n\n return wrappedfunc \n\n\n\ndef primeFactors(n):\n\n \n\n counter = Counter(); \n\n while n % 2 == 0:\n\n counter[2] += 1;\n\n n = n \/ 2\n\n \n\n \n\n for i in range(3,int(math.sqrt(n))+1,2):\n\n \n\n while n % i== 0:\n\n counter[i] += 1;\n\n n = n \/ i\n\n \n\n if (n > 2):\n\n counter[n] += 1;\n\n \n\n return counter;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nn = int(input())\n\n\n\n\n\narray = list(map(int, input().split()))\n\n\n\n\n\nhashMap = {}\n\n\n\n\n\nfor i in range(n):\n\n currentSum = 0\n\n for x in range(i, n):\n\n currentSum += array[x]\n\n left, right = i, x;\n\n if currentSum not in hashMap:\n\n hashMap[currentSum] = [[[left, right], 1]]\n\n else:\n\n currentMax = 0\n\n for (leftOne, rightOne), cnt in hashMap[currentSum]:\n\n if (rightOne) < left:\n\n currentMax = max(currentMax, cnt)\n\n \n\n hashMap[currentSum].append([[left, right], currentMax + 1])\n\n\n\ncurrentMax, sumAss = 1, None;\n\nfor sumElems in hashMap:\n\n for _, cnt in hashMap[sumElems]:\n\n if cnt >= currentMax:\n\n currentMax = cnt;\n\n sumAss = sumElems;\n\n\n\nlastSegment = None;\n\n\n\nresult = []\n\nfor segment, cnt in hashMap[sumAss][::-1]:\n\n if not currentMax:\n\n break;\n\n if cnt == currentMax:\n\n if lastSegment is None:\n\n lastSegment = segment;\n\n result.append(segment);\n\n currentMax -= 1\n\n continue\n\n leftOne, rightOne = lastSegment\n\n leftTwo, rightTwo = segment\n\n if leftOne > rightTwo:\n\n lastSegment = segment\n\n result.append(segment)\n\n currentMax -= 1\n\n \n\n\n\nprint(len(result))\n\n\n\nfor left, right in result:\n\n print(left + 1, right + 1) \n\n \n\n \n\n \n\n \n\n ","language":"py"} -{"contest_id":"1325","problem_id":"A","statement":"A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1\u2264t\u2264100)(1\u2264t\u2264100) \u00a0\u2014 the number of testcases.Each testcase consists of one line containing a single integer, xx (2\u2264x\u2264109)(2\u2264x\u2264109).OutputFor each testcase, output a pair of positive integers aa and bb (1\u2264a,b\u2264109)1\u2264a,b\u2264109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2\n2\n14\nOutputCopy1 1\n6 4\nNoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.","tags":["constructive algorithms","greedy","number theory"],"code":"n=int(input())\n\nfor i in range(n):\n\n print(1,int(input())-1)","language":"py"} -{"contest_id":"1292","problem_id":"A","statement":"A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#\u03a6\u03c9\u03a6 has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2\u00d7n2\u00d7n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2\u2264n\u22641052\u2264n\u2264105, 1\u2264q\u22641051\u2264q\u2264105).The ii-th of qq following lines contains two integers riri, cici (1\u2264ri\u226421\u2264ri\u22642, 1\u2264ci\u2264n1\u2264ci\u2264n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print \"Yes\", otherwise print \"No\". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5\n2 3\n1 4\n2 4\n2 3\n1 4\nOutputCopyYes\nNo\nNo\nNo\nYes\nNoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)\u2192(1,2)\u2192(1,3)\u2192(1,4)\u2192(1,5)\u2192(2,5)(1,1)\u2192(1,2)\u2192(1,3)\u2192(1,4)\u2192(1,5)\u2192(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. ","tags":["data structures","dsu","implementation"],"code":"import sys\n\ninput = lambda: sys.stdin.readline().rstrip()\n\n\n\nn, q = map(int, input().split())\n\n\n\ncur = [[0] * n for _ in range(2)]\n\nblocked_c = 0\n\nfor _ in range(q):\n\n x, y = map(int, input().split())\n\n x -= 1\n\n y -= 1\n\n \n\n nx = x ^ 1\n\n if cur[x][y] == 0:\n\n delta = 1\n\n else:\n\n delta = -1\n\n cur[x][y] ^= 1\n\n \n\n for ny in range(y - 1, y + 2):\n\n if 0 <= ny < n:\n\n if cur[nx][ny] == 1:\n\n blocked_c += delta\n\n \n\n if blocked_c:\n\n print('No')\n\n else:\n\n print('Yes')","language":"py"} -{"contest_id":"1292","problem_id":"B","statement":"B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIV\u039b - \u6f02\u6d41 KIV\u039b & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by)(ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x\u22121,y)(x\u22121,y), (x+1,y)(x+1,y), (x,y\u22121)(x,y\u22121) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1\u2264x0,y0\u226410161\u2264x0,y0\u22641016, 2\u2264ax,ay\u22641002\u2264ax,ay\u2264100, 0\u2264bx,by\u226410160\u2264bx,by\u22641016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1\u2264xs,ys,t\u226410161\u2264xs,ys,t\u22641016)\u00a0\u2013 the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer\u00a0\u2014 the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0\n2 4 20\nOutputCopy3InputCopy1 1 2 3 1 0\n15 27 26\nOutputCopy2InputCopy1 1 2 3 1 0\n2 2 1\nOutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3\u22122|+|3\u22124|=2|3\u22122|+|3\u22124|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1\u22123|+|1\u22123|=4|1\u22123|+|1\u22123|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7\u22121|+|9\u22121|=14|7\u22121|+|9\u22121|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15\u22127|+|27\u22129|=26|15\u22127|+|27\u22129|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.","tags":["brute force","constructive algorithms","geometry","greedy","implementation"],"code":"T = 1\n\nfor test_no in range(T):\n\n x0, y0, ax, ay, bx, by = map(int, input().split())\n\n xs, ys, t = map(int, input().split())\n\n\n\n LIMIT = 2 ** 62 - 1\n\n x, y = [x0], [y0]\n\n while ((LIMIT - bx) \/ ax >= x[-1] and (LIMIT - by) \/ ay >= y[-1]):\n\n x.append(ax * x[-1] + bx)\n\n y.append(ay * y[-1] + by)\n\n\n\n n = len(x)\n\n ans = 0\n\n for i in range(n):\n\n for j in range(i, n):\n\n length = x[j] - x[i] + y[j] - y[i]\n\n dist2Left = abs(xs - x[i]) + abs(ys - y[i])\n\n dist2Right = abs(xs - x[j]) + abs(ys - y[j])\n\n if (length <= t - dist2Left or length <= t - dist2Right): ans = max(ans, j - i + 1)\n\n\n\n print(ans)","language":"py"} -{"contest_id":"1321","problem_id":"C","statement":"C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1\u2264i\u2264|s|1\u2264i\u2264|s| during each operation.For the character sisi adjacent characters are si\u22121si\u22121 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1\u2264|s|\u22641001\u2264|s|\u2264100) \u2014 the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer \u2014 the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8\nbacabcab\nOutputCopy4\nInputCopy4\nbcda\nOutputCopy3\nInputCopy6\nabbbbb\nOutputCopy5\nNoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. ","tags":["brute force","constructive algorithms","greedy","strings"],"code":"import heapq\n\nimport math\n\nimport os\n\nfrom collections import Counter, deque, defaultdict\n\nfrom sys import stdout\n\nimport time\n\nfrom math import factorial, log, gcd\n\nimport sys\n\nfrom decimal import Decimal\n\nimport threading\n\nfrom heapq import *\n\nimport random\n\n\n\n\n\ndef S():\n\n return sys.stdin.readline().split()\n\n\n\n\n\ndef I():\n\n return [int(i) for i in sys.stdin.readline().split()]\n\n\n\n\n\ndef II():\n\n return int(sys.stdin.readline())\n\n\n\n\n\ndef IS():\n\n return sys.stdin.readline().replace('\\n', '')\n\n\n\n\n\ndef main():\n\n n = II()\n\n s = IS()\n\n d = dict([(chr(i + 1), chr(i)) for i in range(ord('a'), ord('z'))])\n\n c = Counter(s)\n\n ans = 0\n\n while True:\n\n flag = False\n\n for i in range(ord('z'), ord('a'), -1):\n\n mx = chr(i)\n\n if flag:\n\n break\n\n if c[mx] > 0:\n\n for j in range(n):\n\n if s[j] == mx:\n\n if (j > 0 and s[j - 1] == d[mx]) or (j < n - 1 and s[j + 1] == d[mx]):\n\n if 0 < j < n - 1:\n\n s = s[:j] + s[j + 1:]\n\n elif j == 0:\n\n s = s[1:]\n\n else:\n\n s = s[:-1]\n\n flag = True\n\n ans += 1\n\n n -= 1\n\n break\n\n if not flag:\n\n break\n\n print(ans)\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n # for _ in range(II()):\n\n # main()\n\n main()","language":"py"} -{"contest_id":"1313","problem_id":"C1","statement":"C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n\u22641000n\u22641000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiaisu:\n su=sum(t);ans=t\nprint(*ans)\n\t\t \t\t\t\t\t \t\t\t \t \t\t\t \t\t\t \t","language":"py"} -{"contest_id":"1325","problem_id":"D","statement":"D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0\u2264u,v\u22641018)(0\u2264u,v\u22641018).OutputIf there's no array that satisfies the condition, print \"-1\". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4\nOutputCopy2\n3 1InputCopy1 3\nOutputCopy3\n1 1 1InputCopy8 5\nOutputCopy-1InputCopy0 0\nOutputCopy0NoteIn the first sample; 3\u22951=23\u22951=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.","tags":["bitmasks","constructive algorithms","greedy","number theory"],"code":"import sys, threading\n\nimport math\n\nfrom os import path\n\nfrom collections import defaultdict, Counter, deque\n\nfrom bisect import *\n\nfrom string import ascii_lowercase\n\nfrom functools import cmp_to_key\n\nimport heapq\n\n \n\n \n\ndef readInts():\n\n x = list(map(int, (sys.stdin.readline().rstrip().split())))\n\n return x[0] if len(x) == 1 else x\n\n \n\n \n\ndef readList(type=int):\n\n x = sys.stdin.readline()\n\n x = list(map(type, x.rstrip('\\n\\r').split()))\n\n return x\n\n \n\n \n\ndef readStr():\n\n x = sys.stdin.readline().rstrip('\\r\\n')\n\n return x\n\n \n\n \n\nwrite = sys.stdout.write\n\nread = sys.stdin.readline\n\n \n\n \n\nMAXN = 1123456\n\n\n\n\n\nclass mydict:\n\n def __init__(self, func):\n\n self.random = randint(0, 1 << 32)\n\n self.default = func\n\n self.dict = {}\n\n \n\n def __getitem__(self, key):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n self.dict[mykey] = self.default()\n\n return self.dict[mykey]\n\n \n\n def get(self, key, default):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n return default\n\n return self.dict[mykey]\n\n \n\n def __setitem__(self, key, item):\n\n mykey = self.random ^ key\n\n self.dict[mykey] = item\n\n \n\n def getkeys(self):\n\n return [self.random ^ i for i in self.dict]\n\n \n\n def __str__(self):\n\n return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'\n\n\n\n \n\ndef lcm(a, b):\n\n return (a*b)\/\/(math.gcd(a,b))\n\n \n\n \n\ndef mod(n):\n\n return n%(10**9 + 7) \n\n\n\n\n\ndef upper_bound(a, num):\n\n l = 0\n\n r = len(a)-1\n\n ans = -1\n\n while l <= r:\n\n mid = (l+r)\/\/2\n\n if a[mid] >= num:\n\n ans = mid\n\n r = mid-1\n\n else:\n\n l = mid+1\n\n\n\n return ans\n\n\n\n\n\ndef solve(t):\n\n # print(f'Case #{t}: ', end = '')\n\n u, v = readInts()\n\n res = []\n\n uc = u\n\n vc = v\n\n\n\n if u&1 != v&1 or u > v:\n\n print(-1)\n\n return\n\n\n\n # print(*xr, sep='')\n\n # print(*sr, sep='')\n\n res = [0 for _ in range(64)]\n\n if uc&1 and vc&1:\n\n res[0] += 1\n\n\n\n for i in range(1, 64):\n\n if not vc&(1 << (i-1)) and vc&(1<<(i-1)) != uc&(1<<(i-1)):\n\n # res[i-1] = 1\n\n vc -= (1< 0:\n\n ans[j] += 1< 0:\n\n ans2.append(num)\n\n # print(bin(num)[2:][::-1])\n\n\n\n print(len(ans2))\n\n if len(ans2) > 0:\n\n print(*ans2) \n\n\n\n\n\ndef main():\n\n t = 1\n\n if path.exists(\"F:\/Comp Programming\/input.txt\"):\n\n sys.stdin = open(\"F:\/Comp Programming\/input.txt\", 'r')\n\n sys.stdout = open(\"F:\/Comp Programming\/output1.txt\", 'w')\n\n # sys.setrecursionlimit(10**5) \n\n # t = readInts()\n\n # print('here')\n\n for i in range(t):\n\n solve(i+1)\n\n \n\n \n\nif __name__ == '__main__':\n\n main() ","language":"py"} -{"contest_id":"1313","problem_id":"C1","statement":"C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n\u22641000n\u22641000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiai> 1\n\n x |= x >> 2\n\n x |= x >> 4\n\n x |= x >> 8\n\n x |= x >> 16\n\n return x ^ (x >> 1)\n\n\n\n\n\ndef nextPowerOf2(N):\n\n if not (N & (N - 1)):\n\n return N\n\n return int(\"1\" + (len(bin(N)) - 2) * \"0\", 2)\n\n\n\n\n\ndef isPrime(x):\n\n if x == 1:\n\n return False\n\n if x == 2:\n\n return True\n\n for i in range(2, int(x ** 0.5) + 1):\n\n if x % i == 0:\n\n return False\n\n return True\n\n\n\n\n\ndef factors(n):\n\n i = 1\n\n ans = []\n\n while i <= sqrt(n):\n\n if (n % i == 0):\n\n if (n \/ i != i):\n\n ans.append(int(n\/i))\n\n if i != 1:\n\n ans.append(i)\n\n i += 1\n\n return ans\n\n\n\n\n\nPrimes = [1] * 100001\n\nprimeNos = []\n\n\n\n\n\ndef SieveOfEratosthenes(n):\n\n p = 2\n\n while (p * p <= n):\n\n if (Primes[p]):\n\n for i in range(p * p, n+1, p):\n\n Primes[i] = 0\n\n p += 1\n\n for p in range(2, n+1):\n\n if Primes[p]:\n\n primeNos.append(p)\n\n\n\n# SieveOfEratosthenes(100000)\n\n# P = len(primeNos)\n\n# print(\"P\", P)\n\n\n\n\n\ndef ncr(n, r):\n\n ans = 1\n\n while(r):\n\n ans *= n\n\n ans %= mod\n\n n -= 1\n\n r -= 1\n\n return ans\n\n\n\n############ Main! #############\n\n# mod = 998244353\n\n\n\n\n\ndef skyScrapper(ind, a, n):\n\n ans = [0]*n\n\n ans[ind] = a[ind]\n\n for i in range(ind+1, n):\n\n ans[i] = min(ans[i-1], a[i])\n\n for i in range(ind-1, -1, -1):\n\n ans[i] = min(ans[i+1], a[i])\n\n return [sum(ans), ans]\n\n\n\n\n\ndef sangee():\n\n n = ri()\n\n a = rl()\n\n k = 0\n\n ans = []\n\n for i in range(n):\n\n ans.append(skyScrapper(i, a, n))\n\n m = max(ans)\n\n print(*m[1])\n\n # print(ans)\n\n\n\n\n\nt = 1\n\nfor _ in range(t):\n\n sangee()\n\n","language":"py"} -{"contest_id":"1296","problem_id":"E1","statement":"E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1\u2264n\u22642001\u2264n\u2264200) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print \"NO\" (without quotes) in the first line.Otherwise, print \"YES\" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9\nabacbecfd\nOutputCopyYES\n001010101\nInputCopy8\naaabbcbb\nOutputCopyYES\n01011011\nInputCopy7\nabcdedc\nOutputCopyNO\nInputCopy5\nabcde\nOutputCopyYES\n00000\n","tags":["constructive algorithms","dp","graphs","greedy","sortings"],"code":"#from sys import stdin\n\n#input = stdin.readline\n\n#\/\/ - remember to add .strip() when input is a string\n\n\n\nn = int(input())\n\n\n\nlets = list(input().strip())\n\n\n\na = []\n\nb = []\n\nbinary_ans = []\n\n\n\nflag = True\n\n\n\nfor i in lets:\n\n\n\n if len(a) == 0:\n\n\n\n a.append(i)\n\n binary_ans.append(\"0\")\n\n\n\n elif i >= a[-1]:\n\n\n\n a.append(i)\n\n binary_ans.append(\"0\")\n\n \n\n elif len(b) == 0:\n\n\n\n b.append(i)\n\n binary_ans.append(\"1\")\n\n \n\n elif i >= b[-1]:\n\n\n\n b.append(i)\n\n binary_ans.append(\"1\")\n\n\n\n else:\n\n\n\n flag = False\n\n break\n\n\n\n\n\nif flag:\n\n print(\"YES\")\n\n print(\"\".join(binary_ans))\n\n\n\nelse:\n\n\n\n print(\"NO\")","language":"py"} -{"contest_id":"1303","problem_id":"B","statement":"B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,\u2026,g1,2,\u2026,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1\u2264T\u22641041\u2264T\u2264104) \u2014 the number of test cases.Next TT lines contain test cases \u2014 one per line. Each line contains three integers nn, gg and bb (1\u2264n,g,b\u22641091\u2264n,g,b\u2264109) \u2014 the length of the highway and the number of good and bad days respectively.OutputPrint TT integers \u2014 one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3\n5 1 1\n8 10 10\n1000000 1 1000000\nOutputCopy5\n8\n499999500000\nNoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.","tags":["math"],"code":"t = int(input())\n\nfor _ in range(t):\n\n n, g, b = map(int, input().split())\n\n half = (n+1) \/\/ 2 # nice way to get ceiling \n\n # ans = multipler * block of g+b days + remainder g days\n\n remainder = half % g\n\n ans = (half\/\/g) * (g+b) + remainder\n\n if remainder == 0: # remove bad days excess\n\n ans -= b\n\n print(max(ans, n))","language":"py"} -{"contest_id":"1303","problem_id":"B","statement":"B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,\u2026,g1,2,\u2026,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1\u2264T\u22641041\u2264T\u2264104) \u2014 the number of test cases.Next TT lines contain test cases \u2014 one per line. Each line contains three integers nn, gg and bb (1\u2264n,g,b\u22641091\u2264n,g,b\u2264109) \u2014 the length of the highway and the number of good and bad days respectively.OutputPrint TT integers \u2014 one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3\n5 1 1\n8 10 10\n1000000 1 1000000\nOutputCopy5\n8\n499999500000\nNoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.","tags":["math"],"code":"for t in range(int(input())):\n\n \n\n n,g,b=map(int,input().split())\n\n l=0\n\n h=10**19\n\n def check(x):\n\n tg=(x\/\/(g+b))*g\n\n tb=(x\/\/(g+b))*b\n\n x=(x%(g+b))\n\n if x<=g:\n\n tg+=x\n\n else:\n\n tg+=g\n\n tb+=x-g\n\n if tg>=(n+1)\/\/2:\n\n left=n-tg\n\n if left<=tb and left<=(n+1)\/\/2:\n\n return True\n\n return False\n\n return False\n\n\n\n while l<=h:\n\n mid=(l+h)\/\/2\n\n if check(mid):\n\n ans=mid\n\n h=mid-1\n\n else:\n\n l=mid+1\n\n print(ans)\n\n ","language":"py"} -{"contest_id":"1285","problem_id":"A","statement":"A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x\u22121x:=x\u22121; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands \"LRLR\", then here are some possible outcomes (underlined commands are sent successfully): \"LRLR\" \u2014 Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; \"LRLR\" \u2014 Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; \"LRLR\" \u2014 Zoma moves to the left, then to the left again and ends up in position \u22122\u22122. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1\u2264n\u2264105)(1\u2264n\u2264105) \u2014 the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer \u2014 the number of different positions Zoma may end up at.ExampleInputCopy4\nLRLR\nOutputCopy5\nNoteIn the example; Zoma may end up anywhere between \u22122\u22122 and 22.","tags":["math"],"code":"n = int(input())\nargs = input()\nprint(args.count('L') + args.count('R') + 1)","language":"py"} -{"contest_id":"1320","problem_id":"A","statement":"A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck\u22121ck>ck\u22121. So, the sequence of visited cities [c1,c2,\u2026,ck][c1,c2,\u2026,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1\u2212ci=bci+1\u2212bcici+1\u2212ci=bci+1\u2212bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1\u2264bi\u22644\u22c51051\u2264bi\u22644\u22c5105), where bibi is the beauty value of the ii-th city.OutputPrint one integer \u2014 the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6\n10 7 1 9 10 15\nOutputCopy26\nInputCopy1\n400000\nOutputCopy400000\nInputCopy7\n8 9 26 11 12 29 14\nOutputCopy55\nNoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].","tags":["data structures","dp","greedy","math","sortings"],"code":"n = int(input())\n\narr = list(map(int, input().split()))\n\ntemp = []\n\nstore = {}\n\nres = 0\n\n\n\nfor i in range(n):\n\n group = i - arr[i]\n\n temp.append(group)\n\n if group not in store:\n\n store[group] = arr[i]\n\n else:\n\n store[group] += arr[i]\n\n\n\n res = max(res, store[group])\n\n\n\nprint(res)\n\n\n\n","language":"py"} -{"contest_id":"1301","problem_id":"C","statement":"C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols \"0\" and \"1\"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to \"1\".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,\u2026,srsl,sl+1,\u2026,sr is equal to \"1\". For example, if s=s=\"01010\" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to \"1\", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u22641051\u2264t\u2264105) \u00a0\u2014 the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1\u2264n\u22641091\u2264n\u2264109, 0\u2264m\u2264n0\u2264m\u2264n)\u00a0\u2014 the length of the string and the number of symbols equal to \"1\" in it.OutputFor every test case print one integer number\u00a0\u2014 the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to \"1\".ExampleInputCopy5\n3 1\n3 2\n3 3\n4 0\n5 2\nOutputCopy4\n5\n6\n0\n12\nNoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to \"1\". These strings are: s1=s1=\"100\", s2=s2=\"010\", s3=s3=\"001\". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is \"101\".In the third test case, the string ss with the maximum value is \"111\".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to \"1\" is \"0000\" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is \"01010\" and it is described as an example in the problem statement.","tags":["binary search","combinatorics","greedy","math","strings"],"code":"\n\nt=int(input())\n\nfor test in range(t):\n\n n,m=map(int,input().split())\n\n r=(n-m)%(m+1)\n\n d=(n-m)\/\/(m+1)\n\n ans=(n-m+r)*(d+1)\n\n print((n*(n+1) - ans)\/\/2)","language":"py"} -{"contest_id":"1304","problem_id":"D","statement":"D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog\u2061n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n\u22121n\u22121, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n\u22121n\u22121.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2\u22c51052\u22c5105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3\n3 <<\n7 >><>><\n5 >>><\nOutputCopy1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3\nNoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.","tags":["constructive algorithms","graphs","greedy","two pointers"],"code":"import sys\n\ninput=sys.stdin.readline\n\n\n\nt=int(input())\n\nfor _ in range(t):\n\n arr=list(input().split())\n\n n=int(arr[0])\n\n s=arr[1]\n\n r=[1]\n\n l=[1]\n\n c=0\n\n for i in range(n-1):\n\n if s[i]=='<':\n\n r[-1]+=1\n\n l.append(1)\n\n else:\n\n l[-1]+=1\n\n r.append(1)\n\n\n\n ans1=[0 for _ in range(n)]\n\n ans2=[0 for _ in range(n)]\n\n p=n\n\n p2=0\n\n for i in range(len(r)):\n\n for j in range(r[i]):\n\n ans1[p2]=p-r[i]+1+j\n\n p2+=1\n\n p-=r[i]\n\n p=1\n\n p2=0\n\n for i in range(len(l)):\n\n for j in range(l[i]):\n\n ans2[p2]=p+l[i]-1-j\n\n p2+=1\n\n p+=l[i]\n\n print(' '.join(map(str,ans1)))\n\n print(' '.join(map(str,ans2)))\n\n \n\n","language":"py"} -{"contest_id":"1312","problem_id":"D","statement":"D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that ajaj+1aj>aj+1, if j\u2265ij\u2265i). InputThe first line contains two integers nn and mm (2\u2264n\u2264m\u22642\u22c51052\u2264n\u2264m\u22642\u22c5105).OutputPrint one integer \u2014 the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4\nOutputCopy6\nInputCopy3 5\nOutputCopy10\nInputCopy42 1337\nOutputCopy806066790\nInputCopy100000 200000\nOutputCopy707899035\nNoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. ","tags":["combinatorics","math"],"code":"import sys\n\nfrom math import *\n\nfrom collections import defaultdict\n\ninp = lambda: sys.stdin.buffer.readline().decode().strip()\n\nout=sys.stdout.write\n\n# n=int(inp())\n\n# arr=list(map(int,inp().split()))\n\nn,m=map(int,inp().split())\n\nmod= 998244353\n\nfact=[1]*(m+1)\n\nfor i in range(1,m+1):\n\n fact[i]=(fact[i-1]*i)%mod\n\ndef modi(x,pri1):\n\n return fast_exp(x,pri1-2,pri1)\n\ndef ncr(n,r,pri1):\n\n return ((fact[n]*modi(fact[r],pri1))%pri1)*((modi(fact[n-r],pri1))%pri1)%pri1\n\ndef fast_exp(x,n,mod):\n\n ans=1\n\n while n>0:\n\n if n%2==1:\n\n ans=(ans*x)%mod\n\n n-=1\n\n x=(x*x)%mod\n\n n \/\/= 2\n\n return ans\n\nans=ncr(m,n-1,mod)*(n-2)*fast_exp(2,n-3,mod)\n\nans%=mod\n\nprint(ans)","language":"py"} -{"contest_id":"1310","problem_id":"A","statement":"A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A\/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn\u00a0\u2014 the number of news categories (1\u2264n\u22642000001\u2264n\u2264200000).The second line of input consists of nn integers aiai\u00a0\u2014 the number of publications of ii-th category selected by the batch algorithm (1\u2264ai\u22641091\u2264ai\u2264109).The third line of input consists of nn integers titi\u00a0\u2014 time it takes for targeted algorithm to find one new publication of category ii (1\u2264ti\u2264105)1\u2264ti\u2264105).OutputPrint one integer\u00a0\u2014 the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5\n3 7 9 7 8\n5 2 5 7 5\nOutputCopy6\nInputCopy5\n1 2 3 4 5\n1 1 1 1 1\nOutputCopy0\nNoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.","tags":["data structures","greedy","sortings"],"code":"import copy\n\nimport random\n\nimport heapq\n\nimport math\n\nimport sys\n\nimport bisect\n\nimport datetime\n\nfrom functools import lru_cache\n\nfrom collections import deque\n\nfrom collections import Counter\n\nfrom collections import defaultdict\n\nfrom itertools import combinations\n\nfrom itertools import permutations\n\nfrom types import GeneratorType\n\nfrom functools import cmp_to_key\n\nfrom functools import reduce\n\nfrom operator import xor\n\nfrom operator import mul\n\nfrom operator import add\n\nfrom decimal import Decimal\n\nfrom heapq import nlargest\n\n\n\ninf = float(\"inf\")\n\n\n\n\n\nclass FastIO:\n\n def __init__(self):\n\n return\n\n\n\n @staticmethod\n\n def _read():\n\n return sys.stdin.readline().strip()\n\n\n\n def read_int(self):\n\n return int(self._read())\n\n\n\n def read_float(self):\n\n return float(self._read())\n\n\n\n def read_ints(self):\n\n return map(int, self._read().split())\n\n\n\n def read_floats(self):\n\n return map(float, self._read().split())\n\n\n\n def read_ints_minus_one(self):\n\n return map(lambda x: int(x) - 1, self._read().split())\n\n\n\n def read_list_ints(self):\n\n return list(map(int, self._read().split()))\n\n\n\n def read_list_floats(self):\n\n return list(map(float, self._read().split()))\n\n\n\n def read_list_ints_minus_one(self):\n\n return list(map(lambda x: int(x) - 1, self._read().split()))\n\n\n\n def read_str(self):\n\n return self._read()\n\n\n\n def read_list_strs(self):\n\n return self._read().split()\n\n\n\n def read_list_str(self):\n\n return list(self._read())\n\n\n\n @staticmethod\n\n def st(x):\n\n return sys.stdout.write(str(x) + '\\n')\n\n\n\n @staticmethod\n\n def lst(x):\n\n return sys.stdout.write(\" \".join(str(w) for w in x) + '\\n')\n\n\n\n @staticmethod\n\n def round_5(f):\n\n res = int(f)\n\n if f - res >= 0.5:\n\n res += 1\n\n return res\n\n\n\n @staticmethod\n\n def max(a, b):\n\n return a if a > b else b\n\n\n\n @staticmethod\n\n def min(a, b):\n\n return a if a < b else b\n\n\n\n @staticmethod\n\n def bootstrap(f, stack=[]):\n\n def wrappedfunc(*args, **kwargs):\n\n if stack:\n\n return f(*args, **kwargs)\n\n else:\n\n to = f(*args, **kwargs)\n\n while True:\n\n if isinstance(to, GeneratorType):\n\n stack.append(to)\n\n to = next(to)\n\n else:\n\n stack.pop()\n\n if not stack:\n\n break\n\n to = stack[-1].send(to)\n\n return to\n\n\n\n return wrappedfunc\n\n\n\n\n\ndef main(ac=FastIO()):\n\n n = ac.read_int()\n\n a = ac.read_list_ints()\n\n t = ac.read_list_ints()\n\n lst = [[a[i], t[i]] for i in range(n)]\n\n del a\n\n del t\n\n lst.sort(key=lambda it: [it[0], -it[1]])\n\n stack = []\n\n total = ans = 0\n\n cur = -1\n\n i = 0\n\n while i < n or stack:\n\n if not stack:\n\n cur = lst[i][0]\n\n while i < n and lst[i][0] == cur:\n\n heapq.heappush(stack, -lst[i][1])\n\n total += lst[i][1]\n\n i += 1\n\n total += heapq.heappop(stack)\n\n ans += total\n\n cur += 1\n\n ac.st(ans)\n\n return\n\n\n\n\n\nmain()\n\n","language":"py"} -{"contest_id":"1285","problem_id":"E","statement":"E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l\u2264x\u2264rl\u2264x\u2264r.Segments can be placed arbitrarily \u00a0\u2014 be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n\u22121n\u22121 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n\u22121n\u22121 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n\u22121n\u22121 segments.InputThe first line contains one integer tt (1\u2264t\u22641041\u2264t\u2264104)\u00a0\u2014 the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105)\u00a0\u2014 the number of segments in the given set. Then nn lines follow, each contains a description of a segment \u2014 a pair of integers lili, riri (\u2212109\u2264li\u2264ri\u2264109\u2212109\u2264li\u2264ri\u2264109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2\u22c51052\u22c5105.OutputPrint tt integers \u2014 the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n\u22121n\u22121 segments if you erase any of the given nn segments.ExampleInputCopy3\n4\n1 4\n2 3\n3 6\n5 7\n3\n5 5\n5 5\n5 5\n6\n3 3\n1 1\n5 5\n1 5\n2 2\n4 4\nOutputCopy2\n1\n5\n","tags":["brute force","constructive algorithms","data structures","dp","graphs","sortings","trees","two pointers"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nfrom itertools import accumulate\n\n\n\nimport random\n\n\n\nt=int(input())\n\n\n\n\n\nfor testcases in range(t):\n\n n=int(input())\n\n S=[list(map(int,input().split())) for i in range(n)]\n\n\n\n compression_list=[]\n\n\n\n for l,r in S:\n\n compression_list.append(l)\n\n compression_list.append(r)\n\n\n\n compression_dict={a: ind for ind, a in enumerate(sorted(set(compression_list)))}\n\n\n\n for i in range(n):\n\n S[i][0]=compression_dict[S[i][0]]*2\n\n S[i][1]=compression_dict[S[i][1]]*2\n\n\n\n LEN=len(compression_dict)*2\n\n\n\n R=[0]*(LEN+1)\n\n\n\n for l,r in S:\n\n R[l]+=1\n\n R[r+1]-=1\n\n\n\n SR=list(accumulate(R))\n\n\n\n NOW=0\n\n\n\n for i in range(LEN):\n\n if SR[i]!=0 and SR[i+1]==0:\n\n NOW+=1\n\n\n\n ONECOUNT=[0]*(LEN+1)\n\n\n\n for i in range(1,LEN):\n\n if SR[i-1]!=1 and SR[i]==1:\n\n ONECOUNT[i]+=1\n\n\n\n SO=list(accumulate(ONECOUNT))\n\n SO.append(0)\n\n\n\n ANS=1\n\n\n\n for l,r in S:\n\n lr=0\n\n if SR[r]==1:\n\n lr-=1\n\n\n\n ANS=max(ANS,NOW+SO[r-1]-SO[l]+lr)\n\n\n\n\n\n print(ANS)\n\n \n\n \n\n \n\n\n\n \n\n\n\n \n\n\n\n \n\n\n\n \n\n \n\n \n\n \n\n\n\n \n\n","language":"py"} -{"contest_id":"1311","problem_id":"E","statement":"E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The only line of each test case contains two integers nn and dd (2\u2264n,d\u226450002\u2264n,d\u22645000) \u2014 the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (\u2211n\u22645000,\u2211d\u22645000\u2211n\u22645000,\u2211d\u22645000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print \"NO\" (without quotes) in the first line. Otherwise, print \"{YES}\" in the first line. Then print n\u22121n\u22121 integers p2,p3,\u2026,pnp2,p3,\u2026,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3\n5 7\n10 19\n10 18\nOutputCopyYES\n1 2 1 3 \nYES\n1 2 3 3 9 9 2 1 6 \nNO\nNotePictures corresponding to the first and the second test cases of the example:","tags":["brute force","constructive algorithms","trees"],"code":"from sys import stdin, stdout\n\nimport __pypy__\n\n\n\ndef main():\n\n T = int(stdin.readline())\n\n for _ in range(T):\n\n a,b = list(map(int, stdin.readline().split()))\n\n a -= 1\n\n mx = int(a*(a+1)\/2)\n\n mn = 0\n\n tmp = a\n\n pw = 1\n\n while (tmp > 0):\n\n c = int(pw * pow(2, pw))\n\n cc = int(pow(2,pw))\n\n if tmp >= cc:\n\n tmp -= cc\n\n mn += c\n\n else:\n\n mn += pw*tmp\n\n tmp = 0\n\n pw +=1\n\n if b < mn or b > mx:\n\n stdout.write(\"NO\\n\")\n\n continue\n\n else:\n\n stdout.write(\"YES\\n\")\n\n slot = [1] * a\n\n mn = 0\n\n cur = mx\n\n while len(slot) - (mn+1) > 0 and cur > b:\n\n #print(slot)\n\n if pow(2,(mn+1)) == slot[mn]:\n\n mn+=1\n\n if len(slot) - (mn+1) <= 0:\n\n break\n\n cur -= len(slot) - (mn+1)\n\n slot.pop()\n\n if cur < b:\n\n mn += b - cur\n\n slot[mn] += 1\n\n ans = __pypy__.builders.StringBuilder()\n\n cur_num = 2\n\n last_row = [1]\n\n for x in slot:\n\n row = []\n\n count = 0\n\n pos = 0\n\n for z in range(x):\n\n row.append(cur_num)\n\n cur_num += 1\n\n ans.append(\"%d \"%last_row[pos])\n\n count += 1\n\n if count == 2:\n\n count = 0\n\n pos +=1\n\n last_row = row\n\n print(ans.build())\n\n \n\nmain()","language":"py"} -{"contest_id":"1286","problem_id":"C1","statement":"C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the string, and the following line should contain the string ss.ExampleInputCopy4\n\na\naa\na\n\ncb\nb\nc\n\ncOutputCopy? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc","tags":["brute force","constructive algorithms","interactive","math"],"code":"from sys import stdout\n\n\n\n\n\ndef req(l, r, k=0):\n\n print('?', l, r)\n\n v = [''.join(sorted(input())) for i in range((r - l + 1) * (r - l + 2) \/\/ 2)]\n\n stdout.flush()\n\n return v\n\n\n\n\n\ndef compute(v):\n\n bukvi = [[0] * (n + 2) for _ in range(26)]\n\n for el in v:\n\n cur = len(el)\n\n for e in el:\n\n bukvi[ord(e) - ord('a')][cur] += 1\n\n return bukvi\n\n\n\n\n\ndef compute2(bukvi):\n\n bukvis = [[] for _ in range(26)]\n\n for i in range(26):\n\n prev = bukvi[i][1]\n\n for j in range(1, n \/\/ 2 + n % 2 + 1):\n\n while bukvi[i][j] != prev:\n\n bukvis[i].append(j)\n\n prev -= 1\n\n return bukvis\n\n\n\n\n\ndef main():\n\n va = req(1, n)\n\n # va2 = req(1, n \/\/ 2)\n\n # va3 = req(n - n \/\/ 2 + 1, n)\n\n # bukvi = compute(va)\n\n # bukvi2 = compute(va2)\n\n # bukvi3 = compute(va3)\n\n if n == 1:\n\n print('!', va[0][0])\n\n return\n\n va2 = req(2, n)\n\n for i in va2:\n\n va.remove(i)\n\n va.sort(key=len)\n\n print('!', va[0], end='')\n\n for i in range(1, len(va)):\n\n for j in range(26):\n\n if va[i].count(chr(ord('a') + j)) != va[i - 1].count(chr(ord('a') + j)):\n\n print(chr(ord('a') + j), end='')\n\n print()\n\n\n\n\n\nn = int(input())\n\nmain()\n\n","language":"py"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"import sys, random\ninput = lambda : sys.stdin.readline().rstrip()\n\n\nwrite = lambda x: sys.stdout.write(x+\"\\n\"); writef = lambda x: print(\"{:.12f}\".format(x))\ndebug = lambda x: sys.stderr.write(x+\"\\n\")\nYES=\"Yes\"; NO=\"No\"; pans = lambda v: print(YES if v else NO); INF=10**18\nLI = lambda : list(map(int, input().split())); II=lambda : int(input()); SI=lambda : [ord(c)-ord(\"a\") for c in input()]\ndef debug(_l_):\n for s in _l_.split():\n print(f\"{s}={eval(s)}\", end=\" \")\n print()\ndef dlist(*l, fill=0):\n if len(l)==1:\n return [fill]*l[0]\n ll = l[1:]\n return [dlist(*ll, fill=fill) for _ in range(l[0])]\n\nn = int(input())\na = list(map(int, input().split()))\nodd = (n+1)\/\/2\neven = n\/\/2\nnum = 0\nfor v in a:\n if v==0:\n num += 1\n else:\n if v%2:\n odd -= 1\n else:\n even -= 1\ndp = [[INF]*(odd+1) for _ in range(2)]\ndp[0][0] = dp[1][0] = 0\nfor v in a:\n ndp = [[INF]*(odd+1) for _ in range(2)]\n for i in range(odd+1):\n if v==0:\n ndp[0][i] = min(dp[0][i], dp[1][i]+1)\n if i>0:\n ndp[1][i] = min(dp[0][i-1]+1, dp[1][i-1])\n elif v%2==1:\n ndp[0][i] = INF\n ndp[1][i] = min(dp[0][i]+1, dp[1][i])\n else:\n ndp[0][i] = min(dp[0][i], dp[1][i]+1)\n ndp[1][i] = INF\n dp = ndp\n# print(dp)\nans = min(dp[0][odd], dp[1][odd])\nprint(ans)","language":"py"} -{"contest_id":"1299","problem_id":"A","statement":"A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)\u2212yf(x,y)=(x|y)\u2212y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)\u22126=15\u22126=9f(11,6)=(11|6)\u22126=15\u22126=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,\u2026,an][a1,a2,\u2026,an] is defined as f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an)f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4\n4 0 11 6\nOutputCopy11 6 4 0InputCopy1\n13\nOutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.","tags":["brute force","greedy","math"],"code":"import sys\n\nfrom math import sqrt, gcd, factorial, ceil, floor, pi, inf, isqrt, lcm\n\nfrom collections import deque, Counter, OrderedDict, defaultdict\n\nfrom heapq import heapify, heappush, heappop\n\n#from sortedcontainers import SortedList\n\n#sys.setrecursionlimit(10**5)\n\nfrom functools import lru_cache\n\n#@lru_cache(None)\n\n\n\n#======================================================#\n\ninput = lambda: sys.stdin.readline()\n\nI = lambda: int(input().strip())\n\nS = lambda: input().strip()\n\nM = lambda: map(int,input().strip().split())\n\nL = lambda: list(map(int,input().strip().split()))\n\n#======================================================#\n\n\n\ndef bs(arr,x):\n\n low,high = 0,len(arr)-1\n\n ans = len(arr)\n\n while low<=high:\n\n mid = (low+high)\/\/2\n\n #if arr[mid]==x:\n\n # return x\n\n if arr[mid]n:\n\n return 0\n\n return ((nfactorial[n]*finverse[k]%mod)*finverse[n-k])%mod\n\n#======================================================#\n\ndef primelist():\n\n L = [False for i in range((10**10)+1)]\n\n primes = [False for i in range((10**10)+1)]\n\n for i in range(2,(10**10)+1):\n\n if not L[i]:\n\n primes[i]=True\n\n for j in range(i,(10**10)+1,i):\n\n L[j]=True\n\n return primes\n\ndef isPrime(n):\n\n p = primelist()\n\n return p[n]\n\n#======================================================#\n\ndef bst(arr,x):\n\n low,high = 0,len(arr)-1\n\n ans = -1\n\n while low<=high:\n\n mid = (low+high)\/\/2\n\n if arr[mid]==x:\n\n return x\n\n if arr[mid]0:\n\n ans.append(\"1\")\n\n else:\n\n ans.append(\"0\")\n\n b = int(b,2)\n\n return b-(int(\"\".join(ans),2)&b)\n\n \n\n \n\n\n\nn = I()\n\na = L()\n\np = [0 for i in range(32)]\n\nfor i in a:\n\n b = format(i,'b')\n\n for j in range(len(b)):\n\n if b[len(b)-1-j]=='1':\n\n p[31-j]+=1\n\nt = 0\n\nq = f(a[0])\n\nfor i in range(1,n):\n\n if f(a[i])>q:\n\n t = i\n\n q = f(a[i])\n\na[0],a[t] = a[t],a[0]\n\nprint(*a)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n \n\n \n\n \n\n","language":"py"} -{"contest_id":"1324","problem_id":"D","statement":"D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (ibi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"import bisect\n\n\n\n\n\nlength = int(input())\n\nnum1 = list(map(int, input().split()))\n\nnum2 = list(map(int, input().split()))\n\n\n\nfor i in range(length):\n\n num1[i] -= num2[i]\n\n\n\nnum1.sort()\n\ncount = 0\n\n\n\nfor i in range(length):\n\n if num1[i] <= 0:\n\n count += length - bisect.bisect(num1, abs(num1[i]))\n\n else:\n\n count += length - i-1\n\nprint(count)","language":"py"} -{"contest_id":"1307","problem_id":"C","statement":"C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1\u2264|s|\u22641051\u2264|s|\u2264105) \u2014 the text that Bessie intercepted.OutputOutput a single integer \u00a0\u2014 the number of occurrences of the secret message.ExamplesInputCopyaaabb\nOutputCopy6\nInputCopyusaco\nOutputCopy1\nInputCopylol\nOutputCopy2\nNoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.","tags":["brute force","dp","math","strings"],"code":"def update(s,aa,ans):\n\n for r in range(26):\n\n if r!=s:\n\n ans[s][r]+=aa[r]\n\n else:\n\n ans[s][r]+=(aa[r]-1)\n\n return\n\na=input()\n\naa=[0]*26\n\nfans=0\n\nans=[[0]*26 for i in range(26)]\n\nfor i in a:\n\n aa[ord(i)-ord('a')]+=1\n\n update((ord(i)-ord('a')),aa,ans)\n\nfor i in range(26):\n\n for j in range(26):\n\n fans=max(fans,ans[i][j])\n\n fans=max(fans,aa[i])\n\nprint(fans)\n\n ","language":"py"} -{"contest_id":"1299","problem_id":"B","statement":"B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)\u2212\u2192\u2212\u2212(x,y)\u2192. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB\u2212\u2192\u2212=(x,y)\u2212\u2192\u2212\u2212AB\u2192=(x,y)\u2192. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3\u2264n\u22641053\u2264n\u2264105)\u00a0\u2014 the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|\u2264109|xi|,|yi|\u2264109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput \"YES\" in a separate line, if PP and TT are similar. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4\n1 0\n4 1\n3 4\n0 3\nOutputCopyYESInputCopy3\n100 86\n50 0\n150 0\nOutputCopynOInputCopy8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3\nOutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.","tags":["geometry"],"code":"import sys; import math; \nCASE=0; rla=''\n\n\n\ndef solve() : \n n=int(rla)\n if n&1 : \n for i in range(n) : a, b=map(int, input().split())\n print(\"NO\"); return\n else : \n x=[]; y=[]\n for i in range(n>>1) : \n a, b=map(int, input().split())\n x.append(a); y.append(b)\n flag=0\n a, b=map(int, input().split())\n for i in range(1, (n>>1)) : \n c, d=map(int, input().split())\n if c-a!=x[i-1]-x[i] or d-b!=y[i-1]-y[i] : flag=1\n a=c; b=d\n print(\"NO\" if flag==1 else \"YES\")\n\nwhile True : \n rla=sys.stdin.readline()\n cases=1\n if not rla: break\n if (rla=='\\n')|(rla=='') : continue\n if CASE==1 : cases=int(rla)\n for cas in range(cases) : \n \n solve()\n \n\n","language":"py"} -{"contest_id":"1324","problem_id":"D","statement":"D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (ibi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"from bisect import bisect\nfrom operator import sub\ndef get(f): return f(input().strip())\ndef gets(f): return [*map(f, input().split())]\n\n\nn = get(int)\na = gets(int)\nb = gets(int)\nd = sorted(map(sub, a, b))\ns = 0\nfor i, v in enumerate(d):\n s += n - bisect(d, -v, i + 1)\nprint(s)\n","language":"py"} -{"contest_id":"1291","problem_id":"B","statement":"B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,\u2026,ana1,\u2026,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1\u2264k\u2264n1\u2264k\u2264n such that a1ak+1>\u2026>anak>ak+1>\u2026>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1\u2264i\u2264n1\u2264i\u2264n) such that ai>0ai>0 and assign ai:=ai\u22121ai:=ai\u22121.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226415\u00a00001\u2264t\u226415\u00a0000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105).The second line of each test case contains a sequence of nn non-negative integers a1,\u2026,ana1,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109).It is guaranteed that the sum of nn over all test cases does not exceed 3\u22c51053\u22c5105.OutputFor each test case, output a single line containing \"Yes\" (without quotes) if it's possible to make the given array sharpened using the described operations, or \"No\" (without quotes) otherwise.ExampleInputCopy10\n1\n248618\n3\n12 10 8\n6\n100 11 15 9 7 8\n4\n0 1 1 0\n2\n0 0\n2\n0 1\n2\n1 0\n2\n1 1\n3\n0 1 0\n3\n1 0 1\nOutputCopyYes\nYes\nYes\nNo\nNo\nYes\nYes\nYes\nYes\nNo\nNoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.","tags":["greedy","implementation"],"code":"for _ in range(int(input())):\n\n n = int(input())\n\n a = list(map(int, input().split()))\n\n i = n\n\n j = -1\n\n for k in range(n):\n\n if a[k] < k:\n\n break\n\n j = k\n\n for k in range(n-1, -1, -1):\n\n if a[k] < (n-k-1):\n\n break\n\n i = k\n\n if j >= i:\n\n print('YES')\n\n else:\n\n print('NO')","language":"py"} -{"contest_id":"1300","problem_id":"A","statement":"A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,\u2026,ana1,a2,\u2026,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1\u2264i\u2264n1\u2264i\u2264n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ \u2026\u2026 +an\u22600+an\u22600 and a1\u22c5a2\u22c5a1\u22c5a2\u22c5 \u2026\u2026 \u22c5an\u22600\u22c5an\u22600.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641031\u2264t\u2264103). The description of the test cases follows.The first line of each test case contains an integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the size of the array.The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (\u2212100\u2264ai\u2264100\u2212100\u2264ai\u2264100)\u00a0\u2014 elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1\nOutputCopy1\n2\n0\n2\nNoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,\u22121,\u22121][3,\u22121,\u22121], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [\u22121,1,1,1][\u22121,1,1,1], the sum will be equal to 22 and the product will be equal to \u22121\u22121. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,\u22122,1][2,\u22122,1], the sum will be 11 and the product will be \u22124\u22124.","tags":["implementation","math"],"code":"a = int(input())\n\nfor i in range(a):\n\n q = int(input())\n\n *s, = map(int, input().split(' '))\n\n d = 0\n\n for j in range(q):\n\n if s[j] == 0:\n\n d += 1\n\n s[j] = 1\n\n if sum(s) == 0:\n\n d += 1\n\n print(d)\n\n","language":"py"} -{"contest_id":"1324","problem_id":"F","statement":"F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n\u22121n\u22121 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw\u2212cntbcntw\u2212cntb.InputThe first line of the input contains one integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of vertices in the tree.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410\u2264ai\u22641), where aiai is the color of the ii-th vertex.Each of the next n\u22121n\u22121 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1\u2264ui,vi\u2264n,ui\u2260vi(1\u2264ui,vi\u2264n,ui\u2260vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,\u2026,resnres1,res2,\u2026,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9\nOutputCopy2 2 2 2 2 1 1 0 2 \nInputCopy4\n0 0 1 0\n1 2\n1 3\n1 4\nOutputCopy0 -1 1 -1 \nNoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.","tags":["dfs and similar","dp","graphs","trees"],"code":"# ------------------- fast io --------------------\n\nimport os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\n\n\nBUFSIZE = 8192\n\n\n\n\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\n\n\n\nclass IOWrapper(IOBase):\n\n\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\n\n\n\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n# ------------------- fast io --------------------\n\n\n\nfrom collections import defaultdict\n\nfrom types import GeneratorType\n\nimport sys\n\nsys.setrecursionlimit(200001)\n\n\n\ndef bootstrap(f, stack=[]):\n\n def wrappedfunc(*args, **kwargs):\n\n if stack:\n\n return f(*args, **kwargs)\n\n else:\n\n to = f(*args, **kwargs)\n\n while True:\n\n if type(to) is GeneratorType:\n\n stack.append(to)\n\n to = next(to)\n\n else:\n\n stack.pop()\n\n if not stack:\n\n break\n\n to = stack[-1].send(to)\n\n return to\n\n return wrappedfunc\n\n\n\n\n\n\n\ndef main():\n\n @bootstrap\n\n def dfs(u, fa):\n\n par[u] = fa\n\n dp[u] = 1 if a[u-1] == 1 else -1\n\n for v in adj[u]:\n\n if v != fa:\n\n yield dfs(v, u)\n\n if dp[v] > 0:\n\n dp[u] += dp[v]\n\n yield\n\n \n\n @bootstrap\n\n def dfs2(u, fa):\n\n par[u] = fa\n\n for v in adj[u]:\n\n if v != fa:\n\n if res[u] > dp[v]:\n\n if dp[v] < 0:\n\n res[v] = res[u] + dp[v]\n\n else:\n\n res[v] = res[u]\n\n else:\n\n res[v] = dp[v]\n\n yield dfs2(v, u)\n\n yield\n\n \n\n n = int(input())\n\n a = list(map(int, input().split(' ')))\n\n adj = defaultdict(list)\n\n for i in range(n - 1):\n\n u, v = map(int, input().split(' '))\n\n adj[u].append(v)\n\n adj[v].append(u)\n\n dp = [0] * (n + 1)\n\n par = [0] * (n + 1)\n\n res = [0] * (n + 1)\n\n dfs(1, 0)\n\n res[1] = dp[1]\n\n dfs2(1, 0)\n\n print(*res[1:])\n\n \n\nmain()","language":"py"} -{"contest_id":"1316","problem_id":"C","statement":"C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+\u22ef+an\u22121xn\u22121f(x)=a0+a1x+\u22ef+an\u22121xn\u22121 and g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1. Let h(x)=f(x)\u22c5g(x)h(x)=f(x)\u22c5g(x). Suppose that h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1\u2264n,m\u2264106,2\u2264p\u22641091\u2264n,m\u2264106,2\u2264p\u2264109), \u00a0\u2014 nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,\u2026,an\u22121a0,a1,\u2026,an\u22121 (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,\u2026,bm\u22121b0,b1,\u2026,bm\u22121 (1\u2264bi\u22641091\u2264bi\u2264109) \u00a0\u2014 bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0\u2264t\u2264n+m\u221220\u2264t\u2264n+m\u22122) \u00a0\u2014 the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2\n1 1 2\n2 1\nOutputCopy1\nInputCopy2 2 999999937\n2 1\n3 1\nOutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.","tags":["constructive algorithms","math","ternary search"],"code":"import os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\n\n\n_print = print\n\nBUFSIZE = 8192\n\n\n\n\n\ndef dbg(*args, **kwargs):\n\n _print('\\33[95m', end='')\n\n _print(*args, **kwargs)\n\n _print('\\33[0m', end='')\n\n\n\n\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = 'x' in file.mode or 'r' not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b'\\n') + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\n\n\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode('ascii'))\n\n self.read = lambda: self.buffer.read().decode('ascii')\n\n self.readline = lambda: self.buffer.readline().decode('ascii')\n\n\n\n\n\ndef inp():\n\n return sys.stdin.readline().rstrip()\n\n\n\n\n\ndef mpint():\n\n return map(int, inp().split(' '))\n\n\n\n\n\ndef itg():\n\n return int(inp())\n\n\n\n\n\n# ############################## import\n\n# ############################## main\n\ndef solve():\n\n n, m, p = mpint()\n\n f = list(mpint())\n\n g = list(mpint())\n\n for i in range(n):\n\n if f[i] % p != 0:\n\n fi = i\n\n break\n\n else:\n\n return -1 # wrong input (gcd should = 1)\n\n\n\n for j in range(m):\n\n if g[j] % p != 0:\n\n gj = j\n\n break\n\n else:\n\n return -1 # wrong input (gcd should = 1)\n\n\n\n return fi + gj\n\n\n\n\n\ndef main():\n\n print(solve())\n\n\n\n\n\nDEBUG = 0\n\nURL = 'https:\/\/codeforces.com\/contest\/1316\/problem\/C'\n\n\n\nif __name__ == '__main__':\n\n # 0: normal, 1: runner, 2: debug, 3: interactive\n\n if DEBUG == 1:\n\n import requests\n\n from ACgenerator.Y_Test_Case_Runner import TestCaseRunner\n\n\n\n runner = TestCaseRunner(main, URL)\n\n inp = runner.input_stream\n\n print = runner.output_stream\n\n runner.checking()\n\n else:\n\n if DEBUG != 2:\n\n dbg = lambda *args, **kwargs: ...\n\n sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\n if DEBUG == 3:\n\n def print(*args, **kwargs):\n\n _print(*args, **kwargs)\n\n sys.stdout.flush()\n\n main()\n\n# Please check!\n\n","language":"py"} -{"contest_id":"1292","problem_id":"D","statement":"D. Chaotic V.time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output\u00c6sir - CHAOS \u00c6sir - V.\"Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect.The time right now...... 00:01:12......It's time.\"The emotion samples are now sufficient. After almost 3 years; it's time for Ivy to awake her bonded sister, Vanessa.The system inside A.R.C.'s Library core can be considered as an undirected graph with infinite number of processing nodes, numbered with all positive integers (1,2,3,\u20261,2,3,\u2026). The node with a number xx (x>1x>1), is directly connected with a node with number xf(x)xf(x), with f(x)f(x) being the lowest prime divisor of xx.Vanessa's mind is divided into nn fragments. Due to more than 500 years of coma, the fragments have been scattered: the ii-th fragment is now located at the node with a number ki!ki! (a factorial of kiki).To maximize the chance of successful awakening, Ivy decides to place the samples in a node PP, so that the total length of paths from each fragment to PP is smallest possible. If there are multiple fragments located at the same node, the path from that node to PP needs to be counted multiple times.In the world of zeros and ones, such a requirement is very simple for Ivy. Not longer than a second later, she has already figured out such a node.But for a mere human like you, is this still possible?For simplicity, please answer the minimal sum of paths' lengths from every fragment to the emotion samples' assembly node PP.InputThe first line contains an integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 number of fragments of Vanessa's mind.The second line contains nn integers: k1,k2,\u2026,knk1,k2,\u2026,kn (0\u2264ki\u226450000\u2264ki\u22645000), denoting the nodes where fragments of Vanessa's mind are located: the ii-th fragment is at the node with a number ki!ki!.OutputPrint a single integer, denoting the minimal sum of path from every fragment to the node with the emotion samples (a.k.a. node PP).As a reminder, if there are multiple fragments at the same node, the distance from that node to PP needs to be counted multiple times as well.ExamplesInputCopy3\n2 1 4\nOutputCopy5\nInputCopy4\n3 1 4 4\nOutputCopy6\nInputCopy4\n3 1 4 1\nOutputCopy6\nInputCopy5\n3 1 4 1 5\nOutputCopy11\nNoteConsidering the first 2424 nodes of the system; the node network will look as follows (the nodes 1!1!, 2!2!, 3!3!, 4!4! are drawn bold):For the first example, Ivy will place the emotion samples at the node 11. From here: The distance from Vanessa's first fragment to the node 11 is 11. The distance from Vanessa's second fragment to the node 11 is 00. The distance from Vanessa's third fragment to the node 11 is 44. The total length is 55.For the second example, the assembly node will be 66. From here: The distance from Vanessa's first fragment to the node 66 is 00. The distance from Vanessa's second fragment to the node 66 is 22. The distance from Vanessa's third fragment to the node 66 is 22. The distance from Vanessa's fourth fragment to the node 66 is again 22. The total path length is 66.","tags":["dp","graphs","greedy","math","number theory","trees"],"code":"T = 1\n\nfor test_no in range(T):\n\n\tMAXK = 5000\n\n\tn = int(input())\n\n\tcnt = [0] * (MAXK + 1)\n\n\tprimeExponential = [[0 for j in range(MAXK + 1)] for i in range(MAXK + 1)]\n\n\n\n\tline, num = (input() + ' '), 0\n\n\tfor c in line:\n\n\t\tif c != ' ': num = num * 10 + (ord(c) - 48)\n\n\t\telse:\n\n\t\t\tcnt[num] += 1\n\n\t\t\tnum = 0\n\n\n\n\tfor i in range(2, MAXK + 1):\n\n\t\tfor j in range(0, MAXK + 1): primeExponential[i][j] += primeExponential[i-1][j]\n\n\t\ttmp, x = i, 2\n\n\t\twhile x * x <= tmp:\n\n\t\t\twhile tmp % x == 0:\n\n\t\t\t\tprimeExponential[i][x] += 1\n\n\t\t\t\ttmp \/\/= x\n\n\t\t\tx += 1\n\n\t\tif tmp > 1: primeExponential[i][tmp] += 1\n\n\n\n\tbestPD = [1] * (MAXK + 1)\n\n\tans, cur = 0, 0\n\n\n\n\tfor i in range(1, MAXK + 1):\n\n\t\tif cnt[i] == 0: continue\n\n\t\tfor j in range(1, MAXK + 1):\n\n\t\t\tans += primeExponential[i][j] * cnt[i]\n\n\t\t\tcur += primeExponential[i][j] * cnt[i]\n\n\t\t\tif primeExponential[i][j]: bestPD[i] = j\n\n\n\n\tfrequency = [0] * (MAXK + 1)\n\n\twhile max(bestPD) > 1:\n\n\t\tfor i in range(MAXK + 1): frequency[i] = 0\n\n\t\tfor i in range(MAXK + 1): frequency[bestPD[i]] += cnt[i]\n\n\n\n\t\tbestGroup = max(frequency)\n\n\t\tbestPrime = frequency.index(bestGroup)\n\n\t\tif bestGroup * 2 <= n: break\n\n\t\tif bestPrime == 1: break\n\n\t\tcur -= bestGroup\n\n\t\tcur += (n - bestGroup); ans = min(ans, cur)\n\n\n\n\t\tfor i in range(MAXK + 1):\n\n\t\t\tif bestPD[i] != bestPrime: bestPD[i] = 1\n\n\t\t\tif bestPD[i] == 1: continue\n\n\t\t\tprimeExponential[i][bestPD[i]] -= 1\n\n\t\t\twhile bestPD[i] > 1 and primeExponential[i][bestPD[i]] == 0: bestPD[i] -= 1\n\n\n\n\tprint(ans)","language":"py"} -{"contest_id":"1141","problem_id":"G","statement":"G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n\u22121n\u22121 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right \u2014 the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2\u2264n\u2264200000,0\u2264k\u2264n\u221212\u2264n\u2264200000,0\u2264k\u2264n\u22121) \u2014 the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n\u22121n\u22121 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1\u2264r\u2264n\u221211\u2264r\u2264n\u22121). In the second line print n\u22121n\u22121 numbers c1,c2,\u2026,cn\u22121c1,c2,\u2026,cn\u22121 (1\u2264ci\u2264r1\u2264ci\u2264r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2\n1 4\n4 3\n3 5\n3 6\n5 2\nOutputCopy2\n1 2 1 1 2 InputCopy4 2\n3 1\n1 4\n1 2\nOutputCopy1\n1 1 1 InputCopy10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9\nOutputCopy3\n1 1 2 3 2 3 1 3 1 ","tags":["binary search","constructive algorithms","dfs and similar","graphs","greedy","trees"],"code":"import os\n\nfrom io import BytesIO\n\ninput = BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\nfrom collections import defaultdict\n\nfrom itertools import islice\n\n\n\ndef solve():\n\n n, k = map(int, input().split())\n\n G = [list() for _ in range(n)]\n\n E = []\n\n ans = defaultdict(lambda: 1)\n\n\n\n for _ in range(n-1):\n\n u, v = map(int, input().split())\n\n u, v = u-1, v-1\n\n G[u].append(v)\n\n G[v].append(u)\n\n E.append((u, v))\n\n\n\n V = list(range(n))\n\n V.sort(key=lambda v: -len(G[v]))\n\n\n\n r = len(G[V[k]])\n\n\n\n visited = [False] * n\n\n stack = []\n\n for u in islice(V, k, None):\n\n if not visited[u]:\n\n stack.append((u, 0))\n\n while stack:\n\n u, skip = stack.pop()\n\n visited[u] = True\n\n e = 0\n\n for v in G[u]:\n\n if not visited[v]:\n\n e += 1\n\n if e == skip:\n\n e += 1\n\n ans[(u, v)] = e\n\n if len(G[v]) <= r:\n\n stack.append((v, e))\n\n\n\n print(r)\n\n out = []\n\n for u, v in E:\n\n if (u, v) not in ans:\n\n u, v = v, u\n\n out.append(str(ans[(u, v)]))\n\n print(' '.join(out))\n\n\n\n\n\nsolve()","language":"py"} -{"contest_id":"1315","problem_id":"C","statement":"C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,\u2026,bnb1,b2,\u2026,bn. Find the lexicographically minimal permutation a1,a2,\u2026,a2na1,a2,\u2026,a2n such that bi=min(a2i\u22121,a2i)bi=min(a2i\u22121,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641001\u2264t\u2264100).The first line of each test case consists of one integer nn\u00a0\u2014 the number of elements in the sequence bb (1\u2264n\u22641001\u2264n\u2264100).The second line of each test case consists of nn different integers b1,\u2026,bnb1,\u2026,bn\u00a0\u2014 elements of the sequence bb (1\u2264bi\u22642n1\u2264bi\u22642n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number \u22121\u22121.Otherwise, print 2n2n integers a1,\u2026,a2na1,\u2026,a2n\u00a0\u2014 required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5\n1\n1\n2\n4 1\n3\n4 1 3\n4\n2 3 4 5\n5\n1 5 7 2 8\nOutputCopy1 2 \n-1\n4 5 1 2 3 6 \n-1\n1 3 5 6 7 9 2 4 8 10 \n","tags":["greedy"],"code":"import sys, math\n\nimport heapq\n\n\n\nfrom collections import deque\n\nfrom bisect import bisect_left, bisect_right\n\n\n\ninput = sys.stdin.readline\n\n\n\npop = heapq.heappop\n\npush = heapq.heappush\n\n\n\n\n\n# input\n\ndef ip(): return int(input())\n\ndef sp(): return str(input().rstrip())\n\n\n\n\n\ndef mip(): return map(int, input().split())\n\ndef msp(): return map(str, input().split())\n\n\n\n\n\ndef lmip(): return list(map(int, input().split()))\n\ndef lmsp(): return list(map(str, input().split()))\n\n\n\n\n\n# gcd, lcm\n\ndef gcd(x, y):\n\n while y:\n\n x, y = y, x % y\n\n return x\n\n\n\n\n\ndef lcm(x, y):\n\n return x * y \/\/ gcd(x, y)\n\n\n\n\n\n# prime\n\ndef isPrime(x):\n\n if x <= 1: return False\n\n for i in range(2, int(x ** 0.5) + 1):\n\n if x % i == 0:\n\n return False\n\n return True\n\n\n\n\n\ndef getPow(a, x):\n\n ret = 1\n\n while x:\n\n if x & 1:\n\n ret = (ret * a) % mod\n\n a = (a * a) % mod\n\n x >>= 1\n\n return ret\n\n\n\n\n\n############ Main! #############\n\n\n\nfor tc in range(ip()):\n\n n = ip()\n\n b = lmip()\n\n a = [0 for _ in range(n * 2)]\n\n c = [False for _ in range(n * 2 + 1)]\n\n for i in range(n):\n\n a[i * 2] = b[i]\n\n c[b[i]] = True\n\n fl = True\n\n for i in range(1, n * 2, 2):\n\n found = False\n\n for j in range(a[i - 1], n * 2 + 1):\n\n if not c[j]:\n\n a[i] = j\n\n c[j] = True\n\n found = True\n\n break\n\n if not found:\n\n fl = False\n\n break\n\n\n\n if fl:\n\n print(*a)\n\n else:\n\n print(-1)\n\n\n\n######## Praise greedev ########","language":"py"} -{"contest_id":"1305","problem_id":"E","statement":"E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the \"Proof by AC\" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,\u2026,ana1,a2,\u2026,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1\u2264a1 M:\n\n lastpop = A.pop()\n\n count -= (lastpop - 1) \/\/ 2\n\n if count >= M:\n\n if len(B) == 0:\n\n B.append(10**9)\n\n else:\n\n B.append(B[-1] - 2 ** 16)\n\n else:\n\n gap = M - count\n\n B.append(2 * (lastpop - gap) - 1)\n\n count += gap\n\n\n\nA += B[::-1]\n\nprint(' '.join(map(str, A)))","language":"py"} -{"contest_id":"1291","problem_id":"A","statement":"A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive\/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n\u22121n\u22121.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 \u2192\u2192 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u226430001\u2264n\u22643000) \u00a0\u2014 the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print \"-1\" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4\n4\n1227\n1\n0\n6\n177013\n24\n222373204424185217171912\nOutputCopy1227\n-1\n17703\n2237344218521717191\nNoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 \u2192\u2192 22237320442418521717191 (delete the last digit).","tags":["greedy","math","strings"],"code":"import os,sys\n\nfrom random import randint, shuffle\n\nfrom io import BytesIO, IOBase\n\n\n\nfrom collections import defaultdict,deque,Counter\n\nfrom bisect import bisect_left,bisect_right\n\nfrom heapq import heappush,heappop\n\nfrom functools import lru_cache\n\nfrom itertools import accumulate, permutations\n\nimport math\n\n\n\n# Fast IO Region\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\n# for _ in range(int(input())):\n\n# n = int(input())\n\n# a = list(map(int, input().split()))\n\n\n\nfor _ in range(int(input())):\n\n n = int(input())\n\n s = input()\n\n ans = ''\n\n for i in range(n):\n\n if int(s[i]) % 2:\n\n ans += s[i]\n\n if len(ans) == 2:\n\n break\n\n if len(ans) == 2:\n\n print(ans)\n\n else:\n\n print(-1)\n\n\n\n\n\n\n\n \n\n\n\n","language":"py"} -{"contest_id":"1325","problem_id":"C","statement":"C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n\u22122n\u22122 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2\u2264n\u22641052\u2264n\u2264105)\u00a0\u2014 the number of nodes in the tree.Each of the next n\u22121n\u22121 lines contains two space-separated integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n\u22121n\u22121 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3\n1 2\n1 3\nOutputCopy0\n1\nInputCopy6\n1 2\n1 3\n2 4\n2 5\n5 6\nOutputCopy0\n3\n2\n4\n1NoteThe tree from the second sample:","tags":["constructive algorithms","dfs and similar","greedy","trees"],"code":"n=int(input())\n\nw=[]\n\nfor j in range(n-1):\n\n w.append([int(k) for k in input().split()])\n\nq={}\n\nfor j in w:\n\n if j[0] in q:\n\n q[j[0]].append(j[1])\n\n else:\n\n q[j[0]]=[j[1]]\n\n if j[1] in q:\n\n q[j[1]].append(j[0])\n\n else:\n\n q[j[1]]=[j[0]]\n\n#print(q)\n\nif n==2:\n\n print(0)\n\nelse:\n\n eta={}\n\n zeta=0\n\n for j in q.keys():\n\n if len(q[j])==1:\n\n eta[(j, q[j][0])]=zeta\n\n zeta+=1\n\n for j in w:\n\n if ((j[0], j[1]) in eta):\n\n print(eta[(j[0], j[1])])\n\n elif ((j[1], j[0]) in eta):\n\n print(eta[(j[1], j[0])])\n\n else:\n\n print(zeta)\n\n zeta+=1","language":"py"} -{"contest_id":"1288","problem_id":"A","statement":"A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in \u2308dx+1\u2309\u2308dx+1\u2309 days (\u2308a\u2309\u2308a\u2309 is the ceiling function: \u23082.4\u2309=3\u23082.4\u2309=3, \u23082\u2309=2\u23082\u2309=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+\u2308dx+1\u2309x+\u2308dx+1\u2309.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1\u2264T\u2264501\u2264T\u226450) \u2014 the number of test cases.The next TT lines contain test cases \u2013 one per line. Each line contains two integers nn and dd (1\u2264n\u22641091\u2264n\u2264109, 1\u2264d\u22641091\u2264d\u2264109) \u2014 the number of days before the deadline and the number of days the program runs.OutputPrint TT answers \u2014 one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3\n1 1\n4 5\n5 11\nOutputCopyYES\nYES\nNO\nNoteIn the first test case; Adilbek decides not to optimize the program at all; since d\u2264nd\u2264n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run \u230852\u2309=3\u230852\u2309=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work \u2308112+1\u2309=4\u2308112+1\u2309=4 days.","tags":["binary search","brute force","math","ternary search"],"code":"T = int(input())\n\ndef Deadline(n,d):\n\n if ((n\/\/2+1)*(n\/\/2-n)+d <=0):\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")\n\nfor x in range (T):\n\n n,d = map(int,input().split())\n\n Deadline(n,d)","language":"py"} -{"contest_id":"1296","problem_id":"A","statement":"A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1\u2264i,j\u2264n1\u2264i,j\u2264n such that i\u2260ji\u2260j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226420001\u2264t\u22642000) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u226420001\u2264n\u22642000) \u2014 the number of elements in aa. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226420001\u2264ai\u22642000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (\u2211n\u22642000\u2211n\u22642000).OutputFor each test case, print the answer on it \u2014 \"YES\" (without quotes) if it is possible to obtain the array with an odd sum of elements, and \"NO\" otherwise.ExampleInputCopy5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1\nOutputCopyYES\nNO\nYES\nNO\nNO\n","tags":["math"],"code":"for i in range(int(input())):\n\n n=int(input())\n\n l=list(map(int,input().split()))\n\n sm=sum(l)\n\n even=0\n\n odd=0\n\n for j in l:\n\n if j%2==1:\n\n odd+=1\n\n else:\n\n even+=1\n\n if sm%2!=0 or (sm%2 == 0 and odd>0 and even>0):\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")","language":"py"} -{"contest_id":"1315","problem_id":"A","statement":"A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a\u00d7ba\u00d7b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0\u2264x2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers\u00a0\u2014 the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6\n8 8 0 0\n1 10 0 3\n17 31 10 4\n2 1 0 0\n5 10 3 9\n10 10 4 8\nOutputCopy56\n6\n442\n1\n45\n80\nNoteIn the first test case; the screen resolution is 8\u00d788\u00d78, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window. ","tags":["implementation"],"code":"from sys import stdin\n\ninput = stdin.readline\n\n#google = lambda : print(\"Case #%d: \"%(T + 1) , end = '')\n\ninp = lambda : list(map(int,input().split()))\n\n\n\ndef answer():\n\n\n\n quad1 = x * b\n\n quad2 = (a - x - 1) * b\n\n quad3 = y * a\n\n quad4 = (b - y - 1) * a\n\n\n\n ans = max(quad1 , quad2 , quad3 , quad4)\n\n return ans\n\n \n\n \n\nfor T in range(int(input())):\n\n\n\n a , b , x , y = inp()\n\n\n\n\n\n print(answer())\n\n \n\n","language":"py"} -{"contest_id":"1299","problem_id":"A","statement":"A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)\u2212yf(x,y)=(x|y)\u2212y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)\u22126=15\u22126=9f(11,6)=(11|6)\u22126=15\u22126=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,\u2026,an][a1,a2,\u2026,an] is defined as f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an)f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4\n4 0 11 6\nOutputCopy11 6 4 0InputCopy1\n13\nOutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.","tags":["brute force","greedy","math"],"code":"n = int(input())\n\na = list(map(int, input().split()))\n\nr = 0\n\n\n\nfor i in range(29, -1, -1):\n\n c = 0\n\n for j in a:\n\n if (j >> i) & 1:\n\n c += 1\n\n r = j\n\n if c == 1:\n\n break\n\n\n\na.remove(r)\n\n\n\nprint(r, ' '.join(map(str, a)))\n\n\n\nnum_inp=lambda: int(input())\n\narr_inp=lambda: list(map(int,input().split()))\n\nsp_inp=lambda: map(int,input().split())\n\nstr_inp=lambda:input()\n\n","language":"py"} -{"contest_id":"1141","problem_id":"E","statement":"E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,\u2026,dnd1,d2,\u2026,dn (\u2212106\u2264di\u2264106\u2212106\u2264di\u2264106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1\u2264H\u226410121\u2264H\u22641012, 1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105). The second line contains the sequence of integers d1,d2,\u2026,dnd1,d2,\u2026,dn (\u2212106\u2264di\u2264106\u2212106\u2264di\u2264106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6\n-100 -200 -300 125 77 -4\nOutputCopy9\nInputCopy1000000000000 5\n-1 0 0 0 0\nOutputCopy4999999999996\nInputCopy10 4\n-3 -6 5 4\nOutputCopy-1\n","tags":["math"],"code":"[h,n]=list(map(int,input().split()))\n\narr=list(map(int,input().split()))\n\nsumm=[arr[0]]\n\nfor i in arr[1:]:\n\n summ.append(i+summ[-1])\n\nmini=min(summ)\n\nk=sum(arr)\n\nif mini+h>0 and k>=0:\n\n print(-1)\n\nelif mini+h<=0:\n\n ans=0\n\n i=0\n\n while(h>0):\n\n h+=arr[i%n]\n\n i+=1\n\n ans+=1\n\n print(ans)\n\nelse:\n\n k=-1*k\n\n # print(mini,k)\n\n ans=((h+mini+k-1)\/\/k)*n\n\n h-=((ans)\/\/n)*k\n\n i=0\n\n # print(ans,h)\n\n while(h>0):\n\n h+=arr[i%n]\n\n i+=1\n\n ans+=1\n\n print(ans)","language":"py"} -{"contest_id":"1307","problem_id":"D","statement":"D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105, n\u22121\u2264m\u22642\u22c5105n\u22121\u2264m\u22642\u22c5105, 2\u2264k\u2264n2\u2264k\u2264n) \u00a0\u2014 the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n) \u00a0\u2014 the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3\n1 3 5\n1 2\n2 3\n3 4\n3 5\n2 4\nOutputCopy3\nInputCopy5 4 2\n2 4\n1 2\n2 3\n3 4\n4 5\nOutputCopy3\nNoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33. ","tags":["binary search","data structures","dfs and similar","graphs","greedy","shortest paths","sortings"],"code":"import sys\n\nimport collections\n\ninput = sys.stdin.readline\n\n\n\nints = lambda: list(map(int, input().split()))\n\n \n\nn, m, k = ints()\n\nspecial = ints()\n\ngraph = [[] for _ in range(n + 1)]\n\nfor _ in range(m):\n\n x, y = ints()\n\n graph[x].append(y)\n\n graph[y].append(x)\n\n\n\nd1 = [-1 for _ in range(n + 1)]\n\nq = collections.deque([1])\n\ndepth = 1\n\nd1[1] = 0\n\nwhile q:\n\n for _ in range(len(q)):\n\n node = q.popleft()\n\n \n\n for nb in graph[node]:\n\n if d1[nb] == -1:\n\n q.append(nb)\n\n d1[nb] = depth\n\n depth += 1\n\n\n\nd2 = [-1 for _ in range(n + 1)]\n\nq = collections.deque([n])\n\ndepth = 1\n\nd2[n] = 0\n\nwhile q:\n\n for _ in range(len(q)):\n\n node = q.popleft()\n\n \n\n for nb in graph[node]:\n\n if d2[nb] == -1:\n\n q.append(nb)\n\n d2[nb] = depth\n\n depth += 1\n\n\n\nans = d2[1]\n\ns_distances = [(d1[i], d2[i]) for i in special]\n\ns_distances.sort(key=lambda x: x[1], reverse=True)\n\nmx = 0\n\nfor i in range(len(s_distances) - 1):\n\n l = s_distances[i + 1][1] + 1 + s_distances[i][0]\n\n mx = max(mx, l)\n\nprint(min(ans, mx))\n\n ","language":"py"} -{"contest_id":"1311","problem_id":"A","statement":"A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a\u2212ya\u2212y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1\u2264a,b\u22641091\u2264a,b\u2264109).OutputFor each test case, print the answer \u2014 the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5\n2 3\n10 10\n2 4\n7 4\n9 3\nOutputCopy1\n0\n2\n2\n1\nNoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.","tags":["greedy","implementation","math"],"code":"for i in range(int(input())):\n\n a,b = map(int, input().split())\n\n if a>b:\n\n diff = a - b\n\n if diff%2 == 0:\n\n print(1)\n\n else:\n\n print(2)\n\n elif aaiai= num:\n\n stack_left.pop()\n\n ans_left[i] = (i + 1) * num if len(stack_left) == 1 else (i - stack_left[-1][0]) * num + ans_left[stack_left[-1][0]]\n\n stack_left.append([i, num])\n\n\n\nans_right = [0] * n\n\nstack_right = [[n, 0]]\n\nfor i in range(n-1, -1, -1):\n\n num = nums[i]\n\n while stack_right[-1][1] >= num:\n\n stack_right.pop()\n\n ans_right[i] = (n - i) * num if len(stack_right) == 1 else (stack_right[-1][0] - i) * num + ans_right[stack_right[-1][0]]\n\n stack_right.append([i, num])\n\n\n\nres, idx = 0, 0\n\nfor i in range(n):\n\n if ans_left[i] + ans_right[i] - nums[i] > res:\n\n res = ans_left[i] + ans_right[i] - nums[i]\n\n idx = i\n\n\n\nfinal = [0] * n\n\nfinal[idx] = nums[idx]\n\n\n\ntmp = nums[idx]\n\nfor j in range(idx-1, -1, -1):\n\n tmp = min(tmp, nums[j])\n\n final[j] = tmp\n\n\n\ntmp = nums[idx]\n\nfor j in range(idx+1, n):\n\n tmp = min(tmp, nums[j])\n\n final[j] = tmp\n\n\n\nprint(*final)","language":"py"} -{"contest_id":"1325","problem_id":"A","statement":"A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1\u2264t\u2264100)(1\u2264t\u2264100) \u00a0\u2014 the number of testcases.Each testcase consists of one line containing a single integer, xx (2\u2264x\u2264109)(2\u2264x\u2264109).OutputFor each testcase, output a pair of positive integers aa and bb (1\u2264a,b\u2264109)1\u2264a,b\u2264109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2\n2\n14\nOutputCopy1 1\n6 4\nNoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.","tags":["constructive algorithms","greedy","number theory"],"code":"import sys\n\ninput = sys.stdin.readline\n\noutput = sys.stdout.write\n\n\n\n\n\ndef main():\n\n tests = int(input().rstrip())\n\n for i in range(tests):\n\n num = int(input().rstrip())\n\n output(str(num - 1) + ' ' + '1')\n\n output('\\n')\n\n\n\n\n\nif __name__ == '__main__':\n\n main()\n\n\n\n","language":"py"} -{"contest_id":"1287","problem_id":"B","statement":"B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game \"Set\" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature \u2014 color, number, shape, and shading \u2014 the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called \"Hyperset\". In her game, there are nn cards with kk features, each feature has three possible values: \"S\", \"E\", or \"T\". The original \"Set\" game can be viewed as \"Hyperset\" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1\u2264n\u226415001\u2264n\u22641500, 1\u2264k\u2264301\u2264k\u226430)\u00a0\u2014 number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters \"S\", \"E\", \"T\". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer\u00a0\u2014 the number of ways to choose three cards that form a set.ExamplesInputCopy3 3\nSET\nETS\nTSE\nOutputCopy1InputCopy3 4\nSETE\nETSE\nTSES\nOutputCopy0InputCopy5 4\nSETT\nTEST\nEEET\nESTE\nSTES\nOutputCopy2NoteIn the third example test; these two triples of cards are sets: \"SETT\"; \"TEST\"; \"EEET\" \"TEST\"; \"ESTE\", \"STES\" ","tags":["brute force","data structures","implementation"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nn, m = map(int, input().split())\n\ng = [input()[:-1] for _ in range(n)]\n\n\n\nd = set(g)\n\nc = 0\n\nq = ord('S') + ord('E') + ord('T')\n\nfor i in range(n-1):\n\n for j in range(i+1, n):\n\n x = ''\n\n for k in range(m):\n\n if g[i][k] == g[j][k]:\n\n x += g[i][k]\n\n else:\n\n x += chr(q - ord(g[i][k]) - ord(g[j][k]))\n\n if x in d:\n\n c += 1\n\n\n\nprint(c\/\/3)\n\n","language":"py"} -{"contest_id":"1301","problem_id":"A","statement":"A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1\u2264i\u2264n1\u2264i\u2264n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci\u2194aici\u2194ai or ci\u2194bici\u2194bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is \"code\", bb is \"true\", and cc is \"help\", you can make cc equal to \"crue\" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes \"hodp\" and bb becomes \"tele\".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print \"YES\" (without quotes), otherwise print \"NO\" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4\naaa\nbbb\nccc\nabc\nbca\nbca\naabb\nbbaa\nbaba\nimi\nmii\niim\nOutputCopyNO\nYES\nYES\nNO\nNoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes \"bca\", bb becomes \"bca\" and cc becomes \"abc\". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes \"baba\", string bb becomes \"baba\" and string cc becomes \"abab\". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.","tags":["implementation","strings"],"code":"t = int(input())\n\nfor i in range(t):\n\n s1 = input()\n\n s2 = input()\n\n s3 = input()\n\n ans =\"YES\"\n\n for i in range(len(s2)):\n\n if s3[i] != s2[i] and s3[i] != s1[i]:\n\n ans = \"NO\"\n\n\n\n print(ans)","language":"py"} -{"contest_id":"1299","problem_id":"B","statement":"B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)\u2212\u2192\u2212\u2212(x,y)\u2192. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB\u2212\u2192\u2212=(x,y)\u2212\u2192\u2212\u2212AB\u2192=(x,y)\u2192. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3\u2264n\u22641053\u2264n\u2264105)\u00a0\u2014 the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|\u2264109|xi|,|yi|\u2264109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput \"YES\" in a separate line, if PP and TT are similar. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4\n1 0\n4 1\n3 4\n0 3\nOutputCopyYESInputCopy3\n100 86\n50 0\n150 0\nOutputCopynOInputCopy8\n0 0\n1 0\n2 1\n3 3\n4 6\n3 6\n2 5\n1 3\nOutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.","tags":["geometry"],"code":"import math\n\nimport queue\n\n\n\n\n\n# -------- info --------\n\n\n\n# https:\/\/codeforces.com\/profile\/Wolxy\n\n\n\n# -------- solve --------\n\n\n\ndef solve() -> None:\n\n n = int(input())\n\n if n % 2 != 0:\n\n print('NO')\n\n return\n\n\n\n ls = []\n\n for _ in range(n):\n\n ls.append(tuple(map(int, input().split(' '))))\n\n ox, oy = (ls[0][0] + ls[n \/\/ 2][0]) \/ 2, (ls[0][1] + ls[n \/\/ 2][1]) \/ 2\n\n for i in range(n \/\/ 2):\n\n if ((ls[i][0] + ls[n \/\/ 2 + i][0]) \/ 2, (ls[i][1] + ls[n \/\/ 2 + i][1]) \/ 2) != (ox, oy):\n\n print('NO')\n\n return\n\n print('YES')\n\n\n\n\n\n# -------- main --------\n\n\n\n\n\nT = 1\n\n# T = int(input())\n\nfor _ in range(T):\n\n solve()\n\n","language":"py"} -{"contest_id":"1294","problem_id":"E","statement":"E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n\u00d7mn\u00d7m consisting of integers from 11 to 2\u22c51052\u22c5105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n\u22c5mn\u22c5m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1\u2264j\u2264m1\u2264j\u2264m) and set a1,j:=a2,j,a2,j:=a3,j,\u2026,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,\u2026,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5ma1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5m (i.e. ai,j=(i\u22121)\u22c5m+jai,j=(i\u22121)\u22c5m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1\u2264n,m\u22642\u22c5105,n\u22c5m\u22642\u22c51051\u2264n,m\u22642\u22c5105,n\u22c5m\u22642\u22c5105) \u2014 the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1\u2264ai,j\u22642\u22c51051\u2264ai,j\u22642\u22c5105).OutputPrint one integer \u2014 the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5ma1,1=1,a1,2=2,\u2026,a1,m=m,a2,1=m+1,a2,2=m+2,\u2026,an,m=n\u22c5m (ai,j=(i\u22121)m+jai,j=(i\u22121)m+j).ExamplesInputCopy3 3\n3 2 1\n1 2 3\n4 5 6\nOutputCopy6\nInputCopy4 3\n1 2 3\n4 5 6\n7 8 9\n10 11 12\nOutputCopy0\nInputCopy3 4\n1 6 3 4\n5 10 7 8\n9 2 11 12\nOutputCopy2\nNoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.","tags":["greedy","implementation","math"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nn, m = map(int, input().split())\n\na = [list(map(int, input().split())) for _ in range(n)]\n\nans = 0\n\nfor i in range(m):\n\n cnt = [n + j for j in range(n)]\n\n j = (i + 1) % m\n\n for k in range(n):\n\n if (a[k][i] % m) ^ j or not 1 <= a[k][i] <= n * m:\n\n continue\n\n x = i + k * m + 1\n\n cnt[((x - a[k][i]) % (n * m)) \/\/ m] -= 1\n\n ans += min(cnt)\n\nprint(ans)","language":"py"} -{"contest_id":"1284","problem_id":"C","statement":"C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n. This indicates the subsegment where l\u22121l\u22121 elements from the beginning and n\u2212rn\u2212r elements from the end are deleted from the sequence.For a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212lmax{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1\u2264n\u22642500001\u2264n\u2264250000, 108\u2264m\u2264109108\u2264m\u2264109, mm is prime).OutputPrint rr (0\u2264r0:\n print(i)\n break\n \t\t\t \t\t\t\t\t\t\t\t\t\t\t \t \t\t \t\t\t","language":"py"} -{"contest_id":"1312","problem_id":"A","statement":"A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m 0:\n a, b = s[i], s[i - 1]\n G[a].add(b)\n G[b].add(a)\n if len(G[a]) > 2 or len(G[b]) > 2:\n return\n\n oneEdges = []\n for k, v in G.items():\n if len(v) <= 1:\n oneEdges.append(k)\n if len(s) > 2 and len(oneEdges) < 2:\n return\n\n output = []\n visited = set([oneEdges[0]])\n queue = deque([oneEdges[0]])\n while queue:\n for _ in range(len(queue)):\n letter = queue.popleft()\n output.append(letter)\n for neigh in G[letter]:\n if neigh not in visited:\n visited.add(neigh)\n queue.append(neigh)\n\n for i in range(97, 123):\n if chr(i) not in visited:\n output.append(chr(i))\n return ''.join(output)\n\n\ndef main():\n t = int(input())\n for _ in range(t):\n s = input()\n output = perfect(s)\n if output:\n print(\"YES\")\n print(output)\n else:\n print(\"NO\")\n\n\nmain()\n","language":"py"} -{"contest_id":"1141","problem_id":"C","statement":"C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,\u2026,pnp1,p2,\u2026,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,\u2026,pnp1,p2,\u2026,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 of length n\u22121n\u22121, where qi=pi+1\u2212piqi=pi+1\u2212pi.Given nn and q=q1,q2,\u2026,qn\u22121q=q1,q2,\u2026,qn\u22121, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the length of the permutation to restore. The second line contains n\u22121n\u22121 integers q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 (\u2212n O(2 * N + M)\n- bfs => O(N + M)\n- calculating max and min => O(K)\n- total => O(2*N + M) + O(N + M) + O(K < N) => O(N + M)\n\nSpace Complexity:\n- inputs => O(1 + 2 * N)\n- dfs => O(maximum depth + N)\n- calculating => O(2)\n- total => O(1 + 2*N) + O(max depth + N) + O(2) => O(N + maxDepth)\n\nWhy the chosen algorithm is good:\n- The runtime is O(N+M) and those have maximum of 2*10^5 each\n- 4 * 10^5 < 10^7 * 2 thus it would finish in time\n\"\"\"\n\nfrom collections import deque\nfrom sys import stdin\n\ndef main():\n input = stdin.readline\n N,M = [int(i) for i in input().split()]\n graph = {i+1:set() for i in range(N)}\n rgraph = {i+1:set() for i in range(N)}\n for _ in range(M):\n u,v = [int(i) for i in input().split()]\n graph[u].add(v)\n rgraph[v].add(u)\n\n k = int(input())\n P = [int(i) for i in input().split()]\n parents = {}\n dist = [float(\"inf\")] * (N+1)\n dist[P[-1]] = 0\n que = deque([P[-1]])\n while que:\n current = que.popleft()\n for next in rgraph[current]:\n if next in parents:\n if dist[current] + 1 == dist[next]:\n parents[next].add(current)\n else:\n dist[next] = dist[current] + 1\n parents[next] = {current}\n que.append(next)\n\n mm = [0,0]\n for i in range(k-1):\n if P[i+1] in parents[P[i]]:\n if len(parents[P[i]]) > 1:\n mm[1] += 1\n else:\n mm[0] += 1\n mm[1] += 1\n print(mm[0],mm[1])\n\n\nif __name__ == '__main__':\n main()\n\t\t \t \t\t\t\t\t\t\t\t\t \t \t\t \t \t","language":"py"} -{"contest_id":"1293","problem_id":"A","statement":"A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin \"ConneR\" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1\u2264t\u226410001\u2264t\u22641000)\u00a0\u2014 the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2\u2264n\u22641092\u2264n\u2264109, 1\u2264s\u2264n1\u2264s\u2264n, 1\u2264k\u2264min(n\u22121,1000)1\u2264k\u2264min(n\u22121,1000))\u00a0\u2014 respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n)\u00a0\u2014 the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer\u00a0\u2014 the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77\nOutputCopy2\n0\n4\n0\n2\nNoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.","tags":["binary search","brute force","implementation"],"code":"import sys\n\nfrom math import sqrt, gcd, factorial, ceil, floor, pi, inf\n\nfrom collections import deque, Counter, OrderedDict\n\nfrom heapq import heapify, heappush, heappop\n\n#sys.setrecursionlimit(10**6)\n\n\n\n#======================================================#\n\ninput = lambda: sys.stdin.readline()\n\nI = lambda: int(input().strip())\n\nS = lambda: input().strip()\n\nM = lambda: map(int,input().strip().split())\n\nL = lambda: list(map(int,input().strip().split()))\n\n#======================================================#\n\n\n\n#======================================================#\n\ndef primelist():\n\n L = [False for i in range(10**9)]\n\n primes = [False for i in range(10**9)]\n\n for i in range(2,10**9):\n\n if not L[i]:\n\n primes[i]=True\n\n for j in range(i,10**9,i):\n\n L[j]=True\n\n return primes\n\ndef isPrime(n):\n\n p = primelist()\n\n return p[n]\n\n#======================================================#\n\ndef bst(arr,x):\n\n low,high = 0,len(arr)-1\n\n ans = -1\n\n while low<=high:\n\n mid = (low+high)\/\/2\n\n if arr[mid]==x:\n\n return mid\n\n elif arr[mid]>i)&1:\n\n if C[i] > 0:\n\n C[i] -= 1\n\n else:\n\n while i < 60 and C[i] == 0:\n\n i += 1\n\n res += 1\n\n C[i] -= 1\n\n continue\n\n C[i+1] += C[i]\/\/2\n\n i += 1\n\n print(res)\n\n","language":"py"} -{"contest_id":"1299","problem_id":"C","statement":"C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), and redistribute water in tanks l,l+1,\u2026,rl,l+1,\u2026,r evenly. In other words, replace each of al,al+1,\u2026,aral,al+1,\u2026,ar by al+al+1+\u22ef+arr\u2212l+1al+al+1+\u22ef+arr\u2212l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 the number of water tanks.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641061\u2264ai\u2264106)\u00a0\u2014 initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10\u2212910\u22129.Formally, let your answer be a1,a2,\u2026,ana1,a2,\u2026,an, and the jury's answer be b1,b2,\u2026,bnb1,b2,\u2026,bn. Your answer is accepted if and only if |ai\u2212bi|max(1,|bi|)\u226410\u22129|ai\u2212bi|max(1,|bi|)\u226410\u22129 for each ii.ExamplesInputCopy4\n7 5 5 7\nOutputCopy5.666666667\n5.666666667\n5.666666667\n7.000000000\nInputCopy5\n7 8 8 10 12\nOutputCopy7.000000000\n8.000000000\n8.000000000\n10.000000000\n12.000000000\nInputCopy10\n3 9 5 5 1 7 5 3 8 7\nOutputCopy3.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n7.500000000\n7.500000000\nNoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.","tags":["data structures","geometry","greedy"],"code":"import sys\ninput = sys.stdin.buffer.readline\n\nn = int(input())\na = list(map(int, input().split()))\n\nstk = []\nfor x in a:\n s = 1.0 * x\n c = 1\n while stk and stk[-1][0] * c >= s * stk[-1][1]:\n s += stk[-1][0]\n c += stk[-1][1]\n stk.pop()\n stk.append((s, c))\n\nsys.stdout.write(''.join('{}\\n'.format(s \/ c) * c for s, c in stk))\n","language":"py"} -{"contest_id":"1305","problem_id":"B","statement":"B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1\u2264|s|\u226410001\u2264|s|\u22641000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk \u00a0\u2014 the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm \u00a0\u2014 the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1\u2264a11:\n\n\t\t\treturn 0\n\n\t\tif temp==1:\n\n\t\t\tbasek.append(i)\n\n\t\tn=n\/\/k\n\n\t\ti+=1\n\n\treturn basek\n\n\t\n\nt=int(input())\n\ndef lyans():\n\n\n\n\ttemp=input()\n\n\ttemp=inp(temp)\n\n\tk=temp[1]\n\n\ta=input()\n\n\ta=inp(a)\n\n\tlistk=[]\n\n \n\n\tfor i in a:\n\n\t\tif i==0:\n\n\t\t\tcontinue\n\n\t\tm=iskpow(i,k)\n\n\t\tif isinstance(m,list) :\n\n\t\t\tlistk+=m\n\n\t\telse:\n\n\t\t\tprint(\"NO\")\n\n\t\t\treturn 0\n\n\tif len(set(listk))==len(listk):\n\n\t\tprint(\"YES\")\n\n\telse:\n\n\t\tprint(\"NO\")\t \t \n\n \t\n\nfor ti in range(t):\n\n\tlyans()","language":"py"} -{"contest_id":"1296","problem_id":"C","statement":"C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x\u22121,y)(x\u22121,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y\u22121)(x,y\u22121). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of \"LURLLR\" are \"LU\", \"LR\", \"LURLLR\", \"URL\", but not \"RR\" and \"UL\".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' \u2014 the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211n\u22642\u22c5105\u2211n\u22642\u22c5105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n \u2014 endpoints of the substring you remove. The value r\u2212l+1r\u2212l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4\n4\nLRUD\n4\nLURD\n5\nRRUDU\n5\nLLDDR\nOutputCopy1 2\n1 4\n3 4\n-1\n","tags":["data structures","implementation"],"code":"t = int(input())\n\n\n\nfor _ in range(t):\n\n n = int(input())\n\n s = input()\n\n\n\n prefix = {(0, 0):-1}\n\n cur = [0, 0]\n\n max_len = float('inf')\n\n answer = [-1, -1]\n\n for idx, char in enumerate(s):\n\n if char == \"U\":\n\n cur[1] += 1\n\n elif char == \"L\":\n\n cur[0] -= 1\n\n elif char == \"R\":\n\n cur[0] += 1\n\n else:\n\n cur[1] -= 1\n\n \n\n key = tuple(cur)\n\n if key in prefix and idx - prefix[key]+1 < max_len:\n\n max_len = idx - prefix[key] + 1\n\n answer = [prefix[key]+1, idx]\n\n \n\n prefix[key] = idx\n\n \n\n if answer == [-1, -1]:\n\n print(-1)\n\n else:\n\n # print(max_len, answer)\n\n print(answer[0] + 1, answer[1] + 1)\n\n\n\n\n\n\n\n","language":"py"} -{"contest_id":"1313","problem_id":"C1","statement":"C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n\u22641000n\u22641000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiai= 0:\n\n b[l] = min(m[l], b[l+1])\n\n x += b[l]\n\n l -= 1\n\n while r < n:\n\n b[r] = min(m[r], b[r-1])\n\n x += b[r]\n\n r += 1\n\n if x > ans:\n\n ans = x\n\n a = b\n\n for i in range(n): print(a[i], end=' ')\n\n \n\n\n\nmain()","language":"py"} -{"contest_id":"1311","problem_id":"F","statement":"F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t\u22c5vixi+t\u22c5vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value \u22111\u2264i>=1\n\n while(i>0):\n\n st[i]=st[i<<1]+st[i<<1|1]\n\n i>>=1\n\n\n\ndef qr(l,r=N):\n\n l+=N\n\n r+=N\n\n add=0\n\n while(l>=1\n\n r>>=1\n\n return add\n\n\n\n\n\n\n\nfor j in range(m):\n\n x = a[j]\n\n i = pos[x]\n\n ans2[x] = max(ans2[x], n - qr(i + 1))\n\n up(i, 0)\n\n pos[x] = m - 1 - j\n\n up(pos[x], 1)\n\n\n\nfor i in range(n):\n\n x = pos[i]\n\n ans2[i] = max(ans2[i], n - qr(x + 1))\n\nfor i in range(n):\n\n print(ans1[i], ans2[i])","language":"py"} -{"contest_id":"1286","problem_id":"B","statement":"B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici\u00a0\u2014 the number of vertices jj in the subtree of vertex ii, such that aj=self._len-_list_lens[-1]:\n\n return len(_list_lens)-1,k+_list_lens[-1]-self._len\n\n if self._rebuild:\n\n self._fen_build()\n\n\n\n _fen_tree = self._fen_tree\n\n idx = -1\n\n for d in reversed(range(len(_fen_tree).bit_length())):\n\n right_idx = idx+(1<=_fen_tree[right_idx]:\n\n idx = right_idx\n\n k -= _fen_tree[idx]\n\n return idx+1,k\n\n\n\n def _delete(self,pos,idx):\n\n \"\"\"Delete value at the given `(pos, idx)`.\"\"\"\n\n _lists = self._lists\n\n _mins = self._mins\n\n _list_lens = self._list_lens\n\n\n\n self._len -= 1\n\n self._fen_update(pos,-1)\n\n del _lists[pos][idx]\n\n _list_lens[pos] -= 1\n\n\n\n if _list_lens[pos]:\n\n _mins[pos] = _lists[pos][0]\n\n else:\n\n del _lists[pos]\n\n del _list_lens[pos]\n\n del _mins[pos]\n\n self._rebuild = True\n\n\n\n def _loc_left(self,value):\n\n \"\"\"Return an index pair that corresponds to the first position of `value` in the sorted list.\"\"\"\n\n if not self._len:\n\n return 0,0\n\n\n\n _lists = self._lists\n\n _mins = self._mins\n\n\n\n lo,pos = -1,len(_lists)-1\n\n while lo+1>1\n\n if value<=_mins[mi]:\n\n pos = mi\n\n else:\n\n lo = mi\n\n\n\n if pos and value<=_lists[pos-1][-1]:\n\n pos -= 1\n\n\n\n _list = _lists[pos]\n\n lo,idx = -1,len(_list)\n\n while lo+1>1\n\n if value<=_list[mi]:\n\n idx = mi\n\n else:\n\n lo = mi\n\n\n\n return pos,idx\n\n\n\n def _loc_right(self,value):\n\n \"\"\"Return an index pair that corresponds to the last position of `value` in the sorted list.\"\"\"\n\n if not self._len:\n\n return 0,0\n\n\n\n _lists = self._lists\n\n _mins = self._mins\n\n\n\n pos,hi = 0,len(_lists)\n\n while pos+1>1\n\n if value<_mins[mi]:\n\n hi = mi\n\n else:\n\n pos = mi\n\n\n\n _list = _lists[pos]\n\n lo,idx = -1,len(_list)\n\n while lo+1>1\n\n if value<_list[mi]:\n\n idx = mi\n\n else:\n\n lo = mi\n\n\n\n return pos,idx\n\n\n\n def add(self,value):\n\n \"\"\"Add `value` to sorted list.\"\"\"\n\n _load = self._load\n\n _lists = self._lists\n\n _mins = self._mins\n\n _list_lens = self._list_lens\n\n\n\n self._len += 1\n\n if _lists:\n\n pos,idx = self._loc_right(value)\n\n self._fen_update(pos,1)\n\n _list = _lists[pos]\n\n _list.insert(idx,value)\n\n _list_lens[pos] += 1\n\n _mins[pos] = _list[0]\n\n if _load+_load= len(nums):\n\n print('NO')\n\n return\n\n val[st[-1]-1] = nums[ans[st[-1]]]\n\n nums.discard(nums[ans[st[-1]]])\n\n lst[st[-1]-1] = cou\n\n cou += 1\n\n while len(st):\n\n if not len(path[st[-1]]):\n\n y,z = 0,st[-1]-1\n\n for j in range(n):\n\n if lst[j] > lst[z] and val[j] < val[z]:\n\n y += 1\n\n if y != ans[z+1]:\n\n print('NO')\n\n return\n\n st.pop()\n\n continue\n\n st.append(path[st[-1]].pop())\n\n if ans[st[-1]] >= len(nums):\n\n print('NO')\n\n return\n\n val[st[-1]-1] = nums[ans[st[-1]]]\n\n nums.discard(nums[ans[st[-1]]])\n\n lst[st[-1]-1] = cou\n\n cou += 1\n\n if val.count(-1):\n\n print('NO')\n\n else:\n\n print('YES')\n\n print(*val)\n\n\n\ndef main():\n\n n = int(input())\n\n path = [[] for _ in range(n+1)]\n\n ans = [0]*(n+1)\n\n for i in range(1,n+1):\n\n p,c = map(int,input().split())\n\n if p:\n\n path[p].append(i)\n\n else:\n\n root = i\n\n ans[i] = c\n\n dfs(root,path,ans,n)\n\n\n\n#Fast IO Region\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\nif __name__ == '__main__':\n\n main()","language":"py"} -{"contest_id":"1322","problem_id":"A","statement":"A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting \"+\" and \"1\" you can get a well-formed mathematical expression from it. For example; sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not.The teacher gave Dmitry's class a very strange task\u00a0\u2014 she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word \"correct\" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for \"))((\" he can choose the substring \")(\" and do reorder \")()(\" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 the length of Dima's sequence.The second line contains string of length nn, consisting of characters \"(\" and \")\" only.OutputPrint a single integer\u00a0\u2014 the minimum number of nanoseconds to make the sequence correct or \"-1\" if it is impossible to do so.ExamplesInputCopy8\n))((())(\nOutputCopy6\nInputCopy3\n(()\nOutputCopy-1\nNoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with \"()()\"; the whole sequence will be \"()()())(\". And then reorder the segment from the seventh to eighth character; replacing it with \"()\". In the end the sequence will be \"()()()()\"; while the total time spent is 4+2=64+2=6 nanoseconds.","tags":["greedy"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nn = int(input())\n\ns = input()[:-1]\n\n\n\nc = 0\n\nd, e = 0, -1\n\nans = 0\n\nfor i in range(n):\n\n if s[i] == '(':\n\n c += 1\n\n else:\n\n c -= 1\n\n if d == 0 and c < 0:\n\n d = 1\n\n e = i\n\n elif d == 1 and c >= 0:\n\n d = 0\n\n ans += i - e + 1\n\n e = -1\n\nif e != -1:\n\n ans += n-e\n\nif c == 0:\n\n print(ans)\n\nelse:\n\n print(-1)","language":"py"} -{"contest_id":"1294","problem_id":"F","statement":"F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3\u2264n\u22642\u22c51053\u2264n\u22642\u22c5105) \u2014 the number of vertices in the tree. Next n\u22121n\u22121 lines describe the edges of the tree in form ai,biai,bi (1\u2264ai1\u2264ai, bi\u2264nbi\u2264n, ai\u2260biai\u2260bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres \u2014 the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1\u2264a,b,c\u2264n1\u2264a,b,c\u2264n and a\u2260,b\u2260c,a\u2260ca\u2260,b\u2260c,a\u2260c.If there are several answers, you can print any.ExampleInputCopy8\n1 2\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8\nOutputCopy5\n1 8 6\nNoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.","tags":["dfs and similar","dp","greedy","trees"],"code":"from sys import stdin\n\ninput = stdin.readline\n\n\n\ninp = lambda : list(map(int,input().split()))\n\n\n\nfrom collections import deque\n\n\"\"\"\n\n\n\nit is obv that two vertices are the end points of the tree diameter\n\nwe can try all third vertices\n\n\n\n\"\"\"\n\n\n\ndef dfs(p , want_update):\n\n\n\n s = [[p , -1 , 0]]\n\n best = -1\n\n while(len(s)):\n\n\n\n p , prev , lvl = s.pop()\n\n if(want_update):\n\n parent[p] = prev\n\n level[p] = lvl\n\n\n\n if(best < lvl):\n\n best = lvl\n\n node = p\n\n\n\n for i in child[p]:\n\n if(i == prev):continue\n\n if(done[i]):continue\n\n\n\n s.append([i , p , lvl + 1])\n\n\n\n return [node , best]\n\n\n\ndef chain(u , v):\n\n\n\n if(level[u] > level[v]):\n\n v , u = u , v\n\n\n\n d = level[v] - level[u]\n\n for i in range(d):\n\n done[v] = True\n\n v = parent[v]\n\n\n\n while(u != v):\n\n done[u] = True\n\n done[v] = True\n\n u = parent[u]\n\n v = parent[v]\n\n\n\n done[u] = True\n\n \n\n\n\nfor T in range(1):\n\n\n\n n = int(input())\n\n\n\n child = [[] for i in range(n + 1)]\n\n for i in range(n - 1):\n\n u , v = inp()\n\n child[u].append(v)\n\n child[v].append(u)\n\n\n\n\n\n done = [False for i in range(n + 1)]\n\n parent = [-1 for i in range(n + 1)]\n\n level = [0 for i in range(n + 1)]\n\n a , dist = dfs(1 , True)\n\n b , dist = dfs(a , False)\n\n\n\n chain(a , b)\n\n\n\n best = -1\n\n for i in range(1 , n + 1):\n\n if(not done[i]):continue\n\n\n\n node , d = dfs(i , False)\n\n if(node == i):continue\n\n\n\n total = dist + d\n\n if(best < total):\n\n best = total\n\n c = node\n\n\n\n if(best == -1):\n\n best = dist\n\n for i in range(1 , n + 1):\n\n if(i != a and i != b):\n\n c = i\n\n break\n\n\n\n print(best)\n\n print(a , b , c)\n\n \n\n","language":"py"} -{"contest_id":"1141","problem_id":"C","statement":"C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,\u2026,pnp1,p2,\u2026,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,\u2026,pnp1,p2,\u2026,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 of length n\u22121n\u22121, where qi=pi+1\u2212piqi=pi+1\u2212pi.Given nn and q=q1,q2,\u2026,qn\u22121q=q1,q2,\u2026,qn\u22121, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the length of the permutation to restore. The second line contains n\u22121n\u22121 integers q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 (\u2212n> 31) & (b - a)\n\n a += diff\n\n b -= diff\n\n return self.path[self.rmq.query(a, b)]\n\n \n\ninp = [int(x) for x in sys.stdin.read().split()]; ii = 0\n\n \n\nn = inp[ii]; ii += 1\n\ncoupl = [[] for _ in range(n)]\n\nfor _ in range(n - 1):\n\n u = inp[ii] - 1; ii += 1\n\n v = inp[ii] - 1; ii += 1\n\n coupl[u].append(v)\n\n coupl[v].append(u)\n\n \n\nroot = 0\n\nlca = LCA(root, coupl)\n\ndepth = [-1]*n\n\ndepth[root] = 0\n\nbfs = [root]\n\nfor node in bfs:\n\n for nei in coupl[node]: \n\n if depth[nei] == -1:\n\n depth[nei] = depth[node] + 1\n\n bfs.append(nei)\n\n \n\ndef dist(a,b):\n\n for _ in range(0): pass\n\n c = lca(a,b)\n\n return depth[a] + depth[b] - 2 * depth[c]\n\n \n\nq = inp[ii]; ii += 1\n\nout = []\n\nfor _ in range(q):\n\n x = inp[ii] - 1; ii += 1\n\n y = inp[ii] - 1; ii += 1\n\n a = inp[ii] - 1; ii += 1\n\n b = inp[ii] - 1; ii += 1\n\n k = inp[ii]; ii += 1\n\n \n\n dists = [dist(a,b), dist(a,x) + dist(y,b) + 1, dist(a,y) + dist(x,b) + 1]\n\n #dist(a,b) + dist(b,x) # this line makes everything 2 s faster for no reason\n\n for d in dists:\n\n if d - k & 1 == 0 and d <= k:\n\n out.append('YES')\n\n break\n\n else:\n\n out.append('NO')\n\nprint('\\n'.join(out))","language":"py"} -{"contest_id":"1294","problem_id":"C","statement":"C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2\u2264a,b,c2\u2264a,b,c and a\u22c5b\u22c5c=na\u22c5b\u22c5c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2\u2264n\u22641092\u2264n\u2264109).OutputFor each test case, print the answer on it. Print \"NO\" if it is impossible to represent nn as a\u22c5b\u22c5ca\u22c5b\u22c5c for some distinct integers a,b,ca,b,c such that 2\u2264a,b,c2\u2264a,b,c.Otherwise, print \"YES\" and any possible such representation.ExampleInputCopy5\n64\n32\n97\n2\n12345\nOutputCopyYES\n2 4 8 \nNO\nNO\nNO\nYES\n3 5 823 \n","tags":["greedy","math","number theory"],"code":"#bisect.bisect_left(a, x, lo=0, hi=len(a)) is the analog of std::lower_bound()\n\n#bisect.bisect_right(a, x, lo=0, hi=len(a)) is the analog of std::upper_bound()\n\n#from heapq import heappop,heappush,heapify #heappop(hq), heapify(list)\n\n#from collections import deque as dq #deque e.g. myqueue=dq(list)\n\n#append\/appendleft\/appendright\/pop\/popleft\n\n#from bisect import bisect as bis #a=[1,3,4,6,7,8] #bis(a,5)-->3\n\n#import bisect #bisect.bisect_left(a,4)-->2 #bisect.bisect(a,4)-->3\n\n#import statistics as stat # stat.median(a), mode, mean\n\n#from itertools import permutations(p,r)#combinations(p,r)\n\n#combinations(p,r) gives r-length tuples #combinations_with_replacement\n\n#every element can be repeated\n\n \n\nimport sys, threading, os, io \n\nimport math\n\nimport time\n\nfrom os import path\n\nfrom collections import defaultdict, Counter, deque\n\nfrom bisect import *\n\nfrom string import ascii_lowercase\n\nfrom functools import cmp_to_key\n\nimport heapq\n\nfrom bisect import bisect_left as lower_bound\n\nfrom bisect import bisect_right as upper_bound\n\nfrom io import BytesIO, IOBase\t\t\t\t\t\t\t\t\n\n# # # # # # # # # # # # # # # #\n\n# JAI SHREE RAM #\n\n# # # # # # # # # # # # # # # #\n\n \n\n \n\ndef lcm(a, b):\n\n return (a*b)\/\/(math.gcd(a,b))\n\n \n\n \n\ninput = lambda: sys.stdin.readline().rstrip(\n\n)\n\ndef lmii():\n\n return list(map(int,input().split()))\n\n\n\ndef ii():\n\n return int(input())\n\n\n\ndef si():\n\n return str(input())\n\ndef lmsi():\n\n return list(map(str,input().split()))\n\ndef mii():\n\n return map(int,input().split())\n\n\n\ndef msi():\n\n return map(str,input().split())\n\n\n\ni2c = lambda n: chr(ord('a') + n)\n\nc2i = lambda c: ord(c) - ord('a')\n\n \n\n \n\n# if(os.path.exists(\"\/Users\/nitishkumar\/Documents\/Template_Codes\/Python\/CP\/Codeforces\/input.txt\")):\n\n# sys.stdin = open(\"\/Users\/nitishkumar\/Documents\/Template_Codes\/Python\/CP\/Codeforces\/input.txt\", 'r')\n\n# sys.stdout = open(\"\/Users\/nitishkumar\/Documents\/Template_Codes\/Python\/CP\/Codeforces\/output.txt\", 'w') \n\n# else:\n\n# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n \n\n## ayush chabra's solution, better and shorter than mine\n\nimport math \n\ndef solve(t):\n\n\n\n n=ii()\n\n\n\n ans=[]\n\n\n\n for ele in range(2,int(math.sqrt(n))+1):\n\n if len(ans)==2:\n\n break\n\n if n%ele==0:\n\n n=n\/\/ele\n\n ans.append(ele)\n\n \n\n ans.append(n)\n\n\n\n if len(ans)==3 and len(set(ans))==3:\n\n print(\"Yes\")\n\n print(*ans)\n\n else:\n\n print(\"No\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\ndef main():\n\n t = 1\n\n if path.exists(\"\/Users\/nitishkumar\/Documents\/Template_Codes\/Python\/CP\/Codeforces\/input.txt\"):\n\n sys.stdin = open(\"\/Users\/nitishkumar\/Documents\/Template_Codes\/Python\/CP\/Codeforces\/input.txt\", 'r')\n\n sys.stdout = open(\"\/Users\/nitishkumar\/Documents\/Template_Codes\/Python\/CP\/Codeforces\/output.txt\", 'w')\n\n start_time = time.time()\n\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n \n\n \n\n sys.setrecursionlimit(10**5)\n\n \n\n t = int(input())\n\n \n\n for i in range(t):\n\n solve(i+1)\n\n \n\n \n\nif __name__ == '__main__':\n\n main()\n\n \n\n \n\n\n\n\n\n","language":"py"} -{"contest_id":"1294","problem_id":"B","statement":"B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1\u2264j\u2264n1\u2264j\u2264n that for all ii from 11 to j\u22121j\u22121 si=tisi=ti and sjl[j+1][1]:\n print(\"NO\")\n break\n else:\n s=\"R\"*l[0][0]+\"U\"*l[0][1]\n for j in range(1,n):\n s+=\"R\"*(l[j][0]-l[j-1][0])+\"U\"*(l[j][1]-l[j-1][1])\n print(\"YES\")\n print(s)\n \t \t\t\t \t \t \t \t\t\t","language":"py"} -{"contest_id":"1285","problem_id":"C","statement":"C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1\u2264X\u226410121\u2264X\u22641012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2\nOutputCopy1 2\nInputCopy6\nOutputCopy2 3\nInputCopy4\nOutputCopy1 4\nInputCopy1\nOutputCopy1 1\n","tags":["brute force","math","number theory"],"code":"from collections import Counter\n\nimport math\n\n\n\nn = int(input())\n\n\n\nnum = Counter()\n\nans = 0\n\n\n\nfor i in range(1, int(n ** 0.5) + 1):\n\n if n % i == 0:\n\n num[i] = n \/\/ i\n\n\n\nre = num.most_common()\n\nre.reverse()\n\n\n\nfor i in re:\n\n if math.gcd(i[0], i[1]) == 1:\n\n print(*i)\n\n break\n\n","language":"py"} -{"contest_id":"1313","problem_id":"C2","statement":"C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n\u2264500000n\u2264500000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiai= a[i]):\n\n q.pop()\n\n \n\n if(not len(q)):\n\n l[i] = (i+1)*a[i]\n\n else:\n\n l[i] = (i-q[-1])*a[i] + l[q[-1]]\n\n q.append(i)\n\n return l\n\n\n\nn = int(input())\n\na = list(map(int,input().split()))\n\n\n\nl = f()\n\n\n\na.reverse()\n\n\n\nr = f()\n\n\n\na.reverse()\n\nr.reverse()\n\n\n\nmx = max([_ for _ in range(0,n)], key=lambda i: l[i]+r[i]-a[i])\n\nfor i in range(mx-1,-1,-1):\n\n a[i] = min(a[i],a[i+1])\n\nfor i in range(mx+1,n,1):\n\n a[i] = min(a[i],a[i-1])\n\nprint(*a)","language":"py"} -{"contest_id":"1287","problem_id":"A","statement":"A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters \"A\" and \"P\": \"A\" corresponds to an angry student \"P\" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt\u00a0\u2014 the number of groups of students (1\u2264t\u22641001\u2264t\u2264100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1\u2264ki\u22641001\u2264ki\u2264100)\u00a0\u2014 the number of students in the group, followed by a string sisi, consisting of kiki letters \"A\" and \"P\", which describes the ii-th group of students.OutputFor every group output single integer\u00a0\u2014 the last moment a student becomes angry.ExamplesInputCopy1\n4\nPPAP\nOutputCopy1\nInputCopy3\n12\nAPPAPPPAPPPP\n3\nAAP\n3\nPPA\nOutputCopy4\n1\n0\nNoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute\u00a0\u2014 AAPAAPPAAPPP after 22 minutes\u00a0\u2014 AAAAAAPAAAPP after 33 minutes\u00a0\u2014 AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.","tags":["greedy","implementation"],"code":"for _ in range(int(input())):\n\n\tinput()\n\n\ts = input().lstrip('P')\n\n\tprint(max(map(len, s.split('A'))))","language":"py"} -{"contest_id":"1324","problem_id":"E","statement":"E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai\u22121ai\u22121 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r= l and total <= r) + dp[i - 1][0]\n\n for j in range(1,i + 1):\n\n dp[i][j] = max(dp[i - 1][j],dp[i - 1][j - 1]) + int((total - j)%h >= l and (total - j)%h <= r)\n\nprint(max(dp[-1]))","language":"py"} -{"contest_id":"1141","problem_id":"D","statement":"D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1\u2264n\u22641500001\u2264n\u2264150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk \u2014 the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1\u2264aj,bj\u2264n1\u2264aj,bj\u2264n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10\ncodeforces\ndodivthree\nOutputCopy5\n7 8\n4 9\n2 2\n9 10\n3 1\nInputCopy7\nabaca?b\nzabbbcc\nOutputCopy5\n6 5\n2 3\n4 6\n7 4\n1 2\nInputCopy9\nbambarbia\nhellocode\nOutputCopy0\nInputCopy10\ncode??????\n??????test\nOutputCopy10\n6 2\n1 6\n7 3\n3 5\n4 8\n9 7\n5 1\n2 4\n10 9\n8 10\n","tags":["greedy","implementation"],"code":"import sys, collections, math, bisect, heapq, random, functools\n\ninput = sys.stdin.readline\n\nout = sys.stdout.flush\n\n\n\ndef solve():\n\n n = int(input())\n\n left = input().rstrip('\\n')\n\n right = input().rstrip('\\n')\n\n c1,c2 = collections.defaultdict(list),collections.defaultdict(list)\n\n c1i,c2i = [],[]\n\n for i in range(n):\n\n c11 = left[i]\n\n c22 = right[i]\n\n if c11 == '?':\n\n c1i.append(i + 1)\n\n else:\n\n c1[c11].append(i + 1)\n\n if c22 == '?':\n\n c2i.append(i + 1)\n\n else:\n\n c2[c22].append(i + 1)\n\n ans = []\n\n for c in c1:\n\n while c1[c] and c2[c]:\n\n l,r = c1[c].pop(-1),c2[c].pop(-1)\n\n ans.append([l,r])\n\n if c1[c]:\n\n while c1[c] and c2i:\n\n l,r = c1[c].pop(-1), c2i.pop(-1)\n\n ans.append([l, r])\n\n for c in c2:\n\n while c1[c] and c2[c]:\n\n l,r = c1[c].pop(-1),c2[c].pop(-1)\n\n ans.append([l,r])\n\n if c2[c]:\n\n while c2[c] and c1i:\n\n r,l = c2[c].pop(-1), c1i.pop(-1)\n\n ans.append([l, r])\n\n posa,posb = [],[]\n\n for c in c1:\n\n posa.extend(c1[c])\n\n for c in c2:\n\n posb.extend(c2[c])\n\n\n\n while c1i:\n\n if not posb and not c2i:\n\n break\n\n while c1i and posb:\n\n l,r = c1i.pop(-1),posb.pop(-1)\n\n ans.append([l,r])\n\n while c1i and c2i:\n\n l,r = c1i.pop(-1),c2i.pop(-1)\n\n ans.append([l,r])\n\n while c2i:\n\n if not posa and not c1i:\n\n break\n\n while c2i and posa:\n\n r,l = c2i.pop(-1),posa.pop(-1)\n\n ans.append([l,r])\n\n while c1i and c2i:\n\n l,r = c1i.pop(-1),c2i.pop(-1)\n\n ans.append([l,r])\n\n\n\n\n\n print(len(ans))\n\n\n\n for l,r in ans:\n\n print(l,r)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n\n solve()","language":"py"} -{"contest_id":"1294","problem_id":"F","statement":"F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3\u2264n\u22642\u22c51053\u2264n\u22642\u22c5105) \u2014 the number of vertices in the tree. Next n\u22121n\u22121 lines describe the edges of the tree in form ai,biai,bi (1\u2264ai1\u2264ai, bi\u2264nbi\u2264n, ai\u2260biai\u2260bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres \u2014 the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1\u2264a,b,c\u2264n1\u2264a,b,c\u2264n and a\u2260,b\u2260c,a\u2260ca\u2260,b\u2260c,a\u2260c.If there are several answers, you can print any.ExampleInputCopy8\n1 2\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8\nOutputCopy5\n1 8 6\nNoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.","tags":["dfs and similar","dp","greedy","trees"],"code":"import sys, collections, math, bisect, heapq\n\ninput = sys.stdin.readline\n\n\n\n\n\nn = int(input())\n\nedges = collections.defaultdict(list)\n\nfor i in range(n - 1):\n\n u,v = map(int,input().split())\n\n edges[u].append(v)\n\n edges[v].append(u)\n\n\n\n# \u627e\u5230\u6811\u7684\u76f4\u5f84\n\ndef bfs1():\n\n queue = collections.deque()\n\n node1,dis1,node2,dis2 = 0,-1,0,-1\n\n queue.append([1,0])\n\n vis = {1}\n\n while queue:\n\n cur,d = queue.popleft()\n\n if dis1 < d:\n\n dis1 = d\n\n node1 = cur\n\n for next_ in edges[cur]:\n\n if next_ not in vis:\n\n vis.add(next_)\n\n queue.append([next_,d + 1])\n\n\n\n vis.clear()\n\n queue.append([node1,0])\n\n vis.add(node1)\n\n while queue:\n\n cur,d = queue.popleft()\n\n if dis2 < d:\n\n dis2 = d\n\n node2 = cur\n\n for next_ in edges[cur]:\n\n if next_ not in vis:\n\n vis.add(next_)\n\n queue.append([next_,d + 1])\n\n return node1,node2,dis2\n\n\n\nnode1,node2,diameter = bfs1()\n\n\n\n# bfs\u627e\u5230\u8ddd\u79bb\u6700\u8fdc\u7684\u70b9\n\ndef bfs2(u):\n\n queue = collections.deque()\n\n dis = [-1] * n\n\n dis[u - 1] = 0\n\n queue.append([u,0])\n\n while queue:\n\n cur,d = queue.popleft()\n\n for next_ in edges[cur]:\n\n if dis[next_ - 1] == -1:\n\n dis[next_ - 1] = d + 1\n\n queue.append([next_,d + 1])\n\n return dis\n\n\n\nc1,c2 = bfs2(node1),bfs2(node2)\n\n\n\n# \u679a\u4e3e\u4e2d\u95f4\u70b9\n\nnode3 = -1\n\ndis = 0\n\nfor i in range(n):\n\n if i + 1 == node1 or i + 1 == node2:\n\n continue\n\n temp = c1[i] + c2[i]\n\n if temp > dis:\n\n dis = temp\n\n node3 = i + 1\n\nprint((diameter + dis) \/\/ 2)\n\nprint(node1,node2,node3)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"py"} -{"contest_id":"1294","problem_id":"A","statement":"A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1\u2264a,b,c,n\u22641081\u2264a,b,c,n\u2264108) \u2014 the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print \"YES\" if Polycarp can distribute all nn coins between his sisters and \"NO\" otherwise.ExampleInputCopy5\n5 3 2 8\n100 101 102 105\n3 2 1 100000000\n10 20 15 14\n101 101 101 3\nOutputCopyYES\nYES\nNO\nNO\nYES\n","tags":["math"],"code":"for _ in range(int(input())):\n\n a,b,c,n=map(int,input().split())\n\n mx=max(a,b)\n\n mx=max(mx,c)\n\n n-=(3*mx)-(a+b+c)\n\n if n<0:\n\n print('NO')\n\n continue\n\n elif n%3==0:\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")","language":"py"} -{"contest_id":"1324","problem_id":"E","statement":"E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai\u22121ai\u22121 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r tmp_dp[idx]:\n\n tmp_dp[idx] = tmp\n\n\n\n idx = (j+nums[i]-1)%h\n\n tmp = v+1 if l <= idx <= r else v\n\n if tmp > tmp_dp[idx]:\n\n tmp_dp[idx] = tmp\n\n \n\n dp = tmp_dp\n\n \n\n print(max(dp))\n\n\n\n\n\nsolve()","language":"py"} -{"contest_id":"1307","problem_id":"C","statement":"C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1\u2264|s|\u22641051\u2264|s|\u2264105) \u2014 the text that Bessie intercepted.OutputOutput a single integer \u00a0\u2014 the number of occurrences of the secret message.ExamplesInputCopyaaabb\nOutputCopy6\nInputCopyusaco\nOutputCopy1\nInputCopylol\nOutputCopy2\nNoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.","tags":["brute force","dp","math","strings"],"code":"# watchu lookin at?\n\n\n\nimport sys\n\nfrom math import *\n\n# from itertools import *\n\n# from heapq import heapify, heappop, heappush\n\n# from bisect import bisect, bisect_left, bisect_right\n\nfrom collections import deque, Counter, defaultdict as dd\n\nmod = 10**9+7\n\nabc = \"abcdefghijklmnopqrstuvwxyz\"\n\n# Sangeeta Singh\n\n\n\n\n\ndef input(): return sys.stdin.readline().rstrip(\"\\r\\n\")\n\ndef ri(): return int(input())\n\ndef rl(): return list(map(int, input().split()))\n\ndef rls(): return list(map(str, input().split()))\n\ndef isPowerOfTwo(x): return (x and (not(x & (x - 1))))\n\ndef lcm(x, y): return (x*y)\/\/gcd(x, y)\n\ndef alpha(x): return ord(x)-ord('A')\n\n\n\n\n\ndef gcd(x, y):\n\n while y:\n\n x, y = y, x % y\n\n return x\n\n\n\n\n\ndef d2b(n):\n\n s = bin(n).replace(\"0b\", \"\")\n\n return (34-len(s))*'0'+s\n\n\n\n\n\ndef highestPowerof2(x):\n\n x |= x >> 1\n\n x |= x >> 2\n\n x |= x >> 4\n\n x |= x >> 8\n\n x |= x >> 16\n\n return x ^ (x >> 1)\n\n\n\n\n\ndef nextPowerOf2(N):\n\n if not (N & (N - 1)):\n\n return N\n\n return int(\"1\" + (len(bin(N)) - 2) * \"0\", 2)\n\n\n\n\n\ndef isPrime(x):\n\n if x == 1:\n\n return False\n\n if x == 2:\n\n return True\n\n for i in range(2, int(x ** 0.5) + 1):\n\n if x % i == 0:\n\n return False\n\n return True\n\n\n\n\n\ndef factors(n):\n\n i = 1\n\n ans = []\n\n while i <= sqrt(n):\n\n if (n % i == 0):\n\n if (n \/ i != i):\n\n ans.append(int(n\/i))\n\n if i != 1:\n\n ans.append(i)\n\n i += 1\n\n return ans\n\n\n\n\n\nPrimes = [1] * 100001\n\nprimeNos = []\n\n\n\n\n\ndef SieveOfEratosthenes(n):\n\n p = 2\n\n while (p * p <= n):\n\n if (Primes[p]):\n\n for i in range(p * p, n+1, p):\n\n Primes[i] = 0\n\n p += 1\n\n for p in range(2, n+1):\n\n if Primes[p]:\n\n primeNos.append(p)\n\n\n\n# SieveOfEratosthenes(100000)\n\n# P = len(primeNos)\n\n# print(\"P\", P)\n\n\n\n\n\ndef ncr(n, r):\n\n ans = 1\n\n while(r):\n\n ans *= n\n\n ans %= mod\n\n n -= 1\n\n r -= 1\n\n return ans\n\n\n\n############ Main! #############\n\n# mod = 998244353\n\n\n\n\n\ndef sangee():\n\n s = input()\n\n d = dd(int)\n\n for i in s:\n\n for a in abc:\n\n d[a+i] += d[a]\n\n d[i] += 1\n\n # print(d)\n\n print(max(d.values()))\n\n\n\n\n\nt = 1\n\nfor _ in range(t):\n\n sangee()\n\n","language":"py"} -{"contest_id":"1324","problem_id":"E","statement":"E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai\u22121ai\u22121 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1\u2264n\u22642000,3\u2264h\u22642000,0\u2264l\u2264r= l and total <= r) + dp[i - 1][0]\n\n for j in range(1,i + 1):\n\n dp[i][j] = max(dp[i - 1][j],dp[i - 1][j - 1]) + int((total - j)%h >= l and (total - j)%h <= r)\n\nprint(max(dp[-1]))","language":"py"} -{"contest_id":"1325","problem_id":"D","statement":"D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0\u2264u,v\u22641018)(0\u2264u,v\u22641018).OutputIf there's no array that satisfies the condition, print \"-1\". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4\nOutputCopy2\n3 1InputCopy1 3\nOutputCopy3\n1 1 1InputCopy8 5\nOutputCopy-1InputCopy0 0\nOutputCopy0NoteIn the first sample; 3\u22951=23\u22951=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.","tags":["bitmasks","constructive algorithms","greedy","number theory"],"code":"[u,v]=list(map(int,input().split(\" \")))\n\nif u==0 and v==0:\n\n print(0)\n\nelif u>v or u%2!=v%2:\n\n print(-1)\n\nelif u==v:\n\n print(1)\n\n print(v)\n\nelse:\n\n t=(v-u)\/\/2\n\n if t&u:\n\n print(3)\n\n print(str(t)+\" \"+str(t)+\" \"+str(u))\n\n else:\n\n print(2)\n\n print(str(t)+\" \"+str(t+u))","language":"py"} -{"contest_id":"1305","problem_id":"B","statement":"B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1\u2264|s|\u226410001\u2264|s|\u22641000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk \u00a0\u2014 the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm \u00a0\u2014 the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1\u2264a1= r:\n PRINT('0')\n return\n L = [l]\n R = [r]\n n = 2\n while True:\n # find the next positions of l and r\n l += 1\n while l < len(s) and s[l] != '(':\n l += 1\n r -= 1\n while r > 0 and s[r] != ')':\n r -= 1\n if l >= r:\n break\n L.append(l)\n R.append(r)\n n += 2\n PRINT('1')\n PRINT(str(n))\n PRINT(' '.join([str(x+1) for x in L]) + ' ' + ' '.join([str(x+1) for x in R[::-1]]))\n #return L + R[::-1]\n\ns = stdin.readline()[:-1]\n\nlogic(s)\n\n##import random as r\n##for k in range(10000):\n## s = ''\n## for i in range(200):\n## s += r.choice(['(',')'])\n## res = logic(s)\n## S = ''\n## for i in range(len(s)):\n## if i not in res:\n## S += s[i]\n##\n## if logic(S) != None:\n## print('issue')\n## print(s,S)\n","language":"py"} -{"contest_id":"1311","problem_id":"B","statement":"B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,\u2026,pmp1,p2,\u2026,pm, where 1\u2264pi a[p]:\n\n a[p - 1], a[p] = a[p], a[p - 1]\n\n\n\n if a == sorted(a):\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")\n\n\n\n\n\nsolve()\n\n","language":"py"}