diff --git "a/data/py/train.jsonl" "b/data/py/train.jsonl" deleted file mode 100644--- "a/data/py/train.jsonl" +++ /dev/null @@ -1,1599 +0,0 @@ -{"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 os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\nfrom collections import Counter\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 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\n\n\n\n\ndef gcd(a, b):\n\n if a == 0:\n\n return b\n\n return gcd(b % a, a)\n\n\n\n\n\ndef lcm(a, b):\n\n return (a * b) \/ gcd(a, b)\n\n\n\n\n\ndef main():\n\n n,m,k=map(int, input().split())\n\n n,m=m,n\n\n ans=[]\n\n f=0\n\n for i in range(m-1):\n\n if k:\n\n t=min(k, n-1)\n\n k-=t\n\n if t:\n\n ans.append([t, 'R'])\n\n if k:\n\n t = min(k, n - 1)\n\n k -= t\n\n if t:\n\n ans.append([t,'L'])\n\n if k:\n\n ans.append([1, 'D'])\n\n k-=1\n\n for i in range(n-1):\n\n if k:\n\n k-=1\n\n ans.append([1,'R'])\n\n if k:\n\n t=min(k, m-1)\n\n k-=t\n\n if t:\n\n ans.append([t, 'U'])\n\n if k:\n\n t = min(k, m - 1)\n\n k -= t\n\n if t:\n\n ans.append([t, 'D'])\n\n if k:\n\n t=min(k, n-1)\n\n if t:\n\n ans.append([t, 'L'])\n\n k-=t\n\n if k:\n\n t = min(k, m - 1)\n\n if t:\n\n ans.append([t, 'U'])\n\n k -= t\n\n if k or len(ans)>3000:\n\n print('NO')\n\n else:\n\n print('YES')\n\n print(len(ans))\n\n for i in ans:\n\n print(*i)\n\n return\n\n\n\n\n\nif __name__ == \"__main__\":\n\n main()","language":"py"} -{"contest_id":"1305","problem_id":"D","statement":"D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most \u230an2\u230b\u230an2\u230b times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2\u2264n\u226410002\u2264n\u22641000), the number of vertices of the tree.Then you will read n\u22121n\u22121 lines, the ii-th of them has two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type \"? u v\" (1\u2264u,v\u2264n1\u2264u,v\u2264n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than \u230an2\u230b\u230an2\u230b queries, the program will print \u22121\u22121 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print \"! rr\" and quit after that. This query does not count towards the \u230an2\u230b\u230an2\u230b limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2\u2264n\u226410002\u2264n\u22641000, 1\u2264r\u2264n1\u2264r\u2264n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n\u22121n\u22121 lines should contain two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n)\u00a0\u2014 denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4\n\nOutputCopy\n\n\n\n\n\n? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:","tags":["constructive algorithms","dfs and similar","interactive","trees"],"code":"import os, sys\n\nfrom io import BytesIO, IOBase\n\nfrom math import log2, ceil, sqrt, gcd\n\nfrom _collections import deque\n\nimport heapq as hp\n\nfrom bisect import bisect_left, bisect_right\n\nfrom math import cos, sin\n\nfrom itertools import permutations\n\n\n\n# sys.setrecursionlimit(2*10**5+10000)\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 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\n\nmod = (10 ** 9 + 7) ^ 1755654\n\n\n\n\n\n\n\ndef ask(x, y):\n\n print('?', x, y, flush=True)\n\n return int(input())\n\n\n\n\n\nn = int(input())\n\na = [set() for _ in range(n + 1)]\n\nfor _ in range(n - 1):\n\n x, y = map(int, input().split())\n\n a[x].add(y)\n\n a[y].add(x)\n\n\n\nck=[]\n\nfor i in range(1,n+1):\n\n if len(a[i])==1:\n\n ck.append(i)\n\n\n\nfor _ in range(n \/\/ 2):\n\n\n\n x = ck.pop()\n\n y = ck.pop()\n\n # print(ck,x,y,dd)\n\n z = ask(x, y)\n\n if z == x:\n\n print('!', x, flush=True)\n\n exit()\n\n if z == y:\n\n print('!', y, flush=True)\n\n exit()\n\n\n\n for i in a[x]:\n\n a[i].remove(x)\n\n if len(a[i])==1:\n\n ck.append(i)\n\n for i in a[y]:\n\n a[i].remove(y)\n\n if len(a[i])==1:\n\n ck.append(i)\n\n\n\nprint('!', ck.pop(), flush=True)\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 sys\n\ninput=lambda:sys.stdin.readline().rstrip()\n\ndef calc(A,i,j,k):\n\n\tif k==0:\n\n\t\treturn 0\n\n\tif A[i]%(k*2)>=k or A[j]%(k*2)=k for l in A[i:j+1]].index(1)\n\n\treturn k+min(calc(A,i,index-1,k\/\/2),calc(A,index,j,k\/\/2))\n\ndef solve():\n\n\tn=int(input())\n\n\tA=sorted(list(map(int,input().split())))\n\n\tprint(calc(A,0,n-1,pow(2,30)))\n\nT=1\n\nfor i in range(T):\n\n\tsolve()","language":"py"} -{"contest_id":"1325","problem_id":"B","statement":"B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?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. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt\u00a0\u2014 the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1\u2264n\u22641051\u2264n\u2264105)\u00a0\u2014 the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, \u2026\u2026, anan (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2\n3\n3 2 1\n6\n3 1 4 1 5 9\nOutputCopy3\n5\nNoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].","tags":["greedy","implementation"],"code":"t=int(input())\n\nfor i in range(t):\n\n n=int(input())\n\n arr=list(map(int,input().split()))\n\n c=set(arr)\n\n print(len(c))","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 sys, os, io\n\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\ndef binary_trie():\n\n G0, G1, cnt = [-1], [-1], [0]\n\n return G0, G1, cnt\n\n\n\ndef insert(x, l):\n\n j = 0\n\n for i in range(l, -1, -1):\n\n cnt[j] += 1\n\n if x & pow2[i]:\n\n if G1[j] == -1:\n\n G0.append(-1)\n\n G1.append(-1)\n\n cnt.append(0)\n\n G1[j] = len(cnt) - 1\n\n j = G1[j]\n\n else:\n\n if G0[j] == -1:\n\n G0.append(-1)\n\n G1.append(-1)\n\n cnt.append(0)\n\n G0[j] = len(cnt) - 1\n\n j = G0[j]\n\n cnt[j] += 1\n\n return\n\n\n\nn = int(input())\n\na = list(map(int, input().split()))\n\nma = max(a)\n\nif not ma:\n\n ans = 0\n\n print(ans)\n\n exit()\n\nG0, G1, cnt = binary_trie()\n\npow2 = [1]\n\nfor _ in range(31):\n\n pow2.append(2 * pow2[-1])\n\nfor i in range(32):\n\n if ma < pow2[i]:\n\n l = i - 1\n\n break\n\nfor i in set(sorted(a)):\n\n insert(i, l)\n\nx = [0]\n\nf = 0\n\nans = 0\n\nfor i in range(l, -1, -1):\n\n if not f:\n\n if G0[x[0]] ^ -1 and G1[x[0]] ^ -1:\n\n ans ^= pow2[i]\n\n x = [G0[x[0]], G1[x[0]]]\n\n f = 1\n\n else:\n\n x = [max(G0[x[0]], G1[x[0]])]\n\n else:\n\n y, z = [], []\n\n for u in x:\n\n if G0[u] ^ -1 and G1[u] ^ -1:\n\n y.append(G0[u])\n\n y.append(G1[u])\n\n else:\n\n z.append(max(G0[u], G1[u]))\n\n if not len(z):\n\n ans ^= pow2[i]\n\n x = y\n\n else:\n\n x = z\n\nprint(ans)","language":"py"} -{"contest_id":"1303","problem_id":"E","statement":"E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,\u2026,siksi1,si2,\u2026,sik where 1\u2264i1 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":"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":"from collections import defaultdict\n\n\n\n\n\nn = int(input())\n\narr = list(map(int, input().split()))\n\n\n\npre = [0]*(n+1)\n\nfor i in range(n):\n\n pre[i+1] = pre[i] + arr[i]\n\n\n\nmp = defaultdict(list)\n\n\n\nfor i in range(n):\n\n for j in range(i,n):\n\n sum = pre[j+1] - pre[i]\n\n mp[sum].append((i,j))\n\n\n\nk = 0\n\nans = None \n\nqs = None\n\nfor x, v in mp.items():\n\n v.sort(key=lambda p: p[1])\n\n\n\n temp = 1\n\n right = v[0][1]\n\n q = [v[0]]\n\n for i in range(1,len(v)):\n\n if(v[i][0] > right):\n\n temp += 1\n\n right = v[i][1]\n\n q.append(v[i])\n\n\n\n # print(x, v, temp)\n\n if(temp > k):\n\n ans = x\n\n k = temp\n\n qs = q\n\nprint(k)\n\n# print(qs)\n\nfor x,y in qs:\n\n print(x+1, y+1)\n\n","language":"py"} -{"contest_id":"1316","problem_id":"D","statement":"D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n\u00d7nn\u00d7n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters \u00a0\u2014 UU, DD, LL, RR or XX \u00a0\u2014 instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c\u22121)(r,c\u22121), for UU the player should move to the top cell (r\u22121,c)(r\u22121,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (\u22121\u22121,\u22121\u22121), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1\u2264n\u22641031\u2264n\u2264103) \u00a0\u2014 the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,\u2026,xn,ynx1,y1,x2,y2,\u2026,xn,yn, where (xj,yj)(xj,yj) (1\u2264xj\u2264n,1\u2264yj\u2264n1\u2264xj\u2264n,1\u2264yj\u2264n, or (xj,yj)=(\u22121,\u22121)(xj,yj)=(\u22121,\u22121)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2\n1 1 1 1\n2 2 2 2\nOutputCopyVALID\nXL\nRX\nInputCopy3\n-1 -1 -1 -1 -1 -1\n-1 -1 2 2 -1 -1\n-1 -1 -1 -1 -1 -1\nOutputCopyVALID\nRRD\nUXD\nULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below : ","tags":["constructive algorithms","dfs and similar","graphs","implementation"],"code":"# -*- coding: utf-8 -*-\n\n\n\nimport math\n\nimport collections\n\nimport bisect\n\nimport heapq\n\nimport time\n\nimport random\n\nimport itertools\n\nimport sys\n\nfrom typing import List\n\n\n\n\"\"\"\n\ncreated by shhuan at 2020\/3\/13 21:15\n\n\n\n\"\"\"\n\n\n\n\n\ndef check(x, y, N):\n\n return 1 <= x <= N and 1 <= y <= N\n\n\n\n\n\ndef dfs(x, y, d, marks, X, Y, N):\n\n if not check(x, y, N) or marks[x][y] != '':\n\n return\n\n marks[x][y] = d\n\n if x+1 <= N and X[x][y] == X[x+1][y] and Y[x][y] == Y[x+1][y]:\n\n dfs(x+1, y, 'U', marks, X, Y, N)\n\n if x-1 > 0 and X[x][y] == X[x-1][y] and Y[x][y] == Y[x-1][y]:\n\n dfs(x-1, y, 'D', marks, X, Y, N)\n\n if y+1 <= N and X[x][y] == X[x][y+1] and Y[x][y] == Y[x][y+1]:\n\n dfs(x, y+1, 'L', marks, X, Y, N)\n\n if y-1 > 0 and X[x][y] == X[x][y-1] and Y[x][y] == Y[x][y-1]:\n\n dfs(x, y-1, 'R', marks, X, Y, N)\n\n\n\n\n\ndef dfs2(x, y, d, marks, X, Y, N):\n\n marks[x][y] = d\n\n q = [(x, y)]\n\n vx, vy = X[x][y], Y[x][y]\n\n while q:\n\n x, y= q.pop()\n\n for nx, ny, nd in [(x+1, y, 'U'), (x-1, y, 'D'), (x, y+1, 'L'), (x, y-1, 'R')]:\n\n if check(nx, ny, N) and X[nx][ny] == vx and Y[nx][ny] == vy and marks[nx][ny] == '':\n\n marks[nx][ny] = nd\n\n q.append((nx, ny))\n\n\n\n\n\ndef connect(x1, y1, x2, y2, d1, d2, marks, X, Y, N):\n\n if not check(x1, y1, N) or not check(x2, y2, N):\n\n return False\n\n\n\n if X[x2][y2] == -1:\n\n marks[x1][y1] = d1\n\n if marks[x2][y2] == '':\n\n marks[x2][y2] = d2\n\n return True\n\n return False\n\n\n\n\n\ndef solve(N, X, Y):\n\n marks = [['' for _ in range(N+2)] for _ in range(N+2)]\n\n for r in range(N+2):\n\n marks[r][0] = '#'\n\n marks[r][N+1] = '#'\n\n marks[0][r] = '#'\n\n marks[N+1][r] = '#'\n\n\n\n for r in range(1, N+1):\n\n for c in range(1, N+1):\n\n if X[r][c] == -1:\n\n res = marks[r][c] != ''\n\n if not res:\n\n res = connect(r, c, r+1, c, 'D', 'U', marks, X, Y, N)\n\n if not res:\n\n res = connect(r, c, r, c+1, 'R', 'L', marks, X, Y, N)\n\n if not res:\n\n res = connect(r, c, r-1, c, 'U', 'D', marks, X, Y, N)\n\n if not res:\n\n res = connect(r, c, r, c-1, 'L', 'R', marks, X, Y, N)\n\n if not res:\n\n return 'INVALID'\n\n elif X[r][c] == r and Y[r][c] == c:\n\n dfs2(r, c, 'X', marks, X, Y, N)\n\n\n\n for r in range(1, N+1):\n\n for c in range(1, N+1):\n\n if marks[r][c] == '':\n\n return 'INVALID'\n\n\n\n ans = ['VALID']\n\n for r in range(1, N+1):\n\n row = ''.join([marks[r][c] for c in range(1, N+1)])\n\n ans.append(row)\n\n\n\n return '\\n'.join(ans)\n\n\n\n\n\ndef test():\n\n N = 1000\n\n X = [[1000 for _ in range(N + 2)] for _ in range(N + 2)]\n\n Y = [[1000 for _ in range(N + 2)] for _ in range(N + 2)]\n\n solve(N, X, Y)\n\n\n\n# test()\n\n\n\nN = int(input())\n\nX = [[0 for _ in range(N+2)] for _ in range(N+2)]\n\nY = [[0 for _ in range(N+2)] for _ in range(N+2)]\n\nfor r in range(1, N+1):\n\n cs = [int(x) for x in input().split()]\n\n for c in range(1, N+1):\n\n X[r][c] = cs[(c-1) * 2]\n\n Y[r][c] = cs[(c-1) * 2 + 1]\n\n\n\nprint(solve(N, X, Y))","language":"py"} -{"contest_id":"1303","problem_id":"E","statement":"E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,\u2026,siksi1,si2,\u2026,sik where 1\u2264i1 0:\n\n x = ord(s[i-1])-97\n\n pos[i][x] = i\n\n flg = 0\n\n for i in range(m):\n\n t1 = t[:i]\n\n t2 = t[i:]\n\n m1 = len(t1)\n\n m2 = len(t2)\n\n dp = [[1000 for i in range(m2+1)] for j in range(m1+1)]\n\n dp[0][0] = 0\n\n for j in range(m1+1):\n\n for k in range(m2+1):\n\n if j > 0 and dp[j-1][k] < 1000:\n\n t1x = ord(t1[j-1])-97\n\n dp[j][k] = min(dp[j][k],pos[dp[j-1][k]+1][t1x])\n\n if k > 0 and dp[j][k-1] < 1000:\n\n t2x = ord(t2[k-1])-97\n\n dp[j][k] = min(dp[j][k],pos[dp[j][k-1]+1][t2x])\n\n if dp[-1][-1] < 1000:\n\n flg = 1\n\n break\n\n if flg:\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")","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":"from collections import defaultdict as dc\n\nn=int(input())\n\na,b=list(input()),list(input())\n\nfrqa=dc(lambda:list())\n\nfrqb=dc(lambda:list())\n\nfor i in range(n):frqa[a[i]].append(i)\n\nfor i in range(n):frqb[b[i]].append(i)\n\ni=96\n\nans=list()\n\n#print(ord('?'))=63\n\nwhile i<=122:\n\n i+=1\n\n c=chr(i)\n\n if c in frqa and c in frqb:\n\n while len(frqa[c]) and len(frqb[c]):ans.append((frqa[c].pop()+1,frqb[c].pop()+1))\n\n if len(frqa[c]):\n\n while len(frqa[c]) and len(frqb['?']):ans.append((frqa[c].pop()+1,frqb['?'].pop()+1))\n\n elif len(frqb[c]):\n\n while len(frqa['?']) and len(frqb[c]):ans.append((frqa['?'].pop()+1,frqb[c].pop()+1))\n\n elif c in frqa:\n\n while len(frqa[c]) and len(frqb['?']):ans.append((frqa[c].pop()+1,frqb['?'].pop()+1))\n\n elif c in frqb:\n\n while len(frqa['?']) and len(frqb[c]):ans.append((frqa['?'].pop()+1,frqb[c].pop()+1))\n\nwhile len(frqa['?']) and len(frqb['?']):ans.append((frqa['?'].pop()+1,frqb['?'].pop()+1))\n\nprint(len(ans))\n\nfor i in ans:print(i[0],i[1])","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":"l = int(input())\ninput()\nprint(l + 1)","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> 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":"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\ndef radix(a):\n\n digits = len(str(max(a)))\n\n for i in range (digits):\n\n b = [[] for _ in range (10)]\n\n e = pow(10, i)\n\n for j in a:\n\n num = (j\/\/e)%10\n\n b[num].append(j)\n\n a *= 0\n\n for l in b:\n\n a += l\n\n return(a)\n\n\n\nN = int(input())\n\na = list(map(int, input().split()))\n\n \n\n\n\nres = 0\n\na = radix(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":"1305","problem_id":"D","statement":"D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most \u230an2\u230b\u230an2\u230b times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2\u2264n\u226410002\u2264n\u22641000), the number of vertices of the tree.Then you will read n\u22121n\u22121 lines, the ii-th of them has two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n, xi\u2260yixi\u2260yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type \"? u v\" (1\u2264u,v\u2264n1\u2264u,v\u2264n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than \u230an2\u230b\u230an2\u230b queries, the program will print \u22121\u22121 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print \"! rr\" and quit after that. This query does not count towards the \u230an2\u230b\u230an2\u230b limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2\u2264n\u226410002\u2264n\u22641000, 1\u2264r\u2264n1\u2264r\u2264n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n\u22121n\u22121 lines should contain two integers xixi and yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n)\u00a0\u2014 denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4\n\nOutputCopy\n\n\n\n\n\n? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:","tags":["constructive algorithms","dfs and similar","interactive","trees"],"code":"import sys\n\nimport math\n\nimport heapq\n\nimport bisect\n\nfrom collections import Counter\n\nfrom collections import defaultdict\n\nfrom io import BytesIO, IOBase\n\nimport string\n\n\n\n\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n\n\n def __init__(self, file):\n\n import os\n\n self.os = os\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 self.BUFSIZE = 8192\n\n\n\n def read(self):\n\n while True:\n\n b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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 = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.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 self.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\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\n\n\ndef get_int():\n\n return int(input())\n\n\n\n\n\ndef get_ints():\n\n return list(map(int, input().split(' ')))\n\n\n\n\n\ndef get_int_grid(n):\n\n return [get_ints() for _ in range(n)]\n\n\n\n\n\ndef get_str():\n\n return input().strip()\n\n\n\n\n\ndef get_strs():\n\n return get_str().split(' ')\n\n\n\n\n\ndef flat_list(arr):\n\n return [item for subarr in arr for item in subarr]\n\n\n\n\n\ndef yes_no(b):\n\n if b:\n\n return \"YES\"\n\n else:\n\n return \"NO\"\n\n\n\n\n\ndef binary_search(good, left, right, delta=1, right_true=False):\n\n \"\"\"\n\n Performs binary search\n\n ----------\n\n Parameters\n\n ----------\n\n :param good: Function used to perform the binary search\n\n :param left: Starting value of left limit\n\n :param right: Starting value of the right limit\n\n :param delta: Margin of error, defaults value of 1 for integer binary search\n\n :param right_true: Boolean, for whether the right limit is the true invariant\n\n :return: Returns the most extremal value interval [left, right] which is good function evaluates to True,\n\n alternatively returns False if no such value found\n\n \"\"\"\n\n\n\n limits = [left, right]\n\n while limits[1] - limits[0] > delta:\n\n if delta == 1:\n\n mid = sum(limits) \/\/ 2\n\n else:\n\n mid = sum(limits) \/ 2\n\n if good(mid):\n\n limits[int(right_true)] = mid\n\n else:\n\n limits[int(~right_true)] = mid\n\n if good(limits[int(right_true)]):\n\n return limits[int(right_true)]\n\n else:\n\n return False\n\n\n\n\n\ndef prefix_sums(a):\n\n p = [0]\n\n for x in a:\n\n p.append(p[-1] + x)\n\n return p\n\n\n\n\n\ndef solve_a():\n\n n = int(input())\n\n a = [int(s) for s in input().split(' ')]\n\n b = [int(s) for s in input().split(' ')]\n\n a.sort()\n\n b.sort()\n\n return ' '.join([str(i) for i in a]), ' '.join([str(j) for j in b])\n\n\n\n\n\ndef get_tree(n):\n\n T = defaultdict(set)\n\n for _ in range(n - 1):\n\n a, b = get_ints()\n\n T[a].add(b)\n\n T[b].add(a)\n\n return T\n\n\n\n\n\ndef solve_d():\n\n n = get_int()\n\n T = get_tree(n)\n\n leafs = [u for u in range(1, n + 1) if len(T[u]) == 1]\n\n\n\n def query(a, b):\n\n print('?', a, b)\n\n sys.stdout.flush()\n\n return get_int()\n\n\n\n def guess(a):\n\n print('!', a)\n\n return\n\n\n\n while leafs:\n\n a, b = leafs.pop(), leafs.pop()\n\n r = query(a, b)\n\n if r == a:\n\n guess(a)\n\n return\n\n elif r == b:\n\n guess(b)\n\n return\n\n else:\n\n c = T[a].pop()\n\n d = T[b].pop()\n\n T[c].remove(a)\n\n T[d].remove(b)\n\n if len(T[c]) == 1:\n\n leafs.append(c)\n\n if len(T[d]) == 1 and c != d:\n\n leafs.append(d)\n\n if len(T[c]) == 0:\n\n lonely = c\n\n elif len(T[d]) == 0:\n\n lonely = d\n\n guess(lonely)\n\n\n\n\n\nsolve_d()\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":"# 13:17-\n\nimport sys\n\ninput = lambda: sys.stdin.readline().rstrip()\n\n\n\nN = int(input())\n\nA = list(map(int, input().split()))\n\n\n\ncnt = [0]*32\n\nfor i in range(32):\n\n\tfor a in A:\n\n\t\tif a&(1<=0:\n\n\tidx = 0\n\n\tfor i in range(N):\n\n\t\tif A[i]&(1< x:\n\n high = mid - 1\n\n else:\n\n return mid\n\n return high\n\ndef find_gcd(x, y):\n\n \n\n while(y):\n\n x, y = y, x % y\n\n \n\n return x\n\n# Python3 program to calculate\n\n# Euler's Totient Function\n\ndef phi(n):\n\n \n\n # Initialize result as n\n\n result = n;\n\n \n\n # Consider all prime factors\n\n # of n and subtract their\n\n # multiples from result\n\n p = 2;\n\n while(p * p <= n):\n\n \n\n # Check if p is a\n\n # prime factor.\n\n if (n % p == 0):\n\n \n\n # If yes, then\n\n # update n and result\n\n while (n % p == 0):\n\n n = int(n \/ p);\n\n result -= int(result \/ p);\n\n p += 1;\n\n \n\n # If n has a prime factor\n\n # greater than sqrt(n)\n\n # (There can be at-most\n\n # one such prime factor)\n\n if (n > 1):\n\n result -= int(result \/ n);\n\n return result;\n\n\n\n\n\ndef main():\n\n n=get_int()\n\n for i in range(n):\n\n [a,m]=get_list_ints()\n\n g=find_gcd(a,m)\n\n p2=m\/\/g\n\n ans=phi(p2)\n\n print(ans)\n\n pass\n\n\n\nif __name__ == '__main__':\n\n main()","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 n = int(input())\n\n m, t = 0, 0\n\n a = input()\n\n if n == 1 or len(set(a)) == 1:\n\n print(0)\n\n continue\n\n j = a.index('A')\n\n for i in range(j + 1, n):\n\n if a[i] == 'P':\n\n t += 1\n\n else:\n\n m = max(m, t)\n\n t = 0\n\n print(max(m, t))","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 _ in range(int(input())):\n\n n = int(input())\n\n arr = list(map(int, input().split()))\n\n for i in range(n):\n\n if arr[i] % 2 == 0:\n\n print(1)\n\n print(i + 1)\n\n break\n\n else:\n\n if n == 1:\n\n print(-1)\n\n else:\n\n print(2)\n\n print(1, 2)\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":"from sys import stdin\ninput = stdin.readline\nimport math \n\nfor case in range(int(input())):\n n, m = map(int, input().split())\n ans = n * (n + 1) \/\/ 2\n \n small = (n - m)\/\/(m + 1); avg_split = (n - m)\/(m + 1)\n large = small + 1\n\n \n num_large = (n - m) % (m + 1)\n num_small = m + 1 - num_large\n\n ans -= (num_large * large * (large + 1)\/\/ 2 + num_small * small * (small + 1)\/\/2)\n \n print(int(ans))\n\n\n\n\n \n\n\n\n","language":"py"} -{"contest_id":"1312","problem_id":"C","statement":"C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,\u2026,vnv1,v2,\u2026,vn filled with zeroes at start. The following operation is applied to the array several times \u2014 at ii-th step (00-indexed) you can: either choose position pospos (1\u2264pos\u2264n1\u2264pos\u2264n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1\u2264T\u226410001\u2264T\u22641000) \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 kk (1\u2264n\u2264301\u2264n\u226430, 2\u2264k\u22641002\u2264k\u2264100) \u2014 the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410160\u2264ai\u22641016) \u2014 the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5\n4 100\n0 0 0 0\n1 2\n1\n3 4\n1 4 1\n3 2\n0 1 3\n3 9\n0 59049 810\nOutputCopyYES\nYES\nNO\nNO\nYES\nNoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.","tags":["bitmasks","greedy","implementation","math","number theory","ternary search"],"code":"R=lambda:map(int,input().split())\nt,=R()\nfor _ in[0]*t:\n n,k=R();a=*R(),;r='YES'\n while any(a):\n if[x%k for x in a if x%k]>[1]:r='NO'\n a=[x\/\/k for x in a]\n print(r)\n\t\t\t \t\t\t\t\t\t \t\t \t\t \t \t\t \t \t\t \t\t","language":"py"} -{"contest_id":"1284","problem_id":"D","statement":"D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai\u2264eaisai\u2264eai) and [sbi,ebi][sbi,ebi] (sbi\u2264ebisbi\u2264ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)\u2264min(y,v)max(x,u)\u2264min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1\u2264n\u22641000001\u2264n\u2264100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1\u2264sai,eai,sbi,ebi\u22641091\u2264sai,eai,sbi,ebi\u2264109, sai\u2264eai,sbi\u2264ebisai\u2264eai,sbi\u2264ebi).OutputPrint \"YES\" if Hyunuk will be happy. Print \"NO\" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2\n1 2 3 6\n3 4 7 8\nOutputCopyYES\nInputCopy3\n1 3 2 4\n4 5 6 7\n3 4 5 5\nOutputCopyNO\nInputCopy6\n1 5 2 9\n2 4 5 8\n3 6 7 11\n7 10 12 16\n8 11 13 17\n9 12 14 18\nOutputCopyYES\nNoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.","tags":["binary search","data structures","hashing","sortings"],"code":"import sys\ninput = lambda: sys.stdin.readline().rstrip()\nN=100101\n\nn = int(input())\n\nrand = [((i+12345)**3)%998244353 for i in range(N*2+20)]\nal,ar,bl,br=[],[],[],[]\nfor _ in range(n):\n a,b,c,d=map(int,input().split())\n al.append(a)\n ar.append(b)\n bl.append(c)\n br.append(d)\ndef calk(l,r):\n ma={s:idx for idx,s in enumerate(sorted(list(set(l+r))))}\n hash=[0]*N*2\n for idx,v in enumerate(l):hash[ma[v]]+=rand[idx]\n for i in range(1,N*2):hash[i]+=hash[i-1]\n return sum([hash[ma[v]]*rand[idx] for idx,v in enumerate(r)])\n\n\nprint(\"YES\" if calk(al, ar) == calk(bl, br) else \"NO\")\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":"for _ in [0]*int(input()):\n\n a,b = map(int, input().split())\n\n print(a*(len(str(b+1))-1))","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":"\n\ndef main():\n\n \n\n t=int(input())\n\n allans=[]\n\n for _ in range(t):\n\n n,s=input().split()\n\n n=int(n)\n\n \n\n s=s+'$'\n\n seq=[] # [isIncreasing,length]\n\n prev=None\n\n l=0\n\n for c in s:\n\n if c!=prev:\n\n if l>0: # not first\n\n seq.append([prev=='<',l])\n\n l=1\n\n else:\n\n l+=1\n\n prev=c\n\n seq[0][1]+=1\n\n \n\n minLIS=[] # large to small\n\n curr=n\n\n # print(seq)\n\n startend=[] # [start, end]\n\n for i in range(len(seq)):\n\n l=seq[i][1]\n\n if seq[i][0]: # is increasing\n\n if i==0:\n\n start=n-l+1\n\n end=n\n\n curr=start-1\n\n else:\n\n start=startend[i-1][0]+1\n\n end=start+l-1\n\n else: # is decreasing\n\n if i+1=0:\n\n start=startend[i-1][0]-1\n\n else:\n\n start=l\n\n curr=start+1\n\n end=start-l+1\n\n startend.append([start,end])\n\n # print(seq)\n\n # print(startend)\n\n for start,end in startend:\n\n if start<=end:\n\n for v in range(start,end+1):\n\n maxLIS.append(v)\n\n else:\n\n for v in range(start,end-1,-1):\n\n maxLIS.append(v)\n\n allans.append(minLIS)\n\n allans.append(maxLIS)\n\n \n\n \n\n multiLineArrayOfArraysPrint(allans)\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":"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\nfrom math import *\n\nfrom collections import *\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\ndef solve():\n\n u,v=map(int,inp().split())\n\n if v%2!=u%2 or u>v:\n\n print(-1)\n\n return\n\n if u==v==0:\n\n print(0)\n\n return\n\n if u==v:\n\n print(1)\n\n print(u)\n\n return\n\n x=(v-u)\/\/2\n\n if (u ^ x)+x==v:\n\n print(2)\n\n print(u ^ x, x)\n\n return\n\n print(3)\n\n print(x,x,u)\n\nsolve()\n\n","language":"py"} -{"contest_id":"1284","problem_id":"D","statement":"D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai\u2264eaisai\u2264eai) and [sbi,ebi][sbi,ebi] (sbi\u2264ebisbi\u2264ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)\u2264min(y,v)max(x,u)\u2264min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1\u2264n\u22641000001\u2264n\u2264100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1\u2264sai,eai,sbi,ebi\u22641091\u2264sai,eai,sbi,ebi\u2264109, sai\u2264eai,sbi\u2264ebisai\u2264eai,sbi\u2264ebi).OutputPrint \"YES\" if Hyunuk will be happy. Print \"NO\" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2\n1 2 3 6\n3 4 7 8\nOutputCopyYES\nInputCopy3\n1 3 2 4\n4 5 6 7\n3 4 5 5\nOutputCopyNO\nInputCopy6\n1 5 2 9\n2 4 5 8\n3 6 7 11\n7 10 12 16\n8 11 13 17\n9 12 14 18\nOutputCopyYES\nNoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.","tags":["binary search","data structures","hashing","sortings"],"code":"from operator import itemgetter\n\nimport sys\n\nimport bisect\n\ninput = sys.stdin.readline\n\n\n\n\n\nclass BIT():\n\n \"\"\"\u533a\u9593\u52a0\u7b97\u3001\u533a\u9593\u53d6\u5f97\u30af\u30a8\u30ea\u3092\u305d\u308c\u305e\u308cO(logN)\u3067\u7b54\u3048\u308b\n\n add: \u533a\u9593[l, r)\u306bval\u3092\u52a0\u3048\u308b\n\n get_sum: \u533a\u9593[l, r)\u306e\u548c\u3092\u6c42\u3081\u308b\n\n l, r\u306f0-indexed\n\n \"\"\"\n\n def __init__(self, n):\n\n self.n = n\n\n self.bit0 = [0] * (n + 1)\n\n self.bit1 = [0] * (n + 1)\n\n\n\n def _add(self, bit, i, val):\n\n i = i + 1\n\n while i <= self.n:\n\n bit[i] += val\n\n i += i & -i\n\n\n\n def _get(self, bit, i):\n\n s = 0\n\n while i > 0:\n\n s += bit[i]\n\n i -= i & -i\n\n return s\n\n\n\n def add(self, l, r, val):\n\n \"\"\"\u533a\u9593[l, r)\u306bval\u3092\u52a0\u3048\u308b\"\"\"\n\n self._add(self.bit0, l, -val * l)\n\n self._add(self.bit0, r, val * r)\n\n self._add(self.bit1, l, val)\n\n self._add(self.bit1, r, -val)\n\n\n\n def get_sum(self, l, r):\n\n \"\"\"\u533a\u9593[l, r)\u306e\u548c\u3092\u6c42\u3081\u308b\"\"\"\n\n return self._get(self.bit0, r) + r * self._get(self.bit1, r) \\\n\n - self._get(self.bit0, l) - l * self._get(self.bit1, l)\n\n\n\n#\u5ea7\u6a19\u5727\u7e2e\u3057\u305f\u30ea\u30b9\u30c8\u3092\u8fd4\u3059\n\ndef compress(array):\n\n n = len(array)\n\n m = len(array[0])\n\n set_ = set()\n\n for i in array:\n\n for j in i:\n\n set_.add(j)\n\n array2 = sorted(set_)\n\n memo = {value : index for index, value in enumerate(array2)}\n\n \n\n for i in range(n):\n\n for j in range(m):\n\n array[i][j] = memo[array[i][j]]\n\n return array, len(memo)\n\n\n\n\n\nn = int(input())\n\ninfo = [list(map(int, input().split())) for i in range(n)]\n\ninfo, m = compress(info)\n\n\n\n\"\"\"\n\nfor i in range(n):\n\n a1, a2, b1, b2 = info[i]\n\n for j in range(i+1, n):\n\n c1, c2, d1, d2 = info[j]\n\n if (max(a1, c1) <= min(a2, c2)) ^ (max(b1, d1) <= min(b2, d2)):\n\n print(2)\n\n\"\"\"\n\n\n\ninfo = sorted(info, key = itemgetter(0))\n\n\n\nbi = [None] * n\n\nfor i in range(n):\n\n bi[i] = (i, info[i][1])\n\nbi = sorted(bi, key = itemgetter(1))\n\nbii = [v for i, v in bi]\n\n\n\nbit = BIT(m)\n\ntmp = 0\n\nfor i in range(n):\n\n l, r, l2, r2 = info[i] \n\n ind = bisect.bisect_left(bii, l)\n\n while tmp < ind:\n\n ii = bi[tmp][0]\n\n bit.add(info[ii][2], info[ii][3] + 1, 1)\n\n tmp += 1\n\n if bit.get_sum(l2, r2 + 1) >= 1:\n\n print(\"NO\")\n\n exit()\n\n\n\nfor i in range(n):\n\n info[i][0], info[i][1], info[i][2], info[i][3] = info[i][2], info[i][3], info[i][0], info[i][1]\n\n\n\ninfo = sorted(info, key = itemgetter(0))\n\n\n\nbi = [None] * n\n\nfor i in range(n):\n\n bi[i] = (i, info[i][1])\n\nbi = sorted(bi, key = itemgetter(1))\n\nbii = [v for i, v in bi]\n\n\n\nbit = BIT(m)\n\ntmp = 0\n\nfor i in range(n):\n\n l, r, l2, r2 = info[i] \n\n ind = bisect.bisect_left(bii, l)\n\n while tmp < ind:\n\n ii = bi[tmp][0]\n\n bit.add(info[ii][2], info[ii][3] + 1, 1)\n\n tmp += 1\n\n if bit.get_sum(l2, r2 + 1) >= 1:\n\n print(\"NO\")\n\n exit()\n\nprint(\"YES\")","language":"py"} -{"contest_id":"1295","problem_id":"A","statement":"A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2\u2264n\u22641052\u2264n\u2264105) \u2014 the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2\n3\n4\nOutputCopy7\n11\n","tags":["greedy"],"code":"t = int(input())\n\n\n\nfor _ in range(t):\n\n segments = int(input())\n\n\n\n if segments < 2:\n\n print(\"1\")\n\n else:\n\n rem = segments % 2\n\n if rem:\n\n total_ones = segments - 3\n\n total = \"7\"+(\"1\"*(total_ones\/\/2))\n\n print(total)\n\n else:\n\n ones = \"1\"*(segments\/\/2)\n\n print(ones)\n\n","language":"py"} -{"contest_id":"1290","problem_id":"A","statement":"A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n\u22121n\u22121 friends have found an array of integers a1,a2,\u2026,ana1,a2,\u2026,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.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 three space-separated integers nn, mm and kk (1\u2264m\u2264n\u226435001\u2264m\u2264n\u22643500, 0\u2264k\u2264n\u221210\u2264k\u2264n\u22121) \u00a0\u2014 the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109) \u00a0\u2014 elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2\nOutputCopy8\n4\n1\n1\nNoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.","tags":["brute force","data structures","implementation"],"code":"#z=int(input()) \n\nimport math\n\n \n\nalfabet = {'a': 1, 'b': 2,'c': 3,'d': 4,'e': 5,'f': 6,'g': 7,'h': 8,'i': 9,'j': 10,'k': 11,'l': 12,'m': 13,'n': 14,'o': 15,'p': 16,'q': 17,'r': 18,'s': 19,'t': 20,'u': 21,'v': 22,'w': 23,'x': 24,'y': 25,'z': 26}\n\nalfabet_2={'1':\"a\", '2':\"b\", '3':\"c\", '4':\"d\", '5':\"e\", '6':\"f\", '7':\"g\", '8':\"h\", '9':\"i\", '10':\"j\", '11':\"k\", '12':\"l\", '13':\"m\", '14':\"n\", '15':\"o\", '16':\"p\", '17':\"q\", '18':\"r\", '19':\"s\", '20':\"t\", '21':\"u\", '22':\"v\", '23':\"w\", '24':\"x\", '25':\"y\", '26':\"z\"}\n\n \n\n \n\ndef transformare_baza(numar,baza):\n\n \n\n transformare=\"\"\n\n while numar>=baza:\n\n rest=numar%baza\n\n numar=numar\/\/baza\n\n transformare+=str(rest)\n\n \n\n transformare+=str(numar)\n\n noua_baza=transformare[::-1]\n\n return noua_baza\n\n \n\n \n\ndef functie_string_baza(stringul,baza):\n\n answ=0\n\n stringul=stringul.lower()\n\n lungime=len(stringul)\n\n for j in range(lungime):\n\n if stringul[j] in alfabet:\n\n answ+=(baza**(lungime-1-j))*(alfabet[stringul[j]]+9)\n\n else:\n\n #print(\"baza=\",baza, lungime-1-j,j)\n\n answ+=(baza**(lungime-1-j))*(int(stringul[j]))\n\n \n\n return (answ)\n\n \n\nfrom decimal import *\n\n \n\nz=int(input())\n\nfor contorr in range(z):\n\n \n\n n,m,k=list(map(int, input().split()))\n\n \n\n bloc=list(map(int, input().split()))\n\n \n\n \n\n vector=[]\n\n start=0\n\n sfarsit=n-1\n\n k=min(k,m-1)\n\n #print(\"k=\",k)\n\n dd=max(bloc)\n\n maximul=-1\n\n \n\n \n\n \n\n for pornire in range(0,k+1):\n\n vector=[]\n\n partialul=dd\n\n \n\n# print(minimul,pornire)\n\n \n\n vector=bloc[pornire:n-(k-pornire)]\n\n #print(\"v=\",vector)\n\n \n\n \n\n target=m-k-1\n\n #print(\"targ=\",target)\n\n \n\n for demaraj in range(0,target+1):\n\n \n\n \n\n last_vector=[]\n\n last_vector=vector[demaraj:len(vector)-(target+1-demaraj)+1]\n\n \n\n partialul=min(partialul,max(last_vector[len(last_vector)-1],last_vector[0]))\n\n \n\n \n\n #print(last_vector,partialul,maximul)\n\n \n\n maximul=max(maximul,partialul) \n\n \n\n \n\n print(maximul) ","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":"import sys\n\ninput = sys.stdin.readline\n\n\n\n\n\nn = int(input())\n\nd = [[] for i in range(n)]\n\nw = []\n\nfor i in range(n-1):\n\n a, b = map(lambda x:int(x)-1, input().split())\n\n d[a].append((b, i))\n\n d[b].append((a, i))\n\n\n\nq = []\n\nfor i in d:\n\n if len(i) >= 3:\n\n q = i\n\n break\n\nif q == []:\n\n for i in range(n-1):\n\n print(i)\n\nelse:\n\n f = set()\n\n c1 = 0\n\n c2 = 3\n\n for i in range(3):\n\n f.add(q[i][1])\n\n for i in range(n-1):\n\n if i in f:\n\n print(c1)\n\n c1 += 1\n\n else:\n\n print(c2)\n\n c2 += 1","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":"n = int(input())\n\noutput = [ ]\n\nfor i in range(n):\n\n A, B = [int(x) for x in input().split()]\n\n\n\n output.append(A * (len(str(B+1)) - 1))\n\n\n\nprint(*output, sep = \"\\n\")","language":"py"} -{"contest_id":"1290","problem_id":"A","statement":"A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n\u22121n\u22121 friends have found an array of integers a1,a2,\u2026,ana1,a2,\u2026,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.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 three space-separated integers nn, mm and kk (1\u2264m\u2264n\u226435001\u2264m\u2264n\u22643500, 0\u2264k\u2264n\u221210\u2264k\u2264n\u22121) \u00a0\u2014 the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109) \u00a0\u2014 elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2\nOutputCopy8\n4\n1\n1\nNoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.","tags":["brute force","data structures","implementation"],"code":"import sys\n\ninput=sys.stdin.readline\n\na = [0 for i in range(3505)]\n\nq = int(input())\n\nfor _ in range(q):\n\n n, m, k = map(int, input().split())\n\n a[1:] = list(map(int, input().split()))\n\n k = min(k, m-1)\n\n re, ans = n-k, 0\n\n for l in range(1, n-re+2):\n\n r, x, len = l + re - 1, int(1e9), n-m+1\n\n for i in range(l, r-len+2):\n\n x = min(x, max(a[i], a[i+len-1]))\n\n ans = max(ans, x)\n\n print(ans)","language":"py"} -{"contest_id":"1288","problem_id":"C","statement":"C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai\u2264biai\u2264bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1\u2264n\u226410001\u2264n\u22641000, 1\u2264m\u2264101\u2264m\u226410).OutputPrint one integer \u2013 the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2\nOutputCopy5\nInputCopy10 1\nOutputCopy55\nInputCopy723 9\nOutputCopy157557417\nNoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. ","tags":["combinatorics","dp"],"code":"mod=int(1e9+7)\n\n\n\ndef read():\n\n\treturn [int(i) for i in input().split()]\n\n\n\n\n\n\"\"\"\n\n\tdp[i][j]: dp[i+x][j-x]\n\n\tnext[i][j]: dp[i][j]+dp[i-1][j]+dp[i][j-1]+dp[i-1][j-1]\n\n\n\n\tincreasing in a, decreasing in b\n\n\n\n\tndp[i][j]: dp[i][j] + dp[i][j+1] + dp[i-1][j]\n\n\n\n\"\"\"\n\n\n\ndef main():\n\n\tn,m=read()\n\n\t# a: increasing, b: decreasing\n\n\t# b[i] >= a[i]\n\n\t# dp:[p][q] : a[i]=p, b[i]=q\n\n\tdp=[[0 for i in range(n+2)] for i in range(n+2)]\n\n\tfor i in range(1,n+1):\n\n\t\tfor j in range(i,n+1):\n\n\t\t\tdp[i][j]=1\n\n\n\n\tfor _ in range(m-1):\n\n\t\tndp=[[0 for i in range(n+2)] for i in range(n+2)]\n\n\t\tfor i in range(1,n+1):\n\n\t\t\tfor j in range(n,i-1,-1):\n\n\t\t\t\tndp[i][j]+=dp[i][j]+ndp[i][j+1]+ndp[i-1][j]-ndp[i-1][j+1]+mod\n\n\t\t\t\tndp[i][j]%=mod\n\n\t\tdp=ndp\n\n\tans=0\n\n\tfor i in range(1,n+1):\n\n\t\tfor j in range(i,n+1):\n\n\t\t\tans=(ans+dp[i][j])%mod\n\n\tprint(ans)\n\n\n\n\n\nmain()","language":"py"} -{"contest_id":"1304","problem_id":"A","statement":"A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x0]) ","language":"py"} -{"contest_id":"1320","problem_id":"B","statement":"B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http:\/\/tk.codeforces.com\/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2\u2264n\u2264m\u22642\u22c51052\u2264n\u2264m\u22642\u22c5105) \u2014 the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2\u2264k\u2264n2\u2264k\u2264n) \u2014 the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1\u2264pi\u2264n1\u2264pi\u2264n, all these integers are pairwise distinct) \u2014 the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i\u2208[1,k\u22121]i\u2208[1,k\u22121] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9\n1 5\n5 4\n1 2\n2 3\n3 4\n4 1\n2 6\n6 4\n4 2\n4\n1 2 3 4\nOutputCopy1 2\nInputCopy7 7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 1\n7\n1 2 3 4 5 6 7\nOutputCopy0 0\nInputCopy8 13\n8 7\n8 6\n7 5\n7 4\n6 5\n6 4\n5 3\n5 2\n4 3\n4 2\n3 1\n2 1\n1 8\n5\n8 7 5 2 1\nOutputCopy0 3\n","tags":["dfs and similar","graphs","shortest paths"],"code":"import bisect\n\nimport collections\n\nimport copy\n\nimport enum\n\nimport functools\n\nimport heapq\n\nimport itertools\n\nimport math\n\nimport random\n\nimport re\n\nimport sys\n\nimport time\n\nimport string\n\nfrom typing import List\n\nsys.setrecursionlimit(3001)\n\n\n\ninput = sys.stdin.readline\n\n\n\nng= collections.defaultdict(list)\n\nsp = collections.defaultdict(list)\n\n\n\nn,m= map(int,input().split())\n\nfor _ in range(m):\n\n u,v = map(int,input().split())\n\n ng[v].append(u)\n\nk = int(input())\n\nks = list(map(int,input().split()))\n\n\n\nq = []\n\nvis=[0]*(n+1)\n\nq.append(ks[-1])\n\nvis[ks[-1]]=1\n\nwhile q:\n\n nxt = set()\n\n for cq in q:\n\n for nq in ng[cq]:\n\n if vis[nq]==0:\n\n sp[nq].append(cq)\n\n nxt.add(nq)\n\n q = list(nxt)\n\n for cq in q:\n\n vis[cq] = 1\n\nmn = 0\n\nmx= 0\n\nfor i in range(1,k):\n\n if ks[i] not in sp[ks[i-1]]:\n\n mn+=1\n\n mx+=1\n\n elif len(sp[ks[i-1]])>1:\n\n mx+=1\n\nprint(mn,mx)\n\n\n\n \n\n\n\n\n\n","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":"t = int(input())\nwhile t > 0:\n t -= 1\n n = int(input())\n s = input()\n ang, mx, cnt = 0, 0, 0\n for i in range(n):\n if s[i] == 'A':\n ang = 1\n mx = max(mx, cnt)\n cnt = 0\n elif ang and s[i] == 'P':\n cnt += 1\n mx = max(mx, cnt)\n print(mx)\n \t \t\t \t\t \t\t\t \t\t \t \t \t\t \t","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":"t = int(input())\n\nfor _ in range(t):\n\n k = int(input())\n\n s = input()\n\n ans = 0\n\n while \"AP\" in s:\n\n s = s.replace(\"AP\", \"AA\")\n\n ans += 1\n\n print(ans)","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":"# template taken from https:\/\/github.com\/cheran-senthil\/PyRival\/blob\/master\/templates\/template.py\n\nimport os\nimport sys\nfrom io import BytesIO, IOBase\nimport math\nfrom heapq import heappop, heappush, heapify, heapreplace\nfrom collections import defaultdict, deque, OrderedDict\nfrom bisect import bisect_left, bisect_right\n#from functools import lru_cache\nimport re\nmod = 1000000007\nmod1 = 998244353\nalpha = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}\n\n\ndef read():\n sys.stdin = open('input.txt', 'r') \n sys.stdout = open('output.txt', 'w') \n\n# ------------------------------------------- Algos --------------------------------------------------------\ndef primeFactors(n):\n arr = []\n l = 0\n while n % 2 == 0:\n arr.append(2)\n l += 1\n n = n \/\/ 2\n for i in range(3,int(math.sqrt(n))+1,2):\n while n % i== 0:\n arr.append(i)\n l += 1\n n = n \/\/ i\n if n > 2:\n arr.append(n)\n l += 1\n return arr\n #return l\ndef primeFactorsSet(n):\n s = set()\n while n % 2 == 0:\n s.add(2)\n n = n \/\/ 2\n for i in range(3,int(math.sqrt(n))+1,2):\n while n % i== 0:\n s.add(i)\n n = n \/\/ i\n if n > 2:\n s.add(n)\n return s\ndef sieve(n):\n res=[0 for i in range(n+1)]\n #prime=set([])\n prime=[]\n for i in range(2,n+1):\n if not res[i]:\n #prime.add(i)\n prime.append(i)\n for j in range(1,n\/\/i+1):\n res[i*j]=1\n return prime\ndef isPrime(n) : # Check Prime Number or not \n if (n <= 1) : return False\n if (n <= 3) : return True\n if (n % 2 == 0 or n % 3 == 0) : return False\n i = 5\n while(i * i <= n) : \n if (n % i == 0 or n % (i + 2) == 0) : \n return False\n i = i + 6\n return True\ndef countPrimesLessThanN(n):\n seen, ans = [0] * n, 0\n for num in range(2, n):\n if seen[num]: continue\n ans += 1\n seen[num*num:n:num] = [1] * ((n - 1) \/\/ num - num + 1)\n return ans\ndef gcd(x, y):\n return math.gcd(x, y)\ndef lcm(a,b):\n return (a \/\/ gcd(a,b))* b\ndef isBitSet(n,k):\n # returns the count of numbers up to N having K-th bit set.\n res = (n >> (k + 1)) << k\n if ((n >> k) & 1):\n res += n & ((1 << k) - 1)\n return res\ndef popcount(x):\n x = x - ((x >> 1) & 0x55555555)\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n x = (x + (x >> 4)) & 0x0f0f0f0f\n x = x + (x >> 8)\n x = x + (x >> 16)\n return x & 0x0000007f\ndef modular_exponentiation(x, y, p): #returns (x^y)%p\n res = 1\n x = x % p\n if (x == 0) :\n return 0\n while (y > 0) :\n if ((y & 1) == 1) :\n res = (res * x) % p\n y = y >> 1\n x = (x * x) % p\n return res\ndef nCr(n, r, p): # returns nCr % p\n num = den = 1\n for i in range(r):\n num = (num * (n - i)) % p\n den = (den * (i + 1)) % p\n return (num * pow(den,\n p - 2, p)) % p\ndef smallestDivisor(n):\n if (n % 2 == 0):\n return 2\n i = 3\n while(i * i <= n):\n if (n % i == 0):\n return i\n i += 2\n return n\ndef numOfDivisors(n):\n def pf(n):\n dic = defaultdict(int)\n while n % 2 == 0:\n dic[2] += 1\n n = n \/\/ 2\n for i in range(3,int(math.sqrt(n))+1,2):\n while n % i== 0:\n dic[i] += 1\n n = n \/\/ i\n if n > 2:\n dic[n] += 1\n return dic\n p = pf(n)\n ans = 1\n for item in p:\n ans *= (p[item] + 1)\n return ans\ndef SPF(spf, MAXN):\n spf[1] = 1\n for i in range(2, MAXN):\n spf[i] = i\n for i in range(4, MAXN, 2):\n spf[i] = 2\n for i in range(3, math.ceil(math.sqrt(MAXN))):\n if (spf[i] == i):\n for j in range(i * i, MAXN, i):\n if (spf[j] == j):\n spf[j] = i\n# A O(log n) function returning prime\n# factorization by dividing by smallest\n# prime factor at every step\ndef factorizationInLogN(x, spf):\n ret = list()\n while (x != 1):\n ret.append(spf[x])\n x = x \/\/ spf[x]\n return ret\n\n'''MAXN = 10000001\nspf = spf = [0 for i in range(MAXN)]\n\nSPF(spf, MAXN)'''\n\nclass DisjointSetUnion:\n def __init__(self, n):\n self.parent = list(range(n))\n self.size = [1] * n\n self.num_sets = n\n\n def find(self, a):\n acopy = a\n while a != self.parent[a]:\n a = self.parent[a]\n while acopy != a:\n self.parent[acopy], acopy = a, self.parent[acopy]\n return a\n\n def union(self, a, b):\n a, b = self.find(a), self.find(b)\n if a == b:\n return False\n if self.size[a] < self.size[b]:\n a, b = b, a\n self.num_sets -= 1\n self.parent[b] = a\n self.size[a] += self. size[b]\n return True\n\n def set_size(self, a):\n return self.size[self.find(a)]\n\n def __len__(self):\n return self.num_sets\n#a = sorted(range(n), key=arr.__getitem__)\n# -------------------------------------------------- code -------------------------------------------------\n\ndef nc2(n):\n return (n*(n+1))\/\/2\n\ndef main():\n \n t = int(input())\n for _ in range(t):\n n,m = map(int, input().split())\n\n x = n-m\n\n k = x\/\/(m+1)\n\n ans = nc2(n) - ((nc2(k)*((m+1)-(x%(m+1)))) + (nc2(k+1)*(x%(m+1))))\n\n print(ans)\n\n\n# ---------------------------------------------- region fastio ---------------------------------------------\nBUFSIZE = 8192\n\n\nclass FastIO(IOBase):\n newlines = 0\n\n def __init__(self, file):\n self._fd = file.fileno()\n self.buffer = BytesIO()\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n while True:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n if not b:\n break\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines = 0\n return self.buffer.read()\n\n def readline(self):\n while self.newlines == 0:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n self.newlines = b.count(b\"\\n\") + (not b)\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines -= 1\n return self.buffer.readline()\n\n def flush(self):\n if self.writable:\n os.write(self._fd, self.buffer.getvalue())\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\nclass IOWrapper(IOBase):\n def __init__(self, file):\n self.buffer = FastIO(file)\n self.flush = self.buffer.flush\n self.writable = self.buffer.writable\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n# -------------------------------------------------- end region ---------------------------------------------\n\nif __name__ == \"__main__\":\n #read()\n main()","language":"py"} -{"contest_id":"13","problem_id":"E","statement":"E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game \u00abHoles\u00bb. This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i\u2009+\u2009ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1\u2009\u2264\u2009N\u2009\u2264\u2009105, 1\u2009\u2264\u2009M\u2009\u2264\u2009105) \u2014 the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N \u2014 initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line \u2014 the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3","tags":["data structures","dsu"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nn, m = map(int, input().split())\n\np = list(map(int, input().split()))\n\n\n\nBLOCK_LENGTH = 350\n\nblock = [i\/\/BLOCK_LENGTH for i in range(n)]\n\n\n\njumps = [0] * n\n\nend = [0] * n\n\n\n\nfor i in range(n - 1, -1, -1):\n\n nex = i + p[i]\n\n if nex >= n:\n\n jumps[i] = 1\n\n end[i] = i + n\n\n elif block[nex] > block[i]:\n\n jumps[i] = 1\n\n end[i] = nex\n\n else:\n\n jumps[i] = jumps[nex] + 1\n\n end[i] = end[nex]\n\n \n\nout = []\n\nfor _ in range(m):\n\n #print(jumps)\n\n #print(end)\n\n #print(block)\n\n s = input().strip()\n\n if s[0] == '0':\n\n _,a,b = s.split()\n\n a = int(a) - 1\n\n b = int(b)\n\n \n\n p[a] = b\n\n i = a\n\n while i >= 0 and block[i] == block[a]:\n\n nex = i + p[i]\n\n if nex >= n:\n\n jumps[i] = 1\n\n end[i] = i + n\n\n elif block[nex] > block[i]:\n\n jumps[i] = 1\n\n end[i] = nex\n\n else:\n\n jumps[i] = jumps[nex] + 1\n\n end[i] = end[nex]\n\n i -= 1\n\n else:\n\n _,a = s.split()\n\n curr = int(a) - 1\n\n jmp = 0\n\n while curr < n:\n\n jmp += jumps[curr]\n\n curr = end[curr]\n\n out.append(str(curr - n + 1)+' '+str(jmp))\n\nprint('\\n'.join(out))","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":"from sys import stdin\n\ninput = stdin.readline\n\n\n\nu, v = [int(x) for x in input().split()]\n\n\n\nif u > v or (v-u)%2 == 1: print(-1)\n\nelif u == v == 0: print(0)\n\nelif u == v: print(1); print(u)\n\nelse:\n\n x = (v-u)\/\/2\n\n # if ((u+x)^x) == u and u+x+x == v: print(2); print(u+x, x)\n\n if (u&x) == 0: print(2); print(u+x, x)\n\n else: print(3); print(u, x, x)\n\n\n\n# https:\/\/blog.csdn.net\/weixin_44668898\/article\/details\/104891186","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":"t=int(input())\n\nfor i in range(t):\n\n a,b=map(int,input().split())\n\n print(a*(len(str(b+1))-1))\n\n","language":"py"} -{"contest_id":"1290","problem_id":"B","statement":"B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k\u22652k\u22652 and 2k2k non-empty strings s1,t1,s2,t2,\u2026,sk,tks1,t1,s2,t2,\u2026,sk,tk that satisfy the following conditions: If we write the strings s1,s2,\u2026,sks1,s2,\u2026,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,\u2026,tkt1,t2,\u2026,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= \"gamegame\". Then the string t=t= \"megamage\" is a reducible anagram of ss, we may choose for example s1=s1= \"game\", s2=s2= \"gam\", s3=s3= \"e\" and t1=t1= \"mega\", t2=t2= \"mag\", t3=t3= \"e\": On the other hand, we can prove that t=t= \"memegaga\" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1\u2264|s|\u22642\u22c51051\u2264|s|\u22642\u22c5105).The second line contains a single integer qq (1\u2264q\u22641051\u2264q\u2264105) \u00a0\u2014 the number of queries.Each of the following qq lines contain two integers ll and rr (1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing \"Yes\" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing \"No\" (without quotes) otherwise.ExamplesInputCopyaaaaa\n3\n1 1\n2 4\n5 5\nOutputCopyYes\nNo\nYes\nInputCopyaabbbbbbc\n6\n1 2\n2 4\n2 2\n1 9\n5 7\n3 5\nOutputCopyNo\nYes\nYes\nYes\nNo\nNo\nNoteIn the first sample; in the first and third queries; the substring is \"a\"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain \"a\". On the other hand; in the second query, the substring is \"aaa\", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= \"a\", s2=s2= \"aa\", t1=t1= \"a\", t2=t2= \"aa\" to show that it is a reducible anagram.In the second query of the second sample, the substring is \"abb\", which has, for example, \"bba\" as an irreducible anagram.","tags":["binary search","constructive algorithms","data structures","strings","two pointers"],"code":"def charToInt(c): #'a'->0\n\n return ord(c)-ord('a')\n\n\n\ndef main():\n\n \n\n s=input()\n\n n=len(s)\n\n arr=[charToInt(c) for c in s]\n\n \n\n p=makeArr(0,n,26)\n\n for i in range(n):\n\n p[i][arr[i]]+=1\n\n for i in range(1,n):\n\n for j in range(26):\n\n p[i][j]+=p[i-1][j]\n\n \n\n def getCnts(char,l,r):\n\n if l==0: return p[r][char]\n\n else: return p[r][char]-p[l-1][char]\n\n \n\n allans=[]\n\n q=int(input())\n\n for _ in range(q):\n\n l,r=readIntArr()\n\n l-=1\n\n r-=1\n\n charTypeCnt=0\n\n for j in range(26):\n\n if getCnts(j,l,r)>0:\n\n charTypeCnt+=1\n\n if l==r:\n\n allans.append('Yes')\n\n elif charTypeCnt==1:\n\n allans.append('No')\n\n elif charTypeCnt==2:\n\n if arr[l]==arr[r]:\n\n allans.append('No')\n\n else:\n\n allans.append('Yes') # swap both sides\n\n else: # more than 2 types\n\n allans.append('Yes')\n\n multiLineArrayPrint(allans)\n\n \n\n return\n\n \n\nimport sys\n\n# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)\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":"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":"import bisect\n\nimport copy\n\nimport gc\n\nimport itertools\n\nfrom array import array\n\nfrom fractions import Fraction\n\nimport heapq\n\nimport math\n\nimport operator\n\nimport os, sys\n\nimport profile\n\nimport cProfile\n\nimport random\n\nimport re\n\nimport string\n\nfrom bisect import bisect_left, bisect_right\n\nfrom collections import defaultdict, deque, Counter\n\nfrom functools import reduce, lru_cache\n\nfrom io import IOBase, BytesIO\n\nfrom itertools import count, groupby, accumulate, permutations, combinations_with_replacement, product\n\nfrom math import gcd\n\nfrom operator import xor, add\n\nfrom typing import List\n\n\n\n\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\n\n\n# print = lambda d: sys.stdout.write(str(d)+\"\\n\")\n\ndef read_int_list(): return list(map(int, input().split()))\n\ndef read_int_tuple(): return tuple(map(int, input().split()))\n\ndef read_int(): return int(input())\n\n\n\n\n\n# endregion\n\n\n\n\n\nif 'AW' in os.environ.get('COMPUTERNAME', ''):\n\n f = open('inputs', 'r')\n\n def input(): return f.readline().rstrip(\"\\r\\n\")\n\n\n\n# sys.setrecursionlimit(500005)\n\n\n\ndef solve(n, nums):\n\n res = 0\n\n q = []\n\n for x in nums:\n\n heapq.heappush(q, -x)\n\n if q and x < -q[0]:\n\n res += -heapq.heapreplace(q, -x) - x\n\n print(res)\n\n\n\n\n\ndef main():\n\n for _ in range(1):\n\n n = read_int()\n\n nums = read_int_list()\n\n solve(n, nums)\n\n\n\nif __name__ == \"__main__\":\n\n main()\n\n# cProfile.run(\"main()\")\n\n","language":"py"} -{"contest_id":"1321","problem_id":"A","statement":"A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, \"Robo-Coder Inc.\" and \"BionicSolver Industries\", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results \u2014 or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the \"Robo-Coder Inc.\" robot to outperform the \"BionicSolver Industries\" robot in the competition. Polycarp wants to set the values of pipi in such a way that the \"Robo-Coder Inc.\" robot gets strictly more points than the \"BionicSolver Industries\" robot. However, if the values of pipi will be large, it may look very suspicious \u2014 so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0\u2264ri\u226410\u2264ri\u22641). ri=1ri=1 means that the \"Robo-Coder Inc.\" robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0\u2264bi\u226410\u2264bi\u22641). bi=1bi=1 means that the \"BionicSolver Industries\" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf \"Robo-Coder Inc.\" robot cannot outperform the \"BionicSolver Industries\" robot by any means, print one integer \u22121\u22121.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the \"Robo-Coder Inc.\" robot gets strictly more points than the \"BionicSolver Industries\" robot.ExamplesInputCopy5\n1 1 1 0 0\n0 1 1 1 1\nOutputCopy3\nInputCopy3\n0 0 0\n0 0 0\nOutputCopy-1\nInputCopy4\n1 1 1 1\n1 1 1 1\nOutputCopy-1\nInputCopy9\n1 0 0 0 0 0 0 0 1\n0 1 1 0 1 1 1 1 0\nOutputCopy4\nNoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the \"Robo-Coder\" gets 77 points, the \"BionicSolver\" \u2014 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.","tags":["greedy"],"code":"i=lambda:input().split()\n\ni();a,b=i(),i();c=d=0\n\nfor i,x in enumerate(a):c+=x>b[i];d+=b[i]>x\n\nprint([[1--(d+1-c)\/\/max(1,c),1][c>d],-1][c<1])","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":"#!\/usr\/bin\/env python\nimport os\nimport sys\nfrom io import BytesIO, IOBase\n\n\ndef main():\n t = int(input())\n\n for _ in range(t):\n n, s = input().split()\n n = int(n)\n\n hi, prev = n, 0\n mi = [0] * n\n for i in range(n):\n if i == n - 1 or s[i] == '>':\n for j in reversed(range(prev, i + 1)):\n mi[j] = hi\n hi -= 1\n prev = i + 1\n\n print(*mi)\n\n lo, hi = -1, 1\n ma = [0] * n\n for i in range(n - 1):\n if s[i] == '<':\n ma[i + 1] = hi\n hi += 1\n else:\n ma[i + 1] = lo\n lo -= 1\n ma = [i - lo for i in ma]\n\n print(*ma)\n\n\n# region fastio\n\nBUFSIZE = 8192\n\n\nclass FastIO(IOBase):\n newlines = 0\n\n def __init__(self, file):\n self._fd = file.fileno()\n self.buffer = BytesIO()\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n while True:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n if not b:\n break\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines = 0\n return self.buffer.read()\n\n def readline(self):\n while self.newlines == 0:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n self.newlines = b.count(b\"\\n\") + (not b)\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines -= 1\n return self.buffer.readline()\n\n def flush(self):\n if self.writable:\n os.write(self._fd, self.buffer.getvalue())\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\nclass IOWrapper(IOBase):\n def __init__(self, file):\n self.buffer = FastIO(file)\n self.flush = self.buffer.flush\n self.writable = self.buffer.writable\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n# endregion\n\nif __name__ == \"__main__\":\n main()\n","language":"py"} -{"contest_id":"1296","problem_id":"E2","statement":"E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard 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 the minimum number of 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 find the minimum number of colors which you have to color the given string in 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\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1\u2264res\u2264n1\u2264res\u2264n) \u2014 the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1\u2264ci\u2264res1\u2264ci\u2264res and cici means the color of the ii-th character.ExamplesInputCopy9\nabacbecfd\nOutputCopy2\n1 1 2 1 2 1 2 1 2 \nInputCopy8\naaabbcbb\nOutputCopy2\n1 2 1 2 1 2 1 1\nInputCopy7\nabcdedc\nOutputCopy3\n1 1 1 1 1 2 3 \nInputCopy5\nabcde\nOutputCopy1\n1 1 1 1 1 \n","tags":["data structures","dp"],"code":"from collections import defaultdict, Counter,deque\n\nfrom math import sqrt, log10, log, floor, factorial,gcd\n\nfrom bisect import bisect_left, bisect_right\n\nfrom itertools import permutations,combinations\n\nimport sys, io, os\n\ninput = sys.stdin.readline\n\n# input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline\n\n# sys.setrecursionlimit(10000)\n\ninf = float('inf')\n\nmod = 10 ** 9 + 7\n\ndef get_list(): return [int(i) for i in input().split()]\n\ndef yn(a): print(\"YES\" if a else \"NO\")\n\nceil = lambda a, b: (a + b - 1) \/\/ b\n\ndef lis_length(nums, cmp=lambda x, y: x < y):\n\n P = [0] * len(nums)\n\n M = [0] * (len(nums) + 1)\n\n L = 0\n\n\n\n for i in range(len(nums)):\n\n lo, hi = 1, L\n\n\n\n while lo <= hi:\n\n mid = (lo + hi) \/\/ 2\n\n if cmp(nums[M[mid]], nums[i]):\n\n lo = mid + 1\n\n else:\n\n hi = mid - 1\n\n\n\n newL = lo\n\n P[i] = M[newL - 1]\n\n M[newL] = i\n\n\n\n L = max(L, newL)\n\n\n\n lislen=[1 for i in P]\n\n for i in range(1,len(nums)):\n\n if P[i]==0:\n\n if cmp(nums[P[i]],nums[i]):\n\n lislen[i]=lislen[P[i]]+1\n\n else:\n\n lislen[i]=lislen[P[i]]\n\n else:\n\n lislen[i] = lislen[P[i]] + 1\n\n return lislen\n\nt=1\n\nfor i in range(t):\n\n n=int(input())\n\n s=input().strip()\n\n lislen=lis_length(s[::-1])[::-1]\n\n print(max(lislen))\n\n print(*lislen)\n\n","language":"py"} -{"contest_id":"1290","problem_id":"B","statement":"B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k\u22652k\u22652 and 2k2k non-empty strings s1,t1,s2,t2,\u2026,sk,tks1,t1,s2,t2,\u2026,sk,tk that satisfy the following conditions: If we write the strings s1,s2,\u2026,sks1,s2,\u2026,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,\u2026,tkt1,t2,\u2026,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= \"gamegame\". Then the string t=t= \"megamage\" is a reducible anagram of ss, we may choose for example s1=s1= \"game\", s2=s2= \"gam\", s3=s3= \"e\" and t1=t1= \"mega\", t2=t2= \"mag\", t3=t3= \"e\": On the other hand, we can prove that t=t= \"memegaga\" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1\u2264|s|\u22642\u22c51051\u2264|s|\u22642\u22c5105).The second line contains a single integer qq (1\u2264q\u22641051\u2264q\u2264105) \u00a0\u2014 the number of queries.Each of the following qq lines contain two integers ll and rr (1\u2264l\u2264r\u2264|s|1\u2264l\u2264r\u2264|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing \"Yes\" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing \"No\" (without quotes) otherwise.ExamplesInputCopyaaaaa\n3\n1 1\n2 4\n5 5\nOutputCopyYes\nNo\nYes\nInputCopyaabbbbbbc\n6\n1 2\n2 4\n2 2\n1 9\n5 7\n3 5\nOutputCopyNo\nYes\nYes\nYes\nNo\nNo\nNoteIn the first sample; in the first and third queries; the substring is \"a\"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain \"a\". On the other hand; in the second query, the substring is \"aaa\", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= \"a\", s2=s2= \"aa\", t1=t1= \"a\", t2=t2= \"aa\" to show that it is a reducible anagram.In the second query of the second sample, the substring is \"abb\", which has, for example, \"bba\" as an irreducible anagram.","tags":["binary search","constructive algorithms","data structures","strings","two pointers"],"code":"# Legends Always Come Up with Solution\n\n# Author: Manvir Singh\n\n\n\nimport os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\n\n\ndef main():\n\n s=input().rstrip()\n\n n=len(s)\n\n dp=[[0 for _ in range(26)] for _ in range(n+1)]\n\n for i,v in enumerate(s):\n\n dp[i+1][ord(v)-97]=1\n\n for j in range(26):\n\n dp[i+1][j]+=dp[i][j]\n\n for _ in range(int(input())):\n\n l,r=map(int,input().split())\n\n if r-l+1==1:\n\n print(\"Yes\")\n\n elif s[l-1]!=s[r-1]:\n\n print(\"Yes\")\n\n else:\n\n z=0\n\n for i in range(26):\n\n z+=(dp[r][i]>dp[l-1][i])\n\n if z>2:\n\n print(\"Yes\")\n\n else:\n\n print(\"No\")\n\n# region fastio\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 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\n\nif __name__ == \"__main__\":\n\n main()","language":"py"} -{"contest_id":"1284","problem_id":"A","statement":"A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (\uacbd\uc790\ub144; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,\u2026,sns1,s2,s3,\u2026,sn and mm strings t1,t2,t3,\u2026,tmt1,t2,t3,\u2026,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings \"code\" and \"forces\" is the string \"codeforces\".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={\"a\", \"b\", \"c\"}, t=t= {\"d\", \"e\", \"f\", \"g\"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1\u2264n,m\u2264201\u2264n,m\u226420).The next line contains nn strings s1,s2,\u2026,sns1,s2,\u2026,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,\u2026,tmt1,t2,\u2026,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1\u2264q\u226420201\u2264q\u22642020).In the next qq lines, an integer yy (1\u2264y\u22641091\u2264y\u2264109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020\nOutputCopysinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja\nNoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.","tags":["implementation","strings"],"code":"import math\n\nn, m = [int(x) for x in input().split()]\n\ns, t = input().split(), input().split()\n\n\n\nlowermn = min(n, m)\n\n\n\nip = int(input())\n\n\n\nfor _ in range(ip):\n\n year = int(input()) - 1\n\n print(s[year%n] + t[year%m])\n\n ","language":"py"} -{"contest_id":"1324","problem_id":"C","statement":"C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2\u2026sns=s1s2\u2026sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i\u2212d);i\u22121][max(0,i\u2212d);i\u22121], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.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. The ii-th test case is described as a string ss consisting of at least 11 and at most 2\u22c51052\u22c5105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211|s|\u22642\u22c5105\u2211|s|\u22642\u22c5105).OutputFor each test case, print the answer \u2014 the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6\nLRLRRLL\nL\nLLR\nRRRR\nLLLLLL\nR\nOutputCopy3\n2\n3\n1\n7\n1\nNoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.","tags":["binary search","data structures","dfs and similar","greedy","implementation"],"code":"for i in range(int(input())):\n\n l = input().split(\"R\")\n\n l.sort()\n\n print(len(l[-1])+1)","language":"py"} -{"contest_id":"1322","problem_id":"C","statement":"C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1\u2264t\u22645000001\u2264t\u2264500000)\u00a0\u2014 the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1\u00a0\u2264\u00a0n,\u00a0m\u00a0\u2264\u00a05000001\u00a0\u2264\u00a0n,\u00a0m\u00a0\u2264\u00a0500000)\u00a0\u2014 the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1\u2264ci\u226410121\u2264ci\u22641012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1\u2264ui,vi\u2264n1\u2264ui,vi\u2264n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer\u00a0\u2014 the required greatest common divisor.ExampleInputCopy3\n2 4\n1 1\n1 1\n1 2\n2 1\n2 2\n\n3 4\n1 1 1\n1 1\n1 2\n2 2\n2 3\n\n4 7\n36 31 96 29\n1 2\n1 3\n1 4\n2 2\n2 4\n3 1\n4 3\nOutputCopy2\n1\n12\nNoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.","tags":["graphs","hashing","math","number theory"],"code":"import sys\n\ninput = sys.stdin.buffer.readline \n\n\n\n\n\n\n\n\n\ndef gcd(a, b):\n\n if a > b:\n\n a, b = b, a\n\n if b % a==0:\n\n return a\n\n return gcd(b % a, a)\n\n\n\n\n\nt = int(input())\n\nfor i in range(t):\n\n n, m = [int(x) for x in input().split()]\n\n C = [int(x) for x in input().split()]\n\n G = []\n\n for j in range(m):\n\n u, v = [int(x) for x in input().split()]\n\n G.append([u, v])\n\n g1 = [0 for i in range(n+1)]\n\n g2 = [0 for i in range(n+1)]\n\n if n >= 100:\n\n p1 = 1039\n\n p2 = 1489\n\n else:\n\n p1 = 13\n\n p2 = 17\n\n for u, v in G:\n\n g1[v] = (g1[v]+pow(2, u, p1)) % p1\n\n g2[v] = (g2[v]+pow(2, u, p2)) % p2\n\n p1_list = [0 for i in range(p1)]\n\n p2_list = [0 for i in range(p2)]\n\n R = []\n\n g_final = None\n\n for v in range(1, n+1):\n\n x1 = g1[v]\n\n x2 = g2[v]\n\n if [x1, x2] != [0, 0]:\n\n p1_list[x1]+=C[v-1]\n\n p2_list[x2]+=C[v-1]\n\n for i in range(p1):\n\n if p1_list[i] != 0:\n\n if g_final is None:\n\n g_final = p1_list[i]\n\n else:\n\n g_final = gcd(g_final, p1_list[i])\n\n for i in range(p2):\n\n if p2_list[i] != 0:\n\n if g_final is None:\n\n g_final = p2_list[i]\n\n else:\n\n g_final = gcd(g_final, p2_list[i])\n\n sys.stdout.write(f'{g_final}\\n')\n\n input()\n\n","language":"py"} -{"contest_id":"1141","problem_id":"A","statement":"A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays \"Game 23\". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1\u2264n\u2264m\u22645\u22c51081\u2264n\u2264m\u22645\u22c5108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840\nOutputCopy7\nInputCopy42 42\nOutputCopy0\nInputCopy48 72\nOutputCopy-1\nNoteIn the first example; the possible sequence of moves is: 120\u2192240\u2192720\u21921440\u21924320\u219212960\u219225920\u219251840.120\u2192240\u2192720\u21921440\u21924320\u219212960\u219225920\u219251840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.","tags":["implementation","math"],"code":"def main(list):\n\n res = 0\n\n if list[1]%list[0]!=0:\n\n return -1\n\n else:\n\n k = list[1]\/\/list[0]\n\n while k>1:\n\n if k%3==0: \n\n k\/\/=3\n\n res+=1\n\n elif k%2==0:\n\n k\/\/=2\n\n res+=1\n\n else:\n\n return -1\n\n return res\n\n \n\n\n\nprint(main([int(i) for i in input().split()]))","language":"py"} -{"contest_id":"1304","problem_id":"A","statement":"A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x0]) \n\n","language":"py"} -{"contest_id":"1288","problem_id":"C","statement":"C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai\u2264biai\u2264bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1\u2264n\u226410001\u2264n\u22641000, 1\u2264m\u2264101\u2264m\u226410).OutputPrint one integer \u2013 the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2\nOutputCopy5\nInputCopy10 1\nOutputCopy55\nInputCopy723 9\nOutputCopy157557417\nNoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1]. ","tags":["combinatorics","dp"],"code":"from math import comb as c\n\nn, m = map(int, input().split())\n\nprint(c(n + 2 * m - 1, 2 * m) % 1000000007)\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":"from math import ceil\n\nH,n=map(int,input().split())\n\narray=list(map(int,input().split()))\n\ncumsum=[array[0]]\n\nminm=array[0]\n\nfor i in range(1,n):\n\n val=cumsum[-1]+array[i]\n\n minm=min(minm,val)\n\n cumsum.append(val)\n\nif cumsum[-1]>=0:\n\n if minm+H>0:\n\n print(-1)\n\n else:\n\n for i in range(n):\n\n if cumsum[i]+H<=0:\n\n print(i+1)\n\n break\n\nelse:\n\n v=H+minm\n\n if v<=0:\n\n for i in range(n):\n\n if cumsum[i] + H <= 0:\n\n print(i + 1)\n\n break\n\n else:\n\n round=ceil(v\/(cumsum[-1]*(-1)))\n\n ans=H+(cumsum[-1]*round)\n\n for i in range(n):\n\n if cumsum[i]+ans<=0:\n\n print(n*round+i+1)\n\n break","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 aj0:\n\n possible[0]=False\n\n val=1\n\n # \"push\" all larger values than val by 1\n\n for zz in range(1,n+1):\n\n if a[zz]>=val:\n\n a[zz]+=1\n\n a[i]=val\n\n # print('leaf:{} a:{}'.format(i,a))\n\n yield [i]\n\n else:\n\n requiredCnts=c[i]\n\n childNodes=[]\n\n for child in children[i]:\n\n for node in (yield dfs(child)):\n\n childNodes.append(node)\n\n if requiredCnts>len(childNodes):\n\n possible[0]=False\n\n yield [] # impossible\n\n childVals=[a[node] for node in childNodes]\n\n childVals.sort()\n\n if requiredCnts==0:\n\n val=1\n\n else:\n\n val=childVals[requiredCnts-1]+1\n\n # \"push\" all larger values than val by 1\n\n for zz in range(1,n+1):\n\n if a[zz]>=val:\n\n a[zz]+=1\n\n \n\n # print('childVals before:{}'.format(childVals))\n\n childVals.append(val)\n\n childNodes.append(i)\n\n a[i]=val\n\n # print('marked i:{} val:{} childVals:{} a:{}'.format(i,val,childVals,a))\n\n yield childNodes\n\n yield []\n\n \n\n possible=[True]\n\n a=[-1 for _ in range(n+1)]\n\n dfs(root)\n\n # print('root:{}'.format(root))\n\n if possible[0]:\n\n print('YES')\n\n ans=a[1:]\n\n oneLineArrayPrint(ans)\n\n else:\n\n print('NO')\n\n return\n\n \n\nimport sys\n\ninput=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)\n\n# input=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(defaultVal,dimensionArr): # eg. makeArr(0,[n,m])\n\n dv=defaultVal;da=dimensionArr\n\n if len(da)==1:return [dv for _ in range(da[0])]\n\n else:return [makeArr(dv,da[1:]) for _ in range(da[0])]\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\n\n\nfor _abc in range(1):\n\n main()","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= 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":"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 os, sys\nfrom io import BytesIO, IOBase\nfrom math import log2, ceil, sqrt, gcd\nfrom _collections import deque\nimport heapq as hp\nfrom bisect import bisect_left, bisect_right\nfrom math import cos, sin\nfrom itertools import permutations\n \n# sys.setrecursionlimit(2*10**5+10000)\nBUFSIZE = 8192\n \n \nclass FastIO(IOBase):\n newlines = 0\n \n def __init__(self, file):\n self._fd = file.fileno()\n self.buffer = BytesIO()\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n self.write = self.buffer.write if self.writable else None\n \n def read(self):\n while True:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n if not b:\n break\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines = 0\n return self.buffer.read()\n \n def readline(self):\n while self.newlines == 0:\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n self.newlines = b.count(b\"\\n\") + (not b)\n ptr = self.buffer.tell()\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n self.newlines -= 1\n return self.buffer.readline()\n \n def flush(self):\n if self.writable:\n os.write(self._fd, self.buffer.getvalue())\n self.buffer.truncate(0), self.buffer.seek(0)\n \n \nclass IOWrapper(IOBase):\n def __init__(self, file):\n self.buffer = FastIO(file)\n self.flush = self.buffer.flush\n self.writable = self.buffer.writable\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n \n \nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n \nmod = (10 ** 9 + 7) # ^ 1755654\n \n \ndef divi(ar, i):\n # print(i,ar)\n ar1 = []\n ar2 = []\n for j in ar:\n if j & (1 << i):\n ar1.append(j)\n else:\n ar2.append(j)\n # print(ar1,ar2)\n if not ar1 or not ar2:\n if ar1 and i - 1 >= 0:\n return divi(ar1, i - 1)\n if ar2 and i - 1 >= 0:\n return divi(ar2, i - 1)\n return 0\n if i - 1 >= 0:\n return (1 << i) + min(divi(ar1, i - 1), divi(ar2, i - 1))\n else:\n return 1 << i\n \n \nn = int(input())\na = list(map(int, input().split()))\nprint(divi(a, 30))","language":"py"} -{"contest_id":"1303","problem_id":"C","statement":"C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him \u2014 his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1\u2264T\u226410001\u2264T\u22641000) \u2014 the number of test cases.Then TT lines follow, each containing one string ss (1\u2264|s|\u22642001\u2264|s|\u2264200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters \u2014 the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5\nababa\ncodedoca\nabcda\nzxzytyz\nabcdefghijklmnopqrstuvwxyza\nOutputCopyYES\nbacdefghijklmnopqrstuvwxyz\nYES\nedocabfghijklmnpqrstuvwxyz\nNO\nYES\nxzytabcdefghijklmnopqrsuvw\nNO\n","tags":["dfs and similar","greedy","implementation"],"code":"# Online Python compiler (interpreter) to run Python online.\n\n# Write Python 3 code in this online editor and run it.\n\nimport sys\n\ninput = sys.stdin.readline\n\nfrom collections import defaultdict\n\nfrom collections import Counter\n\nfrom string import ascii_lowercase \n\nfrom functools import lru_cache\n\nfrom collections import deque\n\nimport heapq\n\n\n\nsys.setrecursionlimit(100000)\n\n############ ---- Input Functions ---- ############\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\ncases = inp()\n\nfor case in range(cases):\n\n loved = defaultdict(set)\n\n s = input().strip()\n\n if len(s) == 1:\n\n print(\"YES\")\n\n print(\"xzytabcdefghijklmnopqrsuvw\")\n\n continue\n\n \n\n test = False\n\n for i in range(len(s)-1):\n\n loved[s[i]].add(s[i+1])\n\n loved[s[i+1]].add(s[i])\n\n if len(loved[s[i]]) > 2 or len(loved[s[i+1]]) > 2:\n\n test = True\n\n break\n\n \n\n \n\n if test:\n\n print(\"NO\")\n\n continue\n\n \n\n que = deque()\n\n ans = \"\"\n\n for key in loved:\n\n if len(loved[key]) == 1:\n\n que.append(key)\n\n \n\n # print(que)\n\n if len(que) == 0:\n\n print(\"NO\")\n\n continue\n\n \n\n visited = set()\n\n def dfs(char):\n\n ans.append(char)\n\n for c in loved[char]:\n\n if c not in visited:\n\n visited.add(c)\n\n dfs(c)\n\n \n\n \n\n ans = []\n\n sest = set()\n\n for cs in que:\n\n if cs not in visited:\n\n visited.add(cs)\n\n dfs(cs)\n\n \n\n \n\n sth = \"xzytabcdefghijklmnopqrsuvw\"\n\n \n\n ans = \"\".join(ans)\n\n for j in ans:\n\n sest.add(j)\n\n \n\n for i in sth:\n\n if i not in sest:\n\n ans += i\n\n sest.add(i)\n\n \n\n print(\"YES\")\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 \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":"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 = int(input())\n arr = list(map(int, input().split(' ')))\n if n == 1:\n print('Yes')\n continue\n left, right = [], []\n cntL, cntR = 0, 0\n for i in range(n):\n if arr[i] >= i:\n cntL += 1\n if arr[n-1-i] >= i:\n cntR += 1\n left.append(cntL)\n right.append(cntR)\n right = right[::-1]\n k = 0\n ans = 'No'\n while k < n-1:\n if left[k] + right[k+1] == n:\n if arr[k] != arr[k+1]:\n ans = 'Yes'\n break\n elif arr[k]-1 > k or arr[k+1] > n-k-2:\n ans = 'Yes'\n break \n \n k += 1\n print(ans)","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":"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.readline().strip('\\n')\n\nmis=lambda:map(int,input().split())\n\nii=lambda:int(input())\n\n#sys.setrecursionlimit(5*(10 ** 3))\n\n\n\nT = ii()\n\nfor _ in range(T):\n\n N = ii()\n\n S = input()\n\n strs = []\n\n for k in range(1, N+1):\n\n if (N-k+1) % 2 == 0:\n\n strs.append((S[k-1:] + S[:k-1], k))\n\n else:\n\n strs.append((S[k-1:] + S[:k-1][::-1], k))\n\n strs.sort()\n\n print(strs[0][0])\n\n print(strs[0][1])\n\n \n\n\n\n\n\n\n\n\n\n","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":"def solve():\n\n n = int(input())\n\n aseq = read_ints()\n\n\n\n acc1 = acc2 = 0\n\n for i in range(n-1):\n\n acc1 += aseq[i]\n\n acc2 += aseq[n-i-1]\n\n if acc1 <= 0 or acc2 <= 0:\n\n return False\n\n\n\n return True\n\n\n\n\n\ndef main():\n\n t = int(input())\n\n output = []\n\n for _ in range(t):\n\n ans = solve()\n\n output.append('YES' if ans else 'NO')\n\n\n\n print_lines(output)\n\n\n\n\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 from os import environ as env\n\n if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']:\n\n import sys\n\n sys.stdout = open('out.txt', 'w')\n\n sys.stdin = open('in.txt', 'r')\n\n\n\n main()\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":"# NOT MY CODE\n\n# https:\/\/codeforces.com\/contest\/1324\/submission\/73179914\n\n \n\n## PYRIVAL BOOTSTRAP\n\n# https:\/\/github.com\/cheran-senthil\/PyRival\/blob\/master\/pyrival\/misc\/bootstrap.py\n\n# This decorator allows for recursion without actually doing recursion\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\n \n\n \n\nimport math\n\nfrom bisect import bisect_left, bisect_right\n\nfrom sys import stdin, stdout, setrecursionlimit\n\nfrom collections import Counter\n\ninput = lambda: stdin.readline().strip()\n\nprint = stdout.write\n\n#setrecursionlimit(10**6)\n\n \n\nn = int(input())\n\nls = list(map(int, input().split()))\n\nchildren = {}\n\nfor i in range(1, n+1):\n\n children[i] = []\n\nfor i in range(n-1):\n\n a, b = map(int, input().split())\n\n children[a].append(b)\n\n children[b].append(a)\n\n \n\nparent = [-1]\n\nans = [-1]\n\nfor i in range(1, n+1):\n\n parent.append(-1)\n\n ans.append(-1)\n\n \n\nvisited = [False]\n\nfor i in range(1, n+1):\n\n visited.append(False)\n\n \n\n@bootstrap\n\ndef dfs(node):\n\n visited[node] = True\n\n ans[node] = 1 if ls[node-1] else -1\n\n for i in children[node]:\n\n if not visited[i]:\n\n parent[i] = node\n\n tmp = (yield dfs(i))\n\n if tmp>0:\n\n ans[node]+=tmp\n\n ans[node] = max(ans[node], 1 if ls[node-1] else -1)\n\n yield ans[node]\n\ndfs(1)\n\n \n\nvisited = [False]\n\nfor i in range(1, n+1):\n\n visited.append(False)\n\n \n\n@bootstrap\n\ndef dfs(node):\n\n visited[node] = True\n\n if node!=1:\n\n ans[node] = max(ans[node], ans[parent[node]] if ans[node]>=0 else ans[parent[node]]-1)\n\n for i in children[node]:\n\n if not visited[i]:\n\n yield dfs(i)\n\n yield\n\ndfs(1)\n\n \n\nfor i in range(1, n+1):\n\n print(str(ans[i])+' ')\n\nprint('\\n')","language":"py"} -{"contest_id":"1304","problem_id":"E","statement":"E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3\u2264n\u22641053\u2264n\u2264105), the number of vertices of the tree.Next n\u22121n\u22121 lines contain two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1\u2264q\u22641051\u2264q\u2264105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1\u2264x,y,a,b\u2264n1\u2264x,y,a,b\u2264n, x\u2260yx\u2260y, 1\u2264k\u22641091\u2264k\u2264109) \u2013 the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print \"YES\" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with \"YES\" answers are: 11-st query: 11 \u2013 33 \u2013 22 22-nd query: 11 \u2013 22 \u2013 33 44-th query: 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 ","tags":["data structures","dfs and similar","shortest paths","trees"],"code":"# by the authority of GOD author: manhar singh sachdev #\n\n\n\nimport os,sys\n\nfrom io import BytesIO, IOBase\n\n\n\ndef euler_path(n,path):\n\n height = [0]*n+[10**10]\n\n euler,st,visi,he = [],[0],[1]+[0]*(n-1),0\n\n first = [-1]*n\n\n while len(st):\n\n x = st[-1]\n\n euler.append(x)\n\n if first[x] == -1:\n\n first[x] = len(euler)-1\n\n while len(path[x]) and visi[path[x][-1]]:\n\n path[x].pop()\n\n if not len(path[x]):\n\n he -= 1\n\n st.pop()\n\n else:\n\n i = path[x].pop()\n\n he += 1\n\n st.append(i)\n\n height[i],visi[i] = he,1\n\n return height,euler,first\n\n\n\ndef cons(euler,height):\n\n n = len(euler)\n\n xx = n.bit_length()\n\n dp = [[n]*n for _ in range(xx)]\n\n dp[0] = euler\n\n for i in range(1,xx):\n\n for j in range(n-(1< r:\n\n l,r = r,l\n\n xx1 = (r-l+1).bit_length()-1\n\n a,b = dp[xx1][l],dp[xx1][r-(1<>= 1\n\n j += 1\n\nc = -1\n\nfor i in d:\n\n if i not in [-1, -2]:\n\n c = i\n\nif c == -1:\n\n print(' '.join(map(str, w)))\n\nelse:\n\n print(w[c], ' '.join(map(str, w[:c])), ' '.join(map(str, w[c+1:])))","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 io\nimport os\n\nfrom collections import Counter, defaultdict, deque\n\n# From: https:\/\/github.com\/cheran-senthil\/PyRival\/blob\/master\/pyrival\/data_structures\/SegmentTree.py\nclass SegmentTree:\n def __init__(self, data, default=0, func=max):\n \"\"\"initialize the segment tree with data\"\"\"\n self._default = default\n self._func = func\n self._len = len(data)\n self._size = _size = 1 << (self._len - 1).bit_length()\n\n self.data = [default] * (2 * _size)\n self.data[_size : _size + self._len] = data\n for i in reversed(range(_size)):\n self.data[i] = func(self.data[i + i], self.data[i + i + 1])\n\n def __delitem__(self, idx):\n self[idx] = self._default\n\n def __getitem__(self, idx):\n return self.data[idx + self._size]\n\n def __setitem__(self, idx, value):\n idx += self._size\n self.data[idx] = value\n idx >>= 1\n while idx:\n self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])\n idx >>= 1\n\n def __len__(self):\n return self._len\n\n def query(self, start, stop):\n \"\"\"func of data[start, stop)\"\"\"\n start += self._size\n stop += self._size\n\n res_left = res_right = self._default\n while start < stop:\n if start & 1:\n res_left = self._func(res_left, self.data[start])\n start += 1\n if stop & 1:\n stop -= 1\n res_right = self._func(self.data[stop], res_right)\n start >>= 1\n stop >>= 1\n\n return self._func(res_left, res_right)\n\n def __repr__(self):\n return \"SegmentTree({0})\".format(self.data)\n\n\nclass SegmentData:\n def __init__(self, a, b, c):\n self.a = a\n self.b = b\n self.c = c\n\n\ndef pack(a, b, c):\n return SegmentData(a, b, c)\n return [a, b, c]\n return (a, b, c)\n return (a << 40) + (b << 20) + c\n\n\ndef unpack(abc):\n return abc.a, abc.b, abc.c\n return abc\n return abc\n ab, c = divmod(abc, 1 << 20)\n a, b = divmod(ab, 1 << 20)\n return a, b, c\n\n\ndef merge(x, y):\n # Track numClose, numNonOverlapping, numOpen:\n # e.g., )))) (...)(...)(...) ((((((\n xClose, xFull, xOpen = unpack(x)\n yClose, yFull, yOpen = unpack(y)\n if xOpen == yClose == 0:\n ret = xClose, xFull + yFull, yOpen\n elif xOpen == yClose:\n ret = xClose, xFull + 1 + yFull, yOpen\n elif xOpen > yClose:\n ret = xClose, xFull, xOpen - yClose + yOpen\n elif xOpen < yClose:\n ret = xClose + yClose - xOpen, yFull, yOpen\n # print(x, y, ret)\n return pack(*ret)\n\n\ndef solve(N, intervals):\n endpoints = []\n for i, (l, r) in enumerate(intervals):\n endpoints.append((l, 0, i))\n endpoints.append((r, 1, i))\n endpoints.sort(key=lambda t: t[1])\n endpoints.sort(key=lambda t: t[0])\n\n # Build the segment tree and track the endpoints of each interval in the segment tree\n data = []\n # Note: defaultdict seems to be faster. Maybe because it traverses in segment tree order rather than randomly?\n idToIndices = defaultdict(list)\n for x, kind, intervalId in endpoints:\n if kind == 0:\n data.append(pack(0, 0, 1)) # '('\n else:\n assert kind == 1\n data.append(pack(1, 0, 0)) # ')'\n idToIndices[intervalId].append(len(data) - 1)\n assert len(data) == 2 * N\n segTree = SegmentTree(data, pack(0, 0, 0), merge)\n # print(\"init\", unpack(segTree.query(0, 2 * N)))\n\n best = 0\n for intervalId, indices in idToIndices.items():\n # Remove the two endpoints\n i, j = indices\n removed1, removed2 = segTree[i], segTree[j]\n segTree[i], segTree[j] = pack(0, 0, 0), pack(0, 0, 0)\n\n # Query\n res = unpack(segTree.query(0, 2 * N))\n assert res[0] == 0\n assert res[2] == 0\n best = max(best, res[1])\n # print(\"after removing\", intervals[intervalId], res)\n\n # Add back the two endpoints\n segTree[i], segTree[j] = removed1, removed2\n\n return best\n\n\nif __name__ == \"__main__\":\n input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n T = int(input())\n for t in range(T):\n (N,) = [int(x) for x in input().split()]\n intervals = [[int(x) for x in input().split()] for i in range(N)]\n ans = solve(N, intervals)\n print(ans)\n","language":"py"} -{"contest_id":"1290","problem_id":"C","statement":"C. Prefix Enlightenmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn lamps on a line, numbered from 11 to nn. Each one has an initial state off (00) or on (11).You're given kk subsets A1,\u2026,AkA1,\u2026,Ak of {1,2,\u2026,n}{1,2,\u2026,n}, such that the intersection of any three subsets is empty. In other words, for all 1\u2264i1 0\n\nlcm = lambda x, y: (x * y) \/\/ math.gcd(x,y)\n\nrotate = lambda seq, k: seq[k:] + seq[:k] # O(n)\n\ninput = stdin.readline\n\n'''\n\nCheck for typos before submit, Check if u can get hacked with Dict (use xor)\n\nObservations\/Notes: \n\n'''\n\nfor _ in range(int(input())):\n\n n = int(input())\n\n ans = []\n\n while n >= 2:\n\n ans.append(\"1\")\n\n n -= 2\n\n if n == 1:\n\n ans.pop()\n\n ans.append(\"7\")\n\n ans = ans[::-1]\n\n print(\"\".join(ans))","language":"py"} -{"contest_id":"1290","problem_id":"A","statement":"A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n\u22121n\u22121 friends have found an array of integers a1,a2,\u2026,ana1,a2,\u2026,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.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 three space-separated integers nn, mm and kk (1\u2264m\u2264n\u226435001\u2264m\u2264n\u22643500, 0\u2264k\u2264n\u221210\u2264k\u2264n\u22121) \u00a0\u2014 the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109) \u00a0\u2014 elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2\nOutputCopy8\n4\n1\n1\nNoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.","tags":["brute force","data structures","implementation"],"code":"import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, functools, copy,statistics\n\ninf = float('inf')\n\nmod = 10**9+7\n\ndef LI(): return [int(x) for x in sys.stdin.readline().split()]\n\ndef LF(): return [float(x) for x in sys.stdin.readline().split()]\n\ndef I(): return int(sys.stdin.readline())\n\ndef F(): return float(sys.stdin.readline())\n\ndef S(): return input()\n\ndef LS(): return input().split()\n\nimport time\n\nt = I()\n\nfor _ in range(t):\n\n n, m, k =LI()\n\n num_list = LI()\n\n ans = 0\n\n new_list = num_list[:m]+num_list[-m:]\n\n new_len = len(new_list)\n\n if m <= k:\n\n ans = max(new_list)\n\n else:\n\n a = []\n\n for i in range(k+1):\n\n if k-i == 0:\n\n a.append(num_list[i:])\n\n else:\n\n a.append(num_list[i:-(k-i)])\n\n ind = m-1-k\n\n b= []\n\n for i in range(len(a)):\n\n a_len = len(a[i])\n\n c = []\n\n for j in range(ind+1):\n\n if ind - j ==0:\n\n c.append(max(a[i][j:][0], a[i][j:][-1]))\n\n else:\n\n c.append(max(a[i][j:-(ind-j)][0],a[i][j:-(ind-j)][-1]))\n\n b.append(min(c))\n\n ans = max(b)\n\n print(ans)\n\n\n\n\n\n","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":"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":"from sys import stdin\ninput = stdin.readline\nimport math \n\nn, a, b, k = map(int, input().split())\nh = list(map(int, input().split()))\n\nans = 0; s = []\nfor e in h:\n if e % (a + b) == 0:\n rem = a + b\n else:\n rem = e % (a + b)\n\n if a >= rem:\n ans += 1\n continue\n else:\n need = int(math.ceil(rem \/ a))\n s.append(need - 1)\n\ns.sort()\nfor e in s:\n if k >= e:\n k -= e\n ans += 1\n\nprint(ans)\n\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":"t=int(input())+1\n\nwhile t := t-1:\n\n n,g,b=[int(x) for x in input().split()]\n\n \n\n mid=(n+1)\/\/2\n\n fb,re=mid\/\/g,mid%g\n\n comb=(b*(fb-1))\n\n ans= 0\n\n if re != 0:\n\n comb+=b\n\n ans+=re\n\n ans=mid+comb \n\n comb=n-mid-comb \n\n if comb >0:\n\n ans+=comb\n\n print( ans ) ","language":"py"} -{"contest_id":"1304","problem_id":"E","statement":"E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3\u2264n\u22641053\u2264n\u2264105), the number of vertices of the tree.Next n\u22121n\u22121 lines contain two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1\u2264q\u22641051\u2264q\u2264105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1\u2264x,y,a,b\u2264n1\u2264x,y,a,b\u2264n, x\u2260yx\u2260y, 1\u2264k\u22641091\u2264k\u2264109) \u2013 the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print \"YES\" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy5\n1 2\n2 3\n3 4\n4 5\n5\n1 3 1 2 2\n1 4 1 3 2\n1 4 1 3 3\n4 2 3 3 9\n5 2 3 3 9\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with \"YES\" answers are: 11-st query: 11 \u2013 33 \u2013 22 22-nd query: 11 \u2013 22 \u2013 33 44-th query: 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 \u2013 44 \u2013 22 \u2013 33 ","tags":["data structures","dfs and similar","shortest paths","trees"],"code":"from types import GeneratorType\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 main():\n\n \n\n n=int(input())\n\n adj=[[] for _ in range(n+1)]\n\n for _ in range(n-1):\n\n u,v=readIntArr()\n\n adj[u].append(v)\n\n adj[v].append(u)\n\n \n\n \n\n # Note: For this question, root the tree at 1\n\n \n\n '''BINARY LIFTING LCA - Preprocess O(nlogn), find dist or LCA between 2 vertices in O(logn)'''\n\n @bootstrap\n\n def dfsPopulateAncestor(node,d): # NEEDS BOOTSTRAP\n\n m=len(path)\n\n b=1\n\n while m-b>=0:\n\n nodeAncestors[node].append(path[m-b])\n\n b*=2\n\n nodeDepths[node]=d\n\n path.append(node)\n\n for nex in adj[node]:\n\n if len(path)>=2 and nex==path[-2]: continue #parent\n\n yield dfsPopulateAncestor(nex,d+1)\n\n path.pop()\n\n yield None\n\n ## Needs adj as a global variable. adj[u]=[v1,v2, ... where there is an edge u-v]\n\n nodeDepths=[None for _ in range(n+1)]\n\n nodeAncestors=[[] for _ in range(n+1)] #[1 up, 2 up, 4 up, ...]\n\n root=1 ## To modify accordingly\n\n path=[]\n\n dfsPopulateAncestor(root,0)\n\n # print(nodeAncestors)\n\n @bootstrap\n\n def dfsEulerTour(node,p): #NEEDS BOOTSTRAP\n\n startTimes[node]=time[0]\n\n time[0]+=1\n\n for nex in adj[node]:\n\n if nex==p: continue #parent\n\n yield dfsEulerTour(nex,node)\n\n endTimes[node]=time[0]\n\n time[0]+=1\n\n yield None\n\n startTimes=[0 for _ in range(n+1)]\n\n endTimes=[0 for _ in range(n+1)]\n\n time=[0]\n\n dfsEulerTour(root,-1)\n\n def isAncestor(node,ancestorCandidate):\n\n ac=ancestorCandidate\n\n return startTimes[ac]<=startTimes[node] and endTimes[ac]>=endTimes[node]\n\n \n\n def getLCA(u,v):\n\n if isAncestor(u,v):\n\n return v\n\n elif isAncestor(v,u):\n\n return u\n\n else:\n\n # Find LCA\n\n ancestor=u\n\n while True:\n\n ancs=nodeAncestors[ancestor]\n\n m=len(ancs)\n\n assert m>0 # should not reach the root\n\n if isAncestor(v,ancs[0]): # found LCA\n\n LCA=ancs[0]\n\n break\n\n broken=False\n\n for i in range(m): # binary search up u's ancestor to find highest non-ancestor\n\n if isAncestor(v,ancs[i]):\n\n ancestor=ancs[i-1]\n\n broken=True\n\n break\n\n if broken==False:\n\n ancestor=ancs[-1]\n\n return LCA\n\n \n\n def getDist(u,v):\n\n LCA=getLCA(u,v)\n\n return nodeDepths[u]+nodeDepths[v]-2*nodeDepths[LCA]\n\n \n\n q=int(input())\n\n allans=[]\n\n for _ in range(q):\n\n x,y,a,b,k=readIntArr()\n\n ans='NO'\n\n \n\n # Don't use the new path\n\n temp=k-getDist(a,b)\n\n if temp>=0 and temp%2==0:\n\n ans='YES'\n\n \n\n # Use the new path\n\n xy=getDist(x,y)\n\n # a-x-y-b, no cycle\n\n temp=k-(getDist(a,x)+getDist(b,y)+1)\n\n if temp>=0 and temp%2==0:\n\n ans='YES'\n\n # a-x-y-b, use 1 cycle\n\n temp=temp-(1+xy)\n\n if temp>=0 and temp%2==0:\n\n ans='YES'\n\n #a-y-x-b, no cycle\n\n temp=k-(getDist(a,y)+getDist(b,x)+1)\n\n if temp>=0 and temp%2==0:\n\n ans='YES'\n\n #a-y-x-b, use 1 cycle\n\n temp=temp-(1+xy)\n\n if temp>=0 and temp%2==0:\n\n ans='YES'\n\n \n\n allans.append(ans)\n\n \n\n multiLineArrayPrint(allans)\n\n \n\n return\n\n \n\nimport sys\n\ninput=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)\n\n# import sys\n\n# input=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 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":"1307","problem_id":"A","statement":"A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1\u2264i,j\u2264n1\u2264i,j\u2264n) such that |i\u2212j|=1|i\u2212j|=1 and ai>0ai>0 and apply ai=ai\u22121ai=ai\u22121, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. Next 2t2t lines contain a description of test cases \u00a0\u2014 two lines per test case.The first line of each test case contains integers nn and dd (1\u2264n,d\u22641001\u2264n,d\u2264100) \u2014 the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641000\u2264ai\u2264100) \u00a0\u2014 the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0\nOutputCopy3\n101\n0\nNoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.","tags":["greedy","implementation"],"code":"for q in range(int(input())):\n\n n,d = [int(x) for x in input().split()]\n\n arr = [int(x) for x in input().split()]\n\n ans = arr[0]\n\n for i in range(1,n):\n\n temp = min(arr[i], d\/\/i)\n\n ans += temp\n\n d -= temp*(i)\n\n print(ans) \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, 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())\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\nfrom collections import deque\nclass CHT:\n \"\"\"\u50be\u304d\u304c\u5358\u8abf\u6e1b\u5c11\u304b\u3064\u8a55\u4fa1\u70b9\u304c\u5358\u8abf\u5897\u52a0\u306e\u3068\u304d\u306e\u6700\u5c0f\u5024\u30af\u30a8\u30ea\n \"\"\"\n def __init__(self):\n self.q = deque()\n @staticmethod\n def _val(t,x):\n return t[0]*x+t[1]\n @staticmethod\n def _check(t1,t2,t3):\n return (t2[0]-t1[0]) * (t3[1]-t2[1]) >= (t2[1]-t1[1]) * (t3[0]-t2[0])\n def add(self, a, b):\n \"\"\"a*x + b\u306e\u8ffd\u52a0\n \"\"\"\n t = (a,b)\n while len(self.q)>=2 and self._check(self.q[-2], self.q[-1], t):\n # \u8ffd\u52a0\u3059\u308b\u7dda\u5206\u3068\u6700\u5f8c\u304b\u30892\u756a\u3081\u306e\u7dda\u5206\u306eCH\u3060\u3051\u3067\u51f8\u5305\u306b\u306a\u308b\n self.q.pop()\n self.q.append(t)\n def query(self, x):\n \"\"\"a*x+b\u306e\u6700\u5c0f\u5024\u3092\u8fd4\u3059\n \"\"\"\n while len(self.q)>=2 and self._val(self.q[0], x) >= self._val(self.q[1], x):\n self.q.popleft()\n return self._val(self.q[0], x)\n \nn = int(input())\na = list(map(int, input().split()))\ncum = [0]\nfor v in a:\n cum.append(cum[-1]+v)\nch = CHT()\nfor i in range(n+1):\n ch.add(-i, cum[i])\nans = [0]*n\na0,b0 = ch.q.popleft()\nfor i in range(len(ch.q)):\n a,b = ch.q.popleft()\n# print(a,b)\n x = -(b0-b)\/(a0-a)\n for ind in range(-a0, -a):\n ans[ind] = x\n a0 = a\n b0 = b\nwrite(\"\\n\".join(map(str, ans)))","language":"py"} -{"contest_id":"1313","problem_id":"A","statement":"A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1\u2264t\u22645001\u2264t\u2264500)\u00a0\u2014 the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0\u2264a,b,c\u2264100\u2264a,b,c\u226410)\u00a0\u2014 the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer\u00a0\u2014 the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.","tags":["brute force","greedy","implementation"],"code":"import re\n\nimport functools\n\nimport random\n\nimport sys\n\nimport os\n\nimport math\n\nfrom collections import Counter, defaultdict, deque\n\nfrom functools import lru_cache, reduce\n\nfrom itertools import accumulate, combinations, permutations\n\nfrom heapq import nsmallest, nlargest, heappushpop, heapify, heappop, heappush\n\nfrom io import BytesIO, IOBase\n\nfrom copy import deepcopy\n\nimport threading\n\nfrom typing import *\n\nfrom operator import add, xor, mul, ior, iand, itemgetter\n\nimport bisect\n\nBUFSIZE = 4096\n\ninf = float('inf')\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\nsys.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 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\nfrom types import GeneratorType\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\nt = II()\n\nfor _ in range(t):\n\n nums = LII()\n\n ans = 0\n\n for i in range(3):\n\n if nums[i]:\n\n nums[i] -= 1\n\n ans += 1\n\n nums.sort()\n\n if nums[1] and nums[2]:\n\n nums[1] -= 1\n\n nums[2] -= 1\n\n ans += 1\n\n if nums[0] and nums[2]:\n\n nums[0] -= 1\n\n nums[2] -= 1\n\n ans += 1\n\n if nums[0] and nums[1]:\n\n nums[0] -= 1\n\n nums[1] -= 1\n\n ans += 1\n\n if nums[0] and nums[1] and nums[2]:\n\n ans += 1\n\n print(ans)","language":"py"} -{"contest_id":"13","problem_id":"A","statement":"A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A\u2009-\u20091.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3\u2009\u2264\u2009A\u2009\u2264\u20091000).OutputOutput should contain required average value in format \u00abX\/Y\u00bb, where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7\/3InputCopy3OutputCopy2\/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.","tags":["implementation","math"],"code":"# LUOGU_RID: 100463992\nn=int(input())\nk=0\nz=n\nfor i in range(2,n):\n while n!=0:\n k+=n%i\n n=n\/\/i\n n=z\na=max(k,n-2)\nb=min(k,n-2)\nn=a%b\nwhile n!=0:\n a=b\n b=n\n n=a%b\nprint(int(k\/b),end='\/')\nprint(int((z-2)\/b))","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":"#Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me,\n\nimport sys\n\n#then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize,\n\nimport os\n\n#just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails\n\nfrom io import BytesIO, IOBase\n\nBUFSIZE = 8192\n\n#every now and then. Just keep coding, just keep working and you'll keep progressing at speed-\n\n# -forcing.\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\n#code by _Frust(CF)\/Frust(AtCoder)\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\nfrom os import path\n\nif(path.exists('input.txt')):\n\n sys.stdin = open(\"input.txt\",\"r\")\n\n sys.stdout = open(\"output.txt\",\"w\")\n\n input = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\nimport math\n\nimport heapq as hq\n\n\n\n\n\nfor _ in range(int(input())):\n\n # n=int(input())\n\n n, m=map(int, input().split())\n\n\n\n if m==0:\n\n print(0)\n\n elif n==m:\n\n print((n*(n+1))\/\/2)\n\n else:\n\n ts=(n*(n+1))\/\/2\n\n gaps=m+1\n\n zeros=(n-m)\n\n p=zeros\/\/gaps\n\n av1=zeros%gaps\n\n av0=m+1-av1\n\n s1=av0 * ((p*(p+1))\/\/2)\n\n s2=av1 * (((p+2)*(p+1))\/\/2)\n\n print(ts-s1-s2)","language":"py"} -{"contest_id":"1324","problem_id":"B","statement":"B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an\u2212i\u22121ai=an\u2212i\u22121 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3\u2264n\u226450003\u2264n\u22645000) \u2014 the length of aa. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u2264n1\u2264ai\u2264n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (\u2211n\u22645000\u2211n\u22645000).OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and \"NO\" otherwise.ExampleInputCopy5\n3\n1 2 1\n5\n1 2 2 3 2\n3\n1 1 2\n4\n1 2 2 1\n10\n1 1 2 2 3 3 4 4 5 5\nOutputCopyYES\nYES\nNO\nYES\nNO\nNoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.","tags":["brute force","strings"],"code":"for _ in \" \"*int(input()):\n\n a=int(input());z=\"NO\"\n\n k=list(map(int,input().split()))\n\n for i in range(a-2):\n\n if k[i] in k[i+2:]:z=\"YES\";break\n\n print(z)","language":"py"} -{"contest_id":"1312","problem_id":"E","statement":"E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,\u2026,ana1,a2,\u2026,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1\u2264n\u22645001\u2264n\u2264500) \u2014 the initial length of the array aa.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u2014 the initial array aa.OutputPrint the only integer \u2014 the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5\n4 3 2 2 3\nOutputCopy2\nInputCopy7\n3 3 4 4 4 3 3\nOutputCopy2\nInputCopy3\n1 3 5\nOutputCopy3\nInputCopy1\n1000\nOutputCopy1\nNoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 \u2192\u2192 44 33 33 33 \u2192\u2192 44 44 33 \u2192\u2192 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 \u2192\u2192 44 44 44 44 33 33 \u2192\u2192 44 44 44 44 44 \u2192\u2192 55 44 44 44 \u2192\u2192 55 55 44 \u2192\u2192 66 44.In the third and fourth tests, you can't perform the operation at all.","tags":["dp","greedy"],"code":"from sys import stderr\nN = 505\n\ndp1 = [N*[-1] for _ in range(N)]\ndp2 = N*[int(1e9)]\n\ndef calculate1():\n for l in range(n):\n dp1[l][l+1] = a[l]\n\n for d in range(2,n+1):\n for l in range(n+1-d):\n r = l + d\n for mid in range(l+1, r):\n lf = dp1[l][mid]\n rg = dp1[mid][r]\n if lf > 0 and lf == rg:\n dp1[l][r] = lf + 1\n break\n #print('\\n'.join(map(lambda x: str(x[:n+1]), dp1[:n+1])))\n\ndef calculate2():\n dp2[0] = 0\n for i in range(n):\n for j in range(i+1,n+1):\n if dp1[i][j] != -1:\n dp2[j] = min(dp2[j], dp2[i]+1)\n print(dp2[n])\n #print(dp2[:n+1])\n\n\nn = int(input())\na = list(map(int, input().split()))\nlimit = 1000\ni = 0\nprint(\" \".join(map(str, a[i*limit:(i+1)*limit])), file=stderr)\ncalculate1()\ncalculate2()\n\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":"#from itertools import *\n\n#from math import *\n\n#from bisect import *\n\n#from collections import *\n\n#from random import *\n\n#from decimal import *\n\n#from heapq import *\n\n#from itertools import * # Things Change ....remember :)\n\nimport sys\n\ninput=sys.stdin.readline\n\ndef inp():\n\n return int(input())\n\ndef st():\n\n return input().rstrip('\\n')\n\ndef lis():\n\n return list(map(int,input().split()))\n\ndef ma():\n\n return map(int,input().split())\n\ndef func(a,b,c):\n\n z1=min(len(a),len(b))\n\n for i in range(z1):\n\n c.append([a.pop(),b.pop()])\n\nt=1\n\nwhile(t):\n\n t-=1\n\n n=inp()\n\n q1=[]\n\n q2=[]\n\n s=st()\n\n s1=st()\n\n r=[]\n\n id1=[[] for i in range(26)]\n\n id2=[[] for i in range(26)]\n\n for i in range(n):\n\n z=ord(s[i])-97\n\n z1=ord(s1[i])-97\n\n if(s[i]!='?'):\n\n id1[z].append(i+1)\n\n else:\n\n q1.append(i+1)\n\n if(s1[i]!='?'):\n\n id2[z1].append(i+1)\n\n else:\n\n q2.append(i+1)\n\n for i in range(26):\n\n func(id1[i],id2[i],r)\n\n for i in range(26):\n\n func(id1[i],q2,r)\n\n func(q1,id2[i],r)\n\n func(q1,q2,r)\n\n print(len(r))\n\n for i in r:\n\n print(*i)\n\n \n\n \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\nfrom collections import defaultdict \n\n\n\ndef main():\n\n n,m = map(int,input().split())\n\n A = [list(map(int,input().split())) for _ in range(n)]\n\n for i in range(n):\n\n for j in range(m):\n\n A[i][j] -= 1\n\n if n == m == 1:\n\n if A[0][0] == 0:\n\n print(0)\n\n else:\n\n print(1)\n\n ans = 0\n\n for j in range(m):\n\n dic = defaultdict(int)\n\n for i in range(n):\n\n #print(i,j,A[i][j],-j)\n\n if (A[i][j] - j) % m != 0: continue\n\n r = (A[i][j] - j) \/\/ m\n\n if r >= n: continue\n\n move = (i + n - r) % n\n\n #print(i,j,A[i][j],r,move)\n\n dic[move] += 1\n\n #print(dic)\n\n req = n #change all\n\n for k,v in dic.items():\n\n temp = k + n - v\n\n req = min(req, temp)\n\n ans += req\n\n print(ans)\n\n\n\n \n\nif __name__ == \"__main__\":\n\n main()","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 print(0)\n\n elif(a%2==0 and b%2==0):\n\n if(a>b):\n\n print(1)\n\n else:\n\n print(2)\n\n elif(a%2==1 and b%2==1):\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","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 math\nimport collections\nimport sys\n\n\ndef inpu():\n return input().split(' ')\n\n\ndef inti(a):\n for i in range(len(a)):\n a[i] = int(a[i])\n return a\n\n\ndef inp():\n a = inpu()\n a = inti(a)\n return a\n\n\ndef solution():\n n, m, k = map(int, input().split())\n c = 0\n i = 0\n if k > 4*n*m-2*n-2*m:\n print(\"NO\")\n exit(0)\n d = []\n m -= 1\n while True:\n if i == 0:\n if k <= m and m > 0:\n d.append([k, \"R\"])\n break\n if m > 0:\n d.append([m, \"R\"])\n c += m\n if c+m >= k and m > 0:\n d.append([k-c, \"L\"])\n break\n elif m > 0:\n d.append([m, \"L\"])\n c += m\n d.append([1, \"D\"])\n c += 1\n if c == k:\n break\n elif i != n-1:\n if c+m >= k and m > 0:\n d.append([k-c, \"R\"])\n break\n elif m > 0:\n d.append([m, \"R\"])\n c += m\n if (k-c)\/\/3 < m:\n if (k-c)\/\/3 > 0:\n d.append([(k-c)\/\/3, \"UDL\"])\n if (k-c) % 3 > 0:\n d.append([1, \"UDL\"[:(k-c) % 3]])\n break\n elif (k-c)\/\/3 == m and (k-c) % 3 == 0 and m > 0:\n d.append([(k-c)\/\/3, \"UDL\"])\n break\n elif m > 0:\n # print((k-c)\/\/3,k,c)\n d.append([m, \"UDL\"])\n c += (m)*3\n d.append([1, \"D\"])\n c += 1\n if c == k:\n break\n else:\n if c+m >= k and m > 0:\n d.append([k-c, \"R\"])\n break\n elif m > 0:\n d.append([m, \"R\"])\n c += m\n if (k-c)\/\/3 < m:\n if (k-c)\/\/3 > 0:\n d.append([(k-c)\/\/3, \"UDL\"])\n if (k-c) % 3 > 0:\n d.append([1, \"UDL\"[:(k-c) % 3]])\n break\n elif (k-c)\/\/3 == m and (k-c) % 3 == 0 and m > 0:\n d.append([(k-c)\/\/3, \"UDL\"])\n break\n elif m > 0:\n d.append([m, \"UDL\"])\n c += (m)*3\n d.append([k-c, \"U\"])\n break\n i += 1\n # print(c,i)\n print(\"YES\")\n print(len(d))\n for i in d:\n print(*i)\n\n\n# for _ in range(int(input())):\nsolution()\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 check(x):\n\n l, r = 0, k\n\n while l < r:\n\n m = l + (r - l) \/\/ 2\n\n if arr[m] == x:\n\n return m \n\n elif arr[m] > x:\n\n r = m\n\n else:\n\n l = m + 1\n\n \n\n return -1\n\n\n\nfor _ in range(int(input())):\n\n n, s, k = map(int, input().split())\n\n arr = list(map(int, input().split()))\n\n arr.sort()\n\n cnt = 0\n\n d, u = s - cnt, s + cnt \n\n while d >= 0 and u <= n:\n\n if check(d) == -1 or check(u) == -1:\n\n print(cnt)\n\n break\n\n else:\n\n cnt += 1 \n\n if d > 1:\n\n d = s - cnt \n\n if u < n:\n\n u = s + cnt\n\n\n\n # print(d, u)\n\n \n\n\n\n \n\n ","language":"py"} -{"contest_id":"1305","problem_id":"C","statement":"C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,\u2026,ana1,a2,\u2026,an. Help Kuroni to calculate \u220f1\u2264i 1):\n print(0)\n exit()\n# print([i for i in range(1, 10)])\ntot = 1\nfor i in range(m):\n if b[i] == 1:\n for j in range(i + 1, m):\n if b[j] == 1:\n tot = tot * abs(c[j] - c[i]) % m\nprint(tot % m)\n \t\t \t \t \t \t\t \t\t","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":"import sys\n\n \n\nq,x=map(int,sys.stdin.readline().split())\n\nmex = 0\n\nmap=dict()\n\n \n\n \n\n \n\nfor _ in range(q):\n\n v=int(sys.stdin.readline())%x\n\n if v in map:\n\n map[v + x*map[v]] = 1\n\n map[v] += 1\n\n else:\n\n map[v] = 1\n\n \n\n while mex in map:\n\n mex += 1\n\n print(mex)","language":"py"} -{"contest_id":"1324","problem_id":"C","statement":"C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2\u2026sns=s1s2\u2026sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i\u2212d);i\u22121][max(0,i\u2212d);i\u22121], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.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. The ii-th test case is described as a string ss consisting of at least 11 and at most 2\u22c51052\u22c5105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211|s|\u22642\u22c5105\u2211|s|\u22642\u22c5105).OutputFor each test case, print the answer \u2014 the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6\nLRLRRLL\nL\nLLR\nRRRR\nLLLLLL\nR\nOutputCopy3\n2\n3\n1\n7\n1\nNoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.","tags":["binary search","data structures","dfs and similar","greedy","implementation"],"code":"for i in[*open(0)][1:]:print(max(map(len,i.replace(\"\\n\",\"\").split(\"R\")))+1)","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 lex(s,k):\n\n\tif (len(s)-k)%2==1:\n\n\t\tt = s[k-1:] + s[0:k-1]\n\n\telse:\n\n\t\tt = s[k-1:] + s[0:k-1][::-1]\n\n\treturn t\n\n\n\nfor times in range(int(input())):\n\n\tn = int(input())\n\n\ts = input()\n\n\tst = lex(s,1)\n\n\tansk = 1\n\n\tfor k in range(2,n+1):\n\n\t\tif lex(s,k)=0):\n l=s[j]\n while(s[j]==l and j>=0):\n j-=1\n if(l=='A'):\n c+=a\n else:\n c+=b\n if(p>=c):\n r=j+2\n print(r)\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":"n=int(input())\n\ns=input()\n\narr=[]\n\nfor i in range(n):\n\n arr.append((s[i],i))\n\narr.sort(key=lambda x:(x[0],x[1]))\n\n# print(arr)\n\nnew=[0 for i in range(n)]\n\nfor i in range(n):\n\n new[arr[i][1]]=i\n\narr=new\n\ncolor=[-1 for i in range(n)]\n\nst=[]\n\nfin=[]\n\ni=0\n\nindex=0\n\nyes=1\n\n# print(arr)\n\ncolored={}\n\nwhile(i