diff --git "a/data/py/validation.jsonl" "b/data/py/validation.jsonl" deleted file mode 100644--- "a/data/py/validation.jsonl" +++ /dev/null @@ -1,200 +0,0 @@ -{"contest_id":"1295","problem_id":"B","statement":"B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss\u2026t=ssss\u2026 For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q\u2212cnt1,qcnt0,q\u2212cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".InputThe first line contains the single integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.Next 2T2T lines contain descriptions of test cases \u2014 two lines per test case. The first line contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, \u2212109\u2264x\u2264109\u2212109\u2264x\u2264109) \u2014 the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si\u2208{0,1}si\u2208{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers \u2014 one per test case. For each test case print the number of prefixes or \u22121\u22121 if there is an infinite number of such prefixes.ExampleInputCopy4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01\nOutputCopy3\n0\n1\n-1\nNoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.","tags":["math","strings"],"code":"# If you win, you live. You cannot win unless you fight.\n\nfrom math import sin\n\nfrom sys import stdin,setrecursionlimit\n\ninput=stdin.readline\n\nimport heapq\n\nrd=lambda: map(lambda s: int(s), input().strip().split())\n\nri=lambda: int(input())\n\nrs=lambda :input().strip()\n\nfrom collections import defaultdict as unsafedict,deque,Counter as unsafeCounter\n\nfrom bisect import bisect_left as bl, bisect_right as br\n\nfrom random import randint\n\nrandom = randint(1, 10 ** 9)\n\nmod=998244353\n\ndef ceil(a,b):\n\n return (a+b-1)\/\/b\n\nclass myDict:\n\n def __init__(self,func):\n\n self.RANDOM = randint(0,1<<32)\n\n self.default=func\n\n self.dict={}\n\n def __getitem__(self,key):\n\n myKey=self.RANDOM^key\n\n if myKey not in self.dict:\n\n self.dict[myKey]=self.default()\n\n return self.dict[myKey]\n\n def get(self,key,default):\n\n myKey=self.RANDOM^key\n\n if myKey not in self.dict:\n\n return default\n\n return self.dict[myKey]\n\n def __setitem__(self,key,item):\n\n myKey=self.RANDOM^key\n\n self.dict[myKey]=item\n\n def getKeys(self):\n\n return [self.RANDOM^i for i in self.dict]\n\n def __str__(self):\n\n return f'{[(self.RANDOM^i,self.dict[i]) for i in self.dict]}'\n\nfrom math import prod\n\n'''\n\nx*ts+y==m\n\n(m-y)%ts==0\n\ntype 2\n\nx*ts-x==m\n\n\n\n'''\n\ndef samepar(a,b):\n\n return (a>=0 and b>=0) or (a<=0 and b<=0)\n\nfor _ in range(ri()):\n\n n,m=rd()\n\n s=rs()\n\n ts=s.count(\"0\")-s.count(\"1\")\n\n if ts==0:\n\n x=0\n\n ans=0\n\n for i in s:\n\n if i==\"0\":\n\n x+=1\n\n else:\n\n x-=1\n\n if x==m:\n\n ans+=1\n\n if ans:\n\n print(-1)\n\n else:\n\n print(0)\n\n continue\n\n ans=0\n\n y=0\n\n st=set()\n\n if (m%ts)==0 and samepar(m,ts) :\n\n # print(\"here \",m ,ts)\n\n st.add((m\/\/ts,n-1))\n\n for i in range(n-1):\n\n if s[i]==\"1\":\n\n y-=1\n\n else:\n\n y+=1\n\n if (m-y)%ts==0:\n\n if (m-y)\/\/ts>=0:\n\n # print(m - y, y, (m - y) \/\/ ts)\n\n st.add(((m-y)\/\/ts,i))\n\n ans+=1\n\n # print(st)\n\n print(len(st))\n\n","language":"py"} -{"contest_id":"1288","problem_id":"A","statement":"A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in \u2308dx+1\u2309\u2308dx+1\u2309 days (\u2308a\u2309\u2308a\u2309 is the ceiling function: \u23082.4\u2309=3\u23082.4\u2309=3, \u23082\u2309=2\u23082\u2309=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+\u2308dx+1\u2309x+\u2308dx+1\u2309.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1\u2264T\u2264501\u2264T\u226450) \u2014 the number of test cases.The next TT lines contain test cases \u2013 one per line. Each line contains two integers nn and dd (1\u2264n\u22641091\u2264n\u2264109, 1\u2264d\u22641091\u2264d\u2264109) \u2014 the number of days before the deadline and the number of days the program runs.OutputPrint TT answers \u2014 one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3\n1 1\n4 5\n5 11\nOutputCopyYES\nYES\nNO\nNoteIn the first test case; Adilbek decides not to optimize the program at all; since d\u2264nd\u2264n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run \u230852\u2309=3\u230852\u2309=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work \u2308112+1\u2309=4\u2308112+1\u2309=4 days.","tags":["binary search","brute force","math","ternary search"],"code":"#\u042d\u0442\u043e \u043a\u0441\u0442\u0430\u0442\u0438 \u043c\u043e\u044f \u0441\u0430\u043c\u0430\u044f \u043f\u0435\u0440\u0432\u0430\u044f \u0440\u0435\u0448\u0435\u043d\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430 \u043d\u0430 \u043a\u043e\u0434\u0444\u043e\u0440\u0441\u0435\u0441 \u0440\u0430\u0443\u043d\u0434\u0435 (13 \u043f\u043e\u043f\u044b\u0442\u043e\u043a 1\u044718\u043c\u0438\u043d)\n\nimport math\n\n\n\nt = int(input())\n\n\n\nfor i in range(t):\n\n n, d = input().split()\n\n n = int(n)\n\n d = int(d)\n\n c = 0\n\n for x in range(n):\n\n if(x + math.ceil(d\/(x + 1)) <= n):\n\n print(\"YES\")\n\n c += 1\n\n break\n\n if c == 0:\n\n print(\"NO\")","language":"py"} -{"contest_id":"1301","problem_id":"A","statement":"A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1\u2264i\u2264n1\u2264i\u2264n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci\u2194aici\u2194ai or ci\u2194bici\u2194bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is \"code\", bb is \"true\", and cc is \"help\", you can make cc equal to \"crue\" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes \"hodp\" and bb becomes \"tele\".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u22641001\u2264t\u2264100) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print \"YES\" (without quotes), otherwise print \"NO\" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4\naaa\nbbb\nccc\nabc\nbca\nbca\naabb\nbbaa\nbaba\nimi\nmii\niim\nOutputCopyNO\nYES\nYES\nNO\nNoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes \"bca\", bb becomes \"bca\" and cc becomes \"abc\". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes \"baba\", string bb becomes \"baba\" and string cc becomes \"abab\". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.","tags":["implementation","strings"],"code":"for _ in range(int(input())):\n print(\n \"YES\"\n if all(ai == ci or bi == ci for ai, bi, ci in zip(input(), input(), input()))\n else \"NO\"\n )\n","language":"py"} -{"contest_id":"1303","problem_id":"D","statement":"D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The first line of each test case contains two integers nn and mm (1\u2264n\u22641018,1\u2264m\u22641051\u2264n\u22641018,1\u2264m\u2264105) \u2014 the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,\u2026,ama1,a2,\u2026,am (1\u2264ai\u22641091\u2264ai\u2264109) \u2014 the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer \u2014 the minimum number of divisions required to fill the bag of size nn (or \u22121\u22121, if it is impossible).ExampleInputCopy3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8\nOutputCopy2\n-1\n0\n","tags":["bitmasks","greedy"],"code":"import os, sys\n\nfrom io import BytesIO, IOBase\n\nfrom array import array\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, 8192))\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, 8192))\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\ninput = lambda: sys.stdin.readline().strip()\n\nints = lambda: list(map(int, input().split()))\n\nInt = lambda: int(input())\n\n\n\n\n\ndef queryInteractive(a, b, c):\n\n print('? {} {} {}'.format(a, b, c))\n\n sys.stdout.flush()\n\n return int(input())\n\n\n\n\n\ndef answerInteractive(x1, x2):\n\n print('! {} {}'.format(x1, x2))\n\n sys.stdout.flush()\n\n\n\n\n\ninf = float('inf')\n\n\n\npow2 = [1]\n\nfor _ in range(30):\n\n pow2.append(2 * pow2[-1])\n\ndic = {pow2[i]:i for i in range(30)}\n\n\n\n\n\nT = Int()\n\nwhile T:\n\n T -= 1\n\n n, m = ints()\n\n arr = ints()\n\n if sum(arr) < n:\n\n print(-1)\n\n continue\n\n \n\n l = [0] * 61\n\n for x in arr:\n\n l[dic[x]] += 1\n\n ans = 0\n\n i = 0\n\n while i < 60:\n\n if (n>>i)&1:\n\n if l[i] > 0:\n\n l[i] -= 1\n\n else:\n\n while l[i] == 0:\n\n i += 1\n\n ans += 1\n\n l[i] -= 1\n\n continue\n\n l[i+1] += l[i]\/\/2\n\n i += 1 \n\n print(ans)\n\n \n\n \n\n","language":"py"} -{"contest_id":"1288","problem_id":"E","statement":"E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,\u2026,n1,2,\u2026,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1\u2264n,m\u22643\u22c51051\u2264n,m\u22643\u22c5105) \u2014 the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,\u2026,ama1,a2,\u2026,am (1\u2264ai\u2264n1\u2264ai\u2264n) \u2014 the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4\n3 5 1 4\nOutputCopy1 3\n2 5\n1 4\n1 5\n1 5\nInputCopy4 3\n1 2 4\nOutputCopy1 3\n1 2\n3 4\n1 4\nNoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3] ","tags":["data structures"],"code":"import 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\nfrom operator import itemgetter\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\n\n\ndef update(i, vl, x):\n\n i += x\n\n tree[i] += vl\n\n while i:\n\n tree[i >> 1] = tree[i] + tree[i ^ 1]\n\n i >>= 1\n\n\n\n\n\ndef query(l, r, x):\n\n l += x\n\n r += x\n\n ans = 0\n\n while l < r:\n\n if l & 1:\n\n ans += tree[l]\n\n l += 1\n\n if r & 1:\n\n r -= 1\n\n ans += tree[r]\n\n l >>= 1\n\n r >>= 1\n\n return ans\n\n\n\n\n\nn, m = map(int, input().split())\n\na = list(map(int, input().split()))\n\ntree = [0] * (2 * n + 5)\n\nans = [[i, i] for i in range(n + 1)]\n\n\n\nfor i in a:\n\n ans[i][0] = 1\n\n if tree[i + n + 1] == 0:\n\n x = query(i, n + 1, n + 1)\n\n ans[i][1] = x + i\n\n update(i, 1, n + 1)\n\ntree = [0] * (2 * m + 5)\n\nv = [-1] * (n + 1)\n\nfor i, vl in enumerate(a):\n\n if v[vl] == -1:\n\n v[vl] = i\n\n update(i, 1, m)\n\n else:\n\n x = query(v[vl], i, m)\n\n ans[vl][1] = max(ans[vl][1], x)\n\n update(v[vl], -1, m)\n\n update(i, 1, m)\n\n v[vl] = i\n\nct = n\n\nfor i in range(n, 0, -1):\n\n if v[i] == -1:\n\n ans[i][1] = max(ans[i][1], ct)\n\n ct -= 1\n\nck = []\n\nfor i in range(1, n + 1):\n\n if v[i] != -1:\n\n ck.append([v[i], i])\n\nck.sort()\n\nfor vl, i in ck:\n\n ans[i][1] = max(ans[i][1], ct)\n\n ct -= 1\n\nfor i in range(1, n + 1):\n\n print(*ans[i])\n\n","language":"py"} -{"contest_id":"1296","problem_id":"A","statement":"A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1\u2264i,j\u2264n1\u2264i,j\u2264n such that i\u2260ji\u2260j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226420001\u2264t\u22642000) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u226420001\u2264n\u22642000) \u2014 the number of elements in aa. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226420001\u2264ai\u22642000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (\u2211n\u22642000\u2211n\u22642000).OutputFor each test case, print the answer on it \u2014 \"YES\" (without quotes) if it is possible to obtain the array with an odd sum of elements, and \"NO\" otherwise.ExampleInputCopy5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1\nOutputCopyYES\nNO\nYES\nNO\nNO\n","tags":["math"],"code":"def main():\n\n t = int(input())\n\n for _ in range(t):\n\n _ = int(input())\n\n a = [int(i) for i in input().split()]\n\n o, e = 0, 0\n\n for x in a:\n\n if x % 2:\n\n o += 1\n\n else:\n\n e += 1\n\n s = sum(a)\n\n if s % 2:\n\n print(\"YES\")\n\n else:\n\n if o != 0 and e != 0:\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")\n\n\n\n\n\nif __name__ == \"__main__\":\n\n main()","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":"n, m, k = map(int, input().split())\n\nout, max_ = [], 4 * n * m - 2 * n - 2 * m\n\nif k > max_:\n\n exit(print('NO'))\n\n\n\nfor i in range(n - 1):\n\n if m > 1:\n\n cur = 'DUR' if i & 1 == 0 else 'DUL'\n\n out.append(f'{m - 1} {cur}')\n\n out.append('1 D')\n\n\n\nif m > 1:\n\n ch = 'R' if n & 1 else 'L'\n\n out.append(f'{m - 1} {ch}')\n\n\n\nfor i in range(n, 0, -1):\n\n if m > 1:\n\n ch = 'L' if i & 1 else 'R'\n\n out.append(f'{m - 1} {ch}')\n\n if i > 1:\n\n out.append('1 U')\n\n\n\nout2 = ['YES', '0']\n\nfor i in out:\n\n num, pat = i.split()\n\n num = int(num)\n\n\n\n if num * len(pat) >= k:\n\n div, mod = divmod(k, len(pat))\n\n if div:\n\n out2.append(f'{div} {pat}')\n\n if mod:\n\n out2.append(f'1 {pat[:mod]}')\n\n break\n\n\n\n k -= num * len(pat)\n\n out2.append(i)\n\n\n\nout2[1] = str(len(out2) - 2)\n\nprint('\\n'.join(out2))\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":"def helper(a):\n\n s=set()\n\n for i in range(n):\n\n c=0\n\n while a[i]>0:\n\n while a[i]%k==0:\n\n a[i]\/\/=k\n\n c+=1\n\n if a[i]%k==1:\n\n a[i]-=1\n\n else:return \"NO\"\n\n if c in s:return \"NO\"\n\n else:s.add(c)\n\n return \"YES\"\n\n\n\nimport sys\n\ninput=sys.stdin.readline\n\n\n\nt=int(input())\n\nfor _ in range(t):\n\n n,k=map(int,input().split())\n\n a=list(map(int,input().strip().split()))\n\n print(helper(a))","language":"py"} -{"contest_id":"1296","problem_id":"E1","statement":"E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1\u2264n\u22642001\u2264n\u2264200) \u2014 the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print \"NO\" (without quotes) in the first line.Otherwise, print \"YES\" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9\nabacbecfd\nOutputCopyYES\n001010101\nInputCopy8\naaabbcbb\nOutputCopyYES\n01011011\nInputCopy7\nabcdedc\nOutputCopyNO\nInputCopy5\nabcde\nOutputCopyYES\n00000\n","tags":["constructive algorithms","dp","graphs","greedy","sortings"],"code":"from math import *\n\nfrom collections import *\n\nimport os\n\nfrom io import BytesIO, IOBase\n\nimport sys\n\nfrom bisect import *\n\nfrom heapq import *\n\n \n\nMOD = 1000000007\n\n\n\n\n\n# Code by Big Dick Daddy Dick\n\n \n\ndef binpow(a, b, m):\n\n a %= m\n\n x = 1\n\n while b > 0:\n\n if b & 1:\n\n x = x * a % m\n\n a = a * a % m\n\n b >>= 1\n\n return x\n\n\n\n \n\n \n\ndef binser(arr, l, r, x):\n\n while l < r:\n\n mid = l + (r - l) \/\/ 2\n\n # print(l, r, mid)\n\n \n\n if arr[mid] == x:\n\n return mid\n\n \n\n elif arr[mid] < x:\n\n l = mid + 1\n\n \n\n else:\n\n r = mid - 1\n\n \n\n return mid\n\n \n\ndef lcm(a, b):\n\n return (a * b) \/\/ gcd(a, b)\n\n \n\ndef sod(n):\n\n l = list(str(n))\n\n s = 0\n\n for i in l:\n\n s += int(i)\n\n return s\n\n \n\n \n\ndef prime_factors(num): \n\n l =[]\n\n if num % 2:\n\n l.append(2)\n\n while num % 2 == 0: \n\n num = num \/ 2 \n\n \n\n for i in range(3, int(sqrt(num)) + 1, 2): \n\n if not num % i:\n\n l.append(i)\n\n while num % i == 0: \n\n num = num \/ i\n\n if num > 2:\n\n l.append(num)\n\n return l\n\n \n\n \n\ndef factmod(n, p):\n\n \n\n f = defaultdict(int)\n\n f[0] = 1\n\n for i in range(1, n + 1):\n\n f[i] = (f[i-1] * i) % MOD\n\n \n\n \"\"\"\n\n res = 1\n\n while (n > 1):\n\n if (n\/\/p) % 2:\n\n res = p - res\n\n \n\n res = res * f[n%p] % p\n\n n \/\/= p\n\n \"\"\"\n\n \n\n return f\n\n \n\n \n\n \n\ndef largestPower(n, p):\n\n \n\n # Initialize result\n\n x = 0\n\n \n\n # Calculate x = n\/p + n\/(p^2) + n\/(p^3) + ....\n\n while (n):\n\n n \/\/= p\n\n x += n\n\n return x\n\n \n\ndef modFact(n, p) :\n\n \n\n if (n >= p) :\n\n return 0\n\n \n\n res = 1\n\n isPrime = [1] * (n + 1)\n\n i = 2\n\n while(i * i <= n):\n\n if (isPrime[i]):\n\n for j in range(2 * i, n, i) :\n\n isPrime[j] = 0\n\n i += 1\n\n \n\n # Consider all primes found by Sieve\n\n for i in range(2, n):\n\n if (isPrime[i]) :\n\n \n\n k = largestPower(n, i)\n\n \n\n # Multiply result with (i^k) % p\n\n res = (res * binpow(i, k, p)) % p\n\n \n\n return res\n\n \n\ndef drec(x, y):\n\n if y == x + 1:\n\n return 'R'\n\n if y == x - 1:\n\n return 'L'\n\n if x < y:\n\n return 'D'\n\n return 'U'\n\n \n\ndef cellhash(x, y):\n\n return (x - 1) * m + y\n\n \n\n\n\n \n\ndef bfs(src, dest):\n\n q = deque([src])\n\n vis[src] = True\n\n \n\n while q:\n\n i = q.popleft()\n\n if i == dest:\n\n return True\n\n for j in ajl[i]:\n\n if not vis[j]:\n\n vis[j] = True\n\n q.append(j)\n\n return False\n\n \n\ndef bins(l, x, n):\n\n i = bisect_left(l, x)\n\n if i < n:\n\n return i\n\n if i:\n\n return (i-1)\n\n else:\n\n return n\n\n\n\ndef cond(l):\n\n for i in range(len(l) - 1):\n\n if l[i] == str(int(l[i + 1]) - 1):\n\n return False\n\n return True\n\n\n\ndef isvowel(s):\n\n if s in list(\"aeiou\"):\n\n return 1\n\n return 0\n\n\n\ndef countOdd(L, R):\n\n \n\n N = (R - L) \/\/ 2\n\n \n\n # if either R or L is odd\n\n if (R % 2 != 0 or L % 2 != 0):\n\n N += 1\n\n \n\n return N\n\n\n\ndef tst(A, B, C):\n\n return ((A|B) & (B|C) & (C|A))\n\n\n\ndef palcheck(n, s):\n\n i, j = 0, n - 1\n\n while i <= j:\n\n if s[i] == s[j]:\n\n return False\n\n i += 1\n\n j -= 1\n\n return True\n\n\n\ndef sakurajima(n):\n\n if n < 9:\n\n n = 10\n\n l = [1] * (n + 1)\n\n l[1] = 0\n\n\n\n for i in range(2, int(n ** 0.5) + 1):\n\n if l[i]:\n\n for j in range(i * i, n + 1, i):\n\n if not j % i:\n\n l[j] = 0\n\n return l\n\n\n\ndef prchck(n):\n\n l = [1] * (n + 1)\n\n l[1] = 0\n\n for i in range(2, n + 1):\n\n for j in range(2, int(sqrt(n)) + 1):\n\n if j % i == 0:\n\n l[j] = 1\n\n return l\n\n\n\ndef ispal(s, n):\n\n for i in range(n \/\/ 2):\n\n if s[i] != s[n - i - 1]:\n\n return False\n\n return True\n\n\n\ndef dfs(i, tmp, vis):\n\n vis[i] = True\n\n if i == int(i):\n\n for j in range(cnt[i]):\n\n tmp.append(i)\n\n\n\n for j in ajl[i]:\n\n if not vis[j]:\n\n tmp = dfs(j, tmp, vis)\n\n\n\n return tmp\n\n\n\n\n\ndef panda(n, s):\n\n\tx, y = '0', '0'\n\n\tans = ['0'] * n\n\n\n\n\tfor i in range(n):\n\n\t\tif s[i] >= x:\n\n\t\t\tans[i] = '1'\n\n\t\t\tx = s[i]\n\n\t\telif s[i] >= y:\n\n\t\t\ty = s[i]\n\n\t\telse:\n\n\t\t\treturn \"NO\"\n\n\n\n\tprint(\"YES\")\n\n\treturn \"\".join(ans)\n\n \n\n\n\n# Code by Big Dick Daddy Dick\n\n\n\n# n = int(input())\n\n# n, k = map(int, input().split())\n\n# s = input()\n\n# l = list(map(int, input().split()))\n\n# memo = [[-1 for i in range(n + 1)] for j in range(2)]\n\n\n\n\n\ninput = sys.stdin.readline\n\n\n\n\n\nt = 1\n\n# t = int(input())\n\nfor _ in range(t):\n\n n = int(input())\n\n s = input()\n\n print(panda(n, s))\n\n\n\n\n\n # print(\"Case #\" + str(_ + 1) + \": \" + str(ans))\n\n","language":"py"} -{"contest_id":"1295","problem_id":"C","statement":"C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.The first line of each testcase contains one string ss (1\u2264|s|\u22641051\u2264|s|\u2264105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1\u2264|t|\u22641051\u2264|t|\u2264105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2\u22c51052\u22c5105.OutputFor each testcase, print one integer \u2014 the minimum number of operations to turn string zz into string tt. If it's impossible print \u22121\u22121.ExampleInputCopy3\naabce\nace\nabacaba\naax\nty\nyyt\nOutputCopy1\n-1\n3\n","tags":["dp","greedy","strings"],"code":"import sys, threading\n\nimport math\n\nfrom os import path\n\nfrom collections import defaultdict, Counter, deque\n\nfrom bisect import *\n\nfrom string import ascii_lowercase\n\nfrom functools import cmp_to_key\n\nimport heapq\n\n \n\n \n\ndef readInts():\n\n x = list(map(int, (sys.stdin.readline().rstrip().split())))\n\n return x[0] if len(x) == 1 else x\n\n \n\n \n\ndef readList(type=int):\n\n x = sys.stdin.readline()\n\n x = list(map(type, x.rstrip('\\n\\r').split()))\n\n return x\n\n \n\n \n\ndef readStr():\n\n x = sys.stdin.readline().rstrip('\\r\\n')\n\n return x\n\n \n\n \n\nwrite = sys.stdout.write\n\nread = sys.stdin.readline\n\n \n\n \n\nMAXN = 1123456\n\n\n\n\n\nclass mydict:\n\n def __init__(self, func):\n\n self.random = randint(0, 1 << 32)\n\n self.default = func\n\n self.dict = {}\n\n \n\n def __getitem__(self, key):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n self.dict[mykey] = self.default()\n\n return self.dict[mykey]\n\n \n\n def get(self, key, default):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n return default\n\n return self.dict[mykey]\n\n \n\n def __setitem__(self, key, item):\n\n mykey = self.random ^ key\n\n self.dict[mykey] = item\n\n \n\n def getkeys(self):\n\n return [self.random ^ i for i in self.dict]\n\n \n\n def __str__(self):\n\n return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'\n\n\n\n \n\ndef lcm(a, b):\n\n return (a*b)\/\/(math.gcd(a,b))\n\n \n\n \n\ndef mod(n):\n\n return n%(1000000000 + 7)\n\n\n\n\n\ndef upper_bound(a, num):\n\n l = 0\n\n r = len(a)-1\n\n ans = -1\n\n while l <= r:\n\n mid = (l+r)\/\/2\n\n if a[mid] > num:\n\n ans = mid\n\n r = mid-1\n\n else:\n\n l = mid+1\n\n \n\n return ans \n\n\n\n\n\ndef solve(t):\n\n # print(f'Case #{t}: ', end = '')\n\n a = readStr()\n\n b = readStr()\n\n cnt = 1\n\n mpind = defaultdict(list)\n\n for i, c in enumerate(a):\n\n mpind[c].append(i)\n\n\n\n j = 0\n\n lind = -1\n\n for c in b:\n\n ui = upper_bound(mpind[c], lind)\n\n\n\n if ui == -1:\n\n lind = -1\n\n ui = upper_bound(mpind[c], lind)\n\n cnt += 1\n\n\n\n\n\n if ui == -1 and lind == -1:\n\n print(-1)\n\n return\n\n else:\n\n lind = mpind[c][ui]\n\n\n\n print(cnt)\n\n\n\n\n\ndef main():\n\n t = 1\n\n if path.exists(\"F:\/Comp Programming\/input.txt\"):\n\n sys.stdin = open(\"F:\/Comp Programming\/input.txt\", 'r')\n\n sys.stdout = open(\"F:\/Comp Programming\/output1.txt\", 'w')\n\n # sys.setrecursionlimit(1e6) \n\n t = readInts()\n\n for i in range(t):\n\n solve(i+1)\n\n \n\n \n\nif __name__ == '__main__':\n\n main() ","language":"py"} -{"contest_id":"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":"m, n = map(int, input().split())\n\n\n\nif n%m != 0:\n\n print(-1)\n\nelse:\n\n d = n\/\/m\n\n p = 0\n\n while d%2 == 0 or d%3 == 0:\n\n if d%2 == 0:\n\n p += 1\n\n d = d\/\/2\n\n if d%3 == 0:\n\n p += 1\n\n d = d\/\/3\n\n if d == 1:\n\n print(p)\n\n else:\n\n print(-1)\n\n","language":"py"} -{"contest_id":"1304","problem_id":"F2","statement":"F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1\u2264n\u2264501\u2264n\u226450, 1\u2264m\u22642\u22c51041\u2264m\u22642\u22c5104, 1\u2264k\u2264m1\u2264k\u2264m) \u2013 the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer \u2013 the maximum number of animals that can be observed.ExamplesInputCopy4 5 2\n0 2 1 1 0\n0 0 3 1 2\n1 0 4 3 1\n3 3 0 0 4\nOutputCopy25\nInputCopy3 3 1\n1 2 3\n4 5 6\n7 8 9\nOutputCopy31\nInputCopy3 3 2\n1 2 3\n4 5 6\n7 8 9\nOutputCopy44\nInputCopy3 3 3\n1 2 3\n4 5 6\n7 8 9\nOutputCopy45\nNoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4: ","tags":["data structures","dp","greedy"],"code":"import sys, os, io\n\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\ndef update(l, r, s):\n\n q, lr, i = [1], [(0, l1 - 1)], 0\n\n while len(q) ^ i:\n\n j = q[i]\n\n l0, r0 = lr[i]\n\n if l <= l0 and r0 <= r:\n\n lazy[j] += s\n\n i += 1\n\n continue\n\n m0 = (l0 + r0) \/\/ 2\n\n if j < l1:\n\n lazy[2 * j] += lazy[j]\n\n lazy[2 * j + 1] += lazy[j]\n\n lazy[j] = 0\n\n if l <= m0 and l0 <= r:\n\n q.append(2 * j)\n\n lr.append((l0, m0))\n\n if l <= r0 and m0 + 1 <= r:\n\n q.append(2 * j + 1)\n\n lr.append((m0 + 1, r0))\n\n i += 1\n\n while q:\n\n i = q.pop()\n\n if i < l1:\n\n tree[i] = max(tree[2 * i] + lazy[2 * i], tree[2 * i + 1] + lazy[2 * i + 1])\n\n return\n\n\n\nn, m, k = map(int, input().split())\n\nif n == 1:\n\n s = list(map(int, input().split()))\n\n c = [0]\n\n for i in s:\n\n c.append(i + c[-1])\n\n ans = 0\n\n for i in range(m - k + 1):\n\n ans = max(ans, c[i + k] - c[i])\n\n print(ans)\n\n exit()\n\ns1 = list(map(int, input().split()))\n\ns2 = list(map(int, input().split()))\n\nc1, c2 = [0], [0]\n\nfor i in s1:\n\n c1.append(i + c1[-1])\n\nfor i in s2:\n\n c2.append(i + c2[-1])\n\nn0 = m - k + 1\n\ndp0 = [0] * n0\n\nfor i in range(n0):\n\n dp0[i] = c1[i + k] - c1[i] + c2[i + k] - c2[i]\n\ns1, c1 = s2, c2\n\nl1 = pow(2, (2 * n0).bit_length())\n\nl2 = 2 * l1\n\nu = [max(i - k + 1, 0) for i in range(m)]\n\nv = [min(i, m - k) for i in range(m)]\n\nfor x in range(n - 1):\n\n s2 = [0] * m if x == n - 2 else list(map(int, input().split()))\n\n c2 = [0]\n\n for i in s2:\n\n c2.append(i + c2[-1])\n\n tree, lazy = [0] * l2, [0] * l2\n\n for i in range(n0):\n\n tree[i + l1] = dp0[i]\n\n for i in range(l1 - 1, 0, -1):\n\n tree[i] = max(tree[2 * i], tree[2 * i + 1])\n\n for i in range(k - 1):\n\n update(u[i], v[i], -s1[i])\n\n dp = [0] * n0\n\n for i in range(n0):\n\n j = i + k - 1\n\n update(u[j], v[j], -s1[j])\n\n dp[i] = c1[i + k] - c1[i] + c2[i + k] - c2[i] + tree[1] + lazy[1]\n\n update(u[i], v[i], s1[i])\n\n dp0 = dp\n\n s1, c1 = s2, c2\n\nans = max(dp0)\n\nprint(ans)","language":"py"} -{"contest_id":"1321","problem_id":"C","statement":"C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1\u2264i\u2264|s|1\u2264i\u2264|s| during each operation.For the character sisi adjacent characters are si\u22121si\u22121 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1\u2264|s|\u22641001\u2264|s|\u2264100) \u2014 the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer \u2014 the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8\nbacabcab\nOutputCopy4\nInputCopy4\nbcda\nOutputCopy3\nInputCopy6\nabbbbb\nOutputCopy5\nNoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a. ","tags":["brute force","constructive algorithms","greedy","strings"],"code":"import sys\n\nimport math\n\nimport collections\n\nimport heapq\n\ninput=sys.stdin.readline\n\nn=int(input())\n\ns=list(input())\n\nif(n==1):\n\n print(0)\n\nelse:\n\n s1=[]\n\n for i in range(n):\n\n s1.append(s[i])\n\n c=1\n\n ans=0\n\n while(c==1):\n\n m=-1\n\n ind=-1\n\n n1=len(s1)\n\n if(n1==1):\n\n break\n\n else:\n\n for i in range(n1):\n\n if(i==0):\n\n if(ord(s1[i])-ord(s1[i+1])==1):\n\n if(s1[i]!='a'):\n\n ind=i\n\n m=s1[i]\n\n elif(i==n1-1):\n\n if(ord(s1[i])-ord(s1[i-1])==1):\n\n if(s1[i]!='a'):\n\n if(m==-1):\n\n ind=i\n\n m=s1[i]\n\n else:\n\n if(s1[i]>m):\n\n ind=i\n\n m=s1[i]\n\n else:\n\n if(ord(s1[i])-ord(s1[i-1])==1 or ord(s1[i])-ord(s1[i+1])==1):\n\n if(s1[i]!='a'):\n\n if(m==-1):\n\n ind=i\n\n m=s1[i]\n\n else:\n\n if(s1[i]>m):\n\n ind=i\n\n m=s1[i]\n\n if(m==-1):\n\n c=0\n\n else:\n\n s2=[]\n\n for i in range(n1):\n\n if(i!=ind):\n\n s2.append(s1[i])\n\n s1=[]\n\n for i in range(n1-1):\n\n s1.append(s2[i])\n\n ans+=1\n\n print(ans)","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":"a = ord('a')\n\n\n\nfor _ in range(int(input())):\n\n s = input()\n\n t = [s[0]]\n\n i = 0\n\n for l in s[1:]:\n\n if i > 0 and l == t[i-1]:\n\n i -= 1\n\n elif i < len(t) - 1 and l == t[i+1]:\n\n i += 1\n\n elif l in t:\n\n print('NO')\n\n break\n\n elif i == len(t) - 1:\n\n t.append(l)\n\n i += 1\n\n elif i == 0:\n\n t.insert(0, l)\n\n i = 0\n\n else:\n\n print('NO')\n\n break\n\n else:\n\n print('YES')\n\n for l in range(26):\n\n l = chr(l + a)\n\n if l not in t:\n\n t.append(l)\n\n print(''.join(t))\n\n","language":"py"} -{"contest_id":"1303","problem_id":"D","statement":"D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The first line of each test case contains two integers nn and mm (1\u2264n\u22641018,1\u2264m\u22641051\u2264n\u22641018,1\u2264m\u2264105) \u2014 the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,\u2026,ama1,a2,\u2026,am (1\u2264ai\u22641091\u2264ai\u2264109) \u2014 the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer \u2014 the minimum number of divisions required to fill the bag of size nn (or \u22121\u22121, if it is impossible).ExampleInputCopy3\n10 3\n1 32 1\n23 4\n16 1 4 1\n20 5\n2 1 16 1 8\nOutputCopy2\n-1\n0\n","tags":["bitmasks","greedy"],"code":"import sys\n\nfrom math import log2\n\n\n\ninput = lambda: sys.stdin.buffer.readline().decode().strip()\n\nget_bit, sz = lambda x, i: (x >> i) & 1, 47\n\n\n\nfor _ in range(int(input())):\n\n n, m = map(int, input().split())\n\n a, mem, ans = [int(x) for x in input().split()], [0] * sz, 0\n\n\n\n if n > sum(a):\n\n print(-1)\n\n continue\n\n\n\n for i in range(m):\n\n mem[int(log2(a[i]))] += 1\n\n\n\n for bit in range(sz - 1):\n\n cur = get_bit(n, bit)\n\n if cur:\n\n if mem[bit]:\n\n mem[bit] -= 1\n\n else:\n\n for j in range(bit + 1, sz):\n\n if mem[j]:\n\n ans += j - bit\n\n mem[j] -= 1\n\n break\n\n n ^= get_bit(n, j) << j\n\n\n\n mem[bit + 1] += mem[bit] >> 1\n\n print(ans)\n\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>= 1\n\n return ret\n\n\n\n\n\n############ Main! #############\n\n\n\nfor tc in range(ip()):\n\n a, b, p = mip()\n\n s = sp()\n\n n = len(s)\n\n i = n - 2\n\n c = [0 for _ in range(n - 1)]\n\n x = 0\n\n while i >= 0:\n\n now = s[i]\n\n while i >= 0 and now == s[i]:\n\n if now == \"A\":\n\n c[i] = x + a\n\n else:\n\n c[i] = x + b\n\n i -= 1\n\n if now == \"A\":\n\n x += a\n\n else:\n\n x += b\n\n\n\n ans = 0\n\n while ans < n - 1:\n\n if c[ans] > p:\n\n ans += 1\n\n else:\n\n break\n\n print(ans + 1)\n\n\n\n\n\n######## Praise greedev ########","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, threading\n\nimport math\n\nfrom os import path\n\nfrom collections import defaultdict, Counter, deque\n\nfrom bisect import *\n\nfrom string import ascii_lowercase\n\nfrom functools import cmp_to_key\n\nimport heapq\n\n \n\n \n\ndef readInts():\n\n x = list(map(int, (sys.stdin.readline().rstrip().split())))\n\n return x[0] if len(x) == 1 else x\n\n \n\n \n\ndef readList(type=int):\n\n x = sys.stdin.readline()\n\n x = list(map(type, x.rstrip('\\n\\r').split()))\n\n return x\n\n \n\n \n\ndef readStr():\n\n x = sys.stdin.readline().rstrip('\\r\\n')\n\n return x\n\n \n\n \n\nwrite = sys.stdout.write\n\nread = sys.stdin.readline\n\n \n\n \n\nMAXN = 1123456\n\n\n\n\n\nclass mydict:\n\n def __init__(self, func):\n\n self.random = randint(0, 1 << 32)\n\n self.default = func\n\n self.dict = {}\n\n \n\n def __getitem__(self, key):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n self.dict[mykey] = self.default()\n\n return self.dict[mykey]\n\n \n\n def get(self, key, default):\n\n mykey = self.random ^ key\n\n if mykey not in self.dict:\n\n return default\n\n return self.dict[mykey]\n\n \n\n def __setitem__(self, key, item):\n\n mykey = self.random ^ key\n\n self.dict[mykey] = item\n\n \n\n def getkeys(self):\n\n return [self.random ^ i for i in self.dict]\n\n \n\n def __str__(self):\n\n return f'{[(self.random ^ i, self.dict[i]) for i in self.dict]}'\n\n\n\n \n\ndef lcm(a, b):\n\n return (a*b)\/\/(math.gcd(a,b))\n\n \n\n \n\ndef mod(n):\n\n return n%(998244353) \n\n\n\n\n\ndef solve(t):\n\n # print(f'Case #{t}: ', end = '')\n\n n, x = readInts()\n\n mp = defaultdict(lambda: 0)\n\n ar = []\n\n for _ in range(n):\n\n ar.append(readInts())\n\n\n\n mexr = [0]\n\n cur = 0\n\n for num in ar:\n\n if num == cur:\n\n cur += 1\n\n\n\n mexr.append(cur)\n\n\n\n res = []\n\n cur = -1\n\n for i in range(1, n+1):\n\n mp[ar[i-1]%x] += 1\n\n\n\n while mp[(cur+1)%x] > 0:\n\n cur += 1\n\n mp[cur%x] -= 1 \n\n\n\n res.append(cur+1)\n\n\n\n\n\n for num in res:\n\n print(num)\n\n\n\n\n\ndef main():\n\n t = 1\n\n if path.exists(\"F:\/Comp Programming\/input.txt\"):\n\n sys.stdin = open(\"F:\/Comp Programming\/input.txt\", 'r')\n\n sys.stdout = open(\"F:\/Comp Programming\/output1.txt\", 'w')\n\n # sys.setrecursionlimit(10**5) \n\n # t = readInts() \n\n for i in range(t):\n\n solve(i+1)\n\n \n\n \n\nif __name__ == '__main__':\n\n main() ","language":"py"} -{"contest_id":"1312","problem_id":"D","statement":"D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that ajaj+1aj>aj+1, if j\u2265ij\u2265i). InputThe first line contains two integers nn and mm (2\u2264n\u2264m\u22642\u22c51052\u2264n\u2264m\u22642\u22c5105).OutputPrint one integer \u2014 the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4\nOutputCopy6\nInputCopy3 5\nOutputCopy10\nInputCopy42 1337\nOutputCopy806066790\nInputCopy100000 200000\nOutputCopy707899035\nNoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3]. ","tags":["combinatorics","math"],"code":"import os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\nfrom collections import Counter, defaultdict\n\nfrom sys import stdin, stdout\n\nimport io\n\nimport math\n\nimport heapq\n\nimport bisect\n\nimport collections\n\ndef ceil(a, b):\n\n return (a + b - 1) \/\/ b\n\ninf = float('inf')\n\ndef get():\n\n return stdin.readline().rstrip()\n\ndef modfac(n, MOD):\n\n f = 1\n\n factorials = [1]\n\n for m in range(1, n + 1):\n\n f *= m\n\n f %= MOD\n\n factorials.append(f)\n\n inv = pow(f, MOD - 2, MOD)\n\n invs = [1] * (n + 1)\n\n invs[n] = inv\n\n for m in range(n, 1, -1):\n\n inv *= m\n\n inv %= MOD\n\n invs[m - 1] = inv\n\n return factorials, invs\n\ndef modnCr(n,r):\n\n return fac[n] * inv[n-r] * inv[r] % mod\n\nmod = 998244353\n\nfac,inv = modfac(500000,mod)\n\n\n\ndef modFact(n, p):\n\n if n >= p:\n\n return 0\n\n\n\n result = 1\n\n for i in range(1, n + 1):\n\n result = (result * i) % p\n\n\n\n return result\n\ndef power(x, y, p):\n\n res = 1\n\n x = x % p\n\n if (x == 0):\n\n return 0\n\n while (y > 0):\n\n if ((y & 1) == 1):\n\n res = (res * x) % p\n\n y = y >> 1 # y = y\/2\n\n x = (x * x) % p\n\n return res\n\n# for _ in range(int(get())):\n\n# n=int(get())\n\n# l=list(map(int,get().split()))\n\n# = map(int,get().split())\n\nn,m= map(int,get().split())\n\nprint(((modnCr(m,n-1)%mod)*((n-2)%mod)*(power(2,n-3,mod)%mod))%mod)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"py"} -{"contest_id":"1296","problem_id":"B","statement":"B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1\u2264x\u2264s1\u2264x\u2264s, buy food that costs exactly xx burles and obtain \u230ax10\u230b\u230ax10\u230b burles as a cashback (in other words, Mishka spends xx burles and obtains \u230ax10\u230b\u230ax10\u230b back). The operation \u230aab\u230b\u230aab\u230b means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1\u2264s\u22641091\u2264s\u2264109) \u2014 the number of burles Mishka initially has.OutputFor each test case print the answer on it \u2014 the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6\n1\n10\n19\n9876\n12345\n1000000000\nOutputCopy1\n11\n21\n10973\n13716\n1111111111\n","tags":["math"],"code":"for _ in range(int(input())):\n\n n=int(input())\n\n print(int(n\/\/(9\/10)))","language":"py"} -{"contest_id":"1292","problem_id":"B","statement":"B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIV\u039b - \u6f02\u6d41 KIV\u039b & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by)(ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x\u22121,y)(x\u22121,y), (x+1,y)(x+1,y), (x,y\u22121)(x,y\u22121) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1\u2264x0,y0\u226410161\u2264x0,y0\u22641016, 2\u2264ax,ay\u22641002\u2264ax,ay\u2264100, 0\u2264bx,by\u226410160\u2264bx,by\u22641016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1\u2264xs,ys,t\u226410161\u2264xs,ys,t\u22641016)\u00a0\u2013 the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer\u00a0\u2014 the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0\n2 4 20\nOutputCopy3InputCopy1 1 2 3 1 0\n15 27 26\nOutputCopy2InputCopy1 1 2 3 1 0\n2 2 1\nOutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3\u22122|+|3\u22124|=2|3\u22122|+|3\u22124|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1\u22123|+|1\u22123|=4|1\u22123|+|1\u22123|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7\u22121|+|9\u22121|=14|7\u22121|+|9\u22121|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15\u22127|+|27\u22129|=26|15\u22127|+|27\u22129|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.","tags":["brute force","constructive algorithms","geometry","greedy","implementation"],"code":"#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\ndef check(p1, p2):\n\n p=tm(p1[0], p1[1], p2[0], p2[1])\n\n return (min(tm(p1[0], p1[1], xs, ys), tm(p2[0], p2[1], xs, ys))+p)<=t\n\n\n\n\n\ndef tm(x1, y1, x2, y2):\n\n return (abs(x2-x1) + abs(y2-y1))\n\n\n\n\n\n\n\nx0 , y0, ax, ay, bx, by=map(int, input().split())\n\nxs , ys, t=map(int, input().split())\n\nxp=x0\n\nyp=y0\n\n# print(x0, y0)\n\n# for i in range(40):\n\n# xp=(xp*ax) + bx\n\n# yp=(yp*ay) + by\n\n# print(xp, yp)\n\n\n\nl=1\n\nxc, yc=x0, y0\n\nprev=float(\"inf\")\n\nflag=False\n\nwhile True:\n\n k=tm(xc, yc, xs, ys)\n\n if k(ans[1]-ans[0]+1):\n\n # print(i, j)\n\n ans=[i, j]\n\n print(ans[1]-ans[0]+1)\n\n\n\n\n\n","language":"py"} -{"contest_id":"1305","problem_id":"E","statement":"E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the \"Proof by AC\" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,\u2026,ana1,a2,\u2026,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1\u2264a1= c:\n\n m -= c\n\n ans.append(i)\n\n else:\n\n u = 2 * m\n\n m = 0\n\n ans.append(ans[-1] + ans[-u])\n\nif m:\n\n ans = [-1]\n\nsys.stdout.write(\" \".join(map(str, ans)))","language":"py"} -{"contest_id":"1325","problem_id":"F","statement":"F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309 vertices. find a simple cycle of length at least \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5\u2264n\u22641055\u2264n\u2264105, n\u22121\u2264m\u22642\u22c5105n\u22121\u2264m\u22642\u22c5105)\u00a0\u2014 the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print \"1\", followed by a line containing \u2308n\u2212\u2212\u221a\u2309\u2308n\u2309 distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print \"2\", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\nOutputCopy1\n1 6 4InputCopy6 8\n1 3\n3 4\n4 2\n2 6\n5 6\n5 1\n1 4\n2 5\nOutputCopy2\n4\n1 5 2 4InputCopy5 4\n1 2\n1 3\n2 4\n2 5\nOutputCopy1\n3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2\u22124\u22123\u22121\u22125\u221262\u22124\u22123\u22121\u22125\u22126 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2\u22125\u221262\u22125\u22126, for example, is acceptable.In the third sample:","tags":["constructive algorithms","dfs and similar","graphs","greedy"],"code":"#!\/usr\/bin\/env python3\nimport sys\nfrom math import *\nfrom collections import defaultdict\nfrom queue import deque # Queues\nfrom heapq import heappush, heappop # Priority Queues\n\n# parse\nlines = [line.strip() for line in sys.stdin.readlines()]\nn, m = list(map(int, lines[0].split()))\nedges = [set() for i in range(n)]\n\nfor i in range(1, m+1):\n u, v = list(map(int, lines[i].split()))\n u -= 1\n v -= 1\n edges[u].add(v)\n edges[v].add(u)\n\nnn = int(ceil(sqrt(n)))\n\ndef find_cycle(v, forbidden):\n used = set([v])\n forbidden = set(forbidden)\n ret = [v]\n while True:\n v = ret[-1]\n ss = edges[v] - used - forbidden\n nxt = None\n for s in ss:\n nxt = s\n break\n \n if nxt is None:\n break\n ret += [nxt]\n used.add(nxt)\n\n i = 0\n while ret[i] not in edges[ret[-1]]:\n i += 1\n\n return ret[i:]\n\n\nq = []\nfor v in range(n):\n heappush(q, (len(edges[v]), v))\n\n# find indep set\nind = set()\ncovered = set()\nwhile q:\n d, v = heappop(q)\n\n if v in covered:\n continue\n\n ind.add(v)\n ss = set(edges[v])\n ss.add(v)\n\n if len(ind) == nn:\n # found an indep set\n print(1)\n print(' '.join('%s' % (i+1) for i in ind))\n break\n if d >= nn - 1:\n # found a cycle\n ys = find_cycle(v, list(covered))\n print(2)\n print(len(ys))\n print(' '.join('%s' % (i+1) for i in ys))\n break\n\n covered |= ss\n\n ws = set()\n for u in edges[v]:\n for w in edges[u]:\n ws.add(w)\n \n ws -= ss\n for w in ws:\n edges[w] -= ss\n heappush(q, (len(edges[w]), w))\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 pratyush in range(int(input())):\n\n a,b=map(int,input().split())\n\n print(a*(len(str(b+1))-1))","language":"py"} -{"contest_id":"13","problem_id":"B","statement":"B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1\u2009\/\u20094 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1\u2009\/\u20094). InputThe first line contains one integer t (1\u2009\u2264\u2009t\u2009\u2264\u200910000) \u2014 the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers \u2014 coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print \u00abYES\u00bb (without quotes), if the segments form the letter A and \u00abNO\u00bb otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES","tags":["geometry","implementation"],"code":"import random\n\nfrom math import sqrt as s\n\n \n\n \n\ndef dist(x1, y1, x2, y2):\n\n return s((x2 - x1) ** 2 + (y2 - y1) ** 2)\n\n \n\n \n\ndef is_dot_on_line(c1, c2, dot):\n\n A = c1[1] - c2[1]\n\n B = c2[0] - c1[0]\n\n C = c1[0] * c2[1] - c2[0] * c1[1]\n\n \n\n maxx, minx = max(c1[0], c2[0]), min(c1[0], c2[0])\n\n maxy, miny = max(c1[1], c2[1]), min(c1[1], c2[1])\n\n \n\n res = A * dot[0] + B * dot[1] + C\n\n \n\n if res == 0 and minx <= dot[0] <= maxx and miny <= dot[1] <= maxy:\n\n return True\n\n return False\n\n \n\n \n\ndef cosangle(x1, y1, x2, y2):\n\n return x1 * x2 + y1 * y2\n\n \n\n \n\ndef same(k11, k12, k21, k22, k31, k32):\n\n if k11 == k21 or k11 == k22 or k12 == k21 or k12 == k22:\n\n return 0, 1, 2\n\n if k11 == k31 or k11 == k32 or k12 == k31 or k12 == k32:\n\n return 0, 2, 1\n\n if k21 == k31 or k21 == k32 or k22 == k31 or k22 == k32:\n\n return 1, 2, 0\n\n return False\n\n \n\n \n\ndef is_a(c1, c2, c3, debug=-1):\n\n al = [c1, c2, c3]\n\n \n\n lines = same(*c1, *c2, *c3)\n\n if not lines:\n\n return False\n\n \n\n c1, c2, c3 = al[lines[0]], al[lines[1]], al[lines[2]]\n\n if c1[0] == c2[1]:\n\n c2[0], c2[1] = c2[1], c2[0]\n\n if c1[1] == c2[0]:\n\n c1[0], c1[1] = c1[1], c1[0]\n\n \n\n if not (is_dot_on_line(c1[0], c1[1], c3[0]) and is_dot_on_line(c2[0], c2[1], c3[1])):\n\n if not (is_dot_on_line(c1[0], c1[1], c3[1]) and is_dot_on_line(c2[0], c2[1], c3[0])):\n\n return False\n\n c3[0], c3[1] = c3[1], c3[0]\n\n \n\n cosa = cosangle(c1[0][0] - c1[1][0],\n\n c1[0][1] - c1[1][1],\n\n c2[0][0] - c2[1][0],\n\n c2[0][1] - c2[1][1])\n\n \n\n if cosa < 0:\n\n return False\n\n \n\n l1 = dist(*c1[0], *c3[0]), dist(*c1[1], *c3[0])\n\n l2 = dist(*c2[0], *c3[1]), dist(*c2[1], *c3[1])\n\n \n\n if min(l1) \/ max(l1) < 1\/4 or min(l2) \/ max(l2) < 1\/4:\n\n return False\n\n \n\n return True\n\n \n\n \n\nn = int(input())\n\nfor i in range(n):\n\n c1 = list(map(int, input().split()))\n\n c2 = list(map(int, input().split()))\n\n c3 = list(map(int, input().split()))\n\n if is_a([c1[:2], c1[2:]], [c2[:2], c2[2:]], [c3[:2], c3[2:]], debug=i):\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")","language":"py"} -{"contest_id":"1316","problem_id":"C","statement":"C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+\u22ef+an\u22121xn\u22121f(x)=a0+a1x+\u22ef+an\u22121xn\u22121 and g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1. Let h(x)=f(x)\u22c5g(x)h(x)=f(x)\u22c5g(x). Suppose that h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1\u2264n,m\u2264106,2\u2264p\u22641091\u2264n,m\u2264106,2\u2264p\u2264109), \u00a0\u2014 nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,\u2026,an\u22121a0,a1,\u2026,an\u22121 (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,\u2026,bm\u22121b0,b1,\u2026,bm\u22121 (1\u2264bi\u22641091\u2264bi\u2264109) \u00a0\u2014 bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0\u2264t\u2264n+m\u221220\u2264t\u2264n+m\u22122) \u00a0\u2014 the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2\n1 1 2\n2 1\nOutputCopy1\nInputCopy2 2 999999937\n2 1\n3 1\nOutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.","tags":["constructive algorithms","math","ternary search"],"code":"from pprint import pprint\n\nimport sys\n\nread = sys.stdin.buffer.read\n\nn,m,p, *dat = map(int, read().split())\n\ndata = dat[:n]\n\ndatb = dat[n:]\n\nfor i in range (n):\n\n if data[i]%p != 0:\n\n inda = i\n\n break\n\nfor i in range (m):\n\n if datb[i]%p != 0:\n\n indb = i\n\n break\n\nprint(indb + inda)","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":"t = int(input())\n\n\n\nfor i in range(t):\n\n a, b = (map(int, input().split()))\n\n\n\n if (a==b):\n\n print(0)\n\n elif (a< b and a%2 == b%2) or (a>b and a%2 != b%2):\n\n print(2)\n\n else:\n\n print(1)","language":"py"} -{"contest_id":"1324","problem_id":"D","statement":"D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (ibi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"from bisect import bisect_left\n\n\n\n\n\nn = int(input())\n\na = list(map(int, input().split()))\n\nb = list(map(int, input().split()))\n\n\n\nc = [a[i] - b[i] for i in range(n)]\n\nc.sort()\n\n\n\nans = 0\n\nfor i in range(n):\n\n if c[i] <= 0:\n\n continue\n\n pos = bisect_left(c, -c[i]+1)\n\n ans += i - pos\n\n\n\nprint(ans)\n\n","language":"py"} -{"contest_id":"1292","problem_id":"E","statement":"E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch\u266a - \u5f69This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: \"C\" (as in Carbon), \"H\" (as in Hydrogen), and \"O\" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1\u2264t\u22645001\u2264t\u2264500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4\u2264n\u2264504\u2264n\u226450), the length of the string pp.Then you can make queries of type \"? s\" (1\u2264|s|\u2264n1\u2264|s|\u2264n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (\u22121\u2264k\u2264n\u22121\u2264k\u2264n). If k=\u22121k=\u22121, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a \"Wrong answer\" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264a10:\n\n\t\t\t\n\n\t\t\tif query(\"OOOC\")>0: \n\n\t\t\t\tfor i in range(n):\n\n\t\t\t\t\tif S[i]=='?': S[i] = 'C'\n\n\t\t\telse:\n\n\t\t\t\tfor i in range(n):\n\n\t\t\t\t\tif S[i]=='?': S[i] = 'H'\n\n\t\t\n\n\t\telse:\n\n\t\t\t\n\n\t\t\tif query(\"CCC\")>0:\n\n\t\t\t\tfor i in range(n):\n\n\t\t\t\t\tif S[i]=='?': S[i] = 'O'\n\n\t\t\telif query(\"HHH\")>0:\n\n\t\t\t\tfor i in range(n):\n\n\t\t\t\t\tif S[i]=='?': S[i] = 'O'\n\n\t\t\telse:\n\n\t\t\t\tS[0] = S[1] = 'O'\n\n\t\t\t\tif query(\"OOHH\")>0:\n\n\t\t\t\t\tS[2] = S[3] = 'H'\n\n\t\t\t\telse:\n\n\t\t\t\t\tS[2] = S[3] = 'C'\n\n\t\t\n\n\t\tanswer()\n\n\t\tcontinue\n\n\t\n\n\tsuf = S[known] + S[known+1]\n\n\twhile known > 0:\n\n\t\tquery(S[known] + suf)\n\n\t\tif S[known-1]=='?':\n\n\t\t\tfor i in range(known):\n\n\t\t\t\tS[i] = 'O'\n\n\t\t\tbreak\n\n\t\tknown-=1\n\n\t\tsuf = S[known] + suf\n\n\t\t\n\n\t\n\n\tr = known\n\n\twhile r < n and S[r]!='?': r+=1\n\n\t\n\n\tpref = \"\"\n\n\tfor i in range(r): pref = pref + S[i]\n\n\t\n\n\twhile r < n:\n\n\t\t\n\n\t\tprint(\"I have now \", pref, file = sys.stderr)\n\n\t\t\n\n\t\tif S[r-1]=='O':\n\n\t\t\tquery(pref + \"O\")\n\n\t\t\t\n\n\t\t\tif S[r]=='?':\n\n\t\t\t\tif r==n-1: # ostatni znak\n\n\t\t\t\t\tif query(pref + \"C\")==0:\n\n\t\t\t\t\t\tS[r] = 'H'\n\n\t\t\t\telse: # jeszcze nie\n\n\t\t\t\t\tquery(pref+ \"CC\")\n\n\t\t\t\t\t\n\n\t\t\t\t\tif S[r]=='?': S[r] = S[r+1] = 'H'\n\n\t\t\t\t\t\n\n\t\t\t\n\n\t\telse:\n\n\t\t\tS[r]=S[r-1]\n\n\t\t\n\n\t\twhile r < n and S[r]!='?': \n\n\t\t\tpref = pref + S[r]\n\n\t\t\tr+=1\n\n\t\t\n\n\t\n\n\tanswer()\n\n\t\n\n\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())\ns = input()\n\nsymbols = [(s[i], i) for i in range(n)]\nunsorted = [-1]*n\n\nresult = None\n\nodd_unsorted = True\neven_unsorted = True\n\npairs = dict()\nfor i in range(n):\n pairs[i] = set()\n\nwhile odd_unsorted or even_unsorted:\n even_unsorted = False\n for i in range(0, 2 * (n\/\/2), 2):\n if symbols[i][0] > symbols[i+1][0]:\n even_unsorted = True\n # check constraints\n if len(pairs[symbols[i][1]].intersection(pairs[symbols[i+1][1]])) != 0:\n result = 'NO'\n break\n pairs[symbols[i][1]].add(symbols[i+1][1])\n pairs[symbols[i+1][1]].add(symbols[i][1])\n symbols[i], symbols[i+1] = symbols[i+1], symbols[i]\n\n if result:\n break\n\n odd_unsorted = False\n for i in range(1, 2 * ((n-1)\/\/2) + 1, 2):\n if symbols[i][0] > symbols[i+1][0]:\n odd_unsorted = True\n # check constraints\n if len(pairs[symbols[i][1]].intersection(pairs[symbols[i+1][1]])) != 0:\n result = 'NO'\n break\n pairs[symbols[i][1]].add(symbols[i+1][1])\n pairs[symbols[i+1][1]].add(symbols[i][1])\n symbols[i], symbols[i+1] = symbols[i+1], symbols[i]\n\n if result:\n break\n\nif not result:\n result = 'YES'\n\n for i in range(n):\n if unsorted[i] == -1:\n unsorted[i] = 0\n for j in pairs[i]:\n if unsorted[j] == -1:\n unsorted[j] = (unsorted[i]+1) % 2 \n # else:\n # if unsorted[i] == unsorted[j]:\n # print('ERROR')\n\nprint(result)\nif result == 'YES':\n print(*unsorted, sep='')","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 N:\n\n print(-1)\n\nelse:\n\n rem = []\n\n last = ans[-1]\n\n tmp = 10**9\n\n for _ in range(N-len(ans)):\n\n rem.append(tmp)\n\n tmp -= last+1\n\n ans = ans + rem[::-1]\n\n print(*ans)","language":"py"} -{"contest_id":"1141","problem_id":"C","statement":"C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,\u2026,pnp1,p2,\u2026,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,\u2026,pnp1,p2,\u2026,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 of length n\u22121n\u22121, where qi=pi+1\u2212piqi=pi+1\u2212pi.Given nn and q=q1,q2,\u2026,qn\u22121q=q1,q2,\u2026,qn\u22121, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the length of the permutation to restore. The second line contains n\u22121n\u22121 integers q1,q2,\u2026,qn\u22121q1,q2,\u2026,qn\u22121 (\u2212n psum[min_ind]\n\n\n\noff = 0; offs = [0]\n\nfor elem in q:\n\n off = (off + elem) % n\n\n offs.append(off)\n\n\n\nif len(set(offs)) != len(offs) or max(psum) > n - 1:\n\n print(-1)\n\nelse:\n\n ans = [0 for i in range(n)]\n\n for i in range(n): ans[i] = (psum[i] - min_val) + 1\n\n if not 1 <= max(ans) <= n:\n\n print(-1)\n\n else:\n\n print(' '.join(str(num) for num in ans))\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":"t = int(input())\n\n\n\nwhile t != 0:\n\n a, b = map(int, input().split())\n\n\n\n #a* vi theo quy tac nhan, con b luon co dang 9999999...\n\n #vd 1 -> 1+9+1*9 = 19, 2 = 2+9+2*9 = 29\n\n\n\n #str(b+1) xong lay len -1\n\n #vi 99 se co len(100)-1 = 2\n\n #98 len(99)-1 = 1 (van la 1 cach)\n\n\n\n print( a * ( (len( str(b+1) )) - 1 ))\n\n \n\n \n\n t -= 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":"t=int(input())\n\nfor _ in range(t):\n\n a,b=map(int,input().split())\n\n n=len(str(b))-1\n\n if str(b)=='9'*(n+1):\n\n n+=1\n\n print(a*n)","language":"py"} -{"contest_id":"1322","problem_id":"D","statement":"D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! nn candidates numbered from 11 to nn have been interviewed. The candidate ii has aggressiveness level lili, and recruiting this candidate will cost the show sisi roubles.The show host reviewes applications of all candidates from i=1i=1 to i=ni=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate ii is strictly higher than that of any already accepted candidates, then the candidate ii will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level vv a corresponding profitability value cvcv is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant ii enters the stage, events proceed as follows: The show makes clicli roubles, where lili is initial aggressiveness level of the participant ii. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes ctct roubles, where tt is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total sisi). Help the host to make the show as profitable as possible.InputThe first line contains two integers nn and mm (1\u2264n,m\u226420001\u2264n,m\u22642000) \u2014 the number of candidates and an upper bound for initial aggressiveness levels.The second line contains nn integers lili (1\u2264li\u2264m1\u2264li\u2264m) \u2014 initial aggressiveness levels of all candidates.The third line contains nn integers sisi (0\u2264si\u226450000\u2264si\u22645000) \u2014 the costs (in roubles) to recruit each of the candidates.The fourth line contains n+mn+m integers cici (|ci|\u22645000|ci|\u22645000) \u2014 profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n+mn+m under given conditions.OutputPrint a single integer\u00a0\u2014 the largest profit of the show.ExamplesInputCopy5 4\n4 3 1 2 1\n1 2 1 2 1\n1 2 3 4 5 6 7 8 9\nOutputCopy6\nInputCopy2 2\n1 2\n0 0\n2 1 -100 -100\nOutputCopy2\nInputCopy5 4\n4 3 2 1 1\n0 2 6 7 4\n12 12 12 6 -3 -5 3 10 -4\nOutputCopy62\nNoteIn the first sample case it is optimal to recruit candidates 1,2,3,51,2,3,5. Then the show will pay 1+2+1+1=51+2+1+1=5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 44 enters the stage, the show makes 44 roubles; a participant with aggressiveness level 33 enters the stage, the show makes 33 roubles; a participant with aggressiveness level 11 enters the stage, the show makes 11 rouble; a participant with aggressiveness level 11 enters the stage, the show makes 11 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 22. The show will make extra 22 roubles for this. Total revenue of the show will be 4+3+1+1+2=114+3+1+1+2=11 roubles, and the profit is 11\u22125=611\u22125=6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 11.","tags":["bitmasks","dp"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nn,m=map(int,input().split())\n\nA=list(map(int,input().split()))\n\nC=list(map(int,input().split()))\n\nP=list(map(int,input().split()))\n\n\n\nDP=[[-1<<30]*(n+1) for i in range(5001)]\n\n# DP[k][cnt] = A\u306emax\u304ck\u3067, \u305d\u3046\u3044\u3046\u4eba\u9593\u304ccnt\u4eba\u3044\u308b\u3068\u304d\u306eprofit\u306e\u6700\u5927\u5024\n\n\n\nfor i in range(5001):\n\n DP[i][0]=0\n\n\n\nfor i in range(n-1,-1,-1):\n\n a,c = A[i]-1,C[i]\n\n\n\n for j in range(n,-1,-1):\n\n if DP[a][j]==-1<<30:\n\n continue\n\n \n\n if DP[a][j] - c + P[a] > DP[a][j+1]:\n\n DP[a][j+1] = DP[a][j] - c + P[a]\n\n\n\n x, w=a, j+1\n\n while x+10s>0) opponents remaining and tt (0\u2264t\u2264s0\u2264t\u2264s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s\u2212ts\u2212t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10\u2212410\u22124. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a\u2212b|max(1,b)\u226410\u22124|a\u2212b|max(1,b)\u226410\u22124.ExamplesInputCopy1\nOutputCopy1.000000000000\nInputCopy2\nOutputCopy1.500000000000\nNoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.","tags":["combinatorics","greedy","math"],"code":"import math\n\nout = 0.0\n\ninp = int(input());\n\nfor i in range(1,inp + 1) :\n\n out = out + 1\/i\n\nprint(out)\n\n","language":"py"} -{"contest_id":"1286","problem_id":"C1","statement":"C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r \u2013 ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s \u2013 guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)2(n+1)2.Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than (n+1)2(n+1)2 substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict.Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the length of the string, and the following line should contain the string ss.ExampleInputCopy4\n\na\naa\na\n\ncb\nb\nc\n\ncOutputCopy? 1 2\n\n? 3 4\n\n? 4 4\n\n! aabc","tags":["brute force","constructive algorithms","interactive","math"],"code":"import sys\n\ninput = sys.stdin.readline\n\nfrom bisect import bisect_left\n\n\n\nn = int(input())\n\nprint('?', 1, n)\n\nsys.stdout.flush()\n\nm = (n + 1) \/\/ 2\n\nl1 = [[0] * 26 for _ in range(m + 1)]\n\nfor i in range(n * (n + 1) \/\/ 2):\n\n s = input()[:-1]\n\n if len(s) <= m:\n\n for j in range(len(s)):\n\n l1[len(s)][ord(s[j]) - 97] += 1\n\nfor i in range(m, 0, -1):\n\n for j in range(26):\n\n l1[i][j] -= l1[i - 1][j]\n\nfor i in range(m):\n\n for j in range(26):\n\n l1[i][j] -= l1[i + 1][j]\n\nif n > 1:\n\n n = n - 1\n\n print('?', 1, n)\n\n sys.stdout.flush()\n\n m = (n + 1) \/\/ 2\n\n l2 = [[0] * 26 for _ in range(m + 1)]\n\n for i in range(n * (n + 1) \/\/ 2):\n\n s = input()[:-1]\n\n if len(s) <= m:\n\n for j in range(len(s)):\n\n l2[len(s)][ord(s[j]) - 97] += 1\n\n for i in range(m, 0, -1):\n\n for j in range(26):\n\n l2[i][j] -= l2[i - 1][j]\n\n for i in range(m):\n\n for j in range(26):\n\n l2[i][j] -= l2[i + 1][j]\n\n n += 1\n\nx = [-1] * n\n\ny = [-1] * n\n\nfor i in range(n):\n\n if i % 2 == 0:\n\n for j in range(26):\n\n if l1[i\/\/2+1][j] >= 1:\n\n l1[i\/\/2+1][j] -= 1\n\n x[i] = j\n\n break\n\n for j in range(26):\n\n if l1[i\/\/2+1][j] >= 1:\n\n l1[i\/\/2+1][j] -= 1\n\n y[i] = j\n\n break\n\n else:\n\n for j in range(26):\n\n if l2[i\/\/2+1][j] >= 1:\n\n l2[i\/\/2+1][j] -= 1\n\n x[i] = j\n\n break\n\n for j in range(26):\n\n if l2[i\/\/2+1][j] >= 1:\n\n l2[i\/\/2+1][j] -= 1\n\n y[i] = j\n\n break\n\nans = [0] * n\n\nm = (n + 1) \/\/ 2\n\nll = []\n\nif n % 2 == 1:\n\n ll.append(n \/\/ 2)\n\n for i in range(n \/\/ 2):\n\n ll.append(n \/\/ 2 - i - 1)\n\n ll.append(n \/\/ 2 + i + 1)\n\nelse:\n\n for i in range(n \/\/ 2):\n\n ll.append(n \/\/ 2 - i - 1)\n\n ll.append(n \/\/ 2 + i)\n\nans[ll[0]] = x[-1]\n\nt = 0\n\nfor i in range(n - 1):\n\n if t == 0:\n\n if x[n - i - 2] == x[n - i - 1]:\n\n ans[ll[i + 1]] = y[n - i - 2]\n\n t = 1\n\n else:\n\n ans[ll[i + 1]] = x[n - i - 2]\n\n else:\n\n if x[n - i - 2] == y[n - i - 1]:\n\n ans[ll[i + 1]] = y[n - i - 2]\n\n else:\n\n ans[ll[i + 1]] = x[n - i - 2]\n\n t = 0\n\nprint('! ', *map(lambda x:chr(x+97), ans), sep='')","language":"py"} -{"contest_id":"1284","problem_id":"C","statement":"C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n. This indicates the subsegment where l\u22121l\u22121 elements from the beginning and n\u2212rn\u2212r elements from the end are deleted from the sequence.For a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212lmax{pl,pl+1,\u2026,pr}\u2212min{pl,pl+1,\u2026,pr}=r\u2212l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1\u2264n\u22642500001\u2264n\u2264250000, 108\u2264m\u2264109108\u2264m\u2264109, mm is prime).OutputPrint rr (0\u2264r 0:\n\n res += self.bit[i]\n\n i -= i & (-i)\n\n return res\n\n\n\nclass RangeAddBIT:\n\n def __init__(self, n):\n\n self.n = n\n\n self.bit1 = BIT(n)\n\n self.bit2 = BIT(n)\n\n\n\n def init(self, init_val):\n\n self.bit2.init(init_val)\n\n\n\n def add(self, l, r, x):\n\n # add x to [l, r)\n\n # l, r: 0-indexed\n\n self.bit1.add(l, x)\n\n self.bit1.add(r, -x)\n\n self.bit2.add(l, -x*l)\n\n self.bit2.add(r, x*r)\n\n\n\n def sum(self, l, r):\n\n # return sum of [l, r)\n\n # l, r: 0-indexed\n\n return self._sum(r) - self._sum(l)\n\n\n\n def _sum(self, i):\n\n # return sum of [0, i)\n\n # i: 0-indexed\n\n return self.bit1._sum(i)*i + self.bit2._sum(i)\n\n\n\n def __str__(self): # for debug\n\n arr = [self.sum(i,i+1) for i in range(self.n)]\n\n return str(arr)\n\n\n\nn, m = map(int, input().split())\n\nA = list(map(int, input().split()))\n\nA = [a-1 for a in A]\n\n\n\nmn = [i for i in range(n)]\n\nfor a in A:\n\n mn[a] = 0\n\n\n\nA = list(range(n-1, -1, -1))+A\n\nbit = RangeAddBIT(len(A)+1)\n\nmx = [i for i in range(n)]\n\nprev = [-1]*n\n\nfor r, a in enumerate(A):\n\n l = prev[a]\n\n mx[a] = max(mx[a], bit.sum(l, l+1))\n\n bit.add(l+1, r, 1)\n\n prev[a] = r\n\nfor a in range(n):\n\n l = prev[a]\n\n mx[a] = max(mx[a], bit.sum(l, l+1))\n\n\n\nfor i in range(n):\n\n print(mn[i]+1, mx[i]+1)\n\n","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\nfor i in range(t):\n\n n=int(input())\n\n if n%2!=0:\n\n s='7'\n\n for j in range((n-3)\/\/2):\n\n s+=\"1\"\n\n print(s)\n\n else:\n\n s=\"\"\n\n for j in range(n\/\/2):\n\n s+='1'\n\n print(s)","language":"py"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"from functools import lru_cache\n\nn = int(input())\n\np = list(map(int, input().split()))\n\nc = [i % 2 for i in p].count(1)\n\nif n % 2 == 0:\n\n t = n \/\/ 2 - c\n\nelse:\n\n t = n \/\/ 2 - c + 1\n\n@lru_cache(None)\n\ndef dfs(i, t, q):\n\n if t < 0 or t > n - i:\n\n return float(\"inf\")\n\n elif i == n:\n\n return 0 if t == 0 else float(\"inf\")\n\n if p[i] == 0:\n\n if q == 0:\n\n return min(dfs(i + 1, t, 0), dfs(i + 1, t - 1, 1) + 1)\n\n else:\n\n return min(dfs(i + 1, t - 1, 1), dfs(i + 1, t, 0) + 1)\n\n else:\n\n return abs(q - p[i] % 2) + dfs(i + 1, t, p[i] % 2)\n\nif p[0] == 0:\n\n print(min(dfs(1, t - 1, 1), dfs(1, t, 0)))\n\nelse:\n\n print(dfs(1, t, p[0] % 2))","language":"py"} -{"contest_id":"1323","problem_id":"B","statement":"B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n\u00d7mn\u00d7m formed by following rule: ci,j=ai\u22c5bjci,j=ai\u22c5bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1\u2264x1\u2264x2\u2264n1\u2264x1\u2264x2\u2264n, 1\u2264y1\u2264y2\u2264m1\u2264y1\u2264y2\u2264m) a subrectangle c[x1\u2026x2][y1\u2026y2]c[x1\u2026x2][y1\u2026y2] is an intersection of the rows x1,x1+1,x1+2,\u2026,x2x1,x1+1,x1+2,\u2026,x2 and the columns y1,y1+1,y1+2,\u2026,y2y1,y1+1,y1+2,\u2026,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1\u2264n,m\u226440000,1\u2264k\u2264n\u22c5m1\u2264n,m\u226440000,1\u2264k\u2264n\u22c5m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410\u2264ai\u22641), elements of aa.The third line contains mm integers b1,b2,\u2026,bmb1,b2,\u2026,bm (0\u2264bi\u226410\u2264bi\u22641), elements of bb.OutputOutput single integer\u00a0\u2014 the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2\n1 0 1\n1 1 1\nOutputCopy4\nInputCopy3 5 4\n1 1 1\n1 1 1 1 1\nOutputCopy14\nNoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is: ","tags":["binary search","greedy","implementation"],"code":"def helper(arr):\n\n res=[0]*(len(arr)+1)\n\n i=0\n\n while ix|z y:\n\n x, y = y, x\n\n edge[(x, y)] = i\n\n cc[x] += 1\n\n cc[y] += 1\n\nck1 = [0] * (n + 1)\n\nno = 0\n\nfor i in cc:\n\n ck1[i] += 1\n\n no = max(no, ck1[i])\n\ntot = 0\n\nfor i in range(n, 0, -1):\n\n if tot <= k:\n\n no = min(no, i)\n\n tot += ck1[i]\n\nprint(no)\n\nans = [0] * (n - 1)\n\nd = deque()\n\nd.append(1)\n\nwhile d:\n\n i = d.popleft()\n\n color = set()\n\n pair = []\n\n for j in a[i]:\n\n x = i\n\n y = j\n\n if x > y:\n\n x, y = y, x\n\n z = ans[edge[(x, y)]]\n\n if z:\n\n color.add(z)\n\n else:\n\n pair.append([x, y])\n\n d.append(j)\n\n j = 1\n\n while pair and j <= no:\n\n if j in color:\n\n j += 1\n\n else:\n\n x, y = pair.pop()\n\n ans[edge[(x, y)]] = j\n\n j += 1\n\n j = no\n\n while pair:\n\n x, y = pair.pop()\n\n ans[edge[(x, y)]] = j\n\n j -= 1\n\n if j == 0:\n\n j = no\n\n\n\nprint(*ans)\n\n","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 os,sys\n\nfrom random import randint, shuffle\n\nfrom io import BytesIO, IOBase\n\n\n\nfrom collections import defaultdict,deque,Counter\n\nfrom bisect import bisect_left,bisect_right\n\nfrom heapq import heappush,heappop\n\nfrom functools import lru_cache\n\nfrom itertools import accumulate, permutations\n\nimport math\n\n\n\n# Fast IO Region\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\n# for _ in range(int(input())):\n\n# n = int(input())\n\n# a = list(map(int, input().split()))\n\n\n\nfor _ in range(int(input())):\n\n a, b, c = list(map(int, input().split()))\n\n ans = 0\n\n for i in range(1 << 7):\n\n x = y = z = 0\n\n cnt = 0\n\n for j in range(7):\n\n if i >> j & 1:\n\n cnt += 1\n\n if j == 0:\n\n x += 1\n\n elif j == 1:\n\n y += 1\n\n elif j == 2:\n\n z += 1\n\n elif j == 3:\n\n x += 1\n\n y += 1\n\n elif j == 4:\n\n x += 1\n\n z += 1\n\n elif j == 5:\n\n y += 1\n\n z += 1\n\n else:\n\n x += 1\n\n y += 1\n\n z += 1\n\n if x <= a and y <= b and z <= c:\n\n ans = max(ans, cnt)\n\n print(ans)\n\n\n\n\n\n\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":"from collections import defaultdict, Counter, deque\n\nimport threading\n\nimport sys\n\n# input = sys.stdin.readline\n\ndef ri(): return int(input())\n\ndef rs(): return input()\n\ndef rl(): return list(map(int, input().split()))\n\ndef rls(): return list(input().split())\n\n\n\n\n\nthreading.stack_size(10**8)\n\nsys.setrecursionlimit(10**6)\n\n\n\n\n\ndef main():\n\n n = ri()\n\n a = [0]+rl()\n\n for i in range(n+1):\n\n if i != 0 and a[i] == 0:\n\n a[i] = -1\n\n g = defaultdict(list)\n\n for _ in range(n-1):\n\n u, v = rl()\n\n g[u].append(v)\n\n g[v].append(u)\n\n par = [-1]*(n+1)\n\n dp = [0]*(n+1)\n\n\n\n def d1(cn, p):\n\n par[cn] = p\n\n dp[cn] = a[cn]\n\n for nn in g[cn]:\n\n if nn != p:\n\n dp[cn] += max(0, d1(nn, cn))\n\n return dp[cn]\n\n d1(1, 0)\n\n\n\n def d2(cn, p):\n\n if cn != 1:\n\n if dp[cn] > 0:\n\n res[cn] = max(res[par[cn]], dp[cn])\n\n else:\n\n res[cn] = max(res[par[cn]]+dp[cn], dp[cn])\n\n for nn in g[cn]:\n\n if nn != p:\n\n d2(nn, cn)\n\n\n\n res = [0]*(n+1)\n\n res[1] = dp[1]\n\n d2(1, 0)\n\n print(*res[1:])\n\n pass\n\n\n\n\n\n# main()\n\nthreading.Thread(target=main).start()\n\n","language":"py"} -{"contest_id":"1292","problem_id":"E","statement":"E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch\u266a - \u5f69This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: \"C\" (as in Carbon), \"H\" (as in Hydrogen), and \"O\" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1\u2264t\u22645001\u2264t\u2264500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4\u2264n\u2264504\u2264n\u226450), the length of the string pp.Then you can make queries of type \"? s\" (1\u2264|s|\u2264n1\u2264|s|\u2264n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (\u22121\u2264k\u2264n\u22121\u2264k\u2264n). If k=\u22121k=\u22121, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a \"Wrong answer\" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264a1= 13:\n\n ans = [''] * (n + 1)\n\n print('? CO')\n\n co = list(map(int, input().split()))[1:]\n\n print('? CH')\n\n ch = list(map(int, input().split()))[1:]\n\n print('? CC')\n\n cc = list(map(int, input().split()))[1:]\n\n for d in co:\n\n ans[d] = 'C'\n\n ans[d + 1] = 'O'\n\n for d in ch:\n\n ans[d] = 'C'\n\n ans[d + 1] = 'H'\n\n for d in cc:\n\n ans[d] = 'C'\n\n ans[d + 1] = 'C'\n\n print('? OO')\n\n oo = list(map(int, input().split()))[1:]\n\n print('? OH')\n\n oh = list(map(int, input().split()))[1:]\n\n for d in oo:\n\n ans[d] = 'O'\n\n ans[d + 1] = 'O'\n\n for d in oh:\n\n ans[d] = 'O'\n\n ans[d + 1] = 'H'\n\n for i in range(1, n):\n\n if ans[i] == 'O' and ans[i + 1] == '':\n\n ans[i + 1] = 'C'\n\n for i in range(1, n):\n\n if ans[i] == '' and ans[i + 1] == 'O':\n\n ans[i] = 'H'\n\n for i in range(1, n):\n\n if ans[i] == '' and ans[i + 1] == 'H':\n\n ans[i] = 'H'\n\n for i in range(1, n):\n\n if ans[i] == '' and ans[i + 1] == '':\n\n ans[i] = 'H'\n\n print('? HOC')\n\n hoc = list(map(int, input().split()))[1:]\n\n for d in hoc:\n\n ans[d] = 'H'\n\n ans[d + 1] = 'O'\n\n ans[d + 2] = 'C'\n\n for d in range(2, n):\n\n if ans[d] == '':\n\n ans[d] = 'H'\n\n if ans[1] == '':\n\n print('?', 'H' + ''.join(ans[2:-1]))\n\n if input()[0] != '0':\n\n ans[1] = 'H'\n\n else:\n\n ans[1] = 'O'\n\n if ans[-1] == '':\n\n print('?', ''.join(ans[1:-1]) + 'H')\n\n if input()[0] != '0':\n\n ans[-1] = 'H'\n\n else:\n\n print('?', ''.join(ans[1:-1]) + 'O')\n\n if input()[0] != '0':\n\n ans[-1] = 'O'\n\n else:\n\n ans[-1] = 'C'\n\n print('!', ''.join(ans[1:]))\n\n kek = input()\n\n else:\n\n L, minID = n, n\n\n s = 'L' * n\n\n\n\n query('?', \"CH\")\n\n query('?', \"CO\")\n\n query('?', \"HC\")\n\n query('?', \"HO\")\n\n if (L == n):\n\n # the string exists in form O...OX...X, with X=C or X=H\n\n # or it's completely mono-character\n\n query('?', \"CCC\")\n\n if (minID < n):\n\n for x in range(minID - 1, -1, -1): fill(x, 'O')\n\n else:\n\n query('?', \"HHH\")\n\n if (minID < n):\n\n for x in range(minID - 1, -1, -1): fill(x, 'O')\n\n else:\n\n query('?', \"OOO\")\n\n if (minID == n):\n\n # obviously n=4\n\n query('?', \"OOCC\")\n\n if (minID == n):\n\n fill(0, 'O')\n\n fill(1, 'O')\n\n fill(2, 'H')\n\n fill(3, 'H')\n\n\n\n if (s[n - 1] == 'L'):\n\n t = s[0:n - 1] + 'C'\n\n if (t[n - 2] == 'L'): t = t[0:n - 2] + 'C' + t[n - 1:]\n\n query('?', t)\n\n if (s[n - 1] == 'L'):\n\n fill(n - 1, 'H')\n\n if (s[n - 2] == 'L'): fill(n - 2, 'H')\n\n else:\n\n maxID = minID\n\n while (maxID < n - 1 and s[maxID + 1] != 'L'): maxID += 1\n\n for i in range(minID - 1, -1, -1):\n\n query('?', s[i + 1:i + 2] + s[minID:maxID + 1])\n\n if (minID != i):\n\n for x in range(i + 1): fill(x, 'O')\n\n break\n\n\n\n nextFilled = None\n\n i = maxID + 1\n\n while i < n:\n\n if (s[i] != 'L'):\n\n i += 1\n\n continue\n\n nextFilled = i\n\n while (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1\n\n query('?', s[0:i] + s[i - 1])\n\n if (s[i] == 'L'):\n\n if (s[i - 1] != 'O'):\n\n fill(i, 'O')\n\n else:\n\n if (nextFilled == n):\n\n query('?', s[0:i] + 'C')\n\n if (s[i] == 'L'): fill(i, 'H')\n\n for x in range(i + 1, nextFilled): fill(x, s[i])\n\n else:\n\n for x in range(i, nextFilled): fill(x, s[nextFilled])\n\n i = nextFilled - 1\n\n i += 1\n\n query('!', s)","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":"def solve(n, d, arr):\n\n\n\n i = 1\n\n while d > 0 and i < n:\n\n\n\n if arr[i] <= 0 or d < i:\n\n i += 1\n\n elif d >= i:\n\n d -= i\n\n arr[0] += 1\n\n arr[i] -= 1\n\n\n\n return arr[0]\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n\n t = int(input())\n\n\n\n results = list()\n\n for _ in range(0, t):\n\n n, d = list(map(int, input().split(\" \")))\n\n arr = list(map(int, input().split(\" \")))\n\n results.append(solve(n, d, arr))\n\n\n\n for result in results:\n\n print(result)","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":"tst = int(input()) \n\nfor i in range(tst) :\n\n arr = list(map(int, input().rstrip().split()))\n\n arr.sort()\n\n a, b, c = arr[2], arr[1], arr[0]\n\n cnt = 0\n\n if a >= 4 and b >= 4 and c >= 4 :\n\n print(7)\n\n continue\n\n if a > 0 :\n\n a -= 1\n\n cnt += 1\n\n if b > 0 :\n\n b -= 1\n\n cnt += 1\n\n if c > 0 :\n\n c -= 1\n\n cnt += 1\n\n if a > 0 and b > 0:\n\n a -= 1\n\n b -= 1\n\n cnt += 1\n\n if a > 0 and c > 0:\n\n a -= 1\n\n c -= 1\n\n cnt += 1\n\n if b > 0 and c > 0 :\n\n b -= 1\n\n c -= 1\n\n cnt += 1\n\n if a > 0 and b > 0 and c > 0 :\n\n a -= 1\n\n b -= 1\n\n c -= 1\n\n cnt += 1\n\n print(cnt)","language":"py"} -{"contest_id":"1322","problem_id":"A","statement":"A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting \"+\" and \"1\" you can get a well-formed mathematical expression from it. For example; sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not.The teacher gave Dmitry's class a very strange task\u00a0\u2014 she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word \"correct\" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for \"))((\" he can choose the substring \")(\" and do reorder \")()(\" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 the length of Dima's sequence.The second line contains string of length nn, consisting of characters \"(\" and \")\" only.OutputPrint a single integer\u00a0\u2014 the minimum number of nanoseconds to make the sequence correct or \"-1\" if it is impossible to do so.ExamplesInputCopy8\n))((())(\nOutputCopy6\nInputCopy3\n(()\nOutputCopy-1\nNoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with \"()()\"; the whole sequence will be \"()()())(\". And then reorder the segment from the seventh to eighth character; replacing it with \"()\". In the end the sequence will be \"()()()()\"; while the total time spent is 4+2=64+2=6 nanoseconds.","tags":["greedy"],"code":"import sys\n\ninput=sys.stdin.readline\n\ndef validparenthesis(s,i,j):\n\n stack=[]\n\n for idx in range(i,j+1):\n\n if s[idx]=='(':stack.append(s[idx])\n\n else:\n\n if len(stack)==0:return False\n\n else:\n\n stack.pop()\n\n if len(stack)!=0:return False\n\n return True\n\nfrom collections import Counter\n\nn=int(input())\n\ns=input().rstrip()\n\nd=Counter(s)\n\nif d[')']!=d['('] or n==1:print(-1)\n\nelse:\n\n i=c1=c2=0\n\n j=0\n\n ans=0\n\n while j 0:\n\n f[i][j] = f[i][j - 1]\n\n if j < a[i][1]:\n\n for k in range(i, -1, -1):\n\n if a[k][1] <= j or j < a[k][0]:\n\n break\n\n if k == 0 or j != 0:\n\n tmp = cal(i - k + 1, g[j])\n\n if k > 0:\n\n f[i][j] += f[k - 1][j - 1] * tmp % M\n\n else:\n\n f[i][j] += tmp\n\n f[i][j] %= M\n\n \n\n#print(f)\n\n#print(f[n - 1][len(b) - 1], res)\n\nprint(f[n - 1][len(b) - 1] * pw(res, M - 2) % M)\n\n","language":"py"} -{"contest_id":"1313","problem_id":"C1","statement":"C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n\u22641000n\u22641000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiaitop:\n\n\t\t\ta=top\n\n\t\telse:\n\n\t\t\ttop=a\n\n\t\tans+=a\n\n\t\tarr.append(a)\n\n\treturn ans,arr\n\n\n\ncnt=0\n\nans=[]\n\nfor i in range(N):\n\n\tA = M[:i][::-1]\n\n\tB = M[i+1:]\n\n\tt1,a1=deal(M[i],A)\n\n\tt2,a2=deal(M[i],B)\n\n\tt = t1+t2+M[i]\n\n\tif t>cnt:\n\n\t\tcnt=t\n\n\t\tans = a1[::-1]+[M[i]]+a2\n\n\n\n#print(cnt)\n\nprint(*ans)\n\n","language":"py"} -{"contest_id":"1141","problem_id":"F1","statement":"F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],\u2026,a[n].a[1],a[2],\u2026,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],\u2026,a[r]a[l],a[l+1],\u2026,a[r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),\u2026,(lk,rk)(l1,r1),(l2,r2),\u2026,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i\u2260ji\u2260j either rikk\u2032>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1\u2264n\u2264501\u2264n\u226450) \u2014 the length of the given array. The second line contains the sequence of elements a[1],a[2],\u2026,a[n]a[1],a[2],\u2026,a[n] (\u2212105\u2264ai\u2264105\u2212105\u2264ai\u2264105).OutputIn the first line print the integer kk (1\u2264k\u2264n1\u2264k\u2264n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1\u2264li\u2264ri\u2264n1\u2264li\u2264ri\u2264n) \u2014 the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7\n4 1 2 2 1 5 3\nOutputCopy3\n7 7\n2 3\n4 5\nInputCopy11\n-5 -4 -3 -2 -1 0 1 2 3 4 5\nOutputCopy2\n3 4\n1 1\nInputCopy4\n1 1 1 1\nOutputCopy4\n4 4\n1 1\n2 2\n3 3\n","tags":["greedy"],"code":"from itertools import*\n\nfrom collections import*\n\nn=int(input())\n\narr=[0] +[*accumulate(map(int,input().split()))]\n\ng=defaultdict(list)\n\nfor i in range(n):\n\n for j in range(i+1,n+1):\n\n g[arr[j] -arr[i]].append([i+1,j])\n\nans=[]\n\nmaxi=[]\n\nfor i in g:\n\n f=sorted(g[i],key=lambda x:x[1])\n\n ans=[f[0]]\n\n for l,r in f:\n\n if l >ans[-1][1]:\n\n ans.append([l,r])\n\n maxi=max(maxi,ans,key=len)\n\nprint(len(maxi))\n\nfor i in maxi:\n\n print(*i)","language":"py"} -{"contest_id":"1303","problem_id":"A","statement":"A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1\u2264|s|\u22641001\u2264|s|\u2264100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3\n010011\n0\n1111000\nOutputCopy2\n0\n0\nNoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).","tags":["implementation","strings"],"code":"t = int(input())\n\nfor i in range(t):\n\n s = input()\n\n if ('1' in s) == True:\n\n l = s.index('1')\n\n r = s.rindex('1')\n\n s = s[l:r].count('0')\n\n print(s)\n\n else:\n\n print(0)","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 if b&1 :\n\n p=p*x\n\n p = p%mod\n\n b = b>>1\n\n x = x**x\n\n x = x%mod\n\n return p%mod\n\n \n\ndef seive(n):\n\n a = []\n\n prime = [True for i in range(n+1)] \n\n p = 2\n\n while (p * p <= n): \n\n if (prime[p] == True): \n\n for i in range(p ** 2,n + 1, p): \n\n prime[i] = False\n\n p = p + 1\n\n for p in range(2,n + 1): \n\n if prime[p]: \n\n primes.append(p)\n\n\n\ndef is_sorted(arr):\n\n return all(arr[i]<=arr[i+1] for i in range(len(arr)-1))\n\n\n\ndef invmod(n):\n\n return power(n,mod-2)\n\n\n\ndef binary_search(a,x,lo=0,hi=None):\n\n if hi is None:\n\n hi = len(a)\n\n while lo < hi:\n\n mid = (lo+hi)\/\/2\n\n midval = a[mid]\n\n if midval < x:\n\n lo = mid+1\n\n elif midval > x: \n\n hi = mid\n\n else:\n\n return mid\n\n return -1\n\n\n\ndef yn(x):\n\n if x :\n\n sys.stdout.write(\"YES\"+\"\\n\")\n\n else :\n\n sys.stdout.write(\"NO\"+\"\\n\")\n\n\n\ndef nCr(n,r)->int :\n\n return factorial(n)\/\/(factorial(r)*factorial(n-r))\n\n\n\ndef solve()->None :\n\n n,m,p=map(int,input().split())\n\n an = list(map(int,input().split()))\n\n am = list(map(int,input().split()))\n\n i,j=0,0\n\n while ic1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck\u22121ck>ck\u22121. So, the sequence of visited cities [c1,c2,\u2026,ck][c1,c2,\u2026,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1\u2212ci=bci+1\u2212bcici+1\u2212ci=bci+1\u2212bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1\u2264bi\u22644\u22c51051\u2264bi\u22644\u22c5105), where bibi is the beauty value of the ii-th city.OutputPrint one integer \u2014 the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6\n10 7 1 9 10 15\nOutputCopy26\nInputCopy1\n400000\nOutputCopy400000\nInputCopy7\n8 9 26 11 12 29 14\nOutputCopy55\nNoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].","tags":["data structures","dp","greedy","math","sortings"],"code":"n = int(input())\na = list(map(int, input().split()))\n\nsol = [i-a[i] for i in range(n)]\n\nval = {}\nans = 0\nfor i in range(n):\n if sol[i] not in val:\n val[sol[i]] = a[i]\n else:\n val[sol[i]] += a[i]\n\n ans = max(ans, val[sol[i]])\n\nprint(ans)\n","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":"t = int(input())\n\nfor i in range(t):\n\n n = int(input())\n\n l = list(map(int,input().split()))\n\n flag = True\n\n for i in range(n-2):\n\n try:\n\n x = l.index(l[i],i+2)\n\n flag = False\n\n print(\"YES\")\n\n break\n\n except:\n\n continue\n\n if flag:\n\n print(\"NO\")\n\n","language":"py"} -{"contest_id":"1294","problem_id":"B","statement":"B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1\u2264j\u2264n1\u2264j\u2264n that for all ii from 11 to j\u22121j\u22121 si=tisi=ti and sj> 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":"1141","problem_id":"B","statement":"B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day \u2014 it is a sequence a1,a2,\u2026,ana1,a2,\u2026,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 number of hours per day.The second line contains nn integer numbers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u226410\u2264ai\u22641), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5\n1 0 1 0 1\nOutputCopy2\nInputCopy6\n0 1 0 1 1 0\nOutputCopy2\nInputCopy7\n1 0 1 1 1 0 1\nOutputCopy3\nInputCopy3\n0 0 0\nOutputCopy0\nNoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.","tags":["implementation"],"code":"from itertools import groupby\n\nn = int(input())\na = list(map(int, input().split()))\ngroups = [(k, sum(1 for _ in v)) for k, v in groupby(a)]\nmidnight = groups[0][1] + groups[-1][1] if groups[0][0] == groups[-1][0] == 1 else 0\nprint(max(midnight, max([n for k, n in groups if k == 1], default=0)))\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":"def solve():\n\n n = int(input())\n\n aseq = read_ints()\n\n\n\n last = aseq[0]\n\n last_idx = 0\n\n for i in range(n):\n\n if aseq[i] >= i:\n\n last = aseq[i]\n\n last_idx = i\n\n else:\n\n break\n\n\n\n # print(last, last_idx)\n\n # print(aseq)\n\n\n\n\n\n for i in range(last_idx+1, n):\n\n # print(aseq[i], last-1)\n\n if aseq[i] >= aseq[i-1]:\n\n if aseq[i-1] - 1 < 0:\n\n return False\n\n\n\n aseq[i] = aseq[i-1] - 1\n\n\n\n return True\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":"1316","problem_id":"C","statement":"C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+\u22ef+an\u22121xn\u22121f(x)=a0+a1x+\u22ef+an\u22121xn\u22121 and g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121g(x)=b0+b1x+\u22ef+bm\u22121xm\u22121, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1gcd(a0,a1,\u2026,an\u22121)=gcd(b0,b1,\u2026,bm\u22121)=1. Let h(x)=f(x)\u22c5g(x)h(x)=f(x)\u22c5g(x). Suppose that h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122h(x)=c0+c1x+\u22ef+cn+m\u22122xn+m\u22122. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1\u2264n,m\u2264106,2\u2264p\u22641091\u2264n,m\u2264106,2\u2264p\u2264109), \u00a0\u2014 nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,\u2026,an\u22121a0,a1,\u2026,an\u22121 (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,\u2026,bm\u22121b0,b1,\u2026,bm\u22121 (1\u2264bi\u22641091\u2264bi\u2264109) \u00a0\u2014 bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0\u2264t\u2264n+m\u221220\u2264t\u2264n+m\u22122) \u00a0\u2014 the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2\n1 1 2\n2 1\nOutputCopy1\nInputCopy2 2 999999937\n2 1\n3 1\nOutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.","tags":["constructive algorithms","math","ternary search"],"code":"t=list(map(int,input().split(\" \")))\n\np=int(t[2])\n\na=list(map(int,input().split(\" \")))\n\nb=list(map(int,input().split(\" \")))\n\nans=0\n\nt=0\n\nfor i in a:\n\n if i%p!=0:\n\n ans+=t\n\n break\n\n t+=1\n\nt=0\n\nfor i in b:\n\n if i%p!=0:\n\n ans+=t\n\n break\n\n t+=1\n\nprint(\"%d\"%(ans))","language":"py"} -{"contest_id":"1294","problem_id":"F","statement":"F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3\u2264n\u22642\u22c51053\u2264n\u22642\u22c5105) \u2014 the number of vertices in the tree. Next n\u22121n\u22121 lines describe the edges of the tree in form ai,biai,bi (1\u2264ai1\u2264ai, bi\u2264nbi\u2264n, ai\u2260biai\u2260bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres \u2014 the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1\u2264a,b,c\u2264n1\u2264a,b,c\u2264n and a\u2260,b\u2260c,a\u2260ca\u2260,b\u2260c,a\u2260c.If there are several answers, you can print any.ExampleInputCopy8\n1 2\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8\nOutputCopy5\n1 8 6\nNoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.","tags":["dfs and similar","dp","greedy","trees"],"code":"import os, sys\n\nfrom io import BytesIO, IOBase\n\nfrom collections import *\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, 8192))\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, 8192))\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\nclass graph:\n\n def __init__(self, n):\n\n self.n, self.gdict = n, [[] for _ in range(n + 1)]\n\n\n\n def addEdge(self, node1, node2):\n\n self.gdict[node1].append(node2)\n\n self.gdict[node2].append(node1)\n\n\n\n def subtree(self, v):\n\n queue, visit, child = deque([v]), [False] * (n + 1), []\n\n visit[v], ma, parent, maxes = True, [0] * (n + 1), [-1] * (n + 1), [[-10 ** 9, 0] for _ in range(n + 1)]\n\n\n\n while queue:\n\n s = queue.popleft()\n\n\n\n for i1 in self.gdict[s]:\n\n if not visit[i1]:\n\n queue.append(i1)\n\n visit[i1] = True\n\n child.append(i1)\n\n parent[i1] = s\n\n\n\n for i in child[::-1]:\n\n ma[parent[i]] = max(ma[i] + 1, ma[parent[i]])\n\n maxes[parent[i]].append(ma[i] + 1)\n\n\n\n for i in range(1, n + 1):\n\n maxes[i] = sorted(maxes[i])[-3:]\n\n\n\n for i in child:\n\n new = -1\n\n if maxes[parent[i]][-1] == ma[i] + 1:\n\n new = -2\n\n\n\n maxes[i].append(maxes[parent[i]][new] + 1)\n\n maxes[i] = sorted(maxes[i])[-3:]\n\n ma[i] = max(ma[i], maxes[parent[i]][new] + 1)\n\n\n\n ix, ans, su = max(range(n + 1), key=[sum(x) for x in maxes].__getitem__), [], 0\n\n visit[ix], mem = False, [() for _ in range(n + 1)]\n\n\n\n for i in self.gdict[ix]:\n\n queue.append((i, 1))\n\n visit[i], parent[i] = False, i\n\n\n\n while queue:\n\n s, lev = queue.popleft()\n\n flag = 1\n\n\n\n for i1 in self.gdict[s]:\n\n if visit[i1]:\n\n queue.append((i1, lev + 1))\n\n visit[i1], flag, parent[i1] = False, 0, parent[s]\n\n\n\n if flag:\n\n mem[parent[s]] = (lev, s)\n\n\n\n mem.sort()\n\n for i in range(n, n - 3, -1):\n\n if not mem[i]:\n\n break\n\n ans.append(mem[i][1])\n\n su += mem[i][0]\n\n\n\n if len(ans) < 3:\n\n ans.append(ix)\n\n print(su, '\\n', *ans)\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\ninp = lambda dtype: [dtype(x) for x in input().split()]\n\ninp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]\n\ninp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]\n\ninp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp(dtype))]\n\ninp_enus = lambda dtype, n: [[i] + inp(dtype) for i in range(n)]\n\nceil1 = lambda a, b: (a + b - 1) \/\/ b\n\n\n\nn = int(input())\n\ng = graph(n)\n\nfor _ in range(n - 1):\n\n u, v = inp(int)\n\n g.addEdge(u, v)\n\ng.subtree(1)\n\n","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":"import sys\n\nfrom array import array\n\n\n\ninput = lambda: sys.stdin.buffer.readline().decode().strip()\n\ninp = lambda dtype: [dtype(x) for x in input().split()]\n\ndebug = lambda *x: print(*x, file=sys.stderr)\n\nceil1 = lambda a, b: (a + b - 1) \/\/ b\n\nMint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, []\n\n\n\n\n\ndef shrink(l, r):\n\n stk = array('i')\n\n for i in range(l, r + 1):\n\n cur = a[i]\n\n while stk and stk[-1] == cur:\n\n stk.pop()\n\n cur += 1\n\n\n\n stk.append(cur)\n\n\n\n return len(stk) == 1\n\n\n\n\n\nfor _ in range(1):\n\n n, a = int(input()), array('i', inp(int))\n\n dp = array('i', [Mint] * (n + 1))\n\n dp[-1] = 0\n\n\n\n for i in range(n):\n\n for j in range(i, -1, -1):\n\n if shrink(j, i): dp[i] = min(dp[i], dp[j - 1] + 1)\n\n\n\n out.append(dp[n - 1])\n\nprint('\\n'.join(map(str, out)))\n\n","language":"py"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"import sys\n\nfrom collections import *\n\nfrom itertools import *\n\nfrom math import *\n\nfrom array import *\n\nfrom functools import lru_cache\n\nimport heapq\n\nimport bisect\n\nimport random\n\nimport io, os\n\nfrom bisect import *\n\n\n\nif sys.hexversion == 50924784:\n\n sys.stdin = open('cfinput.txt')\n\n\n\nRI = lambda: map(int, sys.stdin.buffer.readline().split())\n\nRS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())\n\nRILST = lambda: list(RI())\n\n\n\nMOD = 10 ** 9 + 7\n\n\"\"\"https:\/\/codeforces.com\/problemset\/problem\/1286\/A\n\n\n\n\u8f93\u5165 n(\u2264100) \u548c\u4e00\u4e2a\u957f\u4e3a n \u7684\u6570\u7ec4 p\uff0cp \u539f\u672c\u662f\u4e00\u4e2a 1~n \u7684\u6392\u5217\uff0c\u4f46\u662f\u6709\u4e9b\u6570\u5b57\u4e22\u5931\u4e86\uff0c\u4e22\u5931\u7684\u6570\u5b57\u7528 0 \u8868\u793a\u3002\n\n\u4f60\u9700\u8981\u8fd8\u539f p\uff0c\u4f7f\u5f97 p \u4e2d\u76f8\u90bb\u5143\u7d20\u5947\u5076\u6027\u4e0d\u540c\u7684\u5bf9\u6570\u6700\u5c11\u3002\u8f93\u51fa\u8fd9\u4e2a\u6700\u5c0f\u503c\u3002\n\n\u8f93\u5165\n\n5\n\n0 5 0 2 3\n\n\u8f93\u51fa 2\n\n\n\n\u8f93\u5165\n\n7\n\n1 0 0 5 0 0 2\n\n\u8f93\u51fa 1\n\n\"\"\"\n\n\n\n\n\n# 264 \t ms\n\ndef solve1(n, a):\n\n if n == 1:\n\n return print(0)\n\n even = n \/\/ 2 # \u5076\u6570\n\n ood = n - even # \u5947\u6570\n\n for v in a:\n\n if not v:\n\n continue\n\n if v & 1:\n\n ood -= 1\n\n else:\n\n even -= 1\n\n # f[i][j][k][0] \u524di\u4e2a\u6570\uff0c\u586b\u4e86j\u4e2a\u5947\u6570\uff0cl\u4e2a\u5076\u6570\u65f6\uff0c\u4e14\u672b\u4f4d\u662f\u5076\u6570\u7684\u60c5\u51b5\n\n # f[i][j][k][1] \u524di\u4e2a\u6570\uff0c\u586b\u4e86j\u4e2a\u5947\u6570\uff0cl\u4e2a\u5076\u6570\u65f6\uff0c\u4e14\u672b\u4f4d\u662f\u5947\u6570\u7684\u60c5\u51b5\n\n f = [[[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)] for _ in range(n)]\n\n # f[0][0][0] = 0\n\n if a[0] == 0:\n\n f[0][1][0][1] = 0 # a[0]\u653e\u5947\u6570\n\n f[0][0][1][0] = 0 # a[0]\u653e\u5076\u6570\n\n else:\n\n if a[0] & 1: # \u5947\u6570\n\n f[0][0][0][1] = 0\n\n else:\n\n f[0][0][0][0] = 0\n\n # print(ood,even)\n\n for i in range(1, n):\n\n if a[i] == 0:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n if k:\n\n # a[i]\u653e\u5076\u6570\uff0c\u524d\u4e00\u4e2a\u662f\u5947\u6570\u5c31+1\u5426\u5219\u4e0d+\n\n f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][0])\n\n f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][1] + 1)\n\n if j:\n\n # a[i]\u653e\u5947\u6570\n\n f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][0] + 1)\n\n f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][1])\n\n else:\n\n if a[i] & 1:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[i][j][k][1] = min(f[i - 1][j][k][1], f[i - 1][j][k][0] + 1)\n\n\n\n else:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[i][j][k][0] = min(f[i - 1][j][k][1] + 1, f[i - 1][j][k][0])\n\n # print(f)\n\n print(min(f[-1][-1][-1]))\n\n\n\n\n\n# 155 ms\n\ndef solve2(n, a):\n\n if n == 1:\n\n return print(0)\n\n even = n \/\/ 2 # \u5076\u6570\n\n ood = n - even # \u5947\u6570\n\n for v in a:\n\n if not v:\n\n continue\n\n if v & 1:\n\n ood -= 1\n\n else:\n\n even -= 1\n\n f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]\n\n # f[0][0][0] = 0\n\n if a[0] == 0:\n\n f[1][0][1] = 0 # a[0]\u653e\u5947\u6570\n\n f[0][1][0] = 0 # a[0]\u653e\u5076\u6570\n\n else:\n\n if a[0] & 1: # \u5947\u6570\n\n f[0][0][1] = 0\n\n else:\n\n f[0][0][0] = 0\n\n # print(ood,even)\n\n\n\n for i in range(1, n):\n\n g = f\n\n f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]\n\n if a[i] == 0:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n if k:\n\n # a[i]\u653e\u5076\u6570\uff0c\u524d\u4e00\u4e2a\u662f\u5947\u6570\u5c31+1\u5426\u5219\u4e0d+\n\n f[j][k][0] = min(f[j][k][0], g[j][k - 1][0])\n\n f[j][k][0] = min(f[j][k][0], g[j][k - 1][1] + 1)\n\n if j:\n\n # a[i]\u653e\u5947\u6570\n\n f[j][k][1] = min(f[j][k][1], g[j - 1][k][0] + 1)\n\n f[j][k][1] = min(f[j][k][1], g[j - 1][k][1])\n\n else:\n\n if a[i] & 1:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[j][k][1] = min(g[j][k][1], g[j][k][0] + 1)\n\n\n\n else:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[j][k][0] = min(g[j][k][1] + 1, g[j][k][0])\n\n # print(f)\n\n print(min(f[-1][-1]))\n\n\n\n\n\n# 93 ms\n\ndef solve3(n, a):\n\n if n == 1:\n\n return print(0)\n\n even = n \/\/ 2 # \u5076\u6570\n\n ood = n - even # \u5947\u6570\n\n for v in a:\n\n if not v:\n\n continue\n\n if v & 1:\n\n ood -= 1\n\n else:\n\n even -= 1\n\n # f[i][j][0] \u524di\u4e2a\u6570\uff0c\u586b\u4e86j\u4e2a\u5076\u6570\u4e14\u672b\u5c3e\u662f\u5076\u6570\u7684\u60c5\u51b5\n\n f = [[inf] * 2 for _ in range(even + 1)]\n\n\n\n if a[0] == 0:\n\n f[0][1] = 0 # a[0]\u653e\u5947\u6570\n\n f[1][0] = 0 # a[0]\u653e\u5076\u6570\n\n else:\n\n if a[0] & 1: # \u5947\u6570\n\n f[0][1] = 0\n\n else:\n\n f[0][0] = 0\n\n # print(ood,even)\n\n pos = 0 + (a[0] == 0)\n\n for i in range(1, n):\n\n g = f\n\n f = [[inf] * 2 for _ in range(even + 1)]\n\n if a[i] == 0:\n\n pos += 1\n\n for j in range(min(pos + 1, even + 1)):\n\n if j:\n\n f[j][0] = min(g[j - 1][0], g[j - 1][1] + 1)\n\n f[j][1] = min(g[j][1], g[j][0] + 1)\n\n\n\n else:\n\n p = a[i] & 1\n\n for j in range(min(pos + 1, even + 1)):\n\n f[j][p] = min(g[j][p], g[j][p ^ 1] + 1)\n\n # if a[i] & 1:\n\n # for j in range(min(pos + 1, ood + 1)):\n\n # f[j][1] = min(g[j][1], g[j][0] + 1)\n\n # else:\n\n # for j in range(min(pos + 1, ood + 1)):\n\n # f[j][0] = min(g[j][1] + 1, g[j][0])\n\n # print(f)\n\n print(min(f[-1]))\n\n\n\n\n\n# 93 ms\n\ndef solve(n, a):\n\n if n == 1:\n\n return print(0)\n\n even = n \/\/ 2 # \u5076\u6570\n\n for v in a:\n\n if not v:\n\n continue\n\n if v & 1 == 0:\n\n even -= 1\n\n f = [[inf] * 2 for _ in range(even + 1)]\n\n if a[0] == 0:\n\n f[0][1] = 0 # a[0]\u653e\u5947\u6570\n\n f[1][0] = 0 # a[0]\u653e\u5076\u6570\n\n else:\n\n f[0][a[0] & 1] = 0\n\n # print(ood,even)\n\n for i in range(1, n):\n\n g = f\n\n f = [[inf] * 2 for _ in range(even + 1)]\n\n if a[i] == 0:\n\n for j in range(even + 1):\n\n if j:\n\n f[j][0] = min(g[j - 1][0], g[j - 1][1] + 1)\n\n f[j][1] = min(g[j][1], g[j][0] + 1)\n\n\n\n else:\n\n p = a[i] & 1\n\n for j in range(even + 1):\n\n f[j][p] = min(g[j][p], g[j][p ^ 1] + 1)\n\n\n\n print(min(f[-1]))\n\n\n\n\n\nif __name__ == '__main__':\n\n n, = RI()\n\n a = RILST()\n\n\n\n solve(n, a)\n\n","language":"py"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"import sys\n\nfrom collections import *\n\nfrom itertools import *\n\nfrom math import *\n\nfrom array import *\n\nfrom functools import lru_cache\n\nimport heapq\n\nimport bisect\n\nimport random\n\nimport io, os\n\nfrom bisect import *\n\n\n\nif sys.hexversion == 50924784:\n\n sys.stdin = open('cfinput.txt')\n\n\n\nRI = lambda: map(int, sys.stdin.buffer.readline().split())\n\nRS = lambda: map(bytes.decode, sys.stdin.buffer.readline().strip().split())\n\nRILST = lambda: list(RI())\n\n\n\nMOD = 10 ** 9 + 7\n\n\"\"\"https:\/\/codeforces.com\/problemset\/problem\/1286\/A\n\n\n\n\u8f93\u5165 n(\u2264100) \u548c\u4e00\u4e2a\u957f\u4e3a n \u7684\u6570\u7ec4 p\uff0cp \u539f\u672c\u662f\u4e00\u4e2a 1~n \u7684\u6392\u5217\uff0c\u4f46\u662f\u6709\u4e9b\u6570\u5b57\u4e22\u5931\u4e86\uff0c\u4e22\u5931\u7684\u6570\u5b57\u7528 0 \u8868\u793a\u3002\n\n\u4f60\u9700\u8981\u8fd8\u539f p\uff0c\u4f7f\u5f97 p \u4e2d\u76f8\u90bb\u5143\u7d20\u5947\u5076\u6027\u4e0d\u540c\u7684\u5bf9\u6570\u6700\u5c11\u3002\u8f93\u51fa\u8fd9\u4e2a\u6700\u5c0f\u503c\u3002\n\n\u8f93\u5165\n\n5\n\n0 5 0 2 3\n\n\u8f93\u51fa 2\n\n\n\n\u8f93\u5165\n\n7\n\n1 0 0 5 0 0 2\n\n\u8f93\u51fa 1\n\n\"\"\"\n\n\n\n\n\n# 264 \t ms\n\ndef solve1(n, a):\n\n if n == 1:\n\n return print(0)\n\n even = n \/\/ 2 # \u5076\u6570\n\n ood = n - even # \u5947\u6570\n\n for v in a:\n\n if not v:\n\n continue\n\n if v & 1:\n\n ood -= 1\n\n else:\n\n even -= 1\n\n f = [[[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)] for _ in range(n)]\n\n # f[0][0][0] = 0\n\n if a[0] == 0:\n\n f[0][1][0][1] = 0 # a[0]\u653e\u5947\u6570\n\n f[0][0][1][0] = 0 # a[0]\u653e\u5076\u6570\n\n else:\n\n if a[0] & 1: # \u5947\u6570\n\n f[0][0][0][1] = 0\n\n else:\n\n f[0][0][0][0] = 0\n\n # print(ood,even)\n\n for i in range(1, n):\n\n if a[i] == 0:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n if k:\n\n # a[i]\u653e\u5076\u6570\uff0c\u524d\u4e00\u4e2a\u662f\u5947\u6570\u5c31+1\u5426\u5219\u4e0d+\n\n f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][0])\n\n f[i][j][k][0] = min(f[i][j][k][0], f[i - 1][j][k - 1][1] + 1)\n\n if j:\n\n # a[i]\u653e\u5947\u6570\n\n f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][0] + 1)\n\n f[i][j][k][1] = min(f[i][j][k][1], f[i - 1][j - 1][k][1])\n\n else:\n\n if a[i] & 1:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[i][j][k][1] = min(f[i - 1][j][k][1], f[i - 1][j][k][0] + 1)\n\n\n\n else:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[i][j][k][0] = min(f[i - 1][j][k][1] + 1, f[i - 1][j][k][0])\n\n # print(f)\n\n print(min(f[-1][-1][-1]))\n\n\n\n# ms\n\ndef solve(n, a):\n\n if n == 1:\n\n return print(0)\n\n even = n \/\/ 2 # \u5076\u6570\n\n ood = n - even # \u5947\u6570\n\n for v in a:\n\n if not v:\n\n continue\n\n if v & 1:\n\n ood -= 1\n\n else:\n\n even -= 1\n\n f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]\n\n # f[0][0][0] = 0\n\n if a[0] == 0:\n\n f[1][0][1] = 0 # a[0]\u653e\u5947\u6570\n\n f[0][1][0] = 0 # a[0]\u653e\u5076\u6570\n\n else:\n\n if a[0] & 1: # \u5947\u6570\n\n f[0][0][1] = 0\n\n else:\n\n f[0][0][0] = 0\n\n # print(ood,even)\n\n\n\n for i in range(1, n):\n\n g = f\n\n f = [[[inf] * 2 for _ in range(even + 1)] for _ in range(ood + 1)]\n\n if a[i] == 0:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n if k:\n\n # a[i]\u653e\u5076\u6570\uff0c\u524d\u4e00\u4e2a\u662f\u5947\u6570\u5c31+1\u5426\u5219\u4e0d+\n\n f[j][k][0] = min(f[j][k][0], g[j][k - 1][0])\n\n f[j][k][0] = min(f[j][k][0], g[j][k - 1][1] + 1)\n\n if j:\n\n # a[i]\u653e\u5947\u6570\n\n f[j][k][1] = min(f[j][k][1], g[j - 1][k][0] + 1)\n\n f[j][k][1] = min(f[j][k][1], g[j - 1][k][1])\n\n else:\n\n if a[i] & 1:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[j][k][1] = min(g[j][k][1], g[j][k][0] + 1)\n\n\n\n else:\n\n for j in range(ood + 1):\n\n for k in range(even + 1):\n\n f[j][k][0] = min(g[j][k][1] + 1, g[j][k][0])\n\n # print(f)\n\n print(min(f[-1][-1]))\n\n\n\n\n\nif __name__ == '__main__':\n\n n, = RI()\n\n a = RILST()\n\n\n\n solve(n, a)\n\n","language":"py"} -{"contest_id":"1324","problem_id":"A","statement":"A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2\u00d712\u00d71 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2\u00d712\u00d71 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai\u22121ai\u22121. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.ExampleInputCopy4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\nOutputCopyYES\nNO\nYES\nYES\nNoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.","tags":["implementation","number theory"],"code":"t = int(input())\nwhile t:\n n = int(input())\n a = [int(x) for x in input().split()]\n a = sorted(a)\n a = [a[i] - a[i-1] for i in range(1,len(a))]\n res = any((aa %2) != 0 for aa in a)\n print(\"NO\" if res else \"YES\")\n t -= 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 solve():\n\n n = int(input())\n\n seq = input()\n\n\n\n min_indices = []\n\n cmin = min(seq)\n\n for i, e in enumerate(seq):\n\n if e == cmin:\n\n min_indices.append(i)\n\n\n\n res = (seq, 1)\n\n for idx in min_indices:\n\n head = seq[idx:]\n\n tail = seq[:idx]\n\n if (n - idx) % 2 == 1:\n\n tail = tail[::-1]\n\n\n\n proc_seq = ''.join(head + tail)\n\n res = min(res, (proc_seq, idx+1))\n\n\n\n return res\n\n\n\n\n\ndef main():\n\n t = int(input())\n\n output = []\n\n for _ in range(t):\n\n seq, k = solve()\n\n output.append(seq)\n\n output.append(k)\n\n\n\n print_lines(output)\n\n\n\n\n\ndef input(): return next(test).strip()\n\ndef read_ints(): return [int(c) for c in input().split()]\n\ndef print_lines(lst): print('\\n'.join(map(str, lst)))\n\n\n\n\n\nif __name__ == \"__main__\":\n\n import sys\n\n from os import environ as env\n\n if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']:\n\n sys.stdout = open('out.txt', 'w')\n\n sys.stdin = open('in.txt', 'r')\n\n\n\n test = iter(sys.stdin.readlines())\n\n\n\n main()\n\n","language":"py"} -{"contest_id":"1311","problem_id":"F","statement":"F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t\u22c5vixi+t\u22c5vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value \u22111\u2264i 0:\n\n s += self.tree[i]\n\n i -= i & -i\n\n return s\n\n \n\n def add(self, i, x):\n\n while i <= self.size:\n\n self.tree[i] += x\n\n i += i & -i\n\n \n\n N = int(input())\n\n X = list(map(int, input().split()))\n\n V = list(map(int, input().split()))\n\n \n\n info = [(x, v) for x, v in zip(X, V)]\n\n info.sort(key=lambda p: p[0])\n\n info.sort(key=lambda p: p[1])\n\n X.sort()\n\n x2i = {x: i+1 for i, x in enumerate(X)}\n\n bit_x = Bit(N+1)\n\n bit_cnt = Bit(N+1)\n\n \n\n ans = 0\n\n for x, _ in info:\n\n i = x2i[x]\n\n ans += bit_cnt.sum(i) * x - bit_x.sum(i)\n\n bit_x.add(i, x)\n\n bit_cnt.add(i, 1)\n\n print(ans)\n\n \n\n \n\nif __name__ == '__main__':\n\n main()","language":"py"} -{"contest_id":"1292","problem_id":"B","statement":"B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIV\u039b - \u6f02\u6d41 KIV\u039b & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by)(ax\u22c5xi\u22121+bx,ay\u22c5yi\u22121+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x\u22121,y)(x\u22121,y), (x+1,y)(x+1,y), (x,y\u22121)(x,y\u22121) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1\u2264x0,y0\u226410161\u2264x0,y0\u22641016, 2\u2264ax,ay\u22641002\u2264ax,ay\u2264100, 0\u2264bx,by\u226410160\u2264bx,by\u22641016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1\u2264xs,ys,t\u226410161\u2264xs,ys,t\u22641016)\u00a0\u2013 the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer\u00a0\u2014 the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0\n2 4 20\nOutputCopy3InputCopy1 1 2 3 1 0\n15 27 26\nOutputCopy2InputCopy1 1 2 3 1 0\n2 2 1\nOutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3\u22122|+|3\u22124|=2|3\u22122|+|3\u22124|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1\u22123|+|1\u22123|=4|1\u22123|+|1\u22123|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7\u22121|+|9\u22121|=14|7\u22121|+|9\u22121|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15\u22127|+|27\u22129|=26|15\u22127|+|27\u22129|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.","tags":["brute force","constructive algorithms","geometry","greedy","implementation"],"code":"import sys\n\ninput=lambda:sys.stdin.readline().rstrip()\n\ndef dist(a,b):\n\n return sum([abs(a[i]-b[i]) for i in range(2)])\n\ntemp=list(map(int,input().split()))\n\npoints=[temp[0:2]]\n\na=temp[2:4]\n\nb=temp[4:6]\n\nstart=[0,0]\n\n*start,t=map(int,input().split())\n\nwhile points[-1][0]-start[0]<=t:\n\n\tpoints.append([points[-1][i]*a[i]+b[i] for i in range(2)])\n\nfor i in range(len(points)-1,-1,-1):\n\n\tfor j in range(len(points)-i):\n\n\t\tif dist(points[j],points[j+i])+min(dist(start,points[j]),dist(start,points[j+i]))<=t:\n\n\t\t\tprint(i+1)\n\n\t\t\tsys.exit()\n\nprint(0)","language":"py"} -{"contest_id":"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":"T = int (input()) \n\nfor test in range (T):\n\n n , k = map (int, input ().split(' '))\n\n arr = list (map (int, input ().split(' ')))\n\n mx = max(arr)\n\n values = list () \n\n ind =1 \n\n arr.sort() \n\n arr.reverse()\n\n while len (arr) > 0 and arr[-1] == 0: \n\n arr.pop()\n\n values.append(1)\n\n while ind <= mx: \n\n ind *= k \n\n values.append(ind)\n\n values.sort()\n\n ok = True\n\n while len (arr)>0:\n\n x = arr.pop()\n\n if (x == 0 ) :\n\n break \n\n while x > 0: \n\n mx = 0 \n\n for it in values: \n\n if it <= x: \n\n mx = it \n\n if mx == 0:\n\n break\n\n x -= mx \n\n values.remove(mx)\n\n ok&= x ==0 \n\n print (\"YES\") if ok else print (\"NO\") \n\n\n\n","language":"py"} -{"contest_id":"1291","problem_id":"A","statement":"A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive\/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n\u22121n\u22121.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 \u2192\u2192 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u226430001\u2264n\u22643000) \u00a0\u2014 the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print \"-1\" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4\n4\n1227\n1\n0\n6\n177013\n24\n222373204424185217171912\nOutputCopy1227\n-1\n17703\n2237344218521717191\nNoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 \u2192\u2192 22237320442418521717191 (delete the last digit).","tags":["greedy","math","strings"],"code":"for _ in range(int(input())):\n\n n= int(input())\n\n s= input()\n\n\n\n odd= 0\n\n for i in range(n):\n\n if int(s[i])%2 != 0:\n\n odd += 1\n\n\n\n if odd >= 2:\n\n even= str()\n\n for k in range(n):\n\n if int(s[k])%2 != 0:\n\n even += s[k]\n\n if len(even) == 2:\n\n print(even)\n\n break\n\n else:\n\n print(-1)\n\n else:\n\n print(-1)","language":"py"} -{"contest_id":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!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. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"import sys, os, io\n\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\nt = int(input())\n\nans = []\n\nfor _ in range(t):\n\n n = int(input())\n\n a = list(map(int, input().split()))\n\n b = list(map(int, input().split()))\n\n a.sort()\n\n b.sort()\n\n ans.append(\" \".join(map(str, a)))\n\n ans.append(\" \".join(map(str, b)))\n\nsys.stdout.write(\"\\n\".join(ans))","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":"def get_ints():\n\n return map(int, input().strip().split())\n\n\n\ndef get_list():\n\n return list(map(int, input().strip().split()))\n\n\n\ndef get_string():\n\n return input().strip()\n\n\n\n# For fast IO use sys.stdout.write(str(x) + \"\\n\") instead of print\n\nimport sys\n\nimport math\n\ninput = sys.stdin.readline\n\n\n\nfor t in range(int(input().strip())):\n\n n = int(input().strip())\n\n arr = get_list()\n\n prefix_len, suffix_len = 0, 0\n\n \n\n for i in range(n):\n\n if arr[i] >= i:\n\n prefix_len += 1\n\n else:\n\n break\n\n \n\n for i in range(n-1, -1, -1):\n\n if arr[i] >= n-i-1:\n\n suffix_len += 1\n\n else:\n\n break\n\n \n\n if prefix_len + suffix_len > n:\n\n print(\"Yes\")\n\n else:\n\n print(\"No\")","language":"py"} -{"contest_id":"1295","problem_id":"D","statement":"D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0\u2264x1: continue\n for j in range(i,MAX+1,i):\n prime[j] += 1\n\n\nprimelist = []\nfor i in range(2,MAX+1):\n if prime[i]==1: primelist.append(i)\n\n\n\ndef factorize(num):\n\n pf = []\n for p in primelist:\n if num%p>0: continue\n count = 0 \n while num%p==0:\n num = num\/\/p\n count += 1\n pf.append(p)\n\n if num>1: pf.append(num)\n return pf\n \n\n\n\n\ndef main(t):\n\n\n\n a,m = map(int,input().split())\n\n g = math.gcd(a,m)\n a = a\/\/g\n m = m\/\/g\n\n\n pf = factorize(m)\n# print(pf)\n\n\n tot = 1\n\n\n ans = m\n \n for b in range(1,1< len(left_inds[char]) and left_inds[\"?\"]:\n\n idx1 = left_inds[\"?\"].pop()\n\n idx2 = right_inds[char].pop()\n\n ans.append((idx1, idx2))\n\n\n\nif \"?\" in right_inds:\n\n for char in left_inds:\n\n while len(left_inds[char]) > len(right_inds[char]) and right_inds[\"?\"]:\n\n idx1 = right_inds[\"?\"].pop()\n\n idx2 = left_inds[char].pop()\n\n ans.append((idx2, idx1))\n\n\n\nfor char in right_inds:\n\n res = min(len(right_inds[char]), len(left_inds[char]))\n\n for _ in range(res):\n\n idx1 = left_inds[char].pop()\n\n idx2 = right_inds[char].pop()\n\n\n\n ans.append((idx1, idx2))\n\n\n\nprint(len(ans))\n\nfor a, b in ans:\n\n print(a, b)\n\n\n\n\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":"def find_min(num_list, pos):\n\n if pos < 0:\n\n return 0\n\n zeros = []\n\n ones = []\n\n for num in num_list:\n\n if num >> pos & 1 == 0:\n\n zeros.append(num)\n\n else:\n\n ones.append(num)\n\n if len(zeros) == 0:\n\n return find_min(ones, pos-1)\n\n if len(ones) == 0:\n\n return find_min(zeros, pos-1)\n\n return min(find_min(zeros, pos - 1), find_min(ones, pos - 1)) + (1 << pos)\n\n\n\nn = int(input())\n\nnumbers = list(map(int, input().split()))\n\npos = 30\n\nprint(find_min(numbers, pos))","language":"py"} -{"contest_id":"1284","problem_id":"B","statement":"B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,\u2026,al]a=[a1,a2,\u2026,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1\u2264i= a[i+1] for i in range(len(a)-1))\n\n zc += z\n\n if z:\n\n fc[a[0]] += 1\n\n lc[a[-1]] += 1\n\nans = n*n - zc*zc\n\nless = 0\n\nfor i in range(m):\n\n ans += fc[i] * less\n\n less += lc[i]\n\nprint(ans)\n\n","language":"py"} -{"contest_id":"1284","problem_id":"B","statement":"B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,\u2026,al]a=[a1,a2,\u2026,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1\u2264i0:\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":"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 _ in range(t):\n\n n = int(input())\n\n l = list(map(int,input().split()))\n\n s = set(l)\n\n print(len(s))","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":"1313","problem_id":"C2","statement":"C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n\u2264500000n\u2264500000The outskirts of the capital are being actively built up in Berland. The company \"Kernel Panic\" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1\u2264ai\u2264mi1\u2264ai\u2264mi). Also there mustn't be integers jj and kk such that jaiai= n * 2:\n\n tree = [-inf] * i\n\n break\n\n else:\n\n i *= 2\n\n return tree\n\n\n\ndef update(i, x):\n\n i += len(tree) \/\/ 2\n\n tree[i] = x\n\n i \/\/= 2\n\n while True:\n\n if i == 0:\n\n break\n\n tree[i] = max(tree[2 * i], tree[2 * i + 1])\n\n i \/\/= 2\n\n return\n\n\n\ndef get_max(s, t):\n\n s += len(tree) \/\/ 2\n\n t += len(tree) \/\/ 2\n\n ans = -inf\n\n while s <= t:\n\n if s % 2 == 0:\n\n s \/\/= 2\n\n else:\n\n ans = max(ans, tree[s])\n\n s = (s + 1) \/\/ 2\n\n if t % 2 == 1:\n\n t \/\/= 2\n\n else:\n\n ans = max(ans, tree[t])\n\n t = (t - 1) \/\/ 2\n\n return ans\n\n\n\nn = int(input())\n\nm = list(map(int, input().split()))\n\nd = defaultdict(lambda : [])\n\nfor i in range(n):\n\n d[m[i]].append(i)\n\nx = list(d.keys())\n\nx.sort()\n\ninf = 1\n\ntree = segment_tree(n)\n\ndp1 = [0] * (n + 1)\n\nfor i in x:\n\n for j in d[i]:\n\n k = get_max(0, j)\n\n dp1[j] = dp1[k] + i * (j - k)\n\n update(j, j)\n\ninf = n\n\ntree = segment_tree(n)\n\ndp2 = [0] * (n + 1)\n\nfor i in x:\n\n for j in reversed(d[i]):\n\n k = -get_max(j, n - 1)\n\n dp2[j] = dp2[k] + i * (k - j)\n\n update(j, -j)\n\ns = 0\n\nk = -1\n\nc = 0\n\ndp1.pop()\n\ndp2.pop()\n\nfor i, j, l in zip(dp1, dp2, m):\n\n if s < i + j - l:\n\n s = i + j - l\n\n k = c\n\n c += 1\n\na = [0] * n\n\na[k] = m[k]\n\nfor j in range(k - 1, -1, -1):\n\n a[j] = min(a[j + 1], m[j])\n\n s += a[j]\n\nfor j in range(k + 1, n):\n\n a[j] = min(a[j - 1], m[j])\n\n s += a[j]\n\nsys.stdout.write(\" \".join(map(str, a)))","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":"import sys\n\nfrom array import array\n\n\n\ninput = lambda: sys.stdin.buffer.readline().decode().strip()\n\ninp = lambda dtype: [dtype(x) for x in input().split()]\n\ndebug = lambda *x: print(*x, file=sys.stderr)\n\nceil1 = lambda a, b: (a + b - 1) \/\/ b\n\nMint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, []\n\n\n\n\n\ndef shrink(l, r):\n\n stk = array('i')\n\n for i in range(l, r + 1):\n\n cur = a[i]\n\n while stk and stk[-1] == cur:\n\n stk.pop()\n\n cur += 1\n\n\n\n stk.append(cur)\n\n\n\n return len(stk) == 1\n\n\n\n\n\nfor _ in range(1):\n\n n, a = int(input()), array('i', inp(int))\n\n dp = array('i', [Mint] * (n + 1))\n\n dp[-1] = 0\n\n\n\n for i in range(n):\n\n for j in range(i, -1, -1):\n\n if shrink(j, i) and dp[j - 1] + 1 < dp[i]: dp[i] = dp[j - 1] + 1\n\n\n\n out.append(dp[n - 1])\n\nprint('\\n'.join(map(str, out)))\n\n","language":"py"} -{"contest_id":"1312","problem_id":"B","statement":"B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,\u2026,ana1,a2,\u2026,an. Array is good if for each pair of indexes i= req:\n cyc = []\n while u != par[v]:\n cyc.append(u)\n u = par[u]\n return (None, cyc)\n\ng = defaultdict(set)\ng2 = defaultdict(set)\nn,m = li()\n\n\nfor i in range(m):\n a,b = li()\n g[a].add(b)\n g[b].add(a)\n g2[a].add(b)\n g2[b].add(a)\nfor i in g2:\n g2[i] = set(sorted(list(g2[i])))\ncurrset = set()\nma = math.ceil(n**0.5)\nreq = ma\nfor i in sorted(g,key = lambda x:len(g[x])):\n if i in g:\n\n currset.add(i)\n for k in list(g[i]):\n if k in g:g.pop(k)\n g.pop(i)\n if len(currset) == ma:break\nif len(currset) >= ma:\n print(1)\n print(*list(currset)[:ma])\n exit()\nprint(2)\n_,cycles = dfs()\nprint(len(cycles))\nprint(*cycles)","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":"import sys\n\nimport math\n\nimport copy\n\nimport itertools\n\nimport bisect\n\nfrom heapq import heappop, heappush, heapify\n\n\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\ndef ilst():\n\n return list(map(int,input().split()))\n\n \n\ndef islst():\n\n return list(map(str,input().split()))\n\n \n\ndef inum():\n\n return map(int,input().split())\n\n \n\ndef freq(l):\n\n d = {}\n\n for i in l:\n\n d[i] = d.get(i,0)+1\n\n return d\n\n\n\n\n\nn,m = inum()\n\nprint((math.factorial(n+2*m-1)\/\/(math.factorial(2*m)*math.factorial(n-1)))%(10**9+7))\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 math import ceil\n\n\n\n\n\nn, a, b, k = map(int, input().split())\n\nm = a + b\n\nh = list(map(lambda x: int(x) % m + (m if int(x) % m == 0 else 0), input().split()))\n\nh.sort()\n\ncnt = 0\n\nwhile cnt < n and h[cnt] <= a:cnt += 1\n\ndel h[:cnt]\n\ns = 0\n\nfor hp in h:\n\n cnt += 1\n\n s += ceil(hp \/ a) - 1\n\n if k < s:\n\n cnt -= 1\n\n break\n\nprint(cnt)\n\n","language":"py"} -{"contest_id":"1312","problem_id":"B","statement":"B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,\u2026,ana1,a2,\u2026,an. Array is good if for each pair of indexes i 1:\n\n ret.append(n)\n\n return ret\n\n \n\ndef _pollardrho(n):\n\n if n % 2 == 0: return 2\n\n if _isprime(n): return n\n\n while True:\n\n c = random.randint(2, n -1)\n\n f = lambda x: x**2 + c \n\n x = y = 2 \n\n d = 1 \n\n while d == 1:\n\n x = f(x) % n \n\n y = f(f(y)) % n \n\n d = _gcd((x - y) % n, n)\n\n \n\n if d != n and _isprime(d): return d\n\n\n\ndef _sumdigit(n):\n\n ret = 0\n\n while n > 0:\n\n ret += n % 10\n\n n \/\/= 10\n\n return ret\n\n\n\ndef _modinverse(n, m):\n\n return (n % mod) * (pow(m, mod - 2, mod) % mod) % mod\n\n\n\ndef p(n):\n\n\treturn print(n, end = ' ')\n\ndef lip(type = int):\n\n\treturn list(map(type, input().split()))\n\n \n\ndef mip(type = int):\n\n\treturn map(type, input().split())\n\n \n\ndef tip(type = int):\n\n\treturn type(input())\n\n\t\n\ndef inp():\n\n\treturn input()\n\n\t\n\ndef solve(t):\n\n\t\n\n\tn, m = mip()\n\n\tprint('YES' if n % m == 0 else 'NO')\n\n\t\n\nt = 1\n\nt = int(input())\n\nfor i in range(t):\n\n solve(i + 1)","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":"t = int(input())\nfor _ in range(t):\n n, d = (int(i) for i in input().split())\n a = (int(i) for i in input().split())\n res = next(a)\n for i, e in enumerate(a):\n res += min(d, (i + 1) * e) \/\/ (i + 1)\n d -= (i + 1) * e\n if d <= 0:\n break\n print(res)\n","language":"py"} -{"contest_id":"1292","problem_id":"E","statement":"E. Rin and The Unknown Flowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisoilePunch\u266a - \u5f69This is an interactive problem!On a normal day at the hidden office in A.R.C. Markland-N; Rin received an artifact, given to her by the exploration captain Sagar.After much analysis, she now realizes that this artifact contains data about a strange flower, which has existed way before the New Age. However, the information about its chemical structure has been encrypted heavily.The chemical structure of this flower can be represented as a string pp. From the unencrypted papers included, Rin already knows the length nn of that string, and she can also conclude that the string contains at most three distinct letters: \"C\" (as in Carbon), \"H\" (as in Hydrogen), and \"O\" (as in Oxygen).At each moment, Rin can input a string ss of an arbitrary length into the artifact's terminal, and it will return every starting position of ss as a substring of pp.However, the artifact has limited energy and cannot be recharged in any way, since the technology is way too ancient and is incompatible with any current A.R.C.'s devices. To be specific: The artifact only contains 7575 units of energy. For each time Rin inputs a string ss of length tt, the artifact consumes 1t21t2 units of energy. If the amount of energy reaches below zero, the task will be considered failed immediately, as the artifact will go black forever. Since the artifact is so precious yet fragile, Rin is very nervous to attempt to crack the final data. Can you give her a helping hand?InteractionThe interaction starts with a single integer tt (1\u2264t\u22645001\u2264t\u2264500), the number of test cases. The interaction for each testcase is described below:First, read an integer nn (4\u2264n\u2264504\u2264n\u226450), the length of the string pp.Then you can make queries of type \"? s\" (1\u2264|s|\u2264n1\u2264|s|\u2264n) to find the occurrences of ss as a substring of pp.After the query, you need to read its result as a series of integers in a line: The first integer kk denotes the number of occurrences of ss as a substring of pp (\u22121\u2264k\u2264n\u22121\u2264k\u2264n). If k=\u22121k=\u22121, it means you have exceeded the energy limit or printed an invalid query, and you need to terminate immediately, to guarantee a \"Wrong answer\" verdict, otherwise you might get an arbitrary verdict because your solution will continue to read from a closed stream. The following kk integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264a1= 13:\n\n ans = [''] * (n + 1)\n\n print('? CO')\n\n co = list(map(int, input().split()))[1:]\n\n print('? CH')\n\n ch = list(map(int, input().split()))[1:]\n\n print('? CC')\n\n cc = list(map(int, input().split()))[1:]\n\n for d in co:\n\n ans[d] = 'C'\n\n ans[d + 1] = 'O'\n\n for d in ch:\n\n ans[d] = 'C'\n\n ans[d + 1] = 'H'\n\n for d in cc:\n\n ans[d] = 'C'\n\n ans[d + 1] = 'C'\n\n print('? OO')\n\n oo = list(map(int, input().split()))[1:]\n\n print('? OH')\n\n oh = list(map(int, input().split()))[1:]\n\n for d in oo:\n\n ans[d] = 'O'\n\n ans[d + 1] = 'O'\n\n for d in oh:\n\n ans[d] = 'O'\n\n ans[d + 1] = 'H'\n\n for i in range(1, n):\n\n if ans[i] == 'O' and ans[i + 1] == '':\n\n ans[i + 1] = 'C'\n\n for i in range(1, n):\n\n if ans[i] == '' and ans[i + 1] == 'O':\n\n ans[i] = 'H'\n\n for i in range(1, n):\n\n if ans[i] == '' and ans[i + 1] == 'H':\n\n ans[i] = 'H'\n\n for i in range(1, n):\n\n if ans[i] == '' and ans[i + 1] == '':\n\n ans[i] = 'H'\n\n print('? HOC')\n\n hoc = list(map(int, input().split()))[1:]\n\n for d in hoc:\n\n ans[d] = 'H'\n\n ans[d + 1] = 'O'\n\n ans[d + 2] = 'C'\n\n for d in range(2, n):\n\n if ans[d] == '':\n\n ans[d] = 'H'\n\n if ans[1] == '':\n\n print('?', 'H' + ''.join(ans[2:-1]))\n\n if input()[0] != '0':\n\n ans[1] = 'H'\n\n else:\n\n ans[1] = 'O'\n\n if ans[-1] == '':\n\n print('?', ''.join(ans[1:-1]) + 'H')\n\n if input()[0] != '0':\n\n ans[-1] = 'H'\n\n else:\n\n print('?', ''.join(ans[1:-1]) + 'O')\n\n if input()[0] != '0':\n\n ans[-1] = 'O'\n\n else:\n\n ans[-1] = 'C'\n\n print('!', ''.join(ans[1:]))\n\n kek = input()\n\n else:\n\n L, minID = n, n\n\n s = 'L' * n\n\n \n\n query('?', \"CH\")\n\n query('?', \"CO\")\n\n query('?', \"HC\")\n\n query('?', \"HO\")\n\n if (L == n):\n\n # the string exists in form O...OX...X, with X=C or X=H\n\n # or it's completely mono-character\n\n query('?', \"CCC\")\n\n if (minID < n):\n\n for x in range(minID - 1, -1, -1): fill(x, 'O')\n\n else:\n\n query('?', \"HHH\")\n\n if (minID < n):\n\n for x in range(minID - 1, -1, -1): fill(x, 'O')\n\n else:\n\n query('?', \"OOO\")\n\n if (minID == n):\n\n # obviously n=4\n\n query('?', \"OOCC\")\n\n if (minID == n):\n\n fill(0, 'O')\n\n fill(1, 'O')\n\n fill(2, 'H')\n\n fill(3, 'H')\n\n \n\n if (s[n - 1] == 'L'):\n\n t = s[0:n - 1] + 'C'\n\n if (t[n - 2] == 'L'): t = t[0:n - 2] + 'C' + t[n - 1:]\n\n query('?', t)\n\n if (s[n - 1] == 'L'):\n\n fill(n - 1, 'H')\n\n if (s[n - 2] == 'L'): fill(n - 2, 'H')\n\n else:\n\n maxID = minID\n\n while (maxID < n - 1 and s[maxID + 1] != 'L'): maxID += 1\n\n for i in range(minID - 1, -1, -1):\n\n query('?', s[i + 1:i + 2] + s[minID:maxID + 1])\n\n if (minID != i):\n\n for x in range(i + 1): fill(x, 'O')\n\n break\n\n \n\n nextFilled = None\n\n i = maxID + 1\n\n while i < n:\n\n if (s[i] != 'L'):\n\n i += 1\n\n continue\n\n nextFilled = i\n\n while (nextFilled < n and s[nextFilled] == 'L'): nextFilled += 1\n\n query('?', s[0:i] + s[i - 1])\n\n if (s[i] == 'L'):\n\n if (s[i - 1] != 'O'):\n\n fill(i, 'O')\n\n else:\n\n if (nextFilled == n):\n\n query('?', s[0:i] + 'C')\n\n if (s[i] == 'L'): fill(i, 'H')\n\n for x in range(i + 1, nextFilled): fill(x, s[i])\n\n else:\n\n for x in range(i, nextFilled): fill(x, s[nextFilled])\n\n i = nextFilled - 1\n\n i += 1\n\n query('!', s)","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 for _ in range(len(q)):\n\n node = q.popleft()\n\n visited[node] = True\n\n hold[node] = h\n\n for child in g[node]:\n\n if not(visited[child]):\n\n visited[child] = True\n\n q.append(child) \n\n h+=1\n\n return hold\n\n\n\nx = bfs(1) #dis 1 to i \n\ny = bfs(n) #dis i to n\n\n\n\narr = sorted([(x[i]-y[i],i) for i in a])\n\npref,ans = -1e9,-1e9\n\n\n\nfor v,node in arr:\n\n ans = max(ans,pref+y[node])\n\n pref = max(pref,x[node])\n\n\n\nprint(min(x[n],ans+1))","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":"import array\n\nimport bisect\n\nimport heapq\n\nimport math\n\nimport collections\n\nimport sys\n\nimport copy\n\nfrom functools import reduce\n\nimport decimal\n\nfrom io import BytesIO, IOBase\n\nimport os\n\nimport itertools\n\nimport functools\n\nfrom types import GeneratorType\n\nimport fractions\n\n\n\n# sys.setrecursionlimit(10 ** 9)\n\ndecimal.getcontext().rounding = decimal.ROUND_HALF_UP\n\n\n\ngraphDict = collections.defaultdict\n\n\n\nqueue = collections.deque\n\n\n\n\n\n################## pypy deep recursion handling ##############\n\n# Author = @pajenegod\n\ndef bootstrap(f, stack=[]):\n\n def wrappedfunc(*args, **kwargs):\n\n to = f(*args, **kwargs)\n\n if stack:\n\n return to\n\n else:\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 return to\n\n to = stack[-1].send(to)\n\n\n\n return wrappedfunc\n\n\n\n\n\n################## Graphs ###################\n\nclass Graphs:\n\n def __init__(self):\n\n self.graph = graphDict(set)\n\n\n\n def add_edge(self, u, v):\n\n self.graph[u].add(v)\n\n self.graph[v].add(u)\n\n\n\n def dfs_utility(self, nodes, visited_nodes, colors, parity, level):\n\n global count\n\n if nodes == 1:\n\n colors[nodes] = -1\n\n else:\n\n if len(self.graph[nodes]) == 1 and parity % 2 == 0:\n\n if q == 1:\n\n colors[nodes] = 1\n\n else:\n\n colors[nodes] = -1\n\n count += 1\n\n else:\n\n if parity % 2 == 0:\n\n colors[nodes] = -1\n\n else:\n\n colors[nodes] = 1\n\n visited_nodes.add(nodes)\n\n for neighbour in self.graph[nodes]:\n\n new_level = level + 1\n\n if neighbour not in visited_nodes:\n\n self.dfs_utility(neighbour, visited_nodes, colors, level - 1, new_level)\n\n\n\n def dfs(self, node):\n\n Visited = set()\n\n color = collections.defaultdict()\n\n self.dfs_utility(node, Visited, color, 0, 0)\n\n return color\n\n\n\n def bfs(self, node, f_node):\n\n count = float(\"inf\")\n\n visited = set()\n\n level = 0\n\n if node not in visited:\n\n queue.append([node, level])\n\n visited.add(node)\n\n flag = 0\n\n while queue:\n\n parent = queue.popleft()\n\n if parent[0] == f_node:\n\n flag = 1\n\n count = min(count, parent[1])\n\n level = parent[1] + 1\n\n for item in self.graph[parent[0]]:\n\n if item not in visited:\n\n queue.append([item, level])\n\n visited.add(item)\n\n return count if flag else -1\n\n return False\n\n\n\n\n\n################### Tree Implementaion ##############\n\nclass Tree:\n\n def __init__(self, data):\n\n self.data = data\n\n self.left = None\n\n self.right = None\n\n\n\n\n\ndef inorder(node, lis):\n\n if node:\n\n inorder(node.left, lis)\n\n lis.append(node.data)\n\n inorder(node.right, lis)\n\n return lis\n\n\n\n\n\ndef leaf_node_sum(root):\n\n if root is None:\n\n return 0\n\n if root.left is None and root.right is None:\n\n return root.data\n\n return leaf_node_sum(root.left) + leaf_node_sum(root.right)\n\n\n\n\n\ndef hight(root):\n\n if root is None:\n\n return -1\n\n if root.left is None and root.right is None:\n\n return 0\n\n return max(hight(root.left), hight(root.right)) + 1\n\n\n\n\n\n################## Union Find #######################\n\nclass UnionFind():\n\n parents = []\n\n sizes = []\n\n count = 0\n\n\n\n def __init__(self, n):\n\n self.count = n\n\n self.parents = [i for i in range(n)]\n\n self.sizes = [1 for i in range(n)]\n\n\n\n def find(self, i):\n\n if self.parents[i] == i:\n\n return i\n\n else:\n\n self.parents[i] = self.find(self.parents[i])\n\n return self.parents[i]\n\n\n\n def unite(self, i, j):\n\n root_i = self.find(i)\n\n root_j = self.find(j)\n\n if root_i == root_j:\n\n return\n\n elif root_i < root_j:\n\n self.parents[root_j] = root_i\n\n self.sizes[root_i] += self.sizes[root_j]\n\n else:\n\n self.parents[root_i] = root_j\n\n self.sizes[root_j] += self.sizes[root_i]\n\n\n\n def same(self, i, j):\n\n return self.find(i) == self.find(j)\n\n\n\n def size(self, i):\n\n return self.sizes[self.find(i)]\n\n\n\n def group_count(self):\n\n return len(set(self.find(i) for i in range(self.count)))\n\n\n\n def answer(self, extra, p, q):\n\n dic = collections.Counter()\n\n for q in range(n):\n\n dic[self.find(q)] = self.size(q)\n\n hq = list(dic.values())\n\n heapq._heapify_max(hq)\n\n ans = -1\n\n for z in range(extra + 1):\n\n if hq:\n\n ans += heapq._heappop_max(hq)\n\n else:\n\n break\n\n return ans\n\n\n\n\n\n#################################################\n\n\n\ndef rounding(n):\n\n return int(decimal.Decimal(f'{n}').to_integral_value())\n\n\n\n\n\ndef factors(n):\n\n return set(reduce(list.__add__,\n\n ([i, n \/\/ i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0), [1]))\n\n\n\n\n\ndef p_sum(array):\n\n return list(itertools.accumulate(array))\n\n\n\n\n\ndef base_change(nn, bb):\n\n if nn == 0:\n\n return [0]\n\n digits = []\n\n while nn:\n\n digits.append(int(nn % bb))\n\n nn \/\/= bb\n\n return digits[::-1]\n\n\n\n\n\ndef diophantine(a: int, b: int, c: int):\n\n d, x, y = extended_gcd(a, b)\n\n r = c \/\/ d\n\n return r * x, r * y\n\n\n\n\n\n@bootstrap\n\ndef extended_gcd(a: int, b: int):\n\n if b == 0:\n\n d, x, y = a, 1, 0\n\n else:\n\n (d, p, q) = yield extended_gcd(b, a % b)\n\n x = q\n\n y = p - q * (a \/\/ b)\n\n\n\n yield d, x, y\n\n\n\n\n\n######################################################################################\n\n\n\n'''\n\nKnowledge and awareness are vague, and perhaps better called illusions.\n\nEveryone lives within their own subjective interpretation.\n\n ~Uchiha Itachi\n\n'''\n\n\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, **kwargs):\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\n###########################################################################################\n\n\n\n\n\ndef inp():\n\n return sys.stdin.readline().strip()\n\n\n\n\n\ndef map_inp(v_type):\n\n return map(v_type, inp().split())\n\n\n\n\n\ndef list_inp(v_type):\n\n return list(map_inp(v_type))\n\n\n\n\n\ndef interactive():\n\n return sys.stdout.flush()\n\n\n\n\n\n######################################## Solution ####################################\n\n\n\n@bootstrap\n\ndef create_dp(node, parent):\n\n for item in g.graph[node]:\n\n if item == parent:\n\n continue\n\n yield create_dp(item, node)\n\n dp[node] += max(dp[item], 0)\n\n yield\n\n\n\n@bootstrap\n\ndef solve_dp(node, parent):\n\n global ans\n\n ans[node - 1] = dp[node]\n\n for item in g.graph[node]:\n\n if item == parent:\n\n continue\n\n dp[node] -= max(0, dp[item])\n\n dp[item] += max(0, dp[node])\n\n yield solve_dp(item, node)\n\n dp[item] -= max(dp[node], 0)\n\n dp[node] += max(dp[item], 0)\n\n yield \n\n\n\n\n\nn = int(inp())\n\narr = list_inp(int)\n\ndp = collections.Counter()\n\nfor i in range(n):\n\n if arr[i] == 0:\n\n dp[i + 1] = -1\n\n else:\n\n dp[i + 1] = 1\n\ng = Graphs()\n\nfor i in range(n - 1):\n\n u, v = map_inp(int)\n\n g.add_edge(u, v)\n\nans = [0] * n\n\ncreate_dp(1, -1)\n\nsolve_dp(1, -1)\n\n\n\nprint(*ans)\n\n","language":"py"} -{"contest_id":"1305","problem_id":"F","statement":"F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u00a0\u2014 the number of elements in the array.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an. (1\u2264ai\u226410121\u2264ai\u22641012) \u00a0\u2014 the elements of the array.OutputPrint a single integer \u00a0\u2014 the minimum number of operations required to make the array good.ExamplesInputCopy3\n6 2 4\nOutputCopy0\nInputCopy5\n9 8 7 3 1\nOutputCopy4\nNoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.","tags":["math","number theory","probabilities"],"code":"import random\n\n\n\nn = int(input())\n\na = list(map(int, input().split()))\n\n\n\nlimit = min(8, n)\n\niterations = [x for x in range(n)]\n\nrandom.shuffle(iterations)\n\niterations = iterations[:limit]\n\n\n\ndef factorization(x):\n\n\tprimes = []\n\n\ti = 2\n\n\twhile i * i <= x:\n\n\t\tif x % i == 0:\n\n\t\t\tprimes.append(i)\n\n\t\t\twhile x % i == 0: x \/\/= i\n\n\t\ti = i + 1\n\n\tif x > 1: primes.append(x)\n\n\treturn primes\n\n\n\ndef solve_with_fixed_gcd(arr, gcd):\n\n\tresult = 0\n\n\tfor x in arr:\n\n\t\tif x < gcd: result += (gcd - x)\n\n\t\telse:\n\n\t\t\tremainder = x % gcd\n\n\t\t\tresult += min(remainder, gcd - remainder)\n\n\treturn result\n\n\n\nanswer = float(\"inf\")\n\nprime_list = set()\n\nfor index in iterations:\n\n\tfor x in range(-1, 2):\n\n\t\ttmp = factorization(a[index]-x)\n\n\t\tfor z in tmp: prime_list.add(z)\n\n\n\nfor prime in prime_list:\n\n\tanswer = min(answer, solve_with_fixed_gcd(a, prime))\n\n\tif answer == 0: break\n\n\n\nprint(answer)","language":"py"} -{"contest_id":"1296","problem_id":"B","statement":"B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1\u2264x\u2264s1\u2264x\u2264s, buy food that costs exactly xx burles and obtain \u230ax10\u230b\u230ax10\u230b burles as a cashback (in other words, Mishka spends xx burles and obtains \u230ax10\u230b\u230ax10\u230b back). The operation \u230aab\u230b\u230aab\u230b means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1\u2264s\u22641091\u2264s\u2264109) \u2014 the number of burles Mishka initially has.OutputFor each test case print the answer on it \u2014 the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6\n1\n10\n19\n9876\n12345\n1000000000\nOutputCopy1\n11\n21\n10973\n13716\n1111111111\n","tags":["math"],"code":"t = int(input())\n\nfor _ in range(t):\n\n n = int(input())\n\n ans = 0\n\n while n != 0:\n\n if n > 9:\n\n ans += (n\/\/10) * 10\n\n n = (n - ((n\/\/10) * 10)) + (n\/\/10)\n\n else:\n\n ans += n\n\n break\n\n print(ans)","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":"from collections import deque\n \n \nN = int(input())\n \nm = [[None]*N for i in range(N)]\nv = [[False]*N for i in range(N)]\n \nfor i in range(N):\n\tr = list(map(int, input().split()))\n\tfor j in range(N):\n\t\tx, y = r[2*j] - 1, r[2*j + 1] - 1\n\t\tm[i][j] = (x, y)\n \ndef bfs(x, y):\n\t# x, y is the coordinate of our input\n\tq = deque()\n\tq.append((x, y))\n\twhile len(q):\n\t\tx, y = q.popleft()\n\t\tfor i, j, d in [(x - 1, y, 'D'), (x + 1, y, 'U'), (x, y - 1, 'R'), (x, y + 1, 'L')]:\n\t\t\tif i != -1 and i != N and j != -1 and j != N:\n\t\t\t\tif m[i][j] != m[x][y]: \n\t\t\t\t\tcontinue\n\t\t\t\tif not v[i][j]:\n\t\t\t\t\tv[i][j] = d\n\t\t\t\t\tq.append((i, j))\n \nfor i in range(N):\n\tfor j in range(N):\n\t\tif m[i][j] == (i, j):\n\t\t\tv[i][j] = 'X'\n\t\t\tbfs(i, j)\n\t\telif m[i][j] == (-2, -2):\n\t\t\tfor a, b, nxt, prev in [(i - 1, j, 'U', 'D'), (i + 1, j, 'D', 'U'), (i, j - 1,'L', 'R'), (i, j + 1, 'R', 'L')]:\n\t\t\t\tif a != -1 and a != N and b != -1 and b != N:\n\t\t\t\t\tif m[i][j] != m[a][b]: \n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tv[i][j] = nxt\n\t\t\t\t\t\tv[a][b] = prev\n\t\t\t\t\t\tbreak \n \nfor i in range(N):\n\tfor j in range(N):\n\t\tif not v[i][j]:\n\t\t\tprint('INVALID')\n\t\t\texit()\n \nprint('VALID')\nprint('\\n'.join([''.join(r) for r in v]))\n \n \t \t \t \t\t \t \t\t\t\t\t\t \t \t\t \t","language":"py"} -{"contest_id":"1293","problem_id":"B","statement":"B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show \"1 vs. nn\"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0\u2264t\u2264s0\u2264t\u2264s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s\u2212ts\u2212t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10\u2212410\u22124. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a\u2212b|max(1,b)\u226410\u22124|a\u2212b|max(1,b)\u226410\u22124.ExamplesInputCopy1\nOutputCopy1.000000000000\nInputCopy2\nOutputCopy1.500000000000\nNoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.","tags":["combinatorics","greedy","math"],"code":"from math import * \n\nimport sys\n\ninput = lambda: sys.stdin.readline().strip()\n\nprint = lambda *a, **kw: sys.stdout.write(kw.get('sep', ' ').join(map(str, a)) + kw.get('end', '\\n'))\n\ndebug = lambda *a: sys.stderr.write(' '.join(map(str, a)) + '\\n')\n\nMOD = (10**9)+7\n\ndef prefixSum(arr):\n\n n=len(arr)\n\n if(n==0):\n\n return []\n\n ps = [0] * n\n\n ps[0] =arr[0]\n\n for i in range(1,n):\n\n ps[i]=arr[i]+ps[i-1]\n\n return ps\n\ndef sumDigits(no):\n\n return 0 if no == 0 else int(no % 10) + sumDigits(int(no \/ 10)) \n\ndef inde(arr):\n\n ind = {}\n\n for i in range(len(n)):\n\n ind[arr[i]]=i\n\n return ind\n\ndef freq(arr):\n\n d = {}\n\n for i in arr:\n\n if(i in d):\n\n d[i]+=1\n\n else:\n\n d[i]=1\n\n return d\n\ndef isPrime(num):\n\n if(num > 1):\n\n for i in range(2,int(sqrt(num))+1):\n\n if (num % i == 0):\n\n return False\n\n return True\n\n else:\n\n return False\n\ndef cbrt(num):\n\n return pow(num,1\/3)\n\n \n\n#for _ in range(int(input())):\n\nn = int(input())\n\nx = 0\n\nfor i in range(1,n+1):\n\n x+=(1\/i)\n\nprint(x)","language":"py"} -{"contest_id":"1292","problem_id":"F","statement":"F. Nora's Toy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSIHanatsuka - EMber SIHanatsuka - ATONEMENTBack in time; the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.One day, Nora's adoptive father, Phoenix Wyle, brought Nora nn boxes of toys. Before unpacking, Nora decided to make a fun game for ROBO.She labelled all nn boxes with nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an and asked ROBO to do the following action several (possibly zero) times: Pick three distinct indices ii, jj and kk, such that ai\u2223ajai\u2223aj and ai\u2223akai\u2223ak. In other words, aiai divides both ajaj and akak, that is ajmodai=0ajmodai=0, akmodai=0akmodai=0. After choosing, Nora will give the kk-th box to ROBO, and he will place it on top of the box pile at his side. Initially, the pile is empty. After doing so, the box kk becomes unavailable for any further actions. Being amused after nine different tries of the game, Nora asked ROBO to calculate the number of possible different piles having the largest amount of boxes in them. Two piles are considered different if there exists a position where those two piles have different boxes.Since ROBO was still in his infant stages, and Nora was still too young to concentrate for a long time, both fell asleep before finding the final answer. Can you help them?As the number of such piles can be very large, you should print the answer modulo 109+7109+7.InputThe first line contains an integer nn (3\u2264n\u2264603\u2264n\u226460), denoting the number of boxes.The second line contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u2264601\u2264ai\u226460), where aiai is the label of the ii-th box.OutputPrint the number of distinct piles having the maximum number of boxes that ROBO_Head can have, modulo 109+7109+7.ExamplesInputCopy3\n2 6 8\nOutputCopy2\nInputCopy5\n2 3 4 9 12\nOutputCopy4\nInputCopy4\n5 7 2 9\nOutputCopy1\nNoteLet's illustrate the box pile as a sequence bb; with the pile's bottommost box being at the leftmost position.In the first example, there are 22 distinct piles possible: b=[6]b=[6] ([2,6,8]\u2212\u2192\u2212\u2212(1,3,2)[2,8][2,6,8]\u2192(1,3,2)[2,8]) b=[8]b=[8] ([2,6,8]\u2212\u2192\u2212\u2212(1,2,3)[2,6][2,6,8]\u2192(1,2,3)[2,6]) In the second example, there are 44 distinct piles possible: b=[9,12]b=[9,12] ([2,3,4,9,12]\u2212\u2192\u2212\u2212(2,5,4)[2,3,4,12]\u2212\u2192\u2212\u2212(1,3,4)[2,3,4][2,3,4,9,12]\u2192(2,5,4)[2,3,4,12]\u2192(1,3,4)[2,3,4]) b=[4,12]b=[4,12] ([2,3,4,9,12]\u2212\u2192\u2212\u2212(1,5,3)[2,3,9,12]\u2212\u2192\u2212\u2212(2,3,4)[2,3,9][2,3,4,9,12]\u2192(1,5,3)[2,3,9,12]\u2192(2,3,4)[2,3,9]) b=[4,9]b=[4,9] ([2,3,4,9,12]\u2212\u2192\u2212\u2212(1,5,3)[2,3,9,12]\u2212\u2192\u2212\u2212(2,4,3)[2,3,12][2,3,4,9,12]\u2192(1,5,3)[2,3,9,12]\u2192(2,4,3)[2,3,12]) b=[9,4]b=[9,4] ([2,3,4,9,12]\u2212\u2192\u2212\u2212(2,5,4)[2,3,4,12]\u2212\u2192\u2212\u2212(1,4,3)[2,3,12][2,3,4,9,12]\u2192(2,5,4)[2,3,4,12]\u2192(1,4,3)[2,3,12]) In the third sequence, ROBO can do nothing at all. Therefore, there is only 11 valid pile, and that pile is empty.","tags":["bitmasks","combinatorics","dp"],"code":"MOD = 1000000007\n\ndef isSubset(a, b):\n\n return (a & b) == a\n\ndef isIntersect(a, b):\n\n return (a & b) != 0\n\ndef cntOrder(s, t):\n\n p = len(s)\n\n m = len(t)\n\n inMask = [0 for i in range(m)]\n\n for x in range(p):\n\n for i in range(m):\n\n if t[i] % s[x] == 0:\n\n inMask[i] |= 1 << x\n\n cnt = [0 for mask in range(1 << p)]\n\n for mask in range(1 << p):\n\n for i in range(m):\n\n if isSubset(inMask[i], mask):\n\n cnt[mask] += 1\n\n dp = [[0 for mask in range(1 << p)] for k in range(m + 1)]\n\n for i in range(m):\n\n dp[1][inMask[i]] += 1\n\n for k in range(m):\n\n for mask in range(1 << p):\n\n for i in range(m):\n\n if not isSubset(inMask[i], mask) and isIntersect(inMask[i], mask):\n\n dp[k + 1][mask | inMask[i]] = (dp[k + 1][mask | inMask[i]] + dp[k][mask]) % MOD\n\n dp[k + 1][mask] = (dp[k + 1][mask] + dp[k][mask] * (cnt[mask] - k)) % MOD\n\n return dp[m][(1 << p) - 1]\n\ndef dfs(u):\n\n global a, graph, degIn, visited, s, t\n\n\n\n visited[u] = True\n\n if degIn[u] == 0:\n\n s.append(a[u])\n\n else:\n\n t.append(a[u])\n\n\n\n for v in graph[u]:\n\n if not visited[v]:\n\n dfs(v)\n\ndef main():\n\n global a, graph, degIn, visited, s, t\n\n n = int(input())\n\n a = list(map(int, input().split()))\n\n c = [[0 for j in range(n)] for i in range(n)]\n\n for i in range(n):\n\n c[i][0] = 1\n\n for j in range(1, i + 1):\n\n c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % MOD\n\n degIn = [0 for u in range(n)]\n\n graph = [[] for u in range(n)]\n\n for u in range(n):\n\n for v in range(n):\n\n if u != v and a[v] % a[u] == 0:\n\n graph[u].append(v)\n\n graph[v].append(u)\n\n degIn[v] += 1\n\n ans = 1\n\n curLen = 0\n\n visited = [False for u in range(n)]\n\n for u in range(n):\n\n if not visited[u]:\n\n s = []\n\n t = []\n\n dfs(u)\n\n if len(t) > 0:\n\n sz = len(t) - 1\n\n cnt = cntOrder(s, t)\n\n ans = (ans * cnt) % MOD\n\n ans = (ans * c[curLen + sz][sz]) % MOD\n\n curLen += sz\n\n print(ans)\n\nif __name__ == \"__main__\":\n\n main()\n\n","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 = 450\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":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!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. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"t=int(input())\n\nM,L=[],[]\n\nfor i in range(t):\n\n n=int(input())\n\n L=[int(x) for x in input().split()]\n\n M=[int(x) for x in input().split()]\n\n if len(L)==1 and len(M)==1:\n\n for k in L:\n\n print(k)\n\n for k in M:\n\n print(k)\n\n else:\n\n res1=sorted(L)\n\n res2=sorted(M)\n\n for i in range (len(res1)-1):\n\n print(res1[i],end=' ')\n\n print(res1[len(res1)-1])\n\n for k in range (len(res2)-1):\n\n print(res2[k],end=' ')\n\n print(res2[len(res2)-1])\n\n ","language":"py"} -{"contest_id":"1310","problem_id":"A","statement":"A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A\/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn\u00a0\u2014 the number of news categories (1\u2264n\u22642000001\u2264n\u2264200000).The second line of input consists of nn integers aiai\u00a0\u2014 the number of publications of ii-th category selected by the batch algorithm (1\u2264ai\u22641091\u2264ai\u2264109).The third line of input consists of nn integers titi\u00a0\u2014 time it takes for targeted algorithm to find one new publication of category ii (1\u2264ti\u2264105)1\u2264ti\u2264105).OutputPrint one integer\u00a0\u2014 the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5\n3 7 9 7 8\n5 2 5 7 5\nOutputCopy6\nInputCopy5\n1 2 3 4 5\n1 1 1 1 1\nOutputCopy0\nNoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.","tags":["data structures","greedy","sortings"],"code":"import sys\nfrom collections import defaultdict\nfrom heapq import heapify, heappush, heappop\n\nn = int(sys.stdin.readline())\na = list(map(int, sys.stdin.readline().split()))\nt = list(map(int, sys.stdin.readline().split()))\n\n# create a map that stores list of time for each value of a\numap = defaultdict(list)\nfor i in range(n):\n umap[a[i]].append(t[i])\n\n# maintain a priority queue that will store time of repeating values\n# this will help us in retriving\/deleting greatest time\npq = [] # max heap\nheapify(pq)\nheapsum = 0 # to store sum of heap\n\nans = 0\nfor num in sorted(set(a)):\n if len(umap[num]) > 1 or len(pq) > 0: # either num repeats or pq is not empty\n for val in umap[num]:\n heappush(pq, -1*val) # store negative value since it's min heap\n heapsum += val\n\n # remove the largest time value\n heapsum += pq[0]\n heappop(pq)\n\n # increment all the other values\n temp = num\n while len(pq) > 0:\n temp += 1\n ans += heapsum\n if len(umap[temp]) > 0:\n # the next num also contains many time value\n # hence should be added in next iteration\n break\n else:\n # remove the largest time value\n heapsum += pq[0]\n heappop(pq)\n\n\nprint(ans)\n","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":"for _ in range(int(input())):\n\n input()\n\n print(len(set(input().split())))","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 n*(n-1)\/\/2:\n\n return ['NO', None]\n\n answer = [1]\n\n while True:\n\n if sum(answer)+2*answer[-1] <= n:\n\n answer.append(2*answer[-1])\n\n else:\n\n break\n\n answer.append(n-sum(answer))\n\n curr = sum([i*answer[i] for i in range(len(answer))])\n\n if d < curr:\n\n return ['NO', None]\n\n while curr < d:\n\n for i in range(len(answer)-1, -1, -1):\n\n if answer[i] > 1:\n\n break\n\n answer[i]-=1\n\n if i==len(answer)-1:\n\n answer.append(1)\n\n else:\n\n answer[i+1]+=1\n\n curr+=1\n\n assert sum([i*answer[i] for i in range(len(answer))])==d\n\n depths = [[] for i in range(len(answer))]\n\n depth1 = [None for i in range(n+1)]\n\n children = [0 for i in range(n+1)]\n\n final_answer = [None for i in range(n-1)]\n\n I = 0\n\n p = 1\n\n depth1[p] = 0\n\n for i in range(1, n+1):\n\n if len(depths[I])==answer[I]:\n\n I+=1\n\n while children[p]==2 or depth1[p] < I-1:\n\n p+=1\n\n if i > 1:\n\n final_answer[i-2] = p\n\n children[p]+=1\n\n depths[I].append(i)\n\n depth1[i] = I\n\n # print(answer)\n\n # print(depths)\n\n # print(depth1)\n\n #print(final_answer)\n\n return ['YES', final_answer]\n\n\n\nt = int(input())\n\nfor i in range(t):\n\n n, d = [int(x) for x in input().split()]\n\n a1, a2 = process(n, d)\n\n print(a1)\n\n if a1=='YES':\n\n sys.stdout.write(' '.join(map(str, a2))+'\\n')\n\n ","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 n = int(input())\n\n if n%2 == 0:\n\n print(\"1\"* (n\/\/2))\n\n else:\n\n print(\"7\" + (\"1\" * ((n-3)\/\/2)))\n\n ","language":"py"} -{"contest_id":"1141","problem_id":"F2","statement":"F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],\u2026,a[n].a[1],a[2],\u2026,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],\u2026,a[r]a[l],a[l+1],\u2026,a[r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),\u2026,(lk,rk)(l1,r1),(l2,r2),\u2026,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i\u2260ji\u2260j either rikk\u2032>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1\u2264n\u226415001\u2264n\u22641500) \u2014 the length of the given array. The second line contains the sequence of elements a[1],a[2],\u2026,a[n]a[1],a[2],\u2026,a[n] (\u2212105\u2264ai\u2264105\u2212105\u2264ai\u2264105).OutputIn the first line print the integer kk (1\u2264k\u2264n1\u2264k\u2264n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1\u2264li\u2264ri\u2264n1\u2264li\u2264ri\u2264n) \u2014 the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7\n4 1 2 2 1 5 3\nOutputCopy3\n7 7\n2 3\n4 5\nInputCopy11\n-5 -4 -3 -2 -1 0 1 2 3 4 5\nOutputCopy2\n3 4\n1 1\nInputCopy4\n1 1 1 1\nOutputCopy4\n4 4\n1 1\n2 2\n3 3\n","tags":["data structures","greedy"],"code":"import sys, os, io\n\ninput = lambda: sys.stdin.readline().rstrip('\\r\\n')\n\nfrom collections import defaultdict\n\nn = int(input())\n\na = list(map(int,input().split()))\n\nhas = defaultdict(list)\n\ndef f(a,b):return a*n+b\n\ndef ff(a):return (a\/\/n,a%n)\n\nfor j in range(n):\n\n lin = 0\n\n for i in range(j,-1,-1):\n\n lin += a[i]\n\n if lin in has and ff(has[lin][-1])[1] >= i:continue\n\n has[lin].append(f(i,j))\n\nmx = max(has.values(),key=lambda x:len(x))\n\nprint(len(mx))\n\nfor i in mx:\n\n a,b = ff(i)\n\n print(a+1,b+1)","language":"py"} -{"contest_id":"1295","problem_id":"B","statement":"B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss\u2026t=ssss\u2026 For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q\u2212cnt1,qcnt0,q\u2212cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string \"abcd\" has 5 prefixes: empty string, \"a\", \"ab\", \"abc\" and \"abcd\".InputThe first line contains the single integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.Next 2T2T lines contain descriptions of test cases \u2014 two lines per test case. The first line contains two integers nn and xx (1\u2264n\u22641051\u2264n\u2264105, \u2212109\u2264x\u2264109\u2212109\u2264x\u2264109) \u2014 the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si\u2208{0,1}si\u2208{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers \u2014 one per test case. For each test case print the number of prefixes or \u22121\u22121 if there is an infinite number of such prefixes.ExampleInputCopy4\n6 10\n010010\n5 3\n10101\n1 0\n0\n2 0\n01\nOutputCopy3\n0\n1\n-1\nNoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.","tags":["math","strings"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nt = int(input())\n\nfor _ in range(t):\n\n n, x = map(int, input().split())\n\n s = list(input().rstrip())\n\n a = [0]\n\n for i in s:\n\n a.append(a[-1] + (1 if i == \"0\" else -1))\n\n an = a[n]\n\n if an:\n\n ans = 0\n\n for i in range(n):\n\n if x - a[i] >= 0 and an > 0 or x - a[i] <= 0 and an < 0:\n\n if abs(x - a[i]) % abs(an) == 0:\n\n ans += 1\n\n else:\n\n ans = -1 if x in set(a) else 0\n\n print(ans)","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":"import sys\n\nimport math\n\ninput = sys.stdin.readline\n\nfrom functools import cmp_to_key;\n\n\n\ndef pi():\n\n return(int(input()))\n\ndef pl():\n\n return(int(input(), 16))\n\ndef ti():\n\n return(list(map(int,input().split())))\n\ndef ts():\n\n s = input()\n\n return(list(s[:len(s) - 1]))\n\ndef invr():\n\n return(map(int,input().split()))\n\nmod = 998244353;\n\nf = [];\n\ndef fact(n,m):\n\n global f;\n\n f = [1 for i in range(n+1)];\n\n f[0] = 1;\n\n for i in range(1,n+1):\n\n f[i] = (f[i-1]*i)%m;\n\n\n\ndef fast_mod_exp(a,b,m):\n\n res = 1;\n\n while b > 0:\n\n if b & 1:\n\n res = (res*a)%m;\n\n a = (a*a)%m;\n\n b = b >> 1;\n\n return res;\n\n\n\ndef inverseMod(n,m):\n\n return fast_mod_exp(n,m-2,m);\n\n\n\ndef ncr(n,r,m):\n\n if r == 0: return 1;\n\n return ((f[n]*inverseMod(f[n-r],m))%m*inverseMod(f[r],m))%m;\n\n\n\ndef main():\n\n B(); \n\n\n\ndef B():\n\n s = ts();\n\n t = pi();\n\n c = [[0 for j in range(len(s))] for i in range(26)];\n\n for i in range(26):\n\n for j in range(len(s)):\n\n if ord(s[j])-ord(\"a\") == i:\n\n c[i][j] = c[i][j-1] + 1 if j > 0 else 1;\n\n else:\n\n c[i][j] = c[i][j-1] if j > 0 else 0;\n\n for i in range(t):\n\n [l,r] = ti();\n\n count = 0;\n\n for j in range(26):\n\n count += (1 if c[j][r-1]-c[j][l-1] > 0 else 0);\n\n if s[l-1] != s[r-1] or l == r:\n\n print(\"Yes\");\n\n elif count >= 3:\n\n print(\"Yes\");\n\n else:\n\n print(\"No\");\n\n\n\n \n\n\n\nmain();","language":"py"} -{"contest_id":"1311","problem_id":"B","statement":"B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,\u2026,pmp1,p2,\u2026,pm, where 1\u2264pia[i+1]:\n\n flag=False\n\n if ok[i]:\n\n a[i],a[i+1]=a[i+1],a[i]\n\n else:\n\n print('NO')\n\n return\n\n if flag:\n\n print('YES')\n\n return\n\n\n\nfor _ in range(int(input())):\n\n solve()","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":"import random, sys, os, math, gc\n\nfrom collections import Counter, defaultdict, deque\n\nfrom functools import lru_cache, reduce, cmp_to_key\n\nfrom itertools import accumulate, combinations, permutations, product\n\nfrom heapq import nsmallest, nlargest, heapify, heappop, heappush\n\nfrom io import BytesIO, IOBase\n\nfrom copy import deepcopy\n\nfrom bisect import bisect_left, bisect_right\n\nfrom math import factorial, gcd\n\nfrom operator import mul, xor\n\nfrom types import GeneratorType\n\n# if \"PyPy\" in sys.version:\n\n# import pypyjit; pypyjit.set_param('max_unroll_recursion=-1')\n\n# sys.setrecursionlimit(2*10**5)\n\nBUFSIZE = 8192\n\nMOD = 10**9 + 7\n\nMODD = 998244353\n\nINF = float('inf')\n\nD4 = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n\nD8 = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]\n\n\n\nclass JumpOnTree:\n\n def __init__(self, edges, root=0):\n\n self.n = len(edges)\n\n self.edges = edges\n\n self.root = root\n\n self.logn = (self.n - 1).bit_length()\n\n self.depth = [-1] * self.n\n\n self.depth[self.root] = 0\n\n self.parent = [[-1] * self.n for _ in range(self.logn)]\n\n self.dfs()\n\n self.doubling()\n\n \n\n def dfs(self):\n\n stack = [self.root]\n\n while stack:\n\n u = stack.pop()\n\n for v in self.edges[u]:\n\n if self.depth[v] == -1:\n\n self.depth[v] = self.depth[u] + 1\n\n self.parent[0][v] = u\n\n stack.append(v)\n\n \n\n def doubling(self):\n\n for i in range(1, self.logn):\n\n for u in range(self.n):\n\n p = self.parent[i - 1][u]\n\n if p != -1:\n\n self.parent[i][u] = self.parent[i - 1][p]\n\n \n\n def lca(self, u, v):\n\n du = self.depth[u]\n\n dv = self.depth[v]\n\n if du > dv:\n\n du, dv = dv, du\n\n u, v = v, u\n\n \n\n d = dv - du\n\n i = 0\n\n while d > 0:\n\n if d & 1:\n\n v = self.parent[i][v]\n\n d >>= 1\n\n i += 1\n\n if u == v:\n\n return u\n\n \n\n logn = (du - 1).bit_length()\n\n for i in range(logn - 1, -1, -1):\n\n pu = self.parent[i][u]\n\n pv = self.parent[i][v]\n\n if pu != pv:\n\n u = pu\n\n v = pv\n\n return self.parent[0][u]\n\n \n\n def jump(self, u, v, k):\n\n if k == 0:\n\n return u\n\n p = self.lca(u, v)\n\n d1 = self.depth[u] - self.depth[p]\n\n d2 = self.depth[v] - self.depth[p]\n\n if d1 + d2 < k:\n\n return -1\n\n if k <= d1:\n\n d = k\n\n else:\n\n u = v\n\n d = d1 + d2 - k\n\n i = 0\n\n while d > 0:\n\n if d & 1:\n\n u = self.parent[i][u]\n\n d >>= 1\n\n i += 1\n\n return u\n\n \n\n def dist(self, u, v):\n\n return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)]\n\n\n\ndef solve():\n\n n = II()\n\n d = getGraph(n, n-1)\n\n tree = JumpOnTree(d)\n\n def check(x):\n\n return k >= x and x % 2 == k % 2\n\n for _ in range(II()):\n\n x, y, a, b, k = LII()\n\n x -= 1; y -= 1; a -= 1; b -= 1\n\n ab = tree.dist(a, b)\n\n ax, ay = tree.dist(a, x), tree.dist(a, y)\n\n bx, by = tree.dist(b, x), tree.dist(b, y)\n\n if check(ab) or check(ax + by + 1) or check(ay + bx + 1):\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")\n\n \n\n\n\ndef main():\n\n t = 1\n\n # t = II()\n\n for _ in range(t):\n\n solve()\n\n\n\ndef bootstrap(f, stack=[]):\n\n def wrappedfunc(*args, **kwargs):\n\n if stack:\n\n return f(*args, **kwargs)\n\n else:\n\n to = f(*args, **kwargs)\n\n while True:\n\n if type(to) is GeneratorType:\n\n stack.append(to)\n\n to = next(to)\n\n else:\n\n stack.pop()\n\n if not stack:\n\n break\n\n to = stack[-1].send(to)\n\n return to\n\n return wrappedfunc\n\n\n\ndef bitcnt(n):\n\n c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)\n\n c = (c & 0x3333333333333333) + ((c >> 2) & 0x3333333333333333)\n\n c = (c & 0x0F0F0F0F0F0F0F0F) + ((c >> 4) & 0x0F0F0F0F0F0F0F0F)\n\n c = (c & 0x00FF00FF00FF00FF) + ((c >> 8) & 0x00FF00FF00FF00FF)\n\n c = (c & 0x0000FFFF0000FFFF) + ((c >> 16) & 0x0000FFFF0000FFFF)\n\n c = (c & 0x00000000FFFFFFFF) + ((c >> 32) & 0x00000000FFFFFFFF)\n\n return c\n\n\n\ndef lcm(x, y):\n\n return x * y \/\/ gcd(x, y)\n\n\n\ndef lowbit(x):\n\n return x & -x\n\n\n\ndef perm(n, r):\n\n return factorial(n) \/\/ factorial(n - r) if n >= r else 0\n\n \n\ndef comb(n, r):\n\n return factorial(n) \/\/ (factorial(r) * factorial(n - r)) if n >= r else 0\n\n\n\ndef probabilityMod(x, y, mod):\n\n return x * pow(y, mod-2, mod) % mod\n\n\n\nclass SortedList:\n\n def __init__(self, iterable=[], _load=200):\n\n \"\"\"Initialize sorted list instance.\"\"\"\n\n values = sorted(iterable)\n\n self._len = _len = len(values)\n\n self._load = _load\n\n self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]\n\n self._list_lens = [len(_list) for _list in _lists]\n\n self._mins = [_list[0] for _list in _lists]\n\n self._fen_tree = []\n\n self._rebuild = True\n\n \n\n def _fen_build(self):\n\n \"\"\"Build a fenwick tree instance.\"\"\"\n\n self._fen_tree[:] = self._list_lens\n\n _fen_tree = self._fen_tree\n\n for i in range(len(_fen_tree)):\n\n if i | i + 1 < len(_fen_tree):\n\n _fen_tree[i | i + 1] += _fen_tree[i]\n\n self._rebuild = False\n\n \n\n def _fen_update(self, index, value):\n\n \"\"\"Update `fen_tree[index] += value`.\"\"\"\n\n if not self._rebuild:\n\n _fen_tree = self._fen_tree\n\n while index < len(_fen_tree):\n\n _fen_tree[index] += value\n\n index |= index + 1\n\n \n\n def _fen_query(self, end):\n\n \"\"\"Return `sum(_fen_tree[:end])`.\"\"\"\n\n if self._rebuild:\n\n self._fen_build()\n\n \n\n _fen_tree = self._fen_tree\n\n x = 0\n\n while end:\n\n x += _fen_tree[end - 1]\n\n end &= end - 1\n\n return x\n\n \n\n def _fen_findkth(self, k):\n\n \"\"\"Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).\"\"\"\n\n _list_lens = self._list_lens\n\n if k < _list_lens[0]:\n\n return 0, k\n\n if k >= self._len - _list_lens[-1]:\n\n return len(_list_lens) - 1, k + _list_lens[-1] - self._len\n\n if self._rebuild:\n\n self._fen_build()\n\n \n\n _fen_tree = self._fen_tree\n\n idx = -1\n\n for d in reversed(range(len(_fen_tree).bit_length())):\n\n right_idx = idx + (1 << d)\n\n if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:\n\n idx = right_idx\n\n k -= _fen_tree[idx]\n\n return idx + 1, k\n\n \n\n def _delete(self, pos, idx):\n\n \"\"\"Delete value at the given `(pos, idx)`.\"\"\"\n\n _lists = self._lists\n\n _mins = self._mins\n\n _list_lens = self._list_lens\n\n \n\n self._len -= 1\n\n self._fen_update(pos, -1)\n\n del _lists[pos][idx]\n\n _list_lens[pos] -= 1\n\n \n\n if _list_lens[pos]:\n\n _mins[pos] = _lists[pos][0]\n\n else:\n\n del _lists[pos]\n\n del _list_lens[pos]\n\n del _mins[pos]\n\n self._rebuild = True\n\n \n\n def _loc_left(self, value):\n\n \"\"\"Return an index pair that corresponds to the first position of `value` in the sorted list.\"\"\"\n\n if not self._len:\n\n return 0, 0\n\n \n\n _lists = self._lists\n\n _mins = self._mins\n\n \n\n lo, pos = -1, len(_lists) - 1\n\n while lo + 1 < pos:\n\n mi = (lo + pos) >> 1\n\n if value <= _mins[mi]:\n\n pos = mi\n\n else:\n\n lo = mi\n\n \n\n if pos and value <= _lists[pos - 1][-1]:\n\n pos -= 1\n\n \n\n _list = _lists[pos]\n\n lo, idx = -1, len(_list)\n\n while lo + 1 < idx:\n\n mi = (lo + idx) >> 1\n\n if value <= _list[mi]:\n\n idx = mi\n\n else:\n\n lo = mi\n\n \n\n return pos, idx\n\n \n\n def _loc_right(self, value):\n\n \"\"\"Return an index pair that corresponds to the last position of `value` in the sorted list.\"\"\"\n\n if not self._len:\n\n return 0, 0\n\n \n\n _lists = self._lists\n\n _mins = self._mins\n\n \n\n pos, hi = 0, len(_lists)\n\n while pos + 1 < hi:\n\n mi = (pos + hi) >> 1\n\n if value < _mins[mi]:\n\n hi = mi\n\n else:\n\n pos = mi\n\n \n\n _list = _lists[pos]\n\n lo, idx = -1, len(_list)\n\n while lo + 1 < idx:\n\n mi = (lo + idx) >> 1\n\n if value < _list[mi]:\n\n idx = mi\n\n else:\n\n lo = mi\n\n \n\n return pos, idx\n\n \n\n def add(self, value):\n\n \"\"\"Add `value` to sorted list.\"\"\"\n\n _load = self._load\n\n _lists = self._lists\n\n _mins = self._mins\n\n _list_lens = self._list_lens\n\n \n\n self._len += 1\n\n if _lists:\n\n pos, idx = self._loc_right(value)\n\n self._fen_update(pos, 1)\n\n _list = _lists[pos]\n\n _list.insert(idx, value)\n\n _list_lens[pos] += 1\n\n _mins[pos] = _list[0]\n\n if _load + _load < len(_list):\n\n _lists.insert(pos + 1, _list[_load:])\n\n _list_lens.insert(pos + 1, len(_list) - _load)\n\n _mins.insert(pos + 1, _list[_load])\n\n _list_lens[pos] = _load\n\n del _list[_load:]\n\n self._rebuild = True\n\n else:\n\n _lists.append([value])\n\n _mins.append(value)\n\n _list_lens.append(1)\n\n self._rebuild = True\n\n \n\n def discard(self, value):\n\n \"\"\"Remove `value` from sorted list if it is a member.\"\"\"\n\n _lists = self._lists\n\n if _lists:\n\n pos, idx = self._loc_right(value)\n\n if idx and _lists[pos][idx - 1] == value:\n\n self._delete(pos, idx - 1)\n\n \n\n def remove(self, value):\n\n \"\"\"Remove `value` from sorted list; `value` must be a member.\"\"\"\n\n _len = self._len\n\n self.discard(value)\n\n if _len == self._len:\n\n raise ValueError('{0!r} not in list'.format(value))\n\n \n\n def pop(self, index=-1):\n\n \"\"\"Remove and return value at `index` in sorted list.\"\"\"\n\n pos, idx = self._fen_findkth(self._len + index if index < 0 else index)\n\n value = self._lists[pos][idx]\n\n self._delete(pos, idx)\n\n return value\n\n \n\n def bisect_left(self, value):\n\n \"\"\"Return the first index to insert `value` in the sorted list.\"\"\"\n\n pos, idx = self._loc_left(value)\n\n return self._fen_query(pos) + idx\n\n \n\n def bisect_right(self, value):\n\n \"\"\"Return the last index to insert `value` in the sorted list.\"\"\"\n\n pos, idx = self._loc_right(value)\n\n return self._fen_query(pos) + idx\n\n \n\n def count(self, value):\n\n \"\"\"Return number of occurrences of `value` in the sorted list.\"\"\"\n\n return self.bisect_right(value) - self.bisect_left(value)\n\n \n\n def __len__(self):\n\n \"\"\"Return the size of the sorted list.\"\"\"\n\n return self._len\n\n \n\n def __getitem__(self, index):\n\n \"\"\"Lookup value at `index` in sorted list.\"\"\"\n\n pos, idx = self._fen_findkth(self._len + index if index < 0 else index)\n\n return self._lists[pos][idx]\n\n \n\n def __delitem__(self, index):\n\n \"\"\"Remove value at `index` from sorted list.\"\"\"\n\n pos, idx = self._fen_findkth(self._len + index if index < 0 else index)\n\n self._delete(pos, idx)\n\n \n\n def __contains__(self, value):\n\n \"\"\"Return true if `value` is an element of the sorted list.\"\"\"\n\n _lists = self._lists\n\n if _lists:\n\n pos, idx = self._loc_left(value)\n\n return idx < len(_lists[pos]) and _lists[pos][idx] == value\n\n return False\n\n \n\n def __iter__(self):\n\n \"\"\"Return an iterator over the sorted list.\"\"\"\n\n return (value for _list in self._lists for value in _list)\n\n \n\n def __reversed__(self):\n\n \"\"\"Return a reverse iterator over the sorted list.\"\"\"\n\n return (value for _list in reversed(self._lists) for value in reversed(_list))\n\n \n\n def __repr__(self):\n\n \"\"\"Return string representation of sorted list.\"\"\"\n\n return 'SortedList({0})'.format(list(self))\n\n\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\n\n\nsys.stdin = IOWrapper(sys.stdin)\n\n# sys.stdout = IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n\n\ndef I():\n\n return input()\n\n\n\ndef II():\n\n return int(input())\n\n\n\ndef MI():\n\n return map(int, input().split())\n\n\n\ndef LI():\n\n return list(input().split())\n\n\n\ndef LII():\n\n return list(map(int, input().split()))\n\n\n\ndef GMI():\n\n return map(lambda x: int(x) - 1, input().split())\n\n\n\ndef LGMI():\n\n return list(map(lambda x: int(x) - 1, input().split()))\n\n\n\ndef getGraph(n, m, directed=False):\n\n d = [[] for _ in range(n)]\n\n for _ in range(m):\n\n u, v = LGMI()\n\n d[u].append(v)\n\n if not directed:\n\n d[v].append(u)\n\n return d\n\n\n\ndef getWeightedGraph(n, m, directed=False):\n\n d = [[] for _ in range(n)]\n\n for _ in range(m):\n\n u, v, w = LII()\n\n u -= 1; v -= 1\n\n d[u].append((v, w))\n\n if not directed:\n\n d[v].append((u, w))\n\n return d\n\n\n\nif __name__ == \"__main__\":\n\n main()","language":"py"} -{"contest_id":"1296","problem_id":"B","statement":"B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1\u2264x\u2264s1\u2264x\u2264s, buy food that costs exactly xx burles and obtain \u230ax10\u230b\u230ax10\u230b burles as a cashback (in other words, Mishka spends xx burles and obtains \u230ax10\u230b\u230ax10\u230b back). The operation \u230aab\u230b\u230aab\u230b means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1\u2264s\u22641091\u2264s\u2264109) \u2014 the number of burles Mishka initially has.OutputFor each test case print the answer on it \u2014 the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6\n1\n10\n19\n9876\n12345\n1000000000\nOutputCopy1\n11\n21\n10973\n13716\n1111111111\n","tags":["math"],"code":"from sys import stdin\n\ninput=lambda :stdin.readline()[:-1]\n\n\n\ndef solve():\n\n n=int(input())\n\n ans=n\n\n while n>=10:\n\n x=n\/\/10\n\n ans+=x\n\n n-=9*x\n\n print(ans)\n\n\n\n\n\nfor _ in range(int(input())):\n\n solve()","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":"import sys, os, io\n\ninput = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline\n\n\n\nt = int(input())\n\nans = []\n\nfor _ in range(t):\n\n n, d = map(int, input().split())\n\n a = list(map(int, input().split()))\n\n ans0 = a[0]\n\n for i in range(1, n):\n\n x = min(d \/\/ i, a[i])\n\n ans0 += x\n\n d -= x * i\n\n ans.append(ans0)\n\nsys.stdout.write(\"\\n\".join(map(str, ans)))","language":"py"} -{"contest_id":"1311","problem_id":"C","statement":"C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s=\"abca\" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1\u2264pi 0:\n\n f[i][j] = f[i][j - 1]\n\n if j < a[i][1]:\n\n for k in range(i, -1, -1):\n\n if a[k][1] <= j or j < a[k][0]:\n\n break\n\n if k == 0 or j != 0:\n\n tmp = cal(i - k + 1, g[j])\n\n if k > 0:\n\n f[i][j] += f[k - 1][j - 1] * tmp % M\n\n else:\n\n f[i][j] += tmp\n\n f[i][j] %= M\n\n \n\n#print(f)\n\n#print(f[n - 1][len(b) - 1], res)\n\nprint(f[n - 1][len(b) - 1] * pw(res, M - 2) % M)\n\n","language":"py"} -{"contest_id":"1307","problem_id":"C","statement":"C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1\u2264|s|\u22641051\u2264|s|\u2264105) \u2014 the text that Bessie intercepted.OutputOutput a single integer \u00a0\u2014 the number of occurrences of the secret message.ExamplesInputCopyaaabb\nOutputCopy6\nInputCopyusaco\nOutputCopy1\nInputCopylol\nOutputCopy2\nNoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.","tags":["brute force","dp","math","strings"],"code":"from sys import stdin\n\nfrom collections import defaultdict\n\nimport bisect\n\ninput = stdin.readline \n\n\n\ns = input(); set_s = set()\n\ninds_by_letter = defaultdict(list)\n\n\n\nfor ind, elem in enumerate(s):\n\n inds_by_letter[elem].append(ind); set_s.add(elem)\n\n\n\nans = max(len(inds_by_letter[letter]) for letter in inds_by_letter)\n\n\n\n\n\nfor l1 in set_s:\n\n for l2 in set_s:\n\n res = 0\n\n for ind1 in inds_by_letter[l1]:\n\n pos = bisect.bisect_left(inds_by_letter[l2], ind1)\n\n res += pos\n\n\n\n ans = max(ans, res)\n\n\n\nprint(ans)\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n ","language":"py"} -{"contest_id":"1325","problem_id":"A","statement":"A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1\u2264t\u2264100)(1\u2264t\u2264100) \u00a0\u2014 the number of testcases.Each testcase consists of one line containing a single integer, xx (2\u2264x\u2264109)(2\u2264x\u2264109).OutputFor each testcase, output a pair of positive integers aa and bb (1\u2264a,b\u2264109)1\u2264a,b\u2264109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2\n2\n14\nOutputCopy1 1\n6 4\nNoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.","tags":["constructive algorithms","greedy","number theory"],"code":"for i in range(int(input())):\n\n n = int(input())\n\n print(f\"1 {n-1}\")","language":"py"} -{"contest_id":"1295","problem_id":"F","statement":"F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (xRMIN:\n\n LR[i][1]=RMIN\n\n RMIN=min(RMIN,LR[i][1])\n\n\n\nLMAX=-1\n\nfor i in range(n-1,-1,-1):\n\n if LR[i][0]=compression[i+1]:\n\n DP[j][i]=now\n\n else:\n\n break\n\n now=now*(x+j+1)*pow(j+2,mod-2,mod)%mod\n\n\n\n#print(DP)\n\n\n\nfor i in range(1,n):\n\n SUM=DP[i-1][LEN-1]\n\n #print(DP)\n\n for j in range(LEN-2,-1,-1):\n\n if LR[i][0]<=compression[j] and LR[i][1]+1>=compression[j+1]:\n\n x=SUM*(compression[j+1]-compression[j])%mod\n\n now=x\n\n t=compression[j+1]-compression[j]\n\n #print(x,t)\n\n\n\n for k in range(i,n):\n\n \n\n if LR[k][0]<=compression[j] and LR[k][1]+1>=compression[j+1]:\n\n DP[k][j]=(DP[k][j]+now)%mod\n\n else:\n\n break\n\n now=now*(t+k-i+1)*pow(k-i+2,mod-2,mod)%mod\n\n \n\n \n\n SUM+=DP[i-1][j]\n\n\n\nprint(sum(DP[-1])*ALL%mod)\n\n\n\n \n\n \n\n \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":"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\nimport random\n\nimport copy\n\nimport threading\n\ninput=lambda:sys.stdin.readline().strip('\\n')\n\nmis=lambda:map(int,input().split())\n\nii=lambda:int(input())\n\nsys.setrecursionlimit(10 ** 6)\n\n\n\n\n\nN = ii()\n\nA = list(mis())\n\nedges = defaultdict(list)\n\nfor _ in range(N-1):\n\n u, v = mis()\n\n edges[u].append(v)\n\n edges[v].append(u)\n\n\n\nfor i in range(N):\n\n if A[i] == 0:\n\n A[i] = -1\n\n\n\ndp = [0] * N\n\nans = [0] * N\n\ndef dfs1(node, p = 0):\n\n dp[node-1] = A[node-1]\n\n \n\n for nei in edges[node]:\n\n if nei == p:\n\n continue \n\n dfs1(nei, node)\n\n dp[node-1] += max(0, dp[nei-1])\n\n\n\ndef dfs2(node, p, maxp):\n\n ans[node-1] = maxp + dp[node-1]\n\n for nei in edges[node]:\n\n if nei == p:\n\n continue\n\n\n\n dfs2(nei, node, max(ans[node-1] - max(0, dp[nei-1]), 0))\n\n\n\n# if dp[nei-1] > 0:\n\n# newmaxp = dp[node-1] - dp[nei-1]\n\n# dfs2(nei, node, max(0, maxp + newmaxp))\n\n# else:\n\n# newmaxp = dp[node-1]\n\n# dfs2(nei, node, max(0, maxp + newmaxp))\n\n\n\ndef main():\n\n dfs1(1)\n\n dfs2(1, 0, 0)\n\n print(*ans)\n\n\n\nif __name__ == \"__main__\":\n\n threading.stack_size(10**8)\n\n t = threading.Thread(target=main)\n\n t.start()\n\n t.join()\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":"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 i in range(int(input())):\n\n flag=False\n\n n = int(input())\n\n l1 = list(map(int, input().split()))\n\n for j in l1:\n\n if l1.count(j)>1:\n\n a=l1.index(j)\n\n l1.reverse()\n\n b=n-l1.index(j)-1\n\n if b-a>1:\n\n flag=True\n\n break\n\n if flag:\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")\n\n","language":"py"} -{"contest_id":"1296","problem_id":"F","statement":"F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n\u22121n\u22121 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n\u22121n\u22121 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section \u2014 the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,\u2026,fn\u22121f1,f2,\u2026,fn\u22121, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2\u2264n\u226450002\u2264n\u22645000) \u2014 the number of railway stations in Berland.The next n\u22121n\u22121 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1\u2264xi,yi\u2264n,xi\u2260yi1\u2264xi,yi\u2264n,xi\u2260yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1\u2264m\u226450001\u2264m\u22645000) \u2014 the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1\u2264aj,bj\u2264n1\u2264aj,bj\u2264n; aj\u2260bjaj\u2260bj; 1\u2264gj\u22641061\u2264gj\u2264106) \u2014 the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n\u22121n\u22121 integers f1,f2,\u2026,fn\u22121f1,f2,\u2026,fn\u22121 (1\u2264fi\u22641061\u2264fi\u2264106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4\n1 2\n3 2\n3 4\n2\n1 2 5\n1 3 3\nOutputCopy5 3 5\nInputCopy6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 3\n3 4 1\n6 5 2\n1 2 5\nOutputCopy5 3 1 2 1 \nInputCopy6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 1\n3 4 3\n6 5 3\n1 2 4\nOutputCopy-1\n","tags":["constructive algorithms","dfs and similar","greedy","sortings","trees"],"code":"import sys\n\n\n\n\n\nclass graph:\n\n def __init__(self, n):\n\n self.n, self.gdict = n, [[] for _ in range(n + 1)]\n\n\n\n def add_edge(self, node1, node2, w=None):\n\n self.gdict[node1].append(node2)\n\n self.gdict[node2].append(node1)\n\n\n\n def subtree(self, v):\n\n queue, vis = [v], [False] * (n + 1)\n\n vis[v], self.par, self.level = True, [-1] * (n + 1), [0] * (n + 1)\n\n while queue:\n\n s = queue.pop()\n\n\n\n for i1 in self.gdict[s]:\n\n if not vis[i1]:\n\n queue.append(i1)\n\n vis[i1] = True\n\n self.par[i1], self.level[i1] = s, self.level[s] + 1\n\n\n\n def lca(self, x, y):\n\n if self.level[x] < self.level[y]:\n\n x, y = y, x\n\n while self.level[x] > self.level[y]:\n\n p = self.par[x]\n\n ans[edges[p][x]] = mi\n\n x = p\n\n\n\n while x != y:\n\n p = self.par[x]\n\n ans[edges[p][x]] = mi\n\n x = p\n\n\n\n p = self.par[y]\n\n ans[edges[p][y]] = mi\n\n y = p\n\n\n\n def check(self, x, y):\n\n mi_ = 10 ** 9\n\n if self.level[x] < self.level[y]:\n\n x, y = y, x\n\n while self.level[x] > self.level[y]:\n\n p = self.par[x]\n\n mi_ = min(ans[edges[p][x]], mi_)\n\n x = p\n\n\n\n while x != y:\n\n p = self.par[x]\n\n mi_ = min(ans[edges[p][x]], mi_)\n\n x = p\n\n\n\n p = self.par[y]\n\n mi_ = min(ans[edges[p][y]], mi_)\n\n y = p\n\n return mi_\n\n\n\n\n\ninput = sys.stdin.readline\n\nn = int(input())\n\nadj = [[int(x) for x in input().split()] for _ in range(n - 1)]\n\nm = int(input())\n\na = [tuple([int(x) for x in input().split()]) for _ in range(m)]\n\nans = [1] * (n - 1)\n\nedges = [[0] * (n + 1) for _ in range(n + 1)]\n\ng = graph(n)\n\n\n\nfor _ in range(n - 1):\n\n u, v = adj[_]\n\n g.add_edge(u, v)\n\n edges[u][v] = edges[v][u] = _\n\n\n\na.sort(key=lambda x: x[2])\n\ng.subtree(1)\n\n\n\nfor x, y, mi in a:\n\n g.lca(x, y)\n\n\n\nfor x, y, mi in a:\n\n mi_ = g.check(x, y)\n\n if mi_ != mi:\n\n exit(print(-1))\n\n\n\nprint(' '.join(map(str, ans)))\n\n","language":"py"} -{"contest_id":"1288","problem_id":"D","statement":"D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k\u2208[1,m]k\u2208[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105, 1\u2264m\u226481\u2264m\u22648) \u2014 the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0\u2264ax,y\u22641090\u2264ax,y\u2264109).OutputPrint two integers ii and jj (1\u2264i,j\u2264n1\u2264i,j\u2264n, it is possible that i=ji=j) \u2014 the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5\n5 0 3 1 2\n1 8 9 1 3\n1 2 3 4 5\n9 1 0 3 7\n2 3 0 6 3\n6 4 1 7 0\nOutputCopy1 5\n","tags":["binary search","bitmasks","dp"],"code":"import sys\n\n\n\n\n\n# 1288D\n\ndef solve(a):\n\n m, n = len(a), len(a[0])\n\n maxx = max(max(t) for t in a)\n\n\n\n def check(t):\n\n idx = [-1] * 256\n\n for i in range(m):\n\n mask = 0\n\n for j in range(n):\n\n if a[i][j] >= t:\n\n mask |= 1 << j\n\n # idx: [5,-1,6,8,-1\u2026\u2026]\n\n idx[mask] = i\n\n for i in range(1 << n):\n\n if idx[i] == -1:\n\n continue\n\n for j in range(i, 1 << n):\n\n if idx[j] == -1:\n\n continue\n\n if (i | j) == (1 << n) - 1:\n\n return [idx[i], idx[j]]\n\n return [-1, -1]\n\n\n\n l, r = 0, maxx + 1\n\n while l < r:\n\n mid = (l + r) \/\/ 2\n\n if check(mid) != [-1, -1]:\n\n l = mid + 1\n\n else:\n\n r = mid\n\n # [ TTTTTT FFFFFF ]\n\n # rl\n\n return check(r - 1)\n\n\n\nm, n = map(int, input().split())\n\na = []\n\nfor i in range(m):\n\n a.append([int(i) for i in input().split()])\n\n\n\nres = solve(a)\n\nprint(res[0] + 1, res[1] + 1)\n\n\n\n\n\n# 1103B\n\n# def query(x, y):\n\n# print(\"?\", x, y)\n\n# sys.stdout.flush()\n\n# res = input()\n\n# return res\n\n\n\n# def solve():\n\n# # write function here\n\n# return -1\n\n\n\n# while True:\n\n# res = solve()\n\n# if res == -1: break\n\n# print(\"!\", res)\n\n\n\n# def cutThemAll(lengths, minLength):\n\n# for i in range(len(lengths) - 1):\n\n# if lengths[i] + lengths[i+1] >= minLength:\n\n# return \"Possible\"\n\n# return \"Impossible\"\n\n\n\n# ls = [3,5,6]\n\n# print(cutThemAll(ls, 12))\n\n\n\n# def getUniqueCharacter(s):\n\n# cnt = [0] * 26\n\n# for c in s:\n\n# cnt[ord(c) - ord('a')] += 1\n\n# for i in range(len(s)):\n\n# if cnt[ord(s[i]) - ord('a')] == 1:\n\n# return i + 1\n\n# return -1\n\n\n\n# print(getUniqueCharacter(\"madam\"))\n\n\n\n\n\n# from cmath import log\n\n# from collections import Counter\n\n# from dis import findlabels\n\n\n\n# base = 10**9 + 7\n\n# def findRight(a):\n\n# # find the index of the first less one in the left side, for every a[i]\n\n# n = len(a)\n\n# st, res = [], [0] * n\n\n# for i in range(n - 1, -1, -1):\n\n# while len(st) and a[st[-1]] >= a[i]:\n\n# st.pop()\n\n# res[i] = n if len(st) == 0 else st[-1]\n\n# st.append(i)\n\n# return res\n\n\n\n# def findLeft(a):\n\n# # find the index of the first less or equal one in the right side, for every a[i]\n\n# n = len(a)\n\n# st, res = [], [0] * n\n\n# for i in range(n):\n\n# while len(st) and a[st[-1]] > a[i]:\n\n# st.pop()\n\n# res[i] = -1 if len(st) == 0 else st[-1]\n\n# st.append(i)\n\n# return res\n\n\n\n# def findTotalPower(a):\n\n# # In order to avoid repeated calculations, \n\n# # the left side finds the first element less than a[i], \n\n# # and the right side finds the first element less than or equal to a[i]\n\n# left = findLeft(a)\n\n# right = findRight(a)\n\n \n\n# n, res = len(a), 0\n\n# s = [0] * (n + 1)\n\n# ss = [0] * (n + 2)\n\n\n\n# # s means the prefix sum of a\n\n# for i in range(n): s[i+1] = s[i] + a[i]\n\n# # ss meams the prefix sum of s\n\n# for i in range(n + 1): ss[i+1] = ss[i] + s[i]\n\n\n\n# for i in range(n):\n\n# # every left one could be the leader of subarray, which can be combined with the ending on the right\n\n# l = i - left[i]\n\n# # every right one could be the ending of subarray, which can be combined with the leader on the left\n\n# r = right[i] - i\n\n \n\n# # find the sum(sum([i, r]))\n\n# now = ((ss[right[i] + 1] - ss[i + 1]) - r * s[i]) % base\n\n# # find the sum(sum([i, r])) * a[i] * (i-left)\n\n# res += ((now * l) % base * a[i]) % base\n\n\n\n# # find the sum(sum([l, i]))\n\n# now = (s[i] * (l - 1) - (ss[i] - ss[left[i] + 1])) % base\n\n# # find the sum(sum([l, i])) * a[i] * (right-i)\n\n# res += ((now * r) % base * a[i]) % base\n\n# res %= base\n\n\n\n# return res % base\n\n\n\n\n\n# ls = [2,3,2,1]\n\n# res = findTotalPower(ls)\n\n# print(res)\n\n\n\n\n\n# def solve(a):\n\n# m, n = len(a), len(a[0])\n\n# maxx = max(max(t) for t in a)\n\n# def ok(t):\n\n# idx = [-1] * 256\n\n# maxm = 1 << n\n\n# for i in range(m):\n\n# mask = 0\n\n# for j in range(n):\n\n# if a[i][j] >= t: \n\n# mask |= 1 << j\n\n# if idx[mask] == -1:\n\n# idx[mask] = i\n\n# for i in range(maxm):\n\n# if idx[i] == -1: \n\n# continue\n\n# for j in range(i, maxm):\n\n# if idx[j] == -1: \n\n# continue\n\n# if (i | j) == maxm - 1: \n\n# return [idx[i], idx[j]]\n\n# return [-1, -1]\n\n# l, r = 0, maxx\n\n# while l <= r:\n\n# mid = (l + r) \/\/ 2\n\n# if ok(mid) != [-1, -1]:\n\n# l = mid + 1\n\n# else:\n\n# r = mid - 1\n\n# return ok(r)","language":"py"} -{"contest_id":"1294","problem_id":"A","statement":"A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1\u2264a,b,c,n\u22641081\u2264a,b,c,n\u2264108) \u2014 the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print \"YES\" if Polycarp can distribute all nn coins between his sisters and \"NO\" otherwise.ExampleInputCopy5\n5 3 2 8\n100 101 102 105\n3 2 1 100000000\n10 20 15 14\n101 101 101 3\nOutputCopyYES\nYES\nNO\nNO\nYES\n","tags":["math"],"code":"t=int(input())\n\nfor k in range (t):\n\n unos=input()\n\n niz=[]\n\n for i in unos.split():\n\n broj=int(i)\n\n niz.append(broj)\n\n for i in range (3):\n\n for j in range (2):\n\n if niz[j]>niz[j+1]:\n\n pom=niz[j]\n\n niz[j]=niz[j+1]\n\n niz[j+1]=pom\n\n if (niz[0]+niz[1]+niz[2]+niz[3])%3==0:\n\n if niz[0]!=niz[1] and niz[1]!=niz[2] and abs(niz[0]-niz[2])+abs(niz[1]-niz[2])<=niz[3]:\n\n print(\"YES\")\n\n elif niz[0]==niz[1] and niz[0]!=niz[2] and abs(niz[0]-niz[2])*2<=niz[3]:\n\n print(\"YES\")\n\n elif niz[1]==niz[2] and niz[0]!=niz[1] and abs(niz[0]-niz[1])<=niz[3]:\n\n print(\"YES\")\n\n elif niz[0]==niz[1] and niz[0]==niz[2]:\n\n print(\"YES\")\n\n else:\n\n print(\"NO\")\n\n else:\n\n print(\"NO\")","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 t in range(int(input())):\n\n\ta, b = map(int, input().split())\n\n\tprint(a * (len(str(b + 1)) - 1))","language":"py"} -{"contest_id":"1141","problem_id":"G","statement":"G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n\u22121n\u22121 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right \u2014 the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2\u2264n\u2264200000,0\u2264k\u2264n\u221212\u2264n\u2264200000,0\u2264k\u2264n\u22121) \u2014 the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n\u22121n\u22121 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1\u2264r\u2264n\u221211\u2264r\u2264n\u22121). In the second line print n\u22121n\u22121 numbers c1,c2,\u2026,cn\u22121c1,c2,\u2026,cn\u22121 (1\u2264ci\u2264r1\u2264ci\u2264r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2\n1 4\n4 3\n3 5\n3 6\n5 2\nOutputCopy2\n1 2 1 1 2 InputCopy4 2\n3 1\n1 4\n1 2\nOutputCopy1\n1 1 1 InputCopy10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9\nOutputCopy3\n1 1 2 3 2 3 1 3 1 ","tags":["binary search","constructive algorithms","dfs and similar","graphs","greedy","trees"],"code":"import decimal\nimport heapq\nimport math\nimport os\nimport sys\nfrom collections import Counter, deque\nfrom io import BytesIO, IOBase\nimport bisect\nfrom types import GeneratorType\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\ndef isPrime(n):\n if n <= 1:\n return False\n if n <= 3:\n return True\n if n % 2 == 0 or n % 3 == 0:\n 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\n\n\ndef lcm(a, b): return (a * b) \/\/ math.gcd(a, b)\n\n\ndef ciel(a, b):\n x = a \/\/ b\n if a % b == 0:\n return x\n return x + 1\n\n\ndef ints_get(): return map(int, input().strip().split())\n\n\ndef list_get(): return list(map(int, sys.stdin.readline().strip().split()))\n\n\ndef chars_get(): return list(map(str, sys.stdin.readline().strip().split()))\n\n\ndef ipn(): return int(input())\n\n\ndef bootstrap(f, stack=[]):\n def wrappedfunc(*args, **kwargs):\n if stack:\n return f(*args, **kwargs)\n else:\n to = f(*args, **kwargs)\n while True:\n if type(to) is GeneratorType:\n stack.append(to)\n to = next(to)\n else:\n stack.pop()\n if not stack:\n break\n to = stack[-1].send(to)\n return to\n\n return wrappedfunc\n\n\n# ******************************************************#\n# **************** code starts here ********************#\n# ******************************************************#\n\n\ndef main():\n n, k = ints_get()\n dic = {}\n for i in range(1, n + 1):\n dic[i] = []\n d = {}\n for i in range(n - 1):\n x, y = ints_get()\n dic[x].append(y)\n dic[y].append(x)\n x, y = min(x, y), max(x, y)\n d[(x, y)] = i\n v = []\n for i in dic:\n v.append(len(dic[i]))\n v.sort()\n for _ in range(k):\n v.pop()\n m = v[-1]\n p = [-1 for _ in range(n)]\n out = []\n\n @bootstrap\n def dfs(s, e):\n l = m\n for u in dic[s]:\n if u == e:\n continue\n if l == p[s - 1]:\n l -= 1\n if l == 0:\n l += m\n p[u - 1] = l\n x, y = min(u, s), max(u, s)\n out.append([d[(x, y)], l])\n l -= 1\n if l == 0:\n l += m\n\n for u in dic[s]:\n if u == e:\n continue\n yield dfs(u, s)\n yield\n\n dfs(1, 0)\n\n out.sort()\n print(m)\n for i in out:\n print(i[1], end=\" \")\n print()\n\n return\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","language":"py"} -{"contest_id":"1312","problem_id":"A","statement":"A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m mx:\n\n mx, ind = val, i\n\n a[0], a[ind] = a[ind], a[0]\n\n for ele in a: print(ele, end=' ')\n\n\n\nmain()","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":"for _ in range(int(input())):\n\n n = int(input())\n\n a = list(map(int, input().split()))\n\n s = sum(a)\n\n s1 = s\n\n i = 0\n\n t = 0\n\n l = []\n\n while i < n:\n\n if a[i] >= 0:\n\n t = t + a[i]\n\n l.append(a[i])\n\n else:\n\n if s1>0 and t+a[i]>0:\n\n t = t + a[i]\n\n l.append(a[i])\n\n elif s1>0 and t+a[i]<0:\n\n t = 0\n\n l = []\n\n elif s1<0 and t+a[i]>0:\n\n break\n\n else:\n\n if t>s1-a[i]:\n\n break\n\n else:\n\n t = 0\n\n l = []\n\n s1 = s1 - a[i]\n\n i = i + 1\n\n\n\n if len(l)==n:\n\n t = t - min(l[0],l[-1])\n\n if t>=s:\n\n print('NO')\n\n else:\n\n print('YES')\n\n\n\n","language":"py"} -{"contest_id":"1141","problem_id":"G","statement":"G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n\u22121n\u22121 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right \u2014 the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2\u2264n\u2264200000,0\u2264k\u2264n\u221212\u2264n\u2264200000,0\u2264k\u2264n\u22121) \u2014 the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n\u22121n\u22121 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1\u2264r\u2264n\u221211\u2264r\u2264n\u22121). In the second line print n\u22121n\u22121 numbers c1,c2,\u2026,cn\u22121c1,c2,\u2026,cn\u22121 (1\u2264ci\u2264r1\u2264ci\u2264r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2\n1 4\n4 3\n3 5\n3 6\n5 2\nOutputCopy2\n1 2 1 1 2 InputCopy4 2\n3 1\n1 4\n1 2\nOutputCopy1\n1 1 1 InputCopy10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9\nOutputCopy3\n1 1 2 3 2 3 1 3 1 ","tags":["binary search","constructive algorithms","dfs and similar","graphs","greedy","trees"],"code":"from collections import defaultdict\n\nfrom math import log2\n\nfrom bisect import bisect_left\n\n\n\nimport os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\nfrom types import GeneratorType\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\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\nsys.setrecursionlimit(10**5)\n\n\n\n\n\ndef bootstrap(f, stack=[]):\n\n def wrappedfunc(*args, **kwargs):\n\n if stack:\n\n return f(*args, **kwargs)\n\n else:\n\n to = f(*args, **kwargs)\n\n while True:\n\n if type(to) is GeneratorType:\n\n stack.append(to)\n\n to = next(to)\n\n else:\n\n stack.pop()\n\n if not stack:\n\n break\n\n to = stack[-1].send(to)\n\n return to\n\n return wrappedfunc\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n@bootstrap\n\ndef dfs(u,p,curr):\n\n\n\n global l\n\n cnt=1\n\n for j in adj[u]:\n\n if j!=p:\n\n rem=(curr+cnt)%l\n\n if rem==0:\n\n rem=l\n\n edge[d[(u,j)]]=rem\n\n yield dfs(j,u,rem)\n\n cnt+=1\n\n yield\n\n\n\n\n\n\n\n\n\n\n\nn,k=map(int,input().split())\n\nadj=[[] for i in range(n+1)]\n\ntot=[0 for i in range(n+1)]\n\nd=dict()\n\nfor j in range(n-1):\n\n u,v=map(int,input().split())\n\n adj[u].append(v)\n\n adj[v].append(u)\n\n tot[u]+=1\n\n tot[v]+=1\n\n d[(u,v)]=j\n\n d[(v,u)]=j\n\ntot=tot[1:]\n\ntot.sort()\n\n\n\nl=1\n\nr=n-1\n\nwhile(lk:\n\n l=m+1\n\n else:\n\n r=m\n\n\n\ncnt=[0 for i in range(n+1)]\n\nedge=[-1 for i in range(n-1)]\n\ndfs(1,0,0)\n\nprint(l)\n\nprint(*edge)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","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":"import sys\n\ninput = sys.stdin.readline\n\nINF = float('inf')\n\n\n\nn = int(input())\n\na = list(map(int, input().split()))\n\ndp = [[INF] * (n + 2) for i in range(n + 1)]\n\ncur = [[-1] * (n + 2) for i in range(n + 1)]\n\n\n\nfor i in range(n):\n\n dp[i][i + 1] = 1\n\n cur[i][i + 1] = a[i]\n\n\n\n\n\nfor d in range(2, n + 1):\n\n for l in range(n):\n\n r = l + d\n\n if r > n + 1:\n\n break\n\n\n\n for mid in range(l + 1, r):\n\n if cur[l][mid] == cur[mid][r] and cur[l][mid]!= -1:\n\n dp[l][r] = dp[l][mid]\n\n cur[l][r] = cur[l][mid] + 1\n\n else:\n\n dp[l][r] = min(dp[l][r], dp[l][mid] + dp[mid][r])\n\n\n\nprint(dp[0][n])\n\n","language":"py"} -{"contest_id":"1288","problem_id":"A","statement":"A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in \u2308dx+1\u2309\u2308dx+1\u2309 days (\u2308a\u2309\u2308a\u2309 is the ceiling function: \u23082.4\u2309=3\u23082.4\u2309=3, \u23082\u2309=2\u23082\u2309=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+\u2308dx+1\u2309x+\u2308dx+1\u2309.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1\u2264T\u2264501\u2264T\u226450) \u2014 the number of test cases.The next TT lines contain test cases \u2013 one per line. Each line contains two integers nn and dd (1\u2264n\u22641091\u2264n\u2264109, 1\u2264d\u22641091\u2264d\u2264109) \u2014 the number of days before the deadline and the number of days the program runs.OutputPrint TT answers \u2014 one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3\n1 1\n4 5\n5 11\nOutputCopyYES\nYES\nNO\nNoteIn the first test case; Adilbek decides not to optimize the program at all; since d\u2264nd\u2264n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run \u230852\u2309=3\u230852\u2309=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work \u2308112+1\u2309=4\u2308112+1\u2309=4 days.","tags":["binary search","brute force","math","ternary search"],"code":"for _ in range(int(input())):\n\n n, d = map(int, input().split())\n\n if (n + 1)**2 - (4*d) >= 0:\n\n print('YES')\n\n else:\n\n print('NO')\n\n\n\n\n\n\n\n","language":"py"} -{"contest_id":"1299","problem_id":"A","statement":"A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)\u2212yf(x,y)=(x|y)\u2212y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)\u22126=15\u22126=9f(11,6)=(11|6)\u22126=15\u22126=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,\u2026,an][a1,a2,\u2026,an] is defined as f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an)f(f(\u2026f(f(a1,a2),a3),\u2026an\u22121),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1\u2264n\u22641051\u2264n\u2264105).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u22641090\u2264ai\u2264109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4\n4 0 11 6\nOutputCopy11 6 4 0InputCopy1\n13\nOutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.","tags":["brute force","greedy","math"],"code":"n = int(input())\n\nx = [int(x) for x in input().strip().split()]\n\n\n\nif n == 1:\n\n print(x[0])\n\n exit(0)\n\n\n\npref_and = [0] * n\n\nsuff_and = [0] * n\n\n\n\nfor i in range(0, n):\n\n pref_and[i] = -x[i] - 1\n\n suff_and[i] = -x[i] - 1\n\n\n\nfor i in range(1, len(x)):\n\n pref_and[i] = pref_and[i] & pref_and[i - 1]\n\n suff_and[len(x) - i - 1] = suff_and[len(x) - i - 1] & suff_and[len(x) - i]\n\n\n\nmaxim, best = suff_and[1] & x[0], 0\n\nif pref_and[n - 2] & x[n - 1] > maxim:\n\n maxim = pref_and[n - 2] & x[n - 1]\n\n best = n - 1\n\n\n\nfor i in range(1, len(x) - 1):\n\n if pref_and[i - 1] & suff_and[i + 1] & x[i] > maxim:\n\n maxim = pref_and[i - 1] & suff_and[i + 1] & x[i]\n\n best = i\n\n\n\nx[0], x[best] = x[best], x[0]\n\nans = \" \".join(str(i) for i in x)\n\n\n\nprint(ans)","language":"py"} -{"contest_id":"1324","problem_id":"D","statement":"D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (ibi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"n = int(input())\nA = list(map(int,input().split()))\n\nB = list(map(int,input().split()))\n\nA2 = [0]*n \n\nfor i in range(n):\n A2[i] = A[i] - B[i]\nA2.sort()\n\nans = 0 \nl,r= 0,n-1 \n\nwhile l 1:\n\n if steps % 2 == 0:\n\n count += 1\n\n steps \/\/= 2\n\n elif steps % 3 == 0:\n\n count += 1\n\n steps \/\/= 3\n\n else:\n\n print(-1)\n\n break\n\n else:\n\n print(count)\n\nelse:\n\n print(-1)\n\n\n\n","language":"py"} -{"contest_id":"1291","problem_id":"A","statement":"A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive\/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n\u22121n\u22121.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 \u2192\u2192 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u226430001\u2264n\u22643000) \u00a0\u2014 the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print \"-1\" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4\n4\n1227\n1\n0\n6\n177013\n24\n222373204424185217171912\nOutputCopy1227\n-1\n17703\n2237344218521717191\nNoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 \u2192\u2192 22237320442418521717191 (delete the last digit).","tags":["greedy","math","strings"],"code":"n = int(input())\n\nwhile n:\n\n n-=1\n\n l = int(input())\n\n num = int(input())\n\n new = 0\n\n while num>0:\n\n last = num%10\n\n if last%2!=0:\n\n new*=10\n\n new+=last\n\n num = num\/\/10\n\n # print(num)\n\n new = str(new)\n\n new = new[::-1]\n\n if len(new)==1:\n\n print(-1)\n\n elif len(new)%2==0:\n\n print(new)\n\n else:\n\n print(new[:-1])","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":"for _ in range(int(input())):\n\n [a,b]=list(map(int,input().split(\" \")))\n\n k=(a-b)\/\/(b+1) \n\n extra=(a-b)%(b+1)\n\n print((a*(a+1)-(a-b+extra)*(k+1))\/\/2)","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":"\n\nfrom collections import defaultdict\n\n\n\n\n\ndef isLayoutPossible(password: str) -> None:\n\n \n\n leaf_letters = 0\n\n \n\n adjacents = defaultdict(set)\n\n for index, letter in enumerate(password):\n\n if len(adjacents[letter]) == 1:\n\n leaf_letters -=1\n\n \n\n # adding neighbors of current letter \n\n if index > 0 and password[index-1] != letter:\n\n adjacents[letter].add(password[index-1])\n\n if index < len(password)-1 and password[index+1] != letter:\n\n adjacents[letter].add(password[index+1])\n\n \n\n if len(adjacents[letter]) > 2:\n\n print('NO')\n\n return\n\n \n\n if len(adjacents[letter]) == 1:\n\n leaf_letters +=1\n\n \n\n if leaf_letters != 2 and len(password) > 2:\n\n print('NO')\n\n return\n\n \n\n print('YES')\n\n keyboard_layout = []\n\n start_letter = None\n\n \n\n for letter, neighbors in adjacents.items():\n\n if len(neighbors) == 1:\n\n start_letter = letter\n\n break\n\n \n\n stack = []\n\n if start_letter: stack.append(start_letter)\n\n used = set()\n\n\n\n while stack:\n\n curr_letter = stack.pop()\n\n keyboard_layout.append(curr_letter)\n\n used.add(curr_letter)\n\n \n\n for adjacent_letter in adjacents[curr_letter]:\n\n if adjacent_letter in used: continue\n\n \n\n stack.append(adjacent_letter)\n\n \n\n alphabets = 26\n\n for i in range(alphabets):\n\n char = chr(i+97)\n\n if char in used: continue\n\n keyboard_layout.append(char)\n\n \n\n final_keyboard_layout = \"\".join(keyboard_layout)\n\n print(final_keyboard_layout)\n\n\n\n\n\ntest_cases = int(input())\n\nfor _ in range(test_cases):\n\n password = input()\n\n isLayoutPossible(password)","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":"def is_palindrome(nums):\n\n #if nums[ : : -1] == nums: return \"YES\"\n\n for i in range(1, len(nums) - 1):\n\n if nums[i - 1] in nums[i + 1 : ]: return \"YES\"\n\n \n\n return \"NO\"\n\n\n\nif __name__ == \"__main__\":\n\n \n\n for _ in range(int(input())):\n\n input()\n\n nums = [int(x) for x in input().split()]\n\n\n\n print (is_palindrome(nums))","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 (x= 3:\n\n flag = True\n\n break \n\n\n\n q = deque([char for char in degrees if degrees[char]<2])\n\n order = []\n\n visited = set()\n\n\n\n while q:\n\n char = q.popleft()\n\n if char in visited:\n\n continue \n\n order.append(char)\n\n visited.add(char)\n\n\n\n for adjChar in graph[char]:\n\n graph[adjChar].remove(char)\n\n degrees[adjChar]-=1\n\n\n\n if degrees[adjChar]<=1:\n\n q.appendleft(adjChar)\n\n\n\n if len(order)!=len(graph) or flag == True:\n\n print(\"NO\")\n\n else:\n\n for charOrd in range(ord('a'),ord('z')+1):\n\n char = chr(charOrd)\n\n if char not in graph:\n\n order.append(char)\n\n \n\n print(\"YES\")\n\n print(\"\".join(order))\n\n\n\n\n\n\n\n\n\n ","language":"py"} -{"contest_id":"1296","problem_id":"F","statement":"F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n\u22121n\u22121 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n\u22121n\u22121 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section \u2014 the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,\u2026,fn\u22121f1,f2,\u2026,fn\u22121, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2\u2264n\u226450002\u2264n\u22645000) \u2014 the number of railway stations in Berland.The next n\u22121n\u22121 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1\u2264xi,yi\u2264n,xi\u2260yi1\u2264xi,yi\u2264n,xi\u2260yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1\u2264m\u226450001\u2264m\u22645000) \u2014 the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1\u2264aj,bj\u2264n1\u2264aj,bj\u2264n; aj\u2260bjaj\u2260bj; 1\u2264gj\u22641061\u2264gj\u2264106) \u2014 the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n\u22121n\u22121 integers f1,f2,\u2026,fn\u22121f1,f2,\u2026,fn\u22121 (1\u2264fi\u22641061\u2264fi\u2264106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4\n1 2\n3 2\n3 4\n2\n1 2 5\n1 3 3\nOutputCopy5 3 5\nInputCopy6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 3\n3 4 1\n6 5 2\n1 2 5\nOutputCopy5 3 1 2 1 \nInputCopy6\n1 2\n1 6\n3 1\n1 5\n4 1\n4\n6 1 1\n3 4 3\n6 5 3\n1 2 4\nOutputCopy-1\n","tags":["constructive algorithms","dfs and similar","greedy","sortings","trees"],"code":"import sys\n\nclass RangeMinQuery:\n # O(nlog(n)) construction\/space, O(1) range minimum query\n def __init__(self, data):\n self._data = [list(data)]\n n = len(self._data[0])\n\n # self._data[i][j] stores the min of the segment [j, j + 2 ** i] where i is in [1,2,4,8,...,log(N)]\n w = 1\n while 2 * w <= n:\n prev = self._data[-1]\n self._data.append([min(prev[j], prev[j + w]) for j in range(n - 2 * w + 1)])\n w *= 2\n\n def query(self, begin, end):\n # Find min of [begin, end)\n # Take the min of the overlapping intervals [begin, begin + 2**depth) and [end - 2**depth, end)\n assert begin < end\n depth = (end - begin).bit_length() - 1\n return min(self._data[depth][begin], self._data[depth][end - (1 << depth)])\n\n\nclass LCA:\n def __init__(self, graph, root=1):\n # Euler tour representation recording every visit to each node in the DFS\n self.eulerTour = []\n # For each node record the index of their first visit in the euler tour\n self.preorder = [None] * len(graph)\n # Record last visit\n self.postorder = [None] * len(graph)\n # Depth of each node to the root\n self.depth = [None] * len(graph)\n # Parent of each node\n self.parent = [None] * len(graph)\n\n # DFS\n stack = [root]\n self.depth[root] = 0\n self.parent[root] = None\n while stack:\n node = stack.pop()\n # Record a visit in the euler tour\n self.eulerTour.append(node)\n if self.preorder[node] is None:\n # Record first visit\n self.preorder[node] = len(self.eulerTour) - 1\n\n for nbr in graph[node]:\n if self.preorder[nbr] is None:\n self.depth[nbr] = self.depth[node] + 1\n self.parent[nbr] = node\n stack.append(node)\n stack.append(nbr)\n # Record last visit (this can be overwritten)\n self.postorder[node] = len(self.eulerTour) - 1\n\n # self.rmq = RangeMinQuery(self.preorder[node] for node in self.eulerTour)\n\n if False:\n # Check invariants\n\n assert self.depth[1] == 0\n assert self.parent[1] == None\n for node in range(1, len(graph)):\n assert self.preorder[node] == self.eulerTour.index(node)\n assert self.postorder[node] == max(\n i for i, x in enumerate(self.eulerTour) if x == node\n )\n\n for i in range(len(self.rmq._data)):\n for j in range(i + 1, len(self.rmq._data) + 1):\n assert min(self.rmq._data[0][i:j]) == self.rmq.query(i, j)\n\n for u in range(1, N + 1):\n for v in range(1, N + 1):\n assert self.lca(u, v) == self.lca(v, u)\n lca = self.lca(u, v)\n assert self.isAncestor(lca, u)\n assert self.isAncestor(lca, v)\n path = self.path(u, v)\n assert len(path) == self.dist(u, v) + 1\n for x, y in zip(path, path[1:]):\n assert y in graph[x]\n assert len(set(path)) == len(path)\n\n def lca(self, u, v):\n a = self.preorder[u]\n b = self.preorder[v]\n if a > b:\n a, b = b, a\n return self.eulerTour[self.rmq.query(a, b + 1)]\n\n def dist(self, u, v):\n return self.depth[u] + self.depth[v] - 2 * self.depth[self.lca(u, v)]\n\n def isAncestor(self, ancestor, v):\n # Checks if `ancestor` is an ancestor of `v`\n return (\n self.preorder[ancestor] <= self.preorder[v]\n and self.postorder[v] <= self.postorder[ancestor]\n )\n\n def path(self, u, v):\n # Returns the path from u to v in the tree. This doesn't rely on rmq\n # Walk up from u until u becomes ancestor of v (the LCA)\n uPath = []\n while not self.isAncestor(u, v):\n uPath.append(u)\n u = self.parent[u]\n lca = u\n # Walk up from v until v is at the LCA too\n assert self.isAncestor(u, v)\n vPath = []\n while v != lca:\n vPath.append(v)\n v = self.parent[v]\n ret = uPath + [lca] + vPath[::-1]\n return ret\n\n\ndef solve(N, edges, passengers):\n graph = [[] for i in range(N + 1)]\n for e in edges:\n graph[e[0]].append(e[1])\n graph[e[1]].append(e[0])\n\n tree = LCA(graph)\n\n scores = [[1 for j in range(N + 1)] for i in range(N + 1)]\n for a, b, score in passengers:\n path = tree.path(a, b)\n assert path[0] == a and path[-1] == b\n for u, v in zip(path, path[1:]):\n scores[u][v] = max(scores[u][v], score)\n scores[v][u] = max(scores[v][u], score)\n\n for a, b, score in passengers:\n ans = float(\"inf\")\n path = tree.path(a, b)\n for u, v in zip(path, path[1:]):\n ans = min(ans, scores[u][v])\n if ans != score:\n return -1\n\n return \" \".join(str(scores[e[0]][e[1]]) for e in edges)\n\n\nif False:\n N = 5000\n edges = list(zip(range(N - 1), range(1, N)))\n assert len(edges) == N - 1\n passengers = [(0, p, N - p) for p in range(1, N)]\n solve(N, edges, passengers)\n exit(0)\n\nif __name__ == \"__main__\":\n input = sys.stdin.readline\n\n N = int(input())\n edges = [[int(x) for x in input().split()] for i in range(N - 1)]\n P = int(input())\n passengers = [[int(x) for x in input().split()] for i in range(P)]\n\n ans = solve(N, edges, passengers)\n print(ans)\n","language":"py"} -{"contest_id":"1303","problem_id":"A","statement":"A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1\u2264|s|\u22641001\u2264|s|\u2264100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3\n010011\n0\n1111000\nOutputCopy2\n0\n0\nNoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).","tags":["implementation","strings"],"code":"for _ in range(int(input())):\n\n line = input()\n\n s, f = -1, -1\n\n for i in range(len(line)):\n\n if line[i] == '1':\n\n if s < 0:\n\n s = i\n\n f = i\n\n print(line[s:f].count('0'))\n\n","language":"py"} -{"contest_id":"1295","problem_id":"C","statement":"C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1\u2264T\u22641001\u2264T\u2264100) \u2014 the number of test cases.The first line of each testcase contains one string ss (1\u2264|s|\u22641051\u2264|s|\u2264105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1\u2264|t|\u22641051\u2264|t|\u2264105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2\u22c51052\u22c5105.OutputFor each testcase, print one integer \u2014 the minimum number of operations to turn string zz into string tt. If it's impossible print \u22121\u22121.ExampleInputCopy3\naabce\nace\nabacaba\naax\nty\nyyt\nOutputCopy1\n-1\n3\n","tags":["dp","greedy","strings"],"code":"#z=int(input()) \n\nimport math\n\nfrom itertools import combinations\n\nimport time\n\nimport random\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 bitwise_or(a,b):\n\n stringul_1=transformare_baza(a,2)\n\n stringul_2=transformare_baza(b,2)\n\n \n\n lungime=max(len(stringul_1), len(stringul_2))\n\n raspunsul=0\n\n #print(stringul_1,stringul_2)\n\n \n\n str_answ=[0]*lungime\n\n# print('lungime=', lungime)\n\n \n\n #print(str_answ)\n\n \n\n for i in range(0,lungime):\n\n # print(i,str_answ)\n\n j=lungime-1-i\n\n if len(stringul_1)>i and len(stringul_2)>i:\n\n if stringul_1[len(stringul_1)-1-i]!='0' or stringul_2[len(stringul_2)-1-i]!='0':\n\n raspunsul+=2**(i)\n\n str_answ[i]='1'\n\n elif len(stringul_1)>i and stringul_1[len(stringul_1)-1-i]=='1':\n\n raspunsul+=2**(i)\n\n str_answ[i]='1'\n\n elif len(stringul_2)>i and stringul_2[len(stringul_2)-1-i]=='1':\n\n raspunsul+=2**(i)\n\n str_answ[i]='1'\n\n \n\n #print(str_answ)\n\n \n\n return raspunsul\n\n \n\n \n\ndef bitwise_and(a,b):\n\n stringul_1=transformare_baza(a,2)\n\n stringul_2=transformare_baza(b,2)\n\n \n\n lungime=max(len(stringul_1), len(stringul_2))\n\n raspunsul=0\n\n #print(stringul_1,stringul_2)\n\n \n\n str_answ=[0]*lungime\n\n# print('lungime=', lungime)\n\n \n\n #print(str_answ)\n\n \n\n for i in range(0,lungime):\n\n # print(i,str_answ)\n\n j=lungime-1-i\n\n if len(stringul_1)>i and len(stringul_2)>i:\n\n if stringul_1[len(stringul_1)-1-i]=='1' and stringul_2[len(stringul_2)-1-i]=='1':\n\n raspunsul+=2**(i)\n\n str_answ[i]='1'\n\n else:\n\n str_answ[i]='0'\n\n \n\n #print(str_answ)\n\n \n\n return raspunsul\n\n \n\n \n\n \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\ndef comparatie(a,b):\n\n #print(\"1st\",a,b)\n\n if len(a)<=1:\n\n return a==b\n\n \n\n elif a[0:len(a)\/\/2]==b[0:len(b)\/\/2]:\n\n return comparatie (a[len(a)\/\/2:len(a)],b[len(b)\/\/2:len(b)])\n\n else:\n\n return False\n\n \n\n \n\ndef functie(vector,suma,pozitie,cate):\n\n \n\n answ=0\n\n #if pozitie==2:\n\n #print(suma,min(cate,pozitie+1))\n\n if pozitie>=0:\n\n if suma>=vector[pozitie]:\n\n if pozitie+1>=cate:\n\n suma-=vector[pozitie]\n\n answ+=cate\n\n answ+=functie(vector,suma,pozitie-cate,cate)\n\n \n\n \n\n else:\n\n suma-=vector[pozitie]\n\n answ+=1\n\n answ+=functie(vector,suma,pozitie-1,cate)\n\n \n\n \n\n return answ \n\n \n\n \n\n \n\n \n\ndef functie_string_baza(stringul,baza):\n\n answ=pr\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\n \n\n#z=int(input())\n\n \n\n \n\ntupla=[] \n\ndictionar={}\n\nz=int(input())\n\nfor contorr in range(z):\n\n \n\n #n=int(input())\n\n stringul=input()\n\n target=input()\n\n \n\n #maximul=10**9+1\n\n \n\n #n,m=list(map(int, input().split()))\n\n #bloc=list(map(int, input().split()))\n\n# vector=list(map(int, input().split()))\n\n \n\n \n\n #bloc=[]\n\n #vector=[]\n\n #n=200\n\n #m=200\n\n \n\n vector=[[] for x in range(27)]\n\n setul=set()\n\n \n\n n= len(stringul)\n\n \n\n for i in range(n):\n\n \n\n \n\n vector[(alfabet[stringul[i]])].append(i)\n\n \n\n setul.add(stringul[i])\n\n \n\n cate=0\n\n posibil=1\n\n pornire=0\n\n \n\n first=-1\n\n \n\n for dd in range(len(target)):\n\n \n\n #print(\"dd=\",dd,first)\n\n \n\n i=target[dd]\n\n if i not in setul:\n\n posibil=0\n\n break\n\n \n\n else:\n\n if first==-1:\n\n cate+=1\n\n first=vector[alfabet[i]][0]\n\n else:\n\n \n\n if vector[alfabet[i]][len(vector[alfabet[i]])-1]>first:\n\n #cb\n\n prima= 0\n\n ultima=len(vector[alfabet[i]])-1\n\n \n\n pp=1\n\n centru=prima\n\n while prima+1first and prima+1 2:\n\n core = i\n\n break\n\n if core < 0:\n\n for i in range(n-1): print(i)\n\n return\n\n p, q = 0, 3\n\n for i in range(n-1):\n\n if edge[i][0] == core or edge[i][1] == core:\n\n if p < 3:\n\n print(p)\n\n p += 1\n\n else:\n\n print(q)\n\n q += 1\n\n else:\n\n print(q)\n\n q += 1\n\n\n\nmain()","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":"# 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\nfrom collections import Counter\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 ans=0\n\n for i in range(m):\n\n b=Counter()\n\n for j in range(n):\n\n b[m*j+i+1]=j+1\n\n c=Counter()\n\n for j in range(n):\n\n z=b[a[j][i]]\n\n if z:\n\n c[(j-z+1)%n]+=1\n\n mi=n\n\n for j in c:\n\n mi=min(mi,j+n-c[j])\n\n ans+=mi\n\n print(ans)\n\n\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":"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":"caseNumber = int(input())\n\n\n\nwhile caseNumber != 0:\n\n arraySize = int(input())\n\n array = input().split(\" \")\n\n positionCount = 0\n\n middlePosition = int(arraySize\/2) - 1\n\n Pass = True\n\n if arraySize%2 == 0:\n\n if int(array[middlePosition]) < middlePosition + 1 and int(array[middlePosition + 1]) < middlePosition + 1:\n\n #print(\"proc failure\")\n\n Pass = False\n\n for digit in array:\n\n #print(\"assessing \" + digit)\n\n digit = int(digit)\n\n reversePositionCount = arraySize - 1 - positionCount\n\n if reversePositionCount < positionCount:\n\n relativePosition = reversePositionCount\n\n else:\n\n relativePosition = positionCount\n\n #print(\"relative position: \" + str(relativePosition))\n\n if digit < relativePosition:\n\n #print(\"proc failure\")\n\n Pass = False\n\n break\n\n positionCount = positionCount + 1\n\n if Pass == True:\n\n print(\"Yes\")\n\n else:\n\n print(\"No\")\n\n caseNumber = caseNumber - 1\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":"import math\n\n\n\nn = int(input())\n\narr = list(map(int, input().split()))\n\narr2 =list(map(int, input().split()))\n\n\n\ntotal1 = 0\n\ntotal2 = 0\n\narr_count = 0\n\n\n\ntotal1 = sum(arr)\n\ntotal2 = sum(arr2)\n\n\n\nif total2 == len(arr2):\n\n print(-1)\n\n exit()\n\n\n\nfor i in range(len(arr)):\n\n if arr[i] == 1 and arr[i] == arr2[i]:\n\n arr_count += 1\n\n\n\nif arr_count == total1:\n\n print(-1)\n\n exit()\n\n\n\ntotal1 -= arr_count\n\ntotal2 -= arr_count\n\n\n\nval = math.ceil((total2+1) \/ (total1))\n\n\n\nprint(val)\n\n\n\n\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":"# ------------------- fast io --------------------\n\nimport os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\n \n\nBUFSIZE = 8192\n\n \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 \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# ------------------- fast io --------------------\n\ndict1={}\n\nfor s in range(26):\n\n dict1[s]=0\n\nvals=[ord(k)-97 for k in input()]\n\nn=len(vals);store=[]\n\nfor s in range(n):\n\n dict1[vals[s]]+=1\n\n store.append(dict1.copy())\n\n#always doable when u have 3 distinct\n\nfor j in range(int(input())):\n\n l,r=map(int,input().split())\n\n l-=1;r-=1\n\n distinct=[]\n\n if l==0:\n\n dict2=store[r]\n\n else:\n\n dict2=store[r].copy()\n\n for s in range(26):\n\n dict2[s]-=store[l-1][s]\n\n for s in range(26):\n\n if dict2[s]>=1:\n\n distinct.append(dict2[s])\n\n if len(distinct)>=3:\n\n print(\"Yes\")\n\n else:\n\n if len(distinct)==2:\n\n if vals[l]==vals[r]:\n\n print(\"No\")\n\n else:\n\n print(\"Yes\")\n\n else:\n\n if l==r:\n\n print(\"Yes\")\n\n else:\n\n print(\"No\")","language":"py"} -{"contest_id":"1313","problem_id":"D","statement":"D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1\u2264n\u2264100000,1\u2264m\u2264109,1\u2264k\u226481\u2264n\u2264100000,1\u2264m\u2264109,1\u2264k\u22648)\u00a0\u2014 the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1\u2264Li\u2264Ri\u2264m1\u2264Li\u2264Ri\u2264m)\u00a0\u2014 the parameters of the ii spell.OutputPrint a single integer\u00a0\u2014 the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.","tags":["bitmasks","dp","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\nn, m, k = MII()\n\nevents = []\n\nfor i in range(1, n+1):\n\n l, r = GMI()\n\n events.append([l, i])\n\n events.append([r+1, -i])\n\nevents.sort()\n\nM = 1 << k\n\n\n\ncnt = [0] * M\n\ndp = [-inf] * M\n\ndp[0] = 0\n\nfor i in range(k):\n\n cnt[1 << i] = 1\n\nfor i in range(M):\n\n cnt[i] = cnt[i - (i & -i)] + cnt[i & -i]\n\n\n\nname = [0] * k\n\nfor i in range(2 * n):\n\n idx, event = events[i]\n\n length = events[i+1][0] - events[i][0] if i < 2 * n - 1 else 0\n\n if event > 0:\n\n for j in range(k):\n\n if name[j] == 0:\n\n name[j] = event\n\n pos = j\n\n break\n\n for j in range(M - 1, -1, -1):\n\n if (j >> pos) & 1: dp[j] = dp[j - (1 << pos)] + cnt[j] % 2 * length\n\n else: dp[j] += cnt[j] % 2 * length\n\n else:\n\n for j in range(M):\n\n if name[j] == -event:\n\n name[j] = 0\n\n pos = j\n\n break\n\n for j in range(M):\n\n if (j >> pos) & 1: dp[j] = -inf\n\n else: dp[j] = max(dp[j], dp[j + (1 << pos)]) + cnt[j] % 2 * length\n\nprint(dp[0])","language":"py"} -{"contest_id":"1294","problem_id":"F","statement":"F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3\u2264n\u22642\u22c51053\u2264n\u22642\u22c5105) \u2014 the number of vertices in the tree. Next n\u22121n\u22121 lines describe the edges of the tree in form ai,biai,bi (1\u2264ai1\u2264ai, bi\u2264nbi\u2264n, ai\u2260biai\u2260bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres \u2014 the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1\u2264a,b,c\u2264n1\u2264a,b,c\u2264n and a\u2260,b\u2260c,a\u2260ca\u2260,b\u2260c,a\u2260c.If there are several answers, you can print any.ExampleInputCopy8\n1 2\n2 3\n3 4\n4 5\n4 6\n3 7\n3 8\nOutputCopy5\n1 8 6\nNoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.","tags":["dfs and similar","dp","greedy","trees"],"code":"import 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\nfrom operator import itemgetter\n\n\n\nsys.setrecursionlimit(5 * 10 ** 4)\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\npi = 3.1415926535\n\nmod = 998244353\n\n\n\nfrom types import GeneratorType\n\n\n\n\n\ndef iterative(f, stack=[]):\n\n def wrapped_func(*args, **kwargs):\n\n if stack: return f(*args, **kwargs)\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 continue\n\n stack.pop()\n\n if not stack: break\n\n to = stack[-1].send(to)\n\n return to\n\n\n\n return wrapped_func\n\n\n\n@iterative\n\ndef dfs(x, y):\n\n for i in a[x]:\n\n if i != y:\n\n yield dfs(i, x)\n\n if len(a[x]) == 1:\n\n dp[x].append([0, x])\n\n dp[y].append([1, x])\n\n else:\n\n dp[x].sort(key=itemgetter(0), reverse=True)\n\n while len(dp[x]) > 3:\n\n dp[x].pop()\n\n dp[y].append([dp[x][0][0] + 1, dp[x][0][1]])\n\n yield\n\n\n\n\n\n@iterative\n\ndef dfs2(x, y):\n\n if len(dp[x]) == 3:\n\n ct = 0\n\n for i, j in dp[x]:\n\n ct += i\n\n ct += 1\n\n if ct > tot[0]:\n\n pt[0] = x\n\n tot[0] = ct\n\n ans.clear()\n\n for i, j in dp[x]:\n\n ans.append(j)\n\n elif len(dp[x]) == 2:\n\n ct = 0\n\n for i,j in dp[x]:\n\n ct+=i\n\n if j==x:\n\n ct=-1\n\n break\n\n if ct!=-1:\n\n ct+=1\n\n if ct > tot[0]:\n\n pt[0] = x\n\n tot[0] = ct\n\n ans.clear()\n\n for i, j in dp[x]:\n\n ans.append(j)\n\n ans.append(x)\n\n\n\n for i in a[x]:\n\n if i != y:\n\n for j1, j2 in dp[x]:\n\n if [j1 - 1, j2] not in dp[i]:\n\n dp[i].append([j1 + 1, j2])\n\n break\n\n dp[i].sort(key=itemgetter(0), reverse=True)\n\n while len(dp[i]) > 3:\n\n dp[i].pop()\n\n yield dfs2(i, x)\n\n yield\n\n\n\nn = int(input())\n\na = [[] for _ in range(n + 1)]\n\nfor _ in range(n - 1):\n\n x, y = map(int, input().split())\n\n a[x].append(y)\n\n a[y].append(x)\n\ndp = [[] for _ in range(n + 1)]\n\ndfs(1, 0)\n\ntot = [0]\n\nans = []\n\npt = [-1]\n\ndfs2(1, 0)\n\nprint(tot[0] - 1)\n\nprint(*ans)\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":"d4i=[0,-1,0,1]\n\nd4j=[-1,0,1,0]\n\ndirection=['L','U','R','D']\n\nback=['R','D','L','U']\n\n \n\ndef main():\n\n \n\n # Observations:\n\n # if ri,cj==xi,yj, i,j is x\n\n # if ri,cj==-1,-1, i,j is cycle:\n\n # Steps:\n\n # Mark cycles and Xs\n\n # DFS from all X only to nodes pointing to x\n\n # Fill cycles by pointing to an adjacent cycle square\n\n # Check that all cells are marked\n\n \n\n n=int(input())\n\n finalState=[[] for _ in range(n)] #[xi,yj]\n\n ans=[[None for _ in range(n+1)] for __ in range(n+1)]\n\n \n\n for i in range(n):\n\n temp=readIntArr()\n\n temp.append(-11) #adding extra col to avoid checking for out of grid\n\n temp.append(-11)\n\n for j in range(n+1):\n\n finalState[i].append([temp[2*j]-1,temp[2*j+1]-1]) #0-indexing\n\n finalState.append([None]*(n+1)) #adding extra row to avoid checking for out of grid\n\n \n\n endPoints=[]\n\n cyclePoints=set()\n\n for i in range(n):\n\n for j in range(n):\n\n x,y=finalState[i][j]\n\n if x==i and y==j:\n\n ans[i][j]='X'\n\n endPoints.append([x,y])\n\n elif x==-2: #due to 0-indexing\n\n ans[i][j]='c' #cycle\n\n cyclePoints.add((i,j))\n\n \n\n # multiLineArrayOfArraysPrint(finalState)\n\n # multiLineArrayOfArraysPrint(ans)\n\n \n\n for endX,endY in endPoints:\n\n stack=[[endX,endY]]\n\n while stack:\n\n i,j=stack.pop()\n\n for z in range(4):\n\n ii=i+d4i[z]\n\n jj=j+d4j[z]\n\n if ans[ii][jj]==None and finalState[ii][jj]==[endX,endY]:\n\n ans[ii][jj]=back[z]\n\n stack.append([ii,jj])\n\n \n\n \n\n \n\n # Fill Cycles (point each cycle point to another cycle point)\n\n for ci,cj in cyclePoints:\n\n for z in range(4):\n\n ii=ci+d4i[z]\n\n jj=cj+d4j[z]\n\n if (ii,jj) in cyclePoints:\n\n ans[ci][cj]=direction[z]\n\n break\n\n \n\n ok=True\n\n outcomes={'U','D','R','L','X'}\n\n for i in range(n):\n\n for j in range(n):\n\n if ans[i][j] not in outcomes:\n\n ok=False\n\n if ok:\n\n print('VALID')\n\n ans.pop()#remove extra row\n\n for i in range(n):\n\n ans[i].pop() #remove extra col\n\n multiLineArrayOfArraysPrint(ans)\n\n else:\n\n print('INVALID')\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 \n\ninf=float('inf')\n\nMOD=10**9+7\n\n \n\nfor _ in range(1):\n\n main()","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, 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\nT = II()\nfor ind in range(T):\n n,m = list(map(int, input().split()))\n c = LI()\n ns = [[] for _ in range(n)]\n for _ in range(m):\n u,v = LI()\n u -= 1\n v -= 1\n ns[v].append(u)\n d = {}\n for i in range(n):\n t = tuple(sorted(ns[i]))\n d.setdefault(t, []).append(i)\n ans = 0\n from math import gcd\n for k,v in d.items():\n if not k:\n continue\n val = sum((c[i] for i in v))\n ans = gcd(ans, val)\n print(ans)\n if ind==T-1:\n break\n LI()","language":"py"} -{"contest_id":"1324","problem_id":"A","statement":"A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2\u00d712\u00d71 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2\u00d712\u00d71 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai\u22121ai\u22121. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.ExampleInputCopy4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\nOutputCopyYES\nNO\nYES\nYES\nNoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.","tags":["implementation","number theory"],"code":"n = int(input())\n\n\n\nfor i in range (0,n):\n\n check = 0\n\n a = int(input())\n\n lst = list(map(int, input().split()))\n\n d = max(lst)\n\n for i in lst:\n\n if (d - i)%2 != 0:\n\n check +=1\n\n break\n\n if check != 0:\n\n print(\"NO\")\n\n else:\n\n print(\"YES\")\n\n","language":"py"} -{"contest_id":"1324","problem_id":"A","statement":"A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2\u00d712\u00d71 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2\u00d712\u00d71 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai\u22121ai\u22121. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1\u2264n\u22641001\u2264n\u2264100) \u2014 the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641001\u2264ai\u2264100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer \u2014 \"YES\" (without quotes) if you can clear the whole Tetris field and \"NO\" otherwise.ExampleInputCopy4\n3\n1 1 3\n4\n1 1 2 1\n2\n11 11\n1\n100\nOutputCopyYES\nNO\nYES\nYES\nNoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.","tags":["implementation","number theory"],"code":"q = int(input())\n\nwhile q:\n\n w = int(input())\n\n a = list(map(int, input().split()))\n\n t = a[0]%2\n\n for o in a:\n\n if(o%2!=t):\n\n t=2\n\n break\n\n if(t==2):\n\n print(\"NO\")\n\n else:\n\n print(\"YES\")\n\n q-=1 ","language":"py"} -{"contest_id":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!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. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"def solve():\n\n # process t test-cases\n\n for _ in range(int(input())):\n\n # Read input list a and b\n\n n = int(input())\n\n a = list(map(int, input().split()))\n\n b = list(map(int, input().split()))\n\n \n\n # sort the lists\n\n a = sorted(a)\n\n b = sorted(b)\n\n\n\n # print the result\n\n print(*a)\n\n print(*b)\n\n\n\nsolve()","language":"py"} -{"contest_id":"1141","problem_id":"G","statement":"G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n\u22121n\u22121 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right \u2014 the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2\u2264n\u2264200000,0\u2264k\u2264n\u221212\u2264n\u2264200000,0\u2264k\u2264n\u22121) \u2014 the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n\u22121n\u22121 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1\u2264xi,yi\u2264n1\u2264xi,yi\u2264n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1\u2264r\u2264n\u221211\u2264r\u2264n\u22121). In the second line print n\u22121n\u22121 numbers c1,c2,\u2026,cn\u22121c1,c2,\u2026,cn\u22121 (1\u2264ci\u2264r1\u2264ci\u2264r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2\n1 4\n4 3\n3 5\n3 6\n5 2\nOutputCopy2\n1 2 1 1 2 InputCopy4 2\n3 1\n1 4\n1 2\nOutputCopy1\n1 1 1 InputCopy10 2\n10 3\n1 2\n1 3\n1 4\n2 5\n2 6\n2 7\n3 8\n3 9\nOutputCopy3\n1 1 2 3 2 3 1 3 1 ","tags":["binary search","constructive algorithms","dfs and similar","graphs","greedy","trees"],"code":"import sys\n\nimport io, os\n\ninput = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline\n\n\n\ndef main():\n\n n,k = map(int,input().split())\n\n edge = [[] for i in range(n)]\n\n ind = [0]*n\n\n toid = {}\n\n for i in range(n-1):\n\n x,y =map(int, input().split())\n\n x,y = x-1, y-1\n\n edge[x].append(y)\n\n edge[y].append(x)\n\n ind[x] += 1\n\n ind[y] += 1\n\n toid[(x, y)] = i\n\n toid[(y, x)] = i\n\n\n\n ind.sort()\n\n import bisect\n\n ng = 0\n\n ok = n-1\n\n while ng+1 < ok:\n\n c = (ng+ok)\/\/2\n\n if n-bisect.bisect_left(ind, c+1) <= k:\n\n ok = c\n\n else:\n\n ng = c\n\n\n\n s = []\n\n s.append(0)\n\n par = [-1]*n\n\n order = []\n\n while s:\n\n v = s.pop()\n\n order.append(v)\n\n for u in edge[v]:\n\n if par[v] == u:\n\n continue\n\n s.append(u)\n\n par[u] = v\n\n\n\n ans = [-1]*(n-1)\n\n color = list(range(ok))\n\n for v in order:\n\n p = par[v]\n\n if par[v] != -1:\n\n color[ans[toid[(p, v)]]], color[-1] = color[-1], color[ans[toid[(p, v)]]]\n\n cnt = 0\n\n for u in edge[v]:\n\n if u == p:\n\n continue\n\n ans[toid[(v, u)]] = color[cnt%ok]\n\n cnt += 1\n\n color[ans[toid[(p, v)]]], color[-1] = color[-1], color[ans[toid[(p, v)]]]\n\n else:\n\n cnt = 0\n\n for u in edge[v]:\n\n ans[toid[(v, u)]] = color[cnt%ok]\n\n cnt += 1\n\n print(ok)\n\n ans = [i+1 for i in ans]\n\n print(*ans)\n\n\n\nif __name__ == '__main__':\n\n main()\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\nn,m=map(int,input().split())\nprint(comb(n+2*m-1,2*m)%(10**9+7))","language":"py"} -{"contest_id":"1315","problem_id":"C","statement":"C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,\u2026,bnb1,b2,\u2026,bn. Find the lexicographically minimal permutation a1,a2,\u2026,a2na1,a2,\u2026,a2n such that bi=min(a2i\u22121,a2i)bi=min(a2i\u22121,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641001\u2264t\u2264100).The first line of each test case consists of one integer nn\u00a0\u2014 the number of elements in the sequence bb (1\u2264n\u22641001\u2264n\u2264100).The second line of each test case consists of nn different integers b1,\u2026,bnb1,\u2026,bn\u00a0\u2014 elements of the sequence bb (1\u2264bi\u22642n1\u2264bi\u22642n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number \u22121\u22121.Otherwise, print 2n2n integers a1,\u2026,a2na1,\u2026,a2n\u00a0\u2014 required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5\n1\n1\n2\n4 1\n3\n4 1 3\n4\n2 3 4 5\n5\n1 5 7 2 8\nOutputCopy1 2 \n-1\n4 5 1 2 3 6 \n-1\n1 3 5 6 7 9 2 4 8 10 \n","tags":["greedy"],"code":"for _ in range(int(input())):\n\n n = int(input())\n\n l = list(map(int,input().split()))\n\n lt = sorted(l)\n\n count = 0\n\n imp = False\n\n for k in range(2*n,0,-1):\n\n #print(lt[-1],k, \"max et k\")\n\n if lt[-1]cur: m =e; break\n\n rep.append(m)\n\n l2.pop(l2.index(m))\n\n print(*rep)","language":"py"} -{"contest_id":"1301","problem_id":"B","statement":"B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0\u2264k\u22641090\u2264k\u2264109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai\u2212ai+1||ai\u2212ai+1| for all 1\u2264i\u2264n\u221211\u2264i\u2264n\u22121) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u22641041\u2264t\u2264104) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2\u2264n\u22641052\u2264n\u2264105)\u00a0\u2014 the size of the array aa.The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (\u22121\u2264ai\u2264109\u22121\u2264ai\u2264109). If ai=\u22121ai=\u22121, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4\u22c51054\u22c5105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0\u2264k\u22641090\u2264k\u2264109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7\n5\n-1 10 -1 12 -1\n5\n-1 40 35 -1 35\n6\n-1 -1 9 -1 3 -1\n2\n-1 -1\n2\n0 -1\n4\n1 -1 3 -1\n7\n1 -1 7 5 2 -1 5\nOutputCopy1 11\n5 35\n3 6\n0 42\n0 0\n1 2\n3 4\nNoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be \u22640\u22640. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1\u2212a2|=|6\u22126|=0|a1\u2212a2|=|6\u22126|=0; |a2\u2212a3|=|6\u22129|=3|a2\u2212a3|=|6\u22129|=3; |a3\u2212a4|=|9\u22126|=3|a3\u2212a4|=|9\u22126|=3; |a4\u2212a5|=|6\u22123|=3|a4\u2212a5|=|6\u22123|=3; |a5\u2212a6|=|3\u22126|=3|a5\u2212a6|=|3\u22126|=3. So, the maximum difference between any adjacent elements is 33.","tags":["binary search","greedy","ternary search"],"code":"# chalo shuru karte hai!\n\nimport sys\n\nfrom math import *\n\nfrom itertools import *\n\nfrom heapq import heapify, heappop, heappush\n\nfrom bisect import bisect, bisect_left, bisect_right\n\nfrom collections import deque, Counter, defaultdict as dd\n\nmod = 10**9+7\n\n# Sangeeta Singh\n\n\n\n\n\ndef input(): return sys.stdin.readline().rstrip(\"\\r\\n\")\n\ndef ri(): return int(input())\n\ndef rl(): return list(map(int, input().split()))\n\ndef rls(): return list(map(str, input().split()))\n\ndef isPowerOfTwo(x): return (x and (not(x & (x - 1))))\n\ndef lcm(x, y): return (x*y)\/\/gcd(x, y)\n\ndef alpha(x): return ord(x)-ord('A')\n\n\n\n\n\ndef gcd(x, y):\n\n while y:\n\n x, y = y, x % y\n\n return x\n\n\n\n\n\ndef d2b(n):\n\n s = bin(n).replace(\"0b\", \"\")\n\n return (34-len(s))*'0'+s\n\n\n\n\n\ndef highestPowerof2(x):\n\n x |= x >> 1\n\n x |= x >> 2\n\n x |= x >> 4\n\n x |= x >> 8\n\n x |= x >> 16\n\n return x ^ (x >> 1)\n\n\n\n\n\ndef isPrime(x):\n\n if x == 1:\n\n return False\n\n if x == 2:\n\n return True\n\n for i in range(2, int(x ** 0.5) + 1):\n\n if x % i == 0:\n\n return False\n\n return True\n\n\n\n\n\ndef factors(n):\n\n i = 1\n\n ans = []\n\n while i <= sqrt(n):\n\n if (n % i == 0):\n\n if (n \/ i != i):\n\n ans.append(int(n\/i))\n\n if i != 1:\n\n ans.append(i)\n\n i += 1\n\n return ans\n\n\n\n\n\nPrimes = [1] * 100001\n\nprimeNos = []\n\n\n\n\n\ndef SieveOfEratosthenes(n):\n\n p = 2\n\n while (p * p <= n):\n\n if (Primes[p]):\n\n for i in range(p * p, n+1, p):\n\n Primes[i] = 0\n\n p += 1\n\n for p in range(2, n+1):\n\n if Primes[p]:\n\n primeNos.append(p)\n\n\n\n# SieveOfEratosthenes(100000)\n\n# P = len(primeNos)\n\n# print(\"P\", P)\n\n\n\n############ Main! #############\n\n\n\n\n\n# for _ in range(1):\n\nfor _ in range(ri()):\n\n n = ri()\n\n a = rl()\n\n if a.count(-1) == n:\n\n print(0, 0)\n\n continue\n\n mn = inf\n\n mx = 0\n\n max_dif = 0\n\n for i in range(1, n):\n\n # print(a[i-1], a[i])\n\n if a[i-1] == -1 and a[i] != -1:\n\n mn = min(mn, a[i])\n\n mx = max(mx, a[i])\n\n elif a[i-1] != -1 and a[i] == -1:\n\n mn = min(mn, a[i-1])\n\n mx = max(mx, a[i-1])\n\n # print(\"min:\", mn, \"max:\", mx)\n\n ans = (mx+mn)\/\/2\n\n for i in range(n):\n\n if a[i] == -1:\n\n a[i] = ans\n\n # print(a)\n\n for i in range(1, n):\n\n max_dif = max(max_dif, abs(a[i]-a[i-1]))\n\n print(max_dif, ans)\n\n","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 and a[i1] == a[i] + 1:\n\n l[i] = i1 = l[i1]\n\n if l[i] >= 0:\n\n r[l[i]] = i\n\n c += 1\n\n i2 = r[i]\n\n while i2 < n and a[i2] == a[i] + 1:\n\n r[i] = i2 = r[i2]\n\n if r[i] < n:\n\n l[r[i]] = i\n\n c += 1\n\n\n\n print(c)","language":"py"} -{"contest_id":"1324","problem_id":"D","statement":"D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (ibi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105) \u2014 the number of topics.The second line of the input contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u22641091\u2264bi\u2264109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer \u2014 the number of good pairs of topic.ExamplesInputCopy5\n4 8 2 6 2\n4 5 4 1 3\nOutputCopy7\nInputCopy4\n1 3 2 4\n1 3 2 4\nOutputCopy0\n","tags":["binary search","data structures","sortings","two pointers"],"code":"n=int(input())\n\na=list(map(int,input().split()))\n\nb=list(map(int,input().split()))\n\nfor i in range(n):\n\n a[i]-=b[i]\n\na.sort()\n\ncount=0\n\nlastindex=n\n\npos=0\n\nfor i in range(n):\n\n if a[i]>0:\n\n pos+=1\n\n count+=n-lastindex\n\n if lastindex==0:\n\n continue\n\n for j in range(lastindex-1,-1,-1):\n\n if a[i]+a[j]<=0:\n\n lastindex=j+1\n\n break\n\n if j==0 and a[i]+a[j]>0:\n\n lastindex=0\n\ncount+=n-lastindex\n\nprint((count-pos)\/\/2)","language":"py"} -{"contest_id":"1316","problem_id":"A","statement":"A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0\u2264ai\u2264m0\u2264ai\u2264m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22642001\u2264t\u2264200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1\u2264n\u22641031\u2264n\u2264103, 1\u2264m\u22641051\u2264m\u2264105) \u00a0\u2014 the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (0\u2264ai\u2264m0\u2264ai\u2264m) \u00a0\u2014 scores of the students.OutputFor each testcase, output one integer \u00a0\u2014 the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2\n4 10\n1 2 3 4\n4 5\n1 2 3 4\nOutputCopy10\n5\nNoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0\u2264ai\u226450\u2264ai\u22645. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0\u2264ai\u2264m0\u2264ai\u2264m.","tags":["implementation"],"code":"for _ in range(int(input())):\n n, m = map(int, input().split())\n a = list(map(int, input().split()))\n print(min(m, sum(a)))\n","language":"py"} -{"contest_id":"1325","problem_id":"A","statement":"A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1\u2264t\u2264100)(1\u2264t\u2264100) \u00a0\u2014 the number of testcases.Each testcase consists of one line containing a single integer, xx (2\u2264x\u2264109)(2\u2264x\u2264109).OutputFor each testcase, output a pair of positive integers aa and bb (1\u2264a,b\u2264109)1\u2264a,b\u2264109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2\n2\n14\nOutputCopy1 1\n6 4\nNoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.","tags":["constructive algorithms","greedy","number theory"],"code":"t = int(input())\n\n\n\nfor _ in range(t):\n\n n = int(input())\n\n print(1,n-1)\n\n","language":"py"} -{"contest_id":"1305","problem_id":"E","statement":"E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the \"Proof by AC\" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,\u2026,ana1,a2,\u2026,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1\u2264a1> 2\n\n else:\n\n return ((n - 2) * n) >> 2\n\n \n\nif m > limit(n):\n\n print(-1)\n\n sys.exit()\n\nelif not m:\n\n ans = [10 ** 8 + 1]\n\n while len(ans) < n:\n\n ans.append(ans[-1] + 10 ** 4)\n\n print(*ans)\n\n sys.exit()\n\n\n\nL = 3\n\nR = n + 1\n\nwhile L + 1 < R:\n\n k = (L + R) >> 1\n\n if limit(k) > m:\n\n R = k\n\n else:\n\n L = k\n\nk = L\n\nans = list(range(1, k + 1))\n\n\n\nreq = m - limit(k)\n\nif req > 0:\n\n ans.append(ans[-1] + ans[-2 * req])\n\n k += 1\n\nbig_num = 10 ** 8 + 1\n\nfor i in range(k, n):\n\n ans.append(big_num)\n\n big_num += 10 ** 4\n\n\n\nprint(*ans)\n\n","language":"py"} -{"contest_id":"1305","problem_id":"A","statement":"A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!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. The description of the test cases follows.The first line of each test case contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100) \u00a0\u2014 the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u226410001\u2264ai\u22641000) \u00a0\u2014 the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,\u2026,bnb1,b2,\u2026,bn (1\u2264bi\u226410001\u2264bi\u22641000) \u00a0\u2014 the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,\u2026,xnx1,x2,\u2026,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,\u2026,yny1,y2,\u2026,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,\u2026,xn+ynx1+y1,x2+y2,\u2026,xn+yn should all be distinct. The numbers x1,\u2026,xnx1,\u2026,xn should be equal to the numbers a1,\u2026,ana1,\u2026,an in some order, and the numbers y1,\u2026,yny1,\u2026,yn should be equal to the numbers b1,\u2026,bnb1,\u2026,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2\n3\n1 8 5\n8 4 5\n3\n1 7 5\n6 1 2\nOutputCopy1 8 5\n8 4 5\n5 1 7\n6 2 1\nNoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.","tags":["brute force","constructive algorithms","greedy","sortings"],"code":"# Prewritten code\n\nimport os\n\nimport sys\n\nfrom io import BytesIO, IOBase\n\n\n\nBUFSIZE = 8192\n\n\n\n\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\n\n\n\n\nclass IOWrapper(IOBase):\n\n 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\nimport math\n\n\n\n\n\n\n\n\n\n\n\ndef solve():\n\n n = int(input())\n\n lst1 = list(map(int,input().split()))\n\n lst2 = list(map(int,input().split()))\n\n z1,z2 = lst1.copy(),lst2.copy()\n\n z1.sort()\n\n z2.sort()\n\n ans = []\n\n bew = []\n\n for i in range(n):\n\n ans.append(z1[i])\n\n bew.append(z2[i])\n\n print(*ans)\n\n print(*bew)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfor i in range(int(input())):\n\n solve()","language":"py"} -{"contest_id":"1307","problem_id":"C","statement":"C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1\u2264|s|\u22641051\u2264|s|\u2264105) \u2014 the text that Bessie intercepted.OutputOutput a single integer \u00a0\u2014 the number of occurrences of the secret message.ExamplesInputCopyaaabb\nOutputCopy6\nInputCopyusaco\nOutputCopy1\nInputCopylol\nOutputCopy2\nNoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.","tags":["brute force","dp","math","strings"],"code":"from collections import defaultdict\n\ns = input()\n\nd = defaultdict(int)\n\nfor c in s:\n\n\tfor a in range(97,123):\n\n\t\ta = chr(a)\n\n\t\td[a+c]+=d[a]\n\n\td[c]+=1\n\nprint(max(d.values()))","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 collections import deque, defaultdict, Counter, OrderedDict\n\nfrom math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians\n\nfrom heapq import heappush, heappop, heapify, nlargest, nsmallest\n\nimport os\n\nimport sys\n\n#sys.setrecursionlimit(10**6)\n\nfrom itertools import *\n\nfrom io import BytesIO, IOBase\n\nimport math\n\nimport bisect\n\nfrom math import inf\n\nimport random\n\ndef inp(): return sys.stdin.readline().rstrip(\"\\r\\n\") # for fast input\n\ndef out(var): sys.stdout.write(str(var)) # for fast output, always take string\n\ndef lis(): return list(map(int, inp().split()))\n\ndef stringlis(): return list(map(str, inp().split()))\n\ndef sep(): return map(int, inp().split())\n\ndef strsep(): return map(str, inp().split())\n\ndef fsep(): return map(float, inp().split())\n\ndef inpu(): return int(inp())\n\nM = 1000000007\n\n\n\ndef main():\n\n t=1\n\n #t=inpu()\n\n for _ in range(t):\n\n h,n = sep()\n\n arr = lis()\n\n c = 0\n\n flag = False\n\n ans = -1\n\n for i in range(n):\n\n c+=arr[i]\n\n if c+h<=0:\n\n ans = i+1\n\n flag = True\n\n break\n\n if flag:\n\n print(ans)\n\n continue\n\n if c>=0:\n\n print(-1)\n\n continue\n\n min1 = float(\"inf\")\n\n temp = 0\n\n for i in range(n):\n\n temp+=arr[i]\n\n min1 = min(min1,temp)\n\n ans = 0\n\n while(h>=0):\n\n if h>abs(min1):\n\n p = h-abs(min1)\n\n x = (p+abs(c)-1)\/\/abs(c)\n\n ans += x*n\n\n h+=(x*c)\n\n else:\n\n flag = False\n\n for i in range(n):\n\n ans+=1\n\n h+=arr[i]\n\n if h<=0:\n\n flag = True\n\n break\n\n if flag:\n\n print(ans)\n\n break\n\n else:\n\n print(-1)\n\n\n\n\n\nBUFSIZE = 8192\n\nclass FastIO(IOBase):\n\n newlines = 0\n\n def __init__(self, file):\n\n self._fd = file.fileno()\n\n self.buffer = BytesIO()\n\n self.writable = \"x\" in file.mode or \"r\" not in file.mode\n\n self.write = self.buffer.write if self.writable else None\n\n def read(self):\n\n while True:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n if not b:\n\n break\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines = 0\n\n return self.buffer.read()\n\n def readline(self):\n\n while self.newlines == 0:\n\n b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n\n self.newlines = b.count(b\"\\n\") + (not b)\n\n ptr = self.buffer.tell()\n\n self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n\n self.newlines -= 1\n\n return self.buffer.readline()\n\n def flush(self):\n\n if self.writable:\n\n os.write(self._fd, self.buffer.getvalue())\n\n self.buffer.truncate(0), self.buffer.seek(0)\n\nclass IOWrapper(IOBase):\n\n def __init__(self, file):\n\n self.buffer = FastIO(file)\n\n self.flush = self.buffer.flush\n\n self.writable = self.buffer.writable\n\n self.write = lambda s: self.buffer.write(s.encode(\"ascii\"))\n\n self.read = lambda: self.buffer.read().decode(\"ascii\")\n\n self.readline = lambda: self.buffer.readline().decode(\"ascii\")\n\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\n\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n# endregion\n\nif __name__ == '__main__':\n\n main()\n\n","language":"py"} -{"contest_id":"1286","problem_id":"A","statement":"A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the number of light bulbs on the garland.The second line contains nn integers p1,\u00a0p2,\u00a0\u2026,\u00a0pnp1,\u00a0p2,\u00a0\u2026,\u00a0pn (0\u2264pi\u2264n0\u2264pi\u2264n)\u00a0\u2014 the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number\u00a0\u2014 the minimum complexity of the garland.ExamplesInputCopy5\n0 5 0 2 3\nOutputCopy2\nInputCopy7\n1 0 0 5 0 0 2\nOutputCopy1\nNoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2. ","tags":["dp","greedy","sortings"],"code":"import os,sys, threading\nfrom random import randint, shuffle\nfrom io import BytesIO, IOBase\n\nfrom collections import defaultdict,deque,Counter\nfrom bisect import bisect_left,bisect_right\nfrom heapq import heappush,heappop, heapify\nfrom functools import lru_cache, reduce\nfrom itertools import accumulate, permutations\nimport math, copy\n\n\n# sys.setrecursionlimit(2**20)\n# threading.stack_size(2**20)\n# sys.setrecursionlimit(0x0FFFFFFF)\n# threading.stack_size(0x04000000)\n\n# resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])\n\n\n# Fast IO Region\nBUFSIZE = 8192\nclass FastIO(IOBase):\n newlines = 0\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 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 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 def flush(self):\n if self.writable:\n os.write(self._fd, self.buffer.getvalue())\n self.buffer.truncate(0), self.buffer.seek(0)\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\")\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\n\n# MOD = 998244353 \nfrom math import * \n\n\ndef main():\n def solve():\n n = int(input())\n arr = list(map(int, input().split()))\n @lru_cache(None)\n def dfs(i,j,k):\n if j < 0 or i+j > n:\n return float('inf')\n if i == n:\n return 0 \n res = min(dfs(i+1,j-(k%2 == 0),k), dfs(i+1,j-(k%2 == 0),k^1)+1)\n if arr[i] > 0:\n return float('inf') if k%2 != arr[i]%2 else res \n return res \n\n \n return min(dfs(0,n\/\/2,0), dfs(0,n\/\/2,1))\n\n \n\n\n # sys.stdin = open('contests\/input', 'r')\n # print(input().split(' '))\n # t = int(input())\n t = 1\n for i in range(t):\n # n, k = list(map(int, input().split())) \n # solve()\n print(solve())\n # if solve():\n # print(\"YES\") \n # else:\n # print(\"NO\")\n # print(solve())\n # n = int(input())\n # arr = list(map(int, input().split())) \n # if solve(n, m, k):\n # print(\"YES\")\n # else:\n # print(\"NO\")\n\n\n # debug(ans)\n\n\nif __name__ == \"__main__\":\n main()\n # threading.Thread(target=main).start()\n\n\n","language":"py"} -{"contest_id":"1313","problem_id":"B","statement":"B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round\u00a0\u2014 yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1\u2264t\u22641001\u2264t\u2264100)\u00a0\u2014 the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1\u2264n\u22641091\u2264n\u2264109, 1\u2264x,y\u2264n1\u2264x,y\u2264n)\u00a0\u2014 the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers\u00a0\u2014 the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second\u00a0\u2014 third place.","tags":["constructive algorithms","greedy","implementation","math"],"code":"for i in range(int(input())):\n\n\tn,a,b=map(int,input().split())\n\n\tif((a+b)<(n+1)):\n\n\t\tprint(1,end=\" \")\n\n\telse:\n\n\t\tprint(min((a+b)-n+1,n),end=\" \")\n\n\tprint(min(a+b-1,n))","language":"py"} -{"contest_id":"1300","problem_id":"A","statement":"A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,\u2026,ana1,a2,\u2026,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1\u2264i\u2264n1\u2264i\u2264n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ \u2026\u2026 +an\u22600+an\u22600 and a1\u22c5a2\u22c5a1\u22c5a2\u22c5 \u2026\u2026 \u22c5an\u22600\u22c5an\u22600.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1\u2264t\u22641031\u2264t\u2264103). The description of the test cases follows.The first line of each test case contains an integer nn (1\u2264n\u22641001\u2264n\u2264100)\u00a0\u2014 the size of the array.The second line of each test case contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (\u2212100\u2264ai\u2264100\u2212100\u2264ai\u2264100)\u00a0\u2014 elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1\nOutputCopy1\n2\n0\n2\nNoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,\u22121,\u22121][3,\u22121,\u22121], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [\u22121,1,1,1][\u22121,1,1,1], the sum will be equal to 22 and the product will be equal to \u22121\u22121. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,\u22122,1][2,\u22122,1], the sum will be 11 and the product will be \u22124\u22124.","tags":["implementation","math"],"code":"def get(f): return f(input().strip())\ndef gets(f): return [*map(f, input().split())]\n\n\nfor _ in range(get(int)):\n n = get(int)\n s = 0\n z = 0\n for a in gets(int):\n s += (not a) + a\n z += not a\n print((not s) + z)\n","language":"py"} -{"contest_id":"1312","problem_id":"B","statement":"B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,\u2026,ana1,a2,\u2026,an. Array is good if for each pair of indexes i 0:\n\n e += 1\n\n print(r)","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: 101916896\nfrom fractions import Fraction\n\nn = int(input())\n\ns = 0\n\nfor i in range(2, n):\n\n t = n\n\n while t:\n\n s += t % i\n\n t \/\/= i\n\nif s % (n - 2):\n\n print(Fraction(s, n - 2))\n\nelse:\n\n print(f'{s \/\/ (n - 2)}\/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 arr[n]:\n\n return False, -1\n\n\n\n ind = None\n\n for i in range(1, 5001):\n\n if arr[i] <= m and m <= arr[i+1]:\n\n ind = i\n\n break\n\n \n\n ans = [i for i in range(1, ind+1)]\n\n \n\n if m > arr[ind]:\n\n ans.append(ans[-(m-arr[ind])*2]+ans[-1])\n\n \n\n cur = 100000\n\n step = ans[-1] + 1 \n\n while len(ans) < n:\n\n ans.append(cur)\n\n cur+=step\n\n \n\n return True, ans \n\n\n\narr = [0]\n\nfor i in range(1, 5003):\n\n arr.append(arr[-1] + (i-1) \/\/ 2)\n\n \n\nn, m = map(int, input().split()) \n\nflg, ans = solve(n, m)\n\n\n\nif flg==False:\n\n print(-1)\n\nelse:\n\n print(' '.join([str(x) for x in ans])) ","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\nfrom math import sqrt, gcd, factorial, ceil, floor, pi, inf\n\nfrom collections import deque, Counter, OrderedDict, defaultdict\n\nfrom heapq import heapify, heappush, heappop\n\n#sys.setrecursionlimit(10**5)\n\nfrom functools import lru_cache\n\n#@lru_cache(None)\n\n\n\n#======================================================#\n\ninput = lambda: sys.stdin.readline()\n\nI = lambda: int(input().strip())\n\nS = lambda: input().strip()\n\nM = lambda: map(int,input().strip().split())\n\nL = lambda: list(map(int,input().strip().split()))\n\n#======================================================#\n\n\n\n#======================================================#\n\ndef primelist():\n\n L = [False for i in range((10**10)+1)]\n\n primes = [False for i in range((10**10)+1)]\n\n for i in range(2,(10**10)+1):\n\n if not L[i]:\n\n primes[i]=True\n\n for j in range(i,(10**10)+1,i):\n\n L[j]=True\n\n return primes\n\ndef isPrime(n):\n\n p = primelist()\n\n return p[n]\n\n#======================================================#\n\ndef bst(arr,x):\n\n low,high = 0,len(arr)-1\n\n ans = -1\n\n while low<=high:\n\n mid = (low+high)\/\/2\n\n #if arr[mid]==x:\n\n # return mid\n\n if arr[mid]<=x:\n\n low = mid+1\n\n else:\n\n high = mid-1\n\n ans = mid\n\n return ans\n\n \n\n \n\ndef factors(x):\n\n l1 = []\n\n l2 = []\n\n for i in range(1,int(sqrt(x))+1):\n\n if x%i==0:\n\n if (i*i)==x:\n\n l1.append(i)\n\n else:\n\n l1.append(i)\n\n l2.append(x\/\/i)\n\n for i in range(len(l2)\/\/2):\n\n l2[i],l2[len(l2)-1-i]=l2[len(l2)-1-i],l2[i]\n\n return l1+l2\n\n#======================================================#\n\n\n\ndef power(n,x):\n\n if x==0:\n\n return 1\n\n k = (10**9)+7\n\n if n==1:\n\n return 1\n\n if x==1:\n\n return n\n\n ans = power(n,x\/\/2)\n\n if x%2==0:\n\n return (ans*ans)%k\n\n return (ans*ans*n)%k\n\n\n\n#======================================================#\n\n\n\n\n\nn = I()\n\nadj = [[] for i in range(n)]\n\na = [-1 for i in range(n-1)]\n\nfor _ in range(n-1):\n\n u,v = M()\n\n adj[u-1].append([v-1,_])\n\n adj[v-1].append([u-1,_])\n\nif n==2:\n\n print(0)\n\nelse:\n\n c = 0\n\n for i in range(n):\n\n if len(adj[i])==1:\n\n a[adj[i][0][1]]=c\n\n c+=1\n\n for i in range(n-1):\n\n if a[i]==-1:\n\n a[i]=c\n\n c+=1\n\n for i in a:\n\n print(i)\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":"1311","problem_id":"C","statement":"C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s=\"abca\" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1\u2264pixkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1\u2264n,m,p\u22642\u22c51051\u2264n,m,p\u22642\u22c5105)\u00a0\u2014 the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1\u2264ai\u22641061\u2264ai\u2264106, 1\u2264cai\u22641091\u2264cai\u2264109)\u00a0\u2014 the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1\u2264bj\u22641061\u2264bj\u2264106, 1\u2264cbj\u22641091\u2264cbj\u2264109)\u00a0\u2014 the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1\u2264xk,yk\u22641061\u2264xk,yk\u2264106, 1\u2264zk\u22641031\u2264zk\u2264103)\u00a0\u2014 defense, attack and the number of coins of the monster kk.OutputPrint a single integer\u00a0\u2014 the maximum profit of the grind.ExampleInputCopy2 3 3\n2 3\n4 7\n2 4\n3 2\n5 11\n1 2 4\n2 1 6\n3 4 6\nOutputCopy1\n","tags":["brute force","data structures","sortings"],"code":"import sys\n\ninput = sys.stdin.readline\n\n\n\nn,m,p=map(int,input().split())\n\nW=[tuple(map(int,input().split())) for i in range(n)]\n\nA=[tuple(map(int,input().split())) for i in range(m)]\n\nM=[tuple(map(int,input().split())) for i in range(p)]\n\n\n\nQ=[[] for i in range(10**6+1)]\n\nfor x,y,c in M:\n\n Q[x].append((c,y))\n\n\n\nfor x,c in W:\n\n Q[x-1].append((c,0))\n\n \n\nseg_el=1<<((10**6+1).bit_length())\n\nSEGMAX=[-1<<31]*seg_el\n\n\n\nfor x,y in A:\n\n SEGMAX[x-1]=max(SEGMAX[x-1],-y)\n\n\n\nfor i in range(seg_el-2,-1,-1):\n\n SEGMAX[i]=max(SEGMAX[i+1],SEGMAX[i])\n\n\n\nSEGMAX=[-1<<31]*(seg_el)+SEGMAX\n\n\n\nfor i in range(seg_el-1,0,-1):\n\n SEGMAX[i]=max(SEGMAX[i*2],SEGMAX[(i*2)+1])\n\n\n\nSEGADD=[0]*(2*seg_el)\n\n\n\ndef adds(l,r,x):\n\n L=l+seg_el\n\n R=r+seg_el\n\n\n\n while L>=1\n\n R>>=1\n\n\n\n L=(l+seg_el)>>1\n\n R=(r+seg_el-1)>>1\n\n\n\n while L!=R:\n\n if L>R:\n\n SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)])\n\n L>>=1\n\n else:\n\n SEGMAX[R]=max(SEGMAX[R*2]+SEGADD[R*2],SEGMAX[1+(R*2)]+SEGADD[1+(R*2)])\n\n R>>=1\n\n\n\n while L!=0:\n\n SEGMAX[L]=max(SEGMAX[L*2]+SEGADD[L*2],SEGMAX[1+(L*2)]+SEGADD[1+(L*2)])\n\n L>>=1\n\n\n\nANS=-1<<31\n\nfor i in range(10**6+1):\n\n for c,y in Q[i]:\n\n if y==0:\n\n ANS=max(ANS,SEGMAX[1]-c)\n\n else:\n\n adds(y,seg_el,c)\n\n\n\nprint(ANS)\n\n \n\n\n\n","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":"from collections import defaultdict\n\nfrom string import ascii_lowercase\n\ntest=int(input())\n\nfor _ in range(test):\n\n string=list(input())\n\n value=set(string)\n\n graph=defaultdict(set)\n\n inDegree=defaultdict(int)\n\n x=string[0]\n\n inDegree[x]=0\n\n for i in range(1,len(string)):\n\n if string[i] not in graph[x]:\n\n inDegree[x]+=1\n\n graph[x].add(string[i])\n\n if x not in graph[string[i]]:\n\n inDegree[string[i]]+=1\n\n graph[string[i]].add(x)\n\n x=string[i]\n\n level=[]\n\n visited=set()\n\n for i in inDegree:\n\n if inDegree[i]==1 or inDegree[i]==0:\n\n level.append(i)\n\n visited.add(i)\n\n break\n\n ans=[]\n\n\n\n while level:\n\n node=level.pop()\n\n ans.append(node)\n\n for val in graph[node]:\n\n if val not in visited:\n\n visited.add(val)\n\n inDegree[val]-=1\n\n if inDegree[val]==1 or inDegree[val]==0:\n\n level.append(val)\n\n\n\n if len(value)==len(ans):\n\n print(\"YES\")\n\n for c in ascii_lowercase:\n\n if c not in ans:\n\n ans.append(c)\n\n print(\"\".join(ans))\n\n else:\n\n print(\"NO\")\n\n ","language":"py"} -{"contest_id":"1296","problem_id":"C","statement":"C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x\u22121,y)(x\u22121,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y\u22121)(x,y\u22121). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of \"LURLLR\" are \"LU\", \"LR\", \"LURLLR\", \"URL\", but not \"RR\" and \"UL\".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' \u2014 the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2\u22c51052\u22c5105 (\u2211n\u22642\u22c5105\u2211n\u22642\u22c5105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n \u2014 endpoints of the substring you remove. The value r\u2212l+1r\u2212l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4\n4\nLRUD\n4\nLURD\n5\nRRUDU\n5\nLLDDR\nOutputCopy1 2\n1 4\n3 4\n-1\n","tags":["data structures","implementation"],"code":"test = int(input())\n\nfor t in range(test):\n\n\tn = int(input())\n\n\ts = input()\n\n\tm = {}\n\n\tx = 0\n\n\ty = 0\n\n\tc = False\n\n\tr = -1\n\n\tl = -1\n\n\tlnn = 1000000\n\n\tm[(x,y)] = 0\n\n\tfor i in range(n):\n\n\t\tif s[i] == \"R\":\n\n\t\t\tx += 1\n\n\t\tif s[i] == \"L\":\n\n\t\t\tx -= 1\n\n\t\tif s[i] == \"U\":\n\n\t\t\ty += 1\n\n\t\tif s[i] == \"D\":\n\n\t\t\ty -= 1\n\n\t\tif (x,y) in m:\n\n\t\t\tln = i - m[(x,y)]+1\n\n\t\t\tif ln < lnn:\n\n\t\t\t\tlnn = ln\n\n\t\t\t\tl = m[(x,y)]+1\n\n\t\t\t\tr = i + 1\n\n\t\t\tc = True\n\n\t\tm[(x,y)] = i + 1\n\n\tif not c:\n\n\t\tprint(-1)\n\n\telse:\n\n\t\tprint(l,r)\n\n\t\t\t","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":"import math\n\nimport sys\n\nimport queue\n\nimport itertools\n\nfrom heapq import heappop, heappush\n\nimport random\n\n\n\n\n\ndef solve():\n\n def n(s):\n\n return ord(s) - 97\n\n\n\n s = str(input())\n\n q = int(input())\n\n\n\n d = [[0 for i in range(len(s) + 1)] for j in range(26)]\n\n d[n(s[0])][1] = 1\n\n\n\n for i in range(1, len(s)):\n\n for j in range(26):\n\n d[j][i + 1] = d[j][i]\n\n d[n(s[i])][i + 1] += 1\n\n\n\n for _ in range(q):\n\n l, r = map(int, input().split())\n\n if r - l == 0 or s[l - 1] != s[r - 1]:\n\n print(\"Yes\")\n\n else:\n\n diff = 0\n\n for i in range(26):\n\n f = d[i][r] - d[i][l - 1]\n\n if f != 0:\n\n diff += 1\n\n\n\n if diff >= 3:\n\n print(\"Yes\")\n\n else:\n\n print(\"No\")\n\n\n\n\n\nif __name__ == '__main__':\n\n multi_test = 0\n\n\n\n if multi_test:\n\n t = int(sys.stdin.readline())\n\n for _ in range(t):\n\n solve()\n\n else:\n\n solve()\n\n","language":"py"} -{"contest_id":"1296","problem_id":"B","statement":"B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1\u2264x\u2264s1\u2264x\u2264s, buy food that costs exactly xx burles and obtain \u230ax10\u230b\u230ax10\u230b burles as a cashback (in other words, Mishka spends xx burles and obtains \u230ax10\u230b\u230ax10\u230b back). The operation \u230aab\u230b\u230aab\u230b means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1\u2264t\u22641041\u2264t\u2264104) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1\u2264s\u22641091\u2264s\u2264109) \u2014 the number of burles Mishka initially has.OutputFor each test case print the answer on it \u2014 the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6\n1\n10\n19\n9876\n12345\n1000000000\nOutputCopy1\n11\n21\n10973\n13716\n1111111111\n","tags":["math"],"code":"for t in range(0, int(input())):\n\n n = int(input())\n\n count = 0\n\n inc = 0\n\n while n > 9:\n\n inc = n\/\/10\n\n n = n%10 + inc\n\n count += (inc*10)\n\n count += n\n\n print(count)\n\n","language":"py"} -{"contest_id":"1287","problem_id":"B","statement":"B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game \"Set\" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature \u2014 color, number, shape, and shading \u2014 the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called \"Hyperset\". In her game, there are nn cards with kk features, each feature has three possible values: \"S\", \"E\", or \"T\". The original \"Set\" game can be viewed as \"Hyperset\" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1\u2264n\u226415001\u2264n\u22641500, 1\u2264k\u2264301\u2264k\u226430)\u00a0\u2014 number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters \"S\", \"E\", \"T\". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer\u00a0\u2014 the number of ways to choose three cards that form a set.ExamplesInputCopy3 3\nSET\nETS\nTSE\nOutputCopy1InputCopy3 4\nSETE\nETSE\nTSES\nOutputCopy0InputCopy5 4\nSETT\nTEST\nEEET\nESTE\nSTES\nOutputCopy2NoteIn the third example test; these two triples of cards are sets: \"SETT\"; \"TEST\"; \"EEET\" \"TEST\"; \"ESTE\", \"STES\" ","tags":["brute force","data structures","implementation"],"code":"# 08:58-\n\nimport sys\n\ninput = lambda: sys.stdin.readline().rstrip()\n\nfrom collections import defaultdict,Counter\n\n\n\nN,K = map(int, input().split())\n\nA = []\n\nfor _ in range(N):\n\n\tA.append(input())\n\n\n\nB = set(A)\n\n\n\n# EST\n\nans = 0\n\nfor i in range(N-1):\n\n\tfor j in range(i+1,N):\n\n\t\tkey = []\n\n\t\tfor k in range(K):\n\n\t\t\tif A[i][k]==A[j][k]:\n\n\t\t\t\tkey.append(A[i][k])\n\n\t\t\telse:\n\n\t\t\t\ttmp = [A[i][k],A[j][k]]\n\n\t\t\t\tif 'S' not in tmp:\n\n\t\t\t\t\tkey.append('S')\n\n\t\t\t\telif 'E' not in tmp:\n\n\t\t\t\t\tkey.append('E')\n\n\t\t\t\telse:\n\n\t\t\t\t\tkey.append('T')\n\n\t\tkey = ''.join(key)\n\n\t\tif key in B:\n\n\t\t\tans+=1\n\n\n\nprint(ans\/\/3)\n\n\n\n\n\n\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":"n,m=list(map(int,input().split()))\n\nq=m\/\/n\n\nw=0\n\nwhile(m%n==0 and q%2==0):\n\n w+=1\n\n q=q\/\/2\n\nwhile(m%n==0 and q%3==0):\n\n w+=1\n\n q=q\/\/3\n\nif(m%n==0 and q==1):\n\n print(w)\n\nelse:\n\n print(-1)","language":"py"}