{"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"} {"contest_id":"1285","problem_id":"F","statement":"F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1\u2264i\nusing namespace std;\nusing ll=long long;\nconst ll maxN=2e5+10;\n#define pb push_back\n#define int ll\n#define pli pair\n#define fi first\n#define se second\n#define task \"danang\"\n#define plii pair\nll ct[maxN];\nbool check(ll x)\n{\n ll s=x;\n for(int i=2;i*i<=x;i++)\n {\n ll cnt=0;\n while(x%i==0)\n {\n cnt++;\n x\/=i;\n }\n if(cnt>0) ct[s]++;\n if(cnt>1) return false;\n }\n if(x>1) ct[s]++;\n return true;\n}\nvector d[maxN];\nll cnt[maxN];\nvoid add(ll x)\n{\n for(auto zz:d[x])\n {\n cnt[zz]++;\n }\n}\nvoid del(ll x)\n{\n for(auto zz:d[x])\n {\n cnt[zz]--;\n }\n}\nll cal(ll x)\n{\n ll ans=0;\n for(auto zz:d[x])\n {\n if(ct[zz]%2==0) ans+=cnt[zz];\n else ans-=cnt[zz];\n }\n return ans;\n}\nll n,a[maxN];\nvector vec[maxN];\nbool c[maxN];\nvoid solve()\n{\n cin >> n;\n for(int i=1;i<=n;i++)\n {\n cin >> a[i];\n vec[a[i]].pb(i);\n }\n for(int i=1;i<=1e5;i++)\n {\n c[i]=check(i);\n }\n for(int i=1;i<=1e5;i++)\n {\n if(c[i])\n {\n for(int j=i;j<=1e5;j+=i)\n {\n d[j].pb(i);\n }\n }\n }\n vector x;\n deque dq;\n ll ans=0;\n for(int i=1;i<=1e5;i++)\n {\n x.clear();\n for(int j=i;j<=1e5;j+=i)\n {\n for(int k=0;k=0;j--)\n {\n if(cal(x[j])>=1)\n {\n ll cc=cal(x[j]);\n while(dq.size()>0)\n {\n if(__gcd(x[j],dq.back())==1)\n {\n cc--;\n if(cc==0) break;\n }\n del(dq.back());\n dq.pop_back();\n }\n ans=max(ans,i*x[j]*dq.back());\n }\n dq.pb(x[j]);\n add(x[j]);\n }\n for(int j=0;j\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include \n\n#include \n\n#include \n\n#include \n\n#include\n\nusing namespace std;\n\n\n\n#define ll long long\n\n#define forn(i,k,n) for(int i=k;i>t;\n\n while(t--){\n\n int n;cin>>n;int a[n];forn(i,0,n){cin>>a[i];}\n\n int k=0;\n\n int k1=0;\n\n \/\/ if(n==1){cout<<\"YES\"<\n\n#define int long long\n\n#define fi first\n\n#define se second\n\n#define all(x) (x).begin(), (x).end()\n\n\n\nusing namespace std;\n\n\n\nint32_t main()\n\n{\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(NULL);\n\n int n;\n\n cin >> n;\n\n priority_queue pq;\n\n int ans = 0;\n\n for (int i = 0; i < n; i++) {\n\n int x;\n\n cin >> x;\n\n pq.push(x);\n\n pq.push(x);\n\n ans += pq.top() - x;\n\n pq.pop();\n\n }\n\n cout << ans << '\\n';\n\n return 0;\n\n}","language":"cpp"} {"contest_id":"1299","problem_id":"D","statement":"D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1\u2264n,m\u22641051\u2264n,m\u2264105)\u00a0\u2014 the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1\u2264ai,bi\u2264n,ai\u2260bi,0\u2264wi<321\u2264ai,bi\u2264n,ai\u2260bi,0\u2264wi<32)\u00a0\u2014 the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8\n1 2 0\n2 3 1\n2 4 3\n2 6 2\n3 4 8\n3 5 4\n5 4 5\n5 6 6\nOutputCopy2\nInputCopy7 9\n1 2 0\n1 3 1\n2 3 9\n2 4 3\n2 5 4\n4 5 7\n3 6 6\n3 7 7\n6 7 8\nOutputCopy1\nInputCopy4 4\n1 2 27\n1 3 1\n1 4 1\n3 4 0\nOutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1\u221221\u22122, then there is a cycle 1\u22122\u22124\u22125\u22122\u221211\u22122\u22124\u22125\u22122\u22121 with cost 00; also if we don't remove the edge 1\u221231\u22123, then there is a cycle 1\u22123\u22122\u22124\u22125\u22122\u22123\u221211\u22123\u22122\u22124\u22125\u22122\u22123\u22121 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1\u221231\u22123 and 1\u221241\u22124 are kept.","tags":["bitmasks","combinatorics","dfs and similar","dp","graphs","graphs","math","trees"],"code":"#include \n\n\n\nusing namespace std;\n\n\n\n#define mp make_pair\n\n#define pb emplace_back\n\n#define rep(i, s, e) for (int i = s; i <= e; ++i)\n\n#define drep(i, s, e) for (int i = s; i >= e; --i)\n\n#define file(a) freopen(#a\".in\", \"r\", stdin), freopen(#a\".out\", \"w\", stdout)\n\n#define pv(a) cout << #a << \" = \" << a << endl\n\n#define pa(a, l, r) cout << #a \" : \"; rep(_, l, r) cout << a[_] << ' '; cout << endl\n\n\n\nusing pii = pair ;\n\n\n\nconst int P = 1e9 + 7;\n\n\n\nconst int N = 1e5 + 10;\n\nconst int W = 32;\n\nconst int K = 400;\n\n\n\nint read() {\n\n int x = 0, f = 1; char c = getchar();\n\n for (; c < '0' || c > '9'; c = getchar()) if (c == '-') f = -1;\n\n for (; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - 48;\n\n return x * f;\n\n}\n\n\n\nint inc(int a, int b) { return (a += b) >= P ? a - P : a; }\n\nint dec(int a, int b) { return (a -= b) < 0 ? a + P : a; }\n\nint mul(int a, int b) { return 1ll * a * b % P; }\n\nint qpow(int a, int b) { int res = 1; for (; b; b >>= 1, a = mul(a, a)) if (b & 1) res = mul(res, a); return res; }\n\n\n\nstruct node {\n\n int dat[5];\n\n node() { rep(i, 0, 4) dat[i] = 0; }\n\n void clear() { rep(i, 0, 4) dat[i] = 0; }\n\n bool insert(int x) {\n\n drep(i, 4, 0) if (x >> i & 1) {\n\n if (!dat[i]) {\n\n dat[i] = x;\n\n rep(j, 0, i - 1) if (dat[j] && dat[i] >> j & 1) dat[i] ^= dat[j];\n\n rep(j, i + 1, 4) if (dat[j] && dat[j] >> i & 1) dat[j] ^= dat[i];\n\n return true;\n\n }\n\n else x ^= dat[i];\n\n }\n\n return false;\n\n }\n\n int val() {\n\n int res = 0;\n\n rep(i, 0, 4) res |= dat[i] << i * (i + 1) \/ 2;\n\n return res;\n\n }\n\n} base[K], con;\n\n\n\nint cnt, id[N], h[N], add[K][K];\n\n\n\nvoid dfs(int i, node cur) {\n\n if (i == W) {\n\n if (!id[cur.val()]) id[cur.val()] = ++ cnt, base[cnt] = cur, h[cnt] = cur.val();\n\n return;\n\n }\n\n dfs(i + 1, cur);\n\n if (cur.insert(i)) dfs(i + 1, cur);\n\n}\n\n\n\nint join(int u, int v) {\n\n if (~add[u][v]) return add[u][v];\n\n node s = base[u], t = base[v];\n\n rep(i, 0, 4) if (t.dat[i]) {\n\n if (!s.insert(t.dat[i])) return add[u][v] = add[v][u] = 0;\n\n }\n\n return id[s.val()];\n\n}\n\n\n\nint n, m, d[N], f[K], g[K], ans, v1[N], v2[N];\n\nvector e[N];\n\nmap E[N];\n\nbool tag[N];\n\n\n\nint fa[N];\n\nint get(int u) { return u == fa[u] ? u : fa[u] = get(fa[u]); }\n\nvoid merge(int u, int v) { fa[get(v)] = get(u); }\n\n\n\nbool dfs0(int u, int fa) {\n\n tag[u] = true;\n\n bool flag = true;\n\n for (auto [v, w] : e[u]) if (v != 1 && v != fa) {\n\n if (!tag[v]) d[v] = d[u] ^ w, flag &= dfs0(v, u);\n\n else if (u < v) flag &= con.insert(d[u] ^ d[v] ^ w);\n\n }\n\n return flag;\n\n}\n\n\n\nint main() {\n\n dfs(0, node());\n\n rep(i, 1, cnt) rep(j, 1, cnt) add[i][j] = -1;\n\n n = read(), m = read();\n\n rep(i, 1, n) fa[i] = i;\n\n rep(i, 1, m) {\n\n int u = read(), v = read(), w = read();\n\n e[u].pb(mp(v, w)), e[v].pb(mp(u, w));\n\n E[u][v] = E[v][u] = w;\n\n if (u > 1 && v > 1) merge(u, v);\n\n }\n\n tag[1] = true, f[1] = 1;\n\n for (auto [r, w] : e[1]) {\n\n if (!v1[get(r)]) v1[get(r)] = r;\n\n else v2[get(r)] = r;\n\n }\n\n rep(r, 1, n) if (v1[r]) {\n\n if (!v2[r]) {\n\n int u = v1[r];\n\n if (dfs0(u, 1)) {\n\n int p = id[con.val()];\n\n fill(g, g + K, 0);\n\n rep(i, 1, cnt) {\n\n g[i] = inc(g[i], f[i]);\n\n if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], f[i]);\n\n }\n\n swap(f, g);\n\n }\n\n con.clear();\n\n }\n\n else {\n\n int u = v1[r], v = v2[r];\n\n fill(g, g + K, 0);\n\n rep(i, 1, cnt) g[i] = inc(g[i], f[i]);\n\n if (dfs0(u, 1)) {\n\n int p = id[con.val()];\n\n rep(i, 1, cnt) {\n\n if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], inc(f[i], f[i]));\n\n }\n\n if (con.insert(E[1][u] ^ E[1][v] ^ E[u][v])) {\n\n int p = id[con.val()];\n\n rep(i, 1, cnt) {\n\n if (join(i, p)) g[join(i, p)] = inc(g[join(i, p)], f[i]);\n\n }\n\n }\n\n }\n\n con.clear(), swap(f, g);\n\n }\n\n }\n\n rep(i, 1, cnt) ans = inc(ans, f[i]);\n\n printf(\"%d\\n\", ans);\n\n return 0;\n\n}","language":"cpp"} {"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":"#include\n\nusing namespace std;\n\nint main(){\n\n int t;\n\n cin>>t;\n\n while(t--){\n\n int x;\n\n cin>>x;\n\n int a[x];\n\n int flag=0;\n\n int del=0;\n\n for(int i=0;i>a[i];\n\n if(a[i]%2!=0)\n\n flag=1;\n\n\n\n if(a[i]%2==0)\n\n del=1;\n\n }\n\n if(x%2!=0 && flag==1)\n\n cout<<\"YES\";\n\n else if(x%2==0 && del==1 && flag==1)\n\n cout<<\"YES\";\n\n else \n\n cout<<\"NO\";\n\n cout<\nusing namespace std;\n\n#define ll long long\n#define mod 1000000007ll\n\nbool inPowerOfK(ll num, int k, bool vis[]){\n int bit = 0;\n while(num){\n if(num % k > 1) return false;\n if(num % k == 1) {\n if(!vis[bit]) vis[bit] = true;\n else return false;\n }\n num \/= k;\n bit++;\n }\n return true;\n}\nint main(){\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n int t; cin >> t;\n while(t--){\n bool vis[60] = {false};\n int n, k; cin >> n >> k;\n ll arr[n];\n bool ans = true;\n for(int i = 0; i < n; i++) cin >> arr[i];\n for(int i = 0; i < n; i++){\n if(!inPowerOfK(arr[i], k, vis))\n {ans = false; break;}\n }\n if(ans) cout << \"YES\\n\";\n else cout << \"NO\\n\";\n }\n}","language":"cpp"} {"contest_id":"1322","problem_id":"E","statement":"E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland\u00a0\u2014 is a huge country with diverse geography. One of the most famous natural attractions of Berland is the \"Median mountain range\". This mountain range is nn mountain peaks, located on one straight line and numbered in order of 11 to nn. The height of the ii-th mountain top is aiai. \"Median mountain range\" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 22 to n\u22121n\u22121 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal bibi, then after the alignment new heights aiai are as follows: a1=b1a1=b1, an=bnan=bn and for all ii from 22 to n\u22121n\u22121 ai=median(bi\u22121,bi,bi+1)ai=median(bi\u22121,bi,bi+1). The median of three integers is the second largest number among them. For example, median(5,1,2)=2median(5,1,2)=2, and median(4,2,4)=4median(4,2,4)=4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of cc\u00a0\u2014 how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after cc alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers nn (1\u2264n\u22645000001\u2264n\u2264500000)\u00a0\u2014 the number of mountains.The second line contains integers a1,a2,a3,\u2026,ana1,a2,a3,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109)\u00a0\u2014 current heights of the mountains.OutputIn the first line print cc\u00a0\u2014 the number of alignments, which change the height of at least one mountain.In the second line print nn integers\u00a0\u2014 the final heights of the mountains after cc alignments.ExamplesInputCopy5\n1 2 1 2 1\nOutputCopy2\n1 1 1 1 1 \nInputCopy6\n1 3 2 5 4 6\nOutputCopy1\n1 2 3 4 5 6 \nInputCopy6\n1 1 2 2 1 1\nOutputCopy0\n1 1 2 2 1 1 \nNoteIn the first example; the heights of the mountains at index 11 and 55 never change. Since the median of 11, 22, 11 is 11, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 22, 11, 22 is 22, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 11, 11, 22, 11, 11. After the second alignment the heights change into 11, 11, 11, 11, 11 and never change from now on, so there are only 22 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 00.","tags":["data structures"],"code":"#include \n\n#define int long long\nusing namespace std;\nconst int N = 5e5 + 5;\nconst int LOG = 20;\nint n, type, res, a[N], b[N], lg[N], mn[LOG][N], mx[LOG][N];\n\npair get(int l, int r) {\n int LG = lg[r - l];\n return {min(mn[LG][l], mn[LG][r - (1 << LG)]), max(mx[LG][l], mx[LG][r - (1 << LG)])};\n}\n\nvoid precalc() {\n for (int i = 2; i < N; i++) {\n lg[i] = lg[i \/ 2] + 1;\n }\n for (int i = 0; i <= n; i++) {\n mn[0][i] = max(a[i], a[i + 1]);\n mx[0][i] = min(a[i], a[i + 1]);\n }\n for (int i = 0; i < LOG - 1; i++) {\n for (int j = 0; j <= n - (1 << i); j++) {\n mn[i + 1][j] = min(mn[i][j], mn[i][j + (1 << i)]);\n mx[i + 1][j] = max(mx[i][j], mx[i][j + (1 << i)]);\n }\n }\n}\n\nsigned main() {\n cin >> n;\n type = 1;\n for (int i = 1; i <= n; i++) {\n cin >> a[i];\n }\n a[0] = a[1], a[n + 1] = a[n];\n precalc();\n for (int i = 1; i <= n; i++) {\n int l = 1, r = min(n + 1 - i, i), cnt = 0;\n int pff = 400;\n while (l <= r && pff--) {\n int m = (l + r) \/ 2;\n auto t = get(i - m, i + m);\n if (t.first <= t.second) {\n r = m - 1;\n cnt = m;\n }\n else {\n l = m + 1;\n }\n }\n if (!type)\n continue;\n if (cnt == 1) {\n b[i] = a[i];\n } else {\n auto got = get(i - cnt, i + cnt);\n if (a[i] > a[i - 1]) {\n if (cnt % 2 == 0) {\n b[i] = got.second;\n } else {\n b[i] = got.first;\n }\n } else {\n if (cnt % 2 == 1) {\n b[i] = got.second;\n } else {\n b[i] = got.first;\n }\n }\n }\n res = max(res, cnt - 1);\n }\n cout << res << '\\n';\n if (type == 1) {\n for (int i = 1; i <= n; i++) {\n cout << b[i] << ' ';\n }\n }\n return 0;\n}\n","language":"cpp"} {"contest_id":"1290","problem_id":"E","statement":"E. Cartesian Tree time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIldar is the algorithm teacher of William and Harris. Today; Ildar is teaching Cartesian Tree. However, Harris is sick, so Ildar is only teaching William.A cartesian tree is a rooted tree, that can be constructed from a sequence of distinct integers. We build the cartesian tree as follows: If the sequence is empty, return an empty tree; Let the position of the maximum element be xx; Remove element on the position xx from the sequence and break it into the left part and the right part (which might be empty) (not actually removing it, just taking it away temporarily); Build cartesian tree for each part; Create a new vertex for the element, that was on the position xx which will serve as the root of the new tree. Then, for the root of the left part and right part, if exists, will become the children for this vertex; Return the tree we have gotten.For example, this is the cartesian tree for the sequence 4,2,7,3,5,6,14,2,7,3,5,6,1: After teaching what the cartesian tree is, Ildar has assigned homework. He starts with an empty sequence aa.In the ii-th round, he inserts an element with value ii somewhere in aa. Then, he asks a question: what is the sum of the sizes of the subtrees for every node in the cartesian tree for the current sequence aa?Node vv is in the node uu subtree if and only if v=uv=u or vv is in the subtree of one of the vertex uu children. The size of the subtree of node uu is the number of nodes vv such that vv is in the subtree of uu.Ildar will do nn rounds in total. The homework is the sequence of answers to the nn questions.The next day, Ildar told Harris that he has to complete the homework as well. Harris obtained the final state of the sequence aa from William. However, he has no idea how to find the answers to the nn questions. Help Harris!InputThe first line contains a single integer nn (1\u2264n\u22641500001\u2264n\u2264150000).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u2264n1\u2264ai\u2264n). It is guarenteed that each integer from 11 to nn appears in the sequence exactly once.OutputPrint nn lines, ii-th line should contain a single integer \u00a0\u2014 the answer to the ii-th question.ExamplesInputCopy5\n2 4 1 5 3\nOutputCopy1\n3\n6\n8\n11\nInputCopy6\n1 2 4 5 6 3\nOutputCopy1\n3\n6\n8\n12\n17\nNoteAfter the first round; the sequence is 11. The tree is The answer is 11.After the second round, the sequence is 2,12,1. The tree is The answer is 2+1=32+1=3.After the third round, the sequence is 2,1,32,1,3. The tree is The answer is 2+1+3=62+1+3=6.After the fourth round, the sequence is 2,4,1,32,4,1,3. The tree is The answer is 1+4+1+2=81+4+1+2=8.After the fifth round, the sequence is 2,4,1,5,32,4,1,5,3. The tree is The answer is 1+3+1+5+1=111+3+1+5+1=11.","tags":["data structures"],"code":"#include\n\nusing namespace std;\nint n,a[150003],_[150003];\nstruct BIT{\nint dat[150003];\nvoid init(){\nmemset(dat,0,sizeof(dat));\n}\nint query(int x){\nint ret=0;\nwhile(x){\nret+=dat[x];\nx^=(x&-x);\n}return ret;\n}\nvoid add(int x,int y){\nwhile(x<=n){\ndat[x]+=y;\nx+=(x&-x);\n}\n}\n}tr1,tr2;\nlong long sum;\nvoid add1(int x,int y){\ntr1.add(x,y);\nsum+=1ll*tr2.query(n+1-x)*y;\n}\nvoid add2(int x,int y){\nsum+=1ll*tr1.query(x)*y;\ntr2.add(n+1-x,y);\n}\nstruct sgt{\nint mn[524288],mc[524288],sn[524288],lzy[524288];\nvoid init(){\nsum=0;\nmemset(mn,31,sizeof(mn));\nmemset(mc,0,sizeof(mc));\nmemset(sn,31,sizeof(sn));\nmemset(lzy,-1,sizeof(lzy));\n}\nvoid pushtag(int k,int val,bool tp){\nif(mn[k]>=val)\nreturn;\nif(tp){\nadd1(mn[k],-mc[k]);\nadd1(val,mc[k]);\n}\nmn[k]=val;\nlzy[k]=val;\n}\nvoid pushdown(int k){\npushtag(k<<1,lzy[k],0);\npushtag(k<<1|1,lzy[k],0);\nlzy[k]=0;\n}\nvoid pushup(int k){\nif(mn[k<<1]mn[k<<1|1]){\nmn[k]=mn[k<<1|1];\nmc[k]=mc[k<<1|1];\nsn[k]=min(mn[k<<1],sn[k<<1|1]);\n}\n}\nvoid add(int k){\nk+=262144;\nint tk=k;vectorv;tk>>=1;\nwhile(tk)v.push_back(tk),tk>>=1;\nwhile(v.size())pushdown(v.back()),v.pop_back();\nmn[k]=1;mc[k]=1;\nadd1(1,1);\nk>>=1;\nwhile(k){\npushup(k);\nk>>=1;\n}\n}\nvoid modify(int l,int r,int _l,int _r,int k,int val){\nif(l>_r||r<_l||val<=mn[k])return;\nif(_l<=l&&r<=_r&&val>1,_l,_r,k<<1,val);\nmodify(l+r+1>>1,r,_l,_r,k<<1|1,val);\npushup(k);\n}\n}TR;\nlong long ans[150003];\nint main(){\ncin>>n;\nfor(int i=0;i>_[i],a[_[i]-1]=i+1;\nfor(int i=0;i<2;i++){\ntr1.init();tr2.init();TR.init();sum=0;\nfor(int j=0;j\n\nusing namespace std;\n\nconst int INF=2147483647;\n\nstruct Edge\n\n{\n\n\tint to;\n\n\tint nxt;\n\n\tint flow;\n\n\tint cost;\n\n}e[10005];\n\nint n1,n2,m,r,b,s,t,ss,tt,edgenum=1,head[505],dis[505],a[505],pre[505],d[505];\n\nchar s1[505],s2[505];\n\nbool flag[1005];\n\nqueueq;\n\nvoid add(int u,int v,int f,int c)\n\n{\n\n\te[++edgenum].cost=c;\n\n\te[edgenum].flow=f;\n\n\te[edgenum].to=v;\n\n\te[edgenum].nxt=head[u];\n\n\thead[u]=edgenum;\n\n}\n\nbool SPFA()\n\n{\n\n\twhile(!q.empty()) q.pop();\n\n\tfor(int i=1;i<=t;i++)dis[i]=INF,a[i]=0,flag[i]=0;\n\n\tq.push(s);\n\n\tdis[s]=0;\n\n\ta[s]=INF;\n\n\tflag[s]=1;\n\n\twhile(!q.empty())\n\n\t{\n\n\t\tint node=q.front();\n\n\t\tq.pop();\n\n\t\tflag[node]=0;\n\n\t\tfor(int hd=head[node];hd;hd=e[hd].nxt)\n\n\t\t{\n\n\t\t\tif(e[hd].flow==0)continue;\n\n\t\t\tint to=e[hd].to;\n\n\t\t\tif(dis[to]>dis[node]+e[hd].cost)\n\n\t\t\t{\n\n\t\t\t\tdis[to]=dis[node]+e[hd].cost;\n\n\t\t\t\ta[to]=min(a[node],e[hd].flow);\n\n\t\t\t\tpre[to]=hd;\n\n\t\t\t\tif(!flag[to])\n\n\t\t\t\t{\n\n\t\t\t\t\tq.push(to);\n\n\t\t\t\t\tflag[to]=1;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn dis[t]=0)break;\n\n\t\tans+=dis[t]*a[t];\n\n\t\tint x=t;\n\n\t\twhile(x!=s)\n\n\t\t{\n\n\t\t\tint hd=pre[x];\n\n\t\t\te[hd].flow-=a[t];\n\n\t\t\te[hd^1].flow+=a[t];\n\n\t\t\tx=e[hd^1].to;\n\n\t\t}\n\n\t}\n\n\treturn ans;\n\n}\n\nint main()\n\n{\n\n\tscanf(\"%d%d%d%d%d\",&n1,&n2,&m,&r,&b);\n\n\tss=n1+n2+1;\n\n\ttt=ss+1;\n\n\ts=tt+1;\n\n\tt=s+1;\n\n\tscanf(\"%s%s\",s1+1,s2+1);\n\n\tfor(int i=1;i<=m;i++)\n\n\t{\n\n\t\tint u,v;\n\n\t\tscanf(\"%d%d\",&u,&v);\n\n\t\td[u]++,d[v+n1]++;\n\n\t\tadd(u,v+n1,1,-r);\n\n\t\tadd(v+n1,u,0,r);\n\n\t\tadd(u,v+n1,1,b);\n\n\t\tadd(v+n1,u,0,-b);\n\n\t}\n\n\tfor(int i=1;i<=n1;i++)\n\n\t{\n\n\t\tif(s1[i]=='U')\n\n\t\t{\n\n\t\t\tadd(ss,i,2*d[i],0);\n\n\t\t\tadd(i,ss,0,0);\n\n\t\t}\n\n\t\tif(s1[i]=='R')\n\n\t\t{\n\n\t\t\tadd(ss,i,d[i]-1,0);\n\n\t\t\tadd(i,ss,0,0);\n\n\t\t}\n\n\t\tif(s1[i]=='B')\n\n\t\t{\n\n\t\t\tadd(ss,i,d[i]-1,0);\n\n\t\t\tadd(i,ss,0,0);\n\n\t\t\tadd(s,i,d[i]+1,0);\n\n\t\t\tadd(i,s,0,0);\n\n\t\t\tadd(ss,t,d[i]+1,0);\n\n\t\t\tadd(t,ss,0,0);\n\n\t\t}\n\n\t}\n\n\tfor(int i=1;i<=n2;i++)\n\n\t{\n\n\t\tif(s2[i]=='U')\n\n\t\t{\n\n\t\t\tadd(i+n1,tt,2*d[i+n1],0);\n\n\t\t\tadd(tt,i+n1,0,0);\n\n\t\t}\n\n\t\tif(s2[i]=='R')\n\n\t\t{\n\n\t\t\tadd(i+n1,tt,d[i+n1]-1,0);\n\n\t\t\tadd(tt,i+n1,0,0);\n\n\t\t}\n\n\t\tif(s2[i]=='B')\n\n\t\t{\n\n\t\t\tadd(i+n1,tt,d[i+n1]-1,0);\n\n\t\t\tadd(tt,i+n1,0,0);\n\n\t\t\tadd(s,tt,d[i+n1]+1,0);\n\n\t\t\tadd(tt,s,0,0);\n\n\t\t\tadd(i+n1,t,d[i+n1]+1,0);\n\n\t\t\tadd(t,i+n1,0,0);\n\n\t\t}\n\n\t}\n\n\tadd(tt,ss,INF,0);\n\n\tadd(ss,tt,0,0);\n\n\tint ans=r*m;\n\n\tfor(int i=2;i\n\nusing namespace std;\nenum{N=200001};\nbasic_stringG[N],a,b;\nint n,m,u,v,ok[N],dep[N];\nvoid dfs(int u){\na+=u,dep[u]=a.size();\nfor(int v:G[u])\nif(!dep[v])dfs(v);\nelse if(dep[u]-dep[v]+1>=n){\ncout<<\"2\\n\"<>n>>m,n=sqrt(n-1)+1;\nwhile(m--)cin>>u>>v,G[u]+=v,G[v]+=u;\ndfs(1);\nputs(\"1\");\nfor(m=0;m\n\n\n\nusing i64 = long long;\n\n\n\nint main() {\t\n\n\tstd::ios::sync_with_stdio(false); \n\n\tstd::cin.tie(nullptr);\n\n\n\n\tint n, h, l, r;\n\n\tstd::cin >> n >> h >> l >> r;\n\n\n\n\tstd::vector a(n);\n\n\tfor (int i = 0; i < n; i++) {\n\n\t\tstd::cin >> a[i];\n\n\t}\n\n\n\n\tstd::vector dp(h + 1);\n\n\tstd::vector vis(h);\n\n\tvis[0] = true;\n\n\n\n\tfor (int i = 0; i < n; i++) {\n\n\t\tstd::vector ndp(h), nvis(h);\n\n\t\tfor (int j = 0; j < h; j++) {\n\n\t\t\tif (vis[j]) {\n\n\t\t\t\tint x = (j + a[i]) % h, y = (x - 1 + h) % h;\n\n\t\t\t\tndp[x] = std::max(ndp[x], dp[j] + (x >= l && x <= r));\n\n\t\t\t\tndp[y] = std::max(ndp[y], dp[j] + (y >= l && y <= r));\n\n\t\t\t\tnvis[x] = nvis[y] = true;\n\n\t\t\t}\n\n\t\t}\n\n\t\tstd::swap(nvis, vis);\n\n\t\tstd::swap(ndp, dp);\n\n\t}\n\n\n\n\tstd::cout << *max_element(dp.begin(), dp.end()) << \"\\n\";\n\n\n\n\treturn 0;\n\n}\t\n\n","language":"cpp"} {"contest_id":"1286","problem_id":"C2","statement":"C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy 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 \u23080.777(n+1)2\u2309\u23080.777(n+1)2\u2309 (\u2308x\u2309\u2308x\u2309 is xx rounded up).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 \u23080.777(n+1)2\u2309\u23080.777(n+1)2\u2309 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","hashing","interactive","math"],"code":"#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\nstruct edge\n\n{\n\n\tint to;std::pair s;\n\n\tedge(int to=0,std::pair s=std::make_pair(0,0)){this->to=to,this->s=s;}\n\n};\n\nint n,f[105][30],p[105],q[105],ans[105];\n\nchar st[105];\n\nstd::vector a[105];\n\nvoid print()\n\n{\n\n\tprintf(\"! \");\n\n\tfor (int i=1;i<=n;i++) printf(\"%c\",ans[i]+96);\n\n\tputs(\"\");\n\n\tfflush(stdout);\n\n}\n\nvoid add(int x,int y,std::pair s){\/*printf(\"%d %d (%c,%c)\\n\",x,y,s.first+96,s.second+96);*\/a[x].push_back(edge(y,s));a[y].push_back(edge(x,s));}\n\nvoid solve(int x,int y)\n\n{\n\n\tint len=(y-x+1),ss=len*(len+1)\/2;\n\n\/\/\tprintf(\"ss = %d\\n\",len);\n\n\tassert(1<=x&&x<=y&&y<=n);\n\n\tprintf(\"? %d %d\\n\",x,y);\n\n\tfflush(stdout);\n\n\tfor (int i=0;i<=len+1;i++) for (int ch=1;ch<=26;ch++) f[i][ch]=0;\n\n\tfor (int i=0;i<=len+1;i++) p[i]=q[i]=0;\n\n\tfor (int i=1;i<=ss;i++)\n\n\t{\n\n\t\tscanf(\"%s\",st+1);\n\n\t\tif (st[1]=='-') exit(0);\n\n\t\tint m=std::strlen(st+1);\n\n\t\tif (m>(len+1)\/2) continue;\n\n\t\tfor (int k=1;k<=m;k++) ++f[m][st[k]-96];\n\n\t}\n\n\tfor (int s=(len+1)\/2;s>=1;s--)\n\n\t\tfor (int ch=1;ch<=26;ch++)\n\n\t\t\tf[s][ch]=f[s][ch]-f[s-1][ch];\n\n\tfor (int s=1;s<=(len+1)\/2;s++)\n\n\t\tfor (int ch=1;ch<=26;ch++)\n\n\t\t\tf[s][ch]=f[s][ch]-f[s+1][ch];\n\n\/\/\tfor (int s=1;s<=(len+1)\/2;s++)\n\n\/\/\t{\n\n\/\/\t\tfor (int ch=1;ch<=26;ch++) printf(\"%d \",f[s][ch]);\n\n\/\/\t\tputs(\"\");\n\n\/\/\t}\n\n\tfor (int s=1;s<=(len+1)\/1;s++)\n\n\t\tfor (int ch=1;ch<=26;ch++)\n\n\t\t{\n\n\t\t\tif (!f[s][ch]) continue;\n\n\t\t\tif (f[s][ch]>1){p[s]=q[s]=ch;continue;}\n\n\/\/\t\t\tprintf(\"%d:%d\\n\",s,ch);\n\n\t\t\tif (p[s]) q[s]=ch;else p[s]=ch;\n\n\t\t}\n\n\tfflush(stdout);\n\n}\n\nvoid dfs(int v)\n\n{\n\n\/\/\tprintf(\"dfs %d\\n\",v);\n\n\tfor (int i=0;i<(int)a[v].size();i++)\n\n\t{\n\n\t\tint u=a[v][i].to;\n\n\t\tstd::pair pp=a[v][i].s;\n\n\t\tif (ans[u]!=-1) continue;\n\n\t\tif (ans[v]==pp.first) ans[u]=pp.second;\n\n\t\telse ans[u]=pp.first;\n\n\t\tdfs(u);\n\n\t}\n\n}\n\nint main()\n\n{\n\n\tscanf(\"%d\",&n);\n\n\tif (n==1)\n\n\t{\n\n\t\tprintf(\"? 1 1\\n\");\n\n\t\tfflush(stdout);\n\n\t\tchar st[10];\n\n\t\tscanf(\"%s\",st+1);\n\n\t\tif (st[1]=='-') exit(0);\n\n\t\tprintf(\"! %c\\n\",st[1]);\n\n\t\tfflush(stdout);\n\n\t\treturn 0;\n\n\t}\n\n\tif (n==2)\n\n\t{\n\n\t\tprintf(\"? 1 1\\n\");\n\n\t\tfflush(stdout);\n\n\t\tchar st[10];\n\n\t\tscanf(\"%s\",st+1);\n\n\t\tif (st[1]=='-') exit(0);\n\n\t\tprintf(\"? 2 2\\n\");\n\n\t\tfflush(stdout);\n\n\t\tscanf(\"%s\",st+2);\n\n\t\tif (st[2]=='-') exit(0);\n\n\t\tprintf(\"! %c%c\\n\",st[1],st[2]);\n\n\t\tfflush(stdout);\n\n\t\treturn 0;\n\n\t}\n\n\tif (n==3)\n\n\t{\n\n\t\tprintf(\"? 1 1\\n\");\n\n\t\tfflush(stdout);\n\n\t\tchar st[10];\n\n\t\tscanf(\"%s\",st+1);\n\n\t\tif (st[1]=='-') exit(0);\n\n\t\tprintf(\"? 2 2\\n\");\n\n\t\tfflush(stdout);\n\n\t\tscanf(\"%s\",st+2);\n\n\t\tif (st[2]=='-') exit(0);\n\n\t\tprintf(\"? 3 3\\n\");\n\n\t\tfflush(stdout);\n\n\t\tscanf(\"%s\",st+3);\n\n\t\tif (st[2]=='-') exit(0);\n\n\t\tprintf(\"! %c%c%c\\n\",st[1],st[2],st[3]);\n\n\t\tfflush(stdout);\n\n\t\treturn 0;\n\n\t}\n\n\tint kk=n-n\/3;\n\n\tif (n<=5) kk=n;\n\n\tif (n==6) kk=5;\n\n\tint l1=kk-(n-kk),r1=n;\n\n\/\/\tprintf(\"%d %d\\n\",l1,r1);\n\n\tint l2=l1-1,r2=n;\n\n\tint l3=1,r3=(n>2?2*(l2-2)+1:1);\n\n\tif (r3>n) r3=n;\n\n\tint pt=0;\n\n\tsolve(l1,r1);\n\n\tfor (int i=1;i<=n;i++) ans[i]=-1;\n\n\tfor (int i=1;i<=(r1-l1)\/2+1;i++)\n\n\t{\n\n\t\tint x=l1+i-1,y=r1-i+1;\n\n\t\tif (x!=y) add(x,y,std::make_pair(p[i],q[i]));\n\n\t\telse if (x==y) ans[x]=p[i],pt=x;\n\n\t}\n\n\tsolve(l2,r2);\n\n\tfor (int i=1;i<=(r2-l2)\/2+1;i++)\n\n\t{\n\n\t\tint x=l2+i-1,y=r2-i+1;\n\n\t\tif (x!=y) add(x,y,std::make_pair(p[i],q[i]));\n\n\t\telse if (x==y) ans[x]=p[i];\n\n\t}\n\n\tsolve(l3,r3);\n\n\tfor (int i=1;i<=(r3-l3)\/2+1;i++)\n\n\t{\n\n\t\tint x=l3+i-1,y=r3-i+1;\n\n\t\tif (x!=y) add(x,y,std::make_pair(p[i],q[i]));\n\n\t\telse if (x==y) ans[x]=p[i];\n\n\t}\n\n\/\/\tprintf(\"%d\\n\",pt);\n\n\tassert(pt);\n\n\tdfs(pt);\n\n\tprint();\n\n\treturn 0;\n\n}","language":"cpp"} {"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":"#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n\n\nusing namespace std;\n\n\n\n#define all(x) (x).begin(), (x).end()\n\n#define rall(x) (x).rbegin(), (x).rend()\n\n\n\nvoid __print(int x) { cerr << x; }\n\nvoid __print(long x) { cerr << x; }\n\nvoid __print(long long x) { cerr << x; }\n\nvoid __print(unsigned x) { cerr << x; }\n\nvoid __print(unsigned long x) { cerr << x; }\n\nvoid __print(unsigned long long x) { cerr << x; }\n\nvoid __print(float x) { cerr << x; }\n\nvoid __print(double x) { cerr << x; }\n\nvoid __print(long double x) { cerr << x; }\n\nvoid __print(char x) { cerr << '\\'' << x << '\\''; }\n\nvoid __print(const char *x) { cerr << '\\\"' << x << '\\\"'; }\n\nvoid __print(const string &x) { cerr << '\\\"' << x << '\\\"'; }\n\nvoid __print(bool x) { cerr << (x ? \"true\" : \"false\"); }\n\n\n\ntemplate \n\nvoid __print(const pair &x) {\n\n cerr << '{';\n\n __print(x.first);\n\n cerr << ',';\n\n __print(x.second);\n\n cerr << '}';\n\n}\n\ntemplate \n\nvoid __print(const T &x) {\n\n int f = 0;\n\n cerr << '{';\n\n for (auto &i : x) cerr << (f++ ? \",\" : \"\"), __print(i);\n\n cerr << \"}\";\n\n}\n\nvoid _print() { cerr << \"]\\n\"; }\n\ntemplate \n\nvoid _print(T t, V... v) {\n\n __print(t);\n\n if (sizeof...(v)) cerr << \", \";\n\n _print(v...);\n\n}\n\n#ifdef DUPA\n\n#define debug(x...) \\\n\n cerr << \"[\" << #x << \"] = [\"; \\\n\n _print(x)\n\n#else\n\n#define debug(x, ...)\n\n#endif\n\n\n\ntypedef long long LL;\n\n\/\/ HMMMM\n\n#define int LL\n\n\n\ntypedef pair PII;\n\ntypedef pair PIII;\n\n\n\nconst int INF = 1e18 + 1;\n\nint n, m, k;\n\n\n\nvoid solve() {\n\n cin >> n >> m >> k;\n\n vector> res;\n\n\n\n if (n == 1) {\n\n res.push_back({'R', m - 1});\n\n res.push_back({'L', m - 1});\n\n } else if (m == 1) {\n\n res.push_back({'D', n - 1});\n\n res.push_back({'U', n - 1});\n\n } else {\n\n for (int i = 0; i < n - 1; i++) {\n\n res.push_back({'R', m - 1});\n\n res.push_back({'L', m - 1});\n\n res.push_back({'D', 1});\n\n }\n\n res.push_back({'R', m - 1});\n\n for (int j = m - 1; j > 0; j--) {\n\n res.push_back({'U', n - 1});\n\n res.push_back({'D', n - 1});\n\n res.push_back({'L', 1});\n\n }\n\n res.push_back({'U', n - 1});\n\n }\n\n int sum = 0;\n\n\n\n for (auto [_, x] : res) {\n\n sum += x;\n\n }\n\n assert(sum == 4 * n * m - 2 * n - 2 * m);\n\n if (k > sum) {\n\n cout << \"NO \" << endl;\n\n return;\n\n }\n\n\n\n while (sum != k) {\n\n res.back().second--;\n\n sum--;\n\n if (res.back().second == 0) res.pop_back();\n\n }\n\n\n\n assert(res.size() <= 3000);\n\n cout << \"YES\" << endl;\n\n cout << res.size() << endl;\n\n for (auto [y, x] : res) cout << x << \" \" << y << endl;\n\n}\n\n\n\n#undef int\n\nint main() {\n\n ios::sync_with_stdio(false);\n\n cin.exceptions(cin.failbit);\n\n\n\n cin.tie(0);\n\n int t = 1;\n\n#ifdef DUPA\n\n cin >> t;\n\n#endif\n\n for (int i = 0; i < t; i++) solve();\n\n}\n\n","language":"cpp"} {"contest_id":"1322","problem_id":"B","statement":"B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one\u00a0\u2014 xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)Here x\u2295yx\u2295y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https:\/\/en.wikipedia.org\/wiki\/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2\u2264n\u22644000002\u2264n\u2264400000)\u00a0\u2014 the number of integers in the array.The second line contains integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641071\u2264ai\u2264107).OutputPrint a single integer\u00a0\u2014 xor of all pairwise sums of integers in the given array.ExamplesInputCopy2\n1 2\nOutputCopy3InputCopy3\n1 2 3\nOutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112\u22951002\u22951012=01020112\u22951002\u22951012=0102, thus the answer is 2.\u2295\u2295 is the bitwise xor operation. To define x\u2295yx\u2295y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012\u229500112=0110201012\u229500112=01102.","tags":["binary search","bitmasks","constructive algorithms","data structures","math","sortings"],"code":"\/\/ LUOGU_RID: 102594463\n#include \n\n#define IOS std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);\n\n#define endl '\\n' \n\nusing ll = long long;\n\n#define int long long\n\nusing pll = std::pair;\n\nusing namespace std;\n\n\n\nsigned main()\n\n{\n\n\/\/#ifdef LOCAL\n\n\/\/ freopen(\"in.txt\",\"r\",stdin);\n\n\/\/ freopen(\"out.txt\",\"w\",stdout);\n\n\/\/#endif\n\n IOS;\/\/\/\n\n int n;\n\n cin >> n;\n\n vectora(n + 7), b(n + 7);\n\n for (int i = 1;i <= n;++i)cin >> a[i];\n\n\n\n auto calc = [&](int L, int R) ->bool {\n\n if (L > R) return 0;\n\n ll ret = 0;\n\n for (int i = n, l = 1, r = 1; i; i--) {\n\n while (l <= n && b[i] + b[l] < L) ++l;\n\n while (r <= n && b[i] + b[r] <= R) ++r;\n\n ret += r - l - (l <= i && i < r);\n\n }\n\n return (ret >> 1) & 1;\n\n };\n\n int ans = 0;\n\n\n\n for (int k = 0;k <= 26;++k) {\n\n for (int i = 1;i <= n;++i) {\n\n b[i] = a[i] & ((1 << (k + 1) ) - 1);\n\n }\n\n sort(&b[1], &b[1 + n]);\n\n int g = (calc(1 << k, (1 << (k + 1)) - 1) ^ calc(3 << k, (1 << (k + 2)) - 2));\n\n ans |= (g << k);\n\n }\n\n cout << ans << '\\n';\n\n\n\n return 0;\n\n}","language":"cpp"} {"contest_id":"1293","problem_id":"A","statement":"A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin \"ConneR\" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1\u2264t\u226410001\u2264t\u22641000)\u00a0\u2014 the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2\u2264n\u22641092\u2264n\u2264109, 1\u2264s\u2264n1\u2264s\u2264n, 1\u2264k\u2264min(n\u22121,1000)1\u2264k\u2264min(n\u22121,1000))\u00a0\u2014 respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,\u2026,aka1,a2,\u2026,ak (1\u2264ai\u2264n1\u2264ai\u2264n)\u00a0\u2014 the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer\u00a0\u2014 the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77\nOutputCopy2\n0\n4\n0\n2\nNoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.","tags":["binary search","brute force","implementation"],"code":"#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n cout.tie(nullptr);\n\n std::ios::sync_with_stdio(false);\n\n \n\nint t; cin >> t;\n\nwhile(t--){\n\nint n,s,k;\n\ncin >> n >> s >> k;\n\n\n\nvector v;\n\nfor(int i=0;i> a;\n\n v.push_back(a);\n\n}\n\nint ans=0;\n\nfor (int i=0; i<=k; i++) {\n\n\t\tif (s+i<=n) {\n\n if(find(v.begin(),v.end(),s+i)==v.end()){\n\n ans=i; break;\n\n }\n\n }\n\n\n\n if (s-i>=1){\n\n if(find(v.begin(),v.end(),s-i)==v.end()){\n\n ans=i; break;\n\n }\n\n\t\t}\n\n\t}\n\n\n\ncout << ans << '\\n';\n\n\n\n\n\n\n\n\n\n}\n\n return 0;\n\n}\n\n","language":"cpp"} {"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\n\n#include\n\n#pragma GCC optimize(\"O3\",\"Ofast\",\"unroll-loops\")\n\n#pragma GCC optimize(\"O3\", \"fast-math\")\n\n#define ll long long\n\n#define pb push_back\n\n#define mp make_pair\n\n#define all(x) x.begin(),x.end()\n\n\n\nusing namespace std;\n\n\n\nconst ll mod = (ll)1e9 + 7, mod3 = 998244353, inf = (ll)1e15, P = 997;\n\n\n\nll binpow (ll a, ll b){\n\n if (b == 0) return 1;\n\n if (b & 1) return ((binpow(a, b - 1)) * a);\n\n else return (binpow(a, b \/ 2) * binpow(a, b \/ 2));\n\n}\n\nll gcd(ll a, ll b){\n\n return (b ? gcd(b, a % b) : a);\n\n}\n\nll nums(ll g){\n\n ll cur = 0;\n\n while(g){\n\n cur++, g \/= 10;\n\n }\n\n\n\n return cur;\n\n}\n\n\n\nvector fact(ll n){\n\n ll i = 2;\n\n\n\n vector ans;\n\n\n\n ll save = n;\n\n\n\n while(i * i <= save){\n\n while(n % i == 0){\n\n ans.pb(i);\n\n\n\n n \/= i;\n\n }\n\n\n\n i++;\n\n }\n\n\n\n if (n > 1) ans.pb(n);\n\n\n\n return ans;\n\n}\n\n\n\nll get1(ll q, ll g){\n\n ll cur = 1;\n\n\n\n for (ll i = q; i > g; i--){\n\n cur *= i;\n\n }\n\n\n\n return cur;\n\n}\n\nstruct mo{\n\n ll l, r, id;\n\n};\n\n\n\nll n, m, k, a, b, x, y;\n\n\n\nstring s;\n\n\n\nvector g[200005];\n\n\n\nvoid query(){\n\n cin >> x >> y >> a >> b;\n\n \n\n if ((y - x) % (a + b)) cout << \"-1\\n\";\n\n \n\n else cout << (y - x) \/ (a + b) << '\\n';\n\n}\n\n\n\nint main(){\n\n ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);\n\n\n\n \/\/freopen(\"lca_rmq.in\", \"r\", stdin);\n\n \/\/freopen(\"lca_rmq.out\", \"w\", stdout);\n\n\n\n ll TT = 1;\n\n\n\n cin >> TT;\n\n\n\n while(TT--){\n\n \/\/cout << \"Case \" << cur << \":\\n\";\n\n\n\n query();\n\n\n\n \/\/cur++;\n\n }\n\n\n\n return 0;\n\n}\n\n\n\n\/**\n\n\n\n1 2 4 6 3 5\n\n\n\n\n\n\n\n\n\n*\/\n\n","language":"cpp"} {"contest_id":"1316","problem_id":"F","statement":"F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,\u2026,aka1,a2,\u2026,ak, where a1\u2264a2\u2264\u22ef\u2264aka1\u2264a2\u2264\u22ef\u2264ak. The strength of this battalion is equal to a1a2+a2a3+\u22ef+ak\u22121aka1a2+a2a3+\u22ef+ak\u22121ak. (If the size of Battalion is \u22641\u22641, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p\/qp\/q, where pp and qq are integers and q\u2261\u03380modMq\u22620modM). Output the integer equal to p\u22c5q\u22121modMp\u22c5q\u22121modM. In other words, output such an integer xx that 0\u2264x\n\nusing namespace std;\n\n#define pb push_back\n\n#define ll long long\n\n#define vi vector\n\n#define vvi vector\n\n#define all(x) x.begin(), x.end()\n\n\n\nll mod = 1e9 + 7;\n\nvi tw, in;\n\n\n\nstruct pt {\n\n ll val, cnt, lva, rva;\n\n pt() {};\n\n pt(ll k, ll x) {\n\n cnt = k;\n\n val = (x * x % mod) * (k * in[1] % mod + mod - 1 + in[k]) % mod;\n\n lva = (tw[k] + mod - 1) * x % mod;\n\n rva = (1 + mod - in[k]) * x % mod;\n\n }\n\n pt(ll val, ll cnt, ll lva, ll rva) : val(val), cnt(cnt), lva(lva), rva(rva) {};\n\n};\n\npt operator+(pt x, pt y) {\n\n return pt((x.val + y.val + (x.lva * y.rva % mod) * in[x.cnt]) % mod, x.cnt + y.cnt,\n\n (x.lva + y.lva * tw[x.cnt]) % mod, (x.rva + y.rva * in[x.cnt]) % mod);\n\n}\n\n\n\nll n, m, q;\n\nvi p, x, I, X;\n\nvector t;\n\n\n\nll po(ll x, ll p) {\n\n ll res = 1;\n\n for (; p; p \/= 2) {\n\n if (p % 2)\n\n res = (res * x) % mod;\n\n x = (x * x) % mod;\n\n }\n\n return res;\n\n}\n\nll inv(ll x) { return po(x, mod - 2); }\n\n\n\nvoid add(ll i, ll x) {\n\n ll k = t[i].cnt + 1;\n\n t[i] = pt(k, x);\n\n for (i \/= 2; i > 0; i \/= 2)\n\n t[i] = (t[i + i] + t[i + i + 1]);\n\n}\n\nvoid del(ll i, ll x) {\n\n ll k = t[i].cnt - 1;\n\n t[i] = pt(k, x);\n\n for (i \/= 2; i > 0; i \/= 2)\n\n t[i] = (t[i + i] + t[i + i + 1]);\n\n}\n\n\n\nint main() {\n\n ios_base::sync_with_stdio(false); cin.tie(0);\n\n cin >> n;\n\n ll inv2 = inv(2);\n\n tw.assign(n + 5, 1);\n\n in.assign(n + 5, 1);\n\n for (ll i = 1; i < in.size(); ++i) {\n\n in[i] = (in[i - 1] * inv2) % mod;\n\n tw[i] = (tw[i - 1] * 2) % mod;\n\n }\n\n p.resize(n);\n\n for (auto& el : p) {\n\n cin >> el; x.pb(el);\n\n }\n\n cin >> q;\n\n I = X = vi(q);\n\n for (ll e = 0; e < q; ++e) {\n\n cin >> I[e] >> X[e]; --I[e];\n\n x.pb(X[e]);\n\n }\n\n sort(all(x));\n\n x.resize(unique(all(x)) - x.begin());\n\n m = 1;\n\n while (m < x.size())\n\n m *= 2;\n\n t.assign(2 * m, pt(0, 0, 0, 0));\n\n for (auto el : p) {\n\n ll e = lower_bound(all(x), el) - x.begin();\n\n add(e + m, el);\n\n }\n\n cout << t[1].val << \"\\n\";\n\n for (ll o = 0; o < q; ++o) {\n\n ll i = I[o];\n\n ll to = X[o]; ll eto = lower_bound(all(x), to) - x.begin();\n\n ll fr = p[i]; ll efr = lower_bound(all(x), fr) - x.begin();\n\n p[i] = to;\n\n del(efr + m, fr);\n\n add(eto + m, to);\n\n cout << t[1].val << \"\\n\";\n\n }\n\n\n\n return 0;\n\n}\n\n","language":"cpp"} {"contest_id":"1301","problem_id":"E","statement":"E. Nanosofttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWarawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red; the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of nn rows and mm columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh qq options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 00.Warawreh couldn't find the best option himself so he asked you for help, can you help him?InputThe first line of input contains three integers nn, mm and qq (1\u2264n,m\u2264500,1\u2264q\u22643\u22c5105)(1\u2264n,m\u2264500,1\u2264q\u22643\u22c5105) \u00a0\u2014 the number of row, the number columns and the number of options.For the next nn lines, every line will contain mm characters. In the ii-th line the jj-th character will contain the color of the cell at the ii-th row and jj-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next qq lines, the input will contain four integers r1r1, c1c1, r2r2 and c2c2 (1\u2264r1\u2264r2\u2264n,1\u2264c1\u2264c2\u2264m)(1\u2264r1\u2264r2\u2264n,1\u2264c1\u2264c2\u2264m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r1,c1)(r1,c1) and with the bottom-right corner in the cell (r2,c2)(r2,c2).OutputFor every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 00.ExamplesInputCopy5 5 5\nRRGGB\nRRGGY\nYYBBG\nYYBBR\nRBBRG\n1 1 5 5\n2 2 5 5\n2 2 3 3\n1 1 3 5\n4 4 5 5\nOutputCopy16\n4\n4\n4\n0\nInputCopy6 10 5\nRRRGGGRRGG\nRRRGGGRRGG\nRRRGGGYYBB\nYYYBBBYYBB\nYYYBBBRGRG\nYYYBBBYBYB\n1 1 6 10\n1 3 3 10\n2 2 6 6\n1 7 6 10\n2 1 5 10\nOutputCopy36\n4\n16\n16\n16\nInputCopy8 8 8\nRRRRGGGG\nRRRRGGGG\nRRRRGGGG\nRRRRGGGG\nYYYYBBBB\nYYYYBBBB\nYYYYBBBB\nYYYYBBBB\n1 1 8 8\n5 2 5 7\n3 1 8 6\n2 3 5 8\n1 2 6 8\n2 1 5 5\n2 1 7 7\n6 5 7 5\nOutputCopy64\n0\n16\n4\n16\n4\n36\n0\nNotePicture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black; the border of the sub-square with the maximal possible size; that can be cut is marked with gray.","tags":["binary search","data structures","dp","implementation"],"code":"#include \n\n \n\nusing namespace std;\n\n\n\ntemplate bool maximize(A& x, B y) {if (x < y) return x = y, true; else return false;}\n\ntemplate bool minimize(A& x, B y) {if (x >= y) return x = y, true; else return false;}\n\n\n\nvoid __print(int x) {cerr << x;}\n\nvoid __print(long x) {cerr << x;}\n\nvoid __print(long long x) {cerr << x;}\n\nvoid __print(unsigned x) {cerr << x;}\n\nvoid __print(unsigned long x) {cerr << x;}\n\nvoid __print(unsigned long long x) {cerr << x;}\n\nvoid __print(float x) {cerr << x;}\n\nvoid __print(double x) {cerr << x;}\n\nvoid __print(long double x) {cerr << x;}\n\nvoid __print(char x) {cerr << '\\'' << x << '\\'';}\n\nvoid __print(const char *x) {cerr << '\\\"' << x << '\\\"';}\n\nvoid __print(const string &x) {cerr << '\\\"' << x << '\\\"';}\n\nvoid __print(bool x) {cerr << (x ? \"true\" : \"false\");}\n\n \n\ntemplate\n\nvoid __print(const pair &x) {cerr << '{'; __print(x.first); cerr << \", \"; __print(x.second); cerr << '}';}\n\ntemplate\n\nvoid __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? \", \" : \"\"), __print(i); cerr << \"}\";}\n\nvoid _print() {cerr << \" ]\\n\";}\n\ntemplate \n\nvoid _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << \", \"; _print(v...);}\n\n#define deb(x...) cerr << \"[ in \" <<__func__<< \"() : line \" <<__LINE__<< \" ] : [ \" << #x << \" ] = [ \"; _print(x); cerr << '\\n';\n\n\n\ntypedef long long ll;\n\ntypedef unsigned long long ull;\n\ntypedef double db;\n\ntypedef long double ld;\n\ntypedef pair pdb;\n\ntypedef pair pld;\n\ntypedef pair pii;\n\ntypedef pair pll;\n\ntypedef pair plli;\n\ntypedef pair pill;\n\n\n\n#define all(a) a.begin(), a.end()\n\n#define pb(a) push_back(a)\n\n#define pf(a) push_front(a)\n\n#define fi first\n\n#define se second\n\n\/\/ #define int long long\n\n\n\nconst int MAX_N = 500 + 5;\n\n\n\nint n, m, q;\n\nstring a[MAX_N];\n\nint prefSum[4][MAX_N][MAX_N];\n\nint b[MAX_N][MAX_N];\n\nint rmq[10][MAX_N][10][MAX_N];\n\n\n\nint convert(const char& h) {\n\n\tif (h == 'R') return 0;\n\n\tif (h == 'G') return 1;\n\n\tif (h == 'Y') return 2;\n\n\treturn 3;\n\n}\n\n\n\nbool inside(const int& x, const int& y) {\n\n\treturn x > 0 && x <= n && y > 0 && y <= m;\n\n}\n\n\n\nint get(int t, int x, int y, int u, int v) {\n\n\tif (x > u) swap(x, u);\n\n\tif (y > v) swap(y, v);\n\n\treturn prefSum[t][u][v] - prefSum[t][u][y - 1] - prefSum[t][x - 1][v] + prefSum[t][x - 1][y - 1];\n\n}\n\n\n\nint getMax(int x, int y, int u, int v) {\n\n\tint k1 = __lg(u - x + 1);\n\n\tint k2 = __lg(v - y + 1);\n\n\tint mx1 = max(rmq[k1][x][k2][y], rmq[k1][x][k2][v - (1 << k2) + 1]);\n\n\tint mx2 = max(rmq[k1][u - (1 << k1) + 1][k2][y], rmq[k1][u - (1 << k1) + 1][k2][v - (1 << k2) + 1]);\n\n\treturn max(mx1, mx2);\n\n}\n\n\n\nsigned main() {\n\n\tios_base::sync_with_stdio(false);\n\n\tcin.tie(nullptr);\n\n\n\n\tcin >> n >> m >> q;\n\n\tfor (int i = 1; i <= n; i++) {\n\n\t\tcin >> a[i];\n\n\t\ta[i] = ' ' + a[i];\n\n\t}\n\n\n\n\tfor (int i = 1; i <= n; i++) {\n\n\t\tfor (int j = 1; j <= m; j++) {\n\n\t\t\tfor (int t = 0; t < 4; t++) {\n\n\t\t\t\tprefSum[t][i][j] = prefSum[t][i - 1][j] + prefSum[t][i][j - 1] - prefSum[t][i - 1][j - 1];\n\n\t\t\t}\n\n\t\t\tprefSum[convert(a[i][j])][i][j]++;\n\n\t\t}\n\n\t}\n\n\n\n\tfor (int i = 1; i < n; i++) {\n\n\t\tfor (int j = 1; j < m; j++) {\n\n\t\t\tif (a[i][j] == 'R' && a[i][j + 1] == 'G' && a[i + 1][j] == 'Y' && a[i + 1][j + 1] == 'B') {\n\n\t\t\t\tint low = 1, high = min(n, m);\n\n\t\t\t\twhile (low <= high) {\n\n\t\t\t\t\tint mid = (low + high) >> 1;\n\n\t\t\t\t\tif (inside(i - mid + 1, j - mid + 1) && inside(i - mid + 1, j + mid) && inside(i + mid, j - mid + 1) && inside(i + mid, j + mid) && get(0, i - mid + 1, j - mid + 1, i, j) == mid * mid && get(1, i, j + 1, i - mid + 1, j + mid) == mid * mid && get(2, i + 1, j, i + mid, j - mid + 1) == mid * mid && get(3, i + 1, j + 1, i + mid, j + mid) == mid * mid) {\n\n\t\t\t\t\t\tb[i][j] = mid;\n\n\t\t\t\t\t\tlow = mid + 1;\n\n\t\t\t\t\t}\n\n\t\t\t\t\telse {\n\n\t\t\t\t\t\thigh = mid - 1;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tfor (int ir = 1; ir <= n; ir++) {\n\n\t\tfor (int ic = 1; ic <= m; ic++) {\n\n\t\t\trmq[0][ir][0][ic] = b[ir][ic];\n\n\t\t}\n\n\t\tfor (int jc = 1; jc < 10; jc++) {\n\n\t\t\tfor (int ic = 1; ic <= m; ic++) {\n\n\t\t\t\tif (ic + (1 << jc) > m) break;\n\n\t\t\t\trmq[0][ir][jc][ic] = max(rmq[0][ir][jc - 1][ic], rmq[0][ir][jc - 1][ic + (1 << (jc - 1))]);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tfor (int jc = 0; jc < 10; jc++) {\n\n\t\tfor (int ic = 1; ic <= m; ic++) {\n\n\t\t\tif (ic + (1 << jc) > m) break;\n\n\t\t\tfor (int jr = 1; jr < 10; jr++) {\n\n\t\t\t\tfor (int ir = 1; ir <= n; ir++) {\n\n\t\t\t\t\tif (ir + (1 << jr) > n) break;\n\n\t\t\t\t\trmq[jr][ir][jc][ic] = max(rmq[jr - 1][ir][jc][ic], rmq[jr - 1][ir + (1 << (jr - 1))][jc][ic]);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\twhile (q--) {\n\n\t\tint x1, y1, x2, y2;\n\n\t\tcin >> x1 >> y1 >> x2 >> y2;\n\n\t\tint low = 1, high = min(n, m);\n\n\t\tint ans = 0;\n\n\t\twhile (low <= high) {\n\n\t\t\tint mid = (low + high) >> 1;\n\n\t\t\tint u1 = x1 + mid - 1;\n\n\t\t\tint v1 = y1 + mid - 1;\n\n\t\t\tint u2 = x2 - mid;\n\n\t\t\tint v2 = y2 - mid;\n\n\t\t\tif (u1 <= u2 && v1 <= v2 && getMax(u1, v1, u2, v2) >= mid) {\n\n\t\t\t\tans = mid;\n\n\t\t\t\tlow = mid + 1;\n\n\t\t\t}\n\n\t\t\telse {\n\n\t\t\t\thigh = mid - 1;\n\n\t\t\t}\n\n\t\t}\n\n\t\tcout << 4 * ans * ans << '\\n';\n\n\t}\n\n\n\n\treturn 0;\n\n}\n\n\n\n\/*\n\n\n\n\n\n*\/","language":"cpp"} {"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\nusing namespace std;\n\nconst int MAXN = 2.5e5+100;\nlong long fact[MAXN];\n\nint main(){\n\tint n,m;\n\tcin >> n >> m;\n\tfact[0] = 1;\n\tfor(int i = 1;i <= n;i++){\n\t\tfact[i] = fact[i-1]*i;\n\t\tfact[i]%=m;\n\t}\n\tlong long ans = 0;\n\tlong long tp = 0;\n\tlong long tp1 = 0;\n\tlong long tp3 = 0;\n\tfor (int len = 1;len<=n;len++){\n\t\ttp = fact[n-len]*(n-len+1);\n\t\ttp1 = fact[len]*(n-len+1);\n\t\ttp%=m;\n\t\ttp1%=m;\n\n\t\t\/\/ ans+=fact[n-len]*fact[len]*(n-len+1)*(n-len+1);\n\t\ttp3 = tp*tp1;\n\t\ttp3%=m;\n\t\tans+=tp3;\n\t\tans%=m;\n\t}\n\tcout << ans << endl;\n\n\t\n\n\n\n\n\t\n}","language":"cpp"} {"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\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n int t; cin >> t;\n\n while(t--){\n\n int n, m;\n\n cin >> n >> m;\n\n string s;\n\n cin >> s;\n\n vector freq(n, 0);\n\n for(int i=0; i> x;\n\n freq[0]++;\n\n freq[x]--;\n\n }\n\n freq[0]++;\n\n\n\n for(int i=1; i c(26, 0);\n\n for(int i=0; i\n\n#include \n\n#include \n\n\n\nusing namespace std;\n\nusing namespace __gnu_pbds;\n\n\n\n#define ll long long\n\n#define test int _TEST; cin>>_TEST; while(_TEST--)\n\n#define ff first\n\n#define ss second\n\n#define pb push_back\n\n#define ppb pop_back\n\n#define pf push_front\n\n#define ppf pop_front\n\n\n\ntemplate using Ordered_Set_Tree =\n\n tree, rb_tree_tag, tree_order_statistics_node_update>;\n\ntemplate using Ordered_Multiset_Tree =\n\n tree, rb_tree_tag, tree_order_statistics_node_update>;\n\n\n\ntemplate ostream& operator<<(ostream& s, const pair& self) {s << self.first << ' ' << self.second << ' '; return s; }\n\ntemplate ostream& operator<<(ostream& s, const vector& self) { for (auto e : self) { s << e << '\\n'; } return s; }\n\ntemplate ostream& operator<<(ostream& s, tuple& self) { s << get<0>(self) << ' ' << get<1>(self) << ' ' << get<2>(self); return s; }\n\ntemplate istream& operator>>(istream& s, pair& self) { s >> self.first >> self.second; return s; }\n\ntemplate istream& operator>>(istream& s, tuple& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self); return s; }\n\ntemplate istream& operator>>(istream& s, tuple& self) { s >> get<0>(self) >> get<1>(self) >> get<2>(self) >> get<3>(self); return s; }\n\ntemplate istream& operator>>(istream& s, vector& self) { for (size_t i = 0; i < self.size(); ++i) { s >> self[i]; } return s; }\n\n\n\n\/\/\/DEBUG\n\nvoid _Print(int t) {cerr << t;}\n\nvoid _Print(string t) {cerr << t;}\n\nvoid _Print(char t) {cerr << t;}\n\nvoid _Print(long long t) {cerr << t;}\n\nvoid _Print(double t) {cerr << t;}\n\nvoid _Print(unsigned long long t) {cerr << t;}\n\n\n\ntemplate void _Print(pair &p);\n\ntemplate void _Print(list &v);\n\ntemplate void _Print(vector &v);\n\ntemplate void _Print(deque &v);\n\ntemplate void _Print(T *v, V sz);\n\ntemplate void _Print(T *v, V sz, P sm);\n\ntemplate void _Print(set &v);\n\ntemplate void _Print(map &v);\n\ntemplate void _Print(multiset &v);\n\n\n\ntemplate void _Print(pair &p) {cerr << \"{\"; _Print(p.ff); cerr << \",\"; _Print(p.ss); cerr << \"}\\n\\n\";}\n\ntemplate void _Print(list &v) {cerr << \"[ \"; for (T i : v) {_Print(i); cerr << \" \";} cerr << \"]\\n\\n\";}\n\ntemplate void _Print(vector &v) {cerr << \"[ \"; for (T i : v) {_Print(i); cerr << \" \";} cerr << \"]\\n\\n\";}\n\ntemplate void _Print(deque &v) {cerr << \"[ \"; for (T i : v) {_Print(i); cerr << \" \";} cerr << \"]\\n\\n\";}\n\ntemplate void _Print(T *v, V sz) {cerr << \"[ \"; for(int i=0; i void _Print(T *v, V sz, P sm) {cerr << \"[\\n\"; for(int i=0; i void _Print(set &v) {cerr << \"[ \"; for (T i : v) {_Print(i); cerr << \" \";} cerr << \"]\\n\\n\";}\n\ntemplate void _Print(multiset & v) {cerr << \"[ \"; for (T i : v) {_Print(i); cerr << \" \";} cerr << \"]\\n\\n\";}\n\ntemplate void _Print(map &v) {cerr << \"[ \"; for (auto i : v) {_Print(i); cerr << \" \";} cerr << \"]\\n\\n\";}\n\n\n\n#define debug(...) debug_out(vec_splitter(#__VA_ARGS__), 0, __LINE__, __VA_ARGS__)\n\nvector vec_splitter(string s)\n\n{\n\n s += ',';\n\n vector res;\n\n while(!s.empty())\n\n {\n\n res.push_back(s.substr(0, s.find(',')));\n\n s = s.substr(s.find(',') + 1);\n\n }\n\n return res;\n\n}\n\nvoid debug_out(vector __attribute__ ((unused)) args, __attribute__ ((unused)) int idx, __attribute__ ((unused)) int LINE_NUM) { cerr << endl; }\n\ntemplate void debug_out(vector args, int idx, int LINE_NUM, Head H, Tail... T)\n\n{\n\n if(idx > 0) cerr << \", \"; else cerr << \"Line(\" << LINE_NUM << \") \";\n\n stringstream ss; ss << H;\n\n cerr << args[idx] << \" = \" << ss.str();\n\n debug_out(args, idx + 1, LINE_NUM, T...);\n\n}\n\n\/\/\/DEBUG\n\n\n\n\n\nint main()\n\n{\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(NULL);\n\n\n\n test\n\n {\n\n string s, t;\n\n cin>>s>>t;\n\n\n\n vector> nextPos(s.size()+1, vector (26, 1e9));\n\n for(int i=s.size()-1; i>=0; i--)\n\n {\n\n nextPos[i] = nextPos[i+1];\n\n nextPos[i][s[i]-'a'] =i;\n\n }\n\n\n\n vector> dp(s.size()+2, vector (s.size()+2));\n\n\n\n auto cal = [&](string a, string b)\n\n {\n\n for(int i=0; i<=a.size(); i++)\n\n {\n\n for(int j=0; j<=b.size(); j++)\n\n dp[i][j] = 1e9;\n\n }\n\n\n\n dp[0][0] = 0;\n\n\n\n for(int i=0; i<=a.size(); i++)\n\n {\n\n for(int j=0; j<=b.size(); j++)\n\n {\n\n if(dp[i][j] > s.size()) continue;\n\n\n\n int lenS = dp[i][j];\n\n\n\n if(i\n\n#include \/\/ Common file\n\n#include \/\/ Including tree_order_statistics_node_update\n\n#include \n\nusing namespace std;\n\nmt19937 rng((int)std::chrono::steady_clock::now().time_since_epoch().count());\n\nstruct custom_hash{\n\n static uint64_t splitmix64(uint64_t x){\n\n x += 0x9e3779b97f4a7c15;\n\n x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;\n\n x = (x ^ (x >> 27)) * 0x94d049bb133111eb;\n\n return x ^ (x >> 31);\n\n }\n\n size_t operator()(uint64_t a) const {\n\n static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n\n return splitmix64(a + FIXED_RANDOM);\n\n }\n\n template size_t operator()(T a) const {\n\n static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n\n hash x;\n\n return splitmix64(x(a) + FIXED_RANDOM);\n\n }\n\n template size_t operator()(pair a) const {\n\n static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();\n\n hash x;\n\n hash y;\n\n return splitmix64(x(a.f) * 37 + y(a.s) + FIXED_RANDOM);\n\n }\n\n};\n\ntemplateusing umap=unordered_map;\n\nconst int MAXN = 2e5 + 10;\n\nconst int MOD = 998244353;\n\n#define int long long\n\nusing namespace __gnu_pbds;\n\nint bm(int b, int p) { \/\/ bigmod\n\n if(p==0) return 1;\n\n int r = bm(b, p\/2);\n\n if(p&1) return (((r*r) % MOD) * b) % MOD;\n\n return (r*r) % MOD;\n\n}\n\nint inv(int b) { \/\/ modinv\n\n return bm(b, MOD-2);\n\n}\n\nint f[MAXN];\n\nint nCr(int n, int r) { \/\/ nCr main function, requires precomputation function\n\n int ans = f[n]; ans *= inv(f[r]); ans %= MOD;\n\n ans *= inv(f[n-r]); ans %= MOD; return ans;\n\n}\n\nint dsu[MAXN]; \/\/ disjoint set union\n\nint set_of(int u) {\n\n if(dsu[u] == u) return u;\n\n return dsu[u] = set_of(dsu[u]);\n\n}\n\nvoid union_(int u, int v) {\n\n dsu[set_of(u)] = set_of(v);\n\n}\n\nvoid precomp() { \/\/ factorials for nCr\n\n f[0] = 1;\n\n for(int i=1; i(x, y)(rng); return u;\n\n}\n\nint sd(int n) { \/\/ sum of digits\n\n int sum = 0;\n\n while(n) {\n\n sum += n%10;\n\n n \/= 10;\n\n }\n\n return sum;\n\n}\n\nstring binAdd(string a, string b) { \/\/O(max(n,m)) time binary addition\n\n string result = \"\"; int s = 0;\n\n int i = a.size()-1, j = b.size()-1;\n\n while(i >= 0 || j >= 0 || s == 1) {\n\n s += ((i>=0 ? a[i] - '0':0));\n\n s += ((j>=0 ? b[j] - '0':0));\n\n result += char(s%2 + '0');\n\n s \/= 2;\n\n i--, j--;\n\n }\n\n reverse(result.begin(), result.end());\n\n return result;\n\n}\n\nstring binSub(string a, string b) { \/\/ O(max(n,m)) time binary subtraction, a \u2265 b required\n\n string result = \"\"; int s = 0;\n\n int i = a.size()-1, j = b.size()-1;\n\n while(i >= 0 || j >= 0 || s != 0) {\n\n s += ((i>=0 ? a[i] - '0':0));\n\n s -= ((j>=0 ? b[j] - '0':0));\n\n result += char(abs(s)%2 + '0');\n\n if(s >= 0) s \/= 2;\n\n else s = (s-1) \/ 2;\n\n i--, j--;\n\n }\n\n while(result.size() > 1 && result[result.size() - 1] == '0') {\n\n result.erase(result.size() - 1, 1);\n\n }\n\n reverse(result.begin(), result.end());\n\n return result;\n\n}\n\nint fastlog(int x) {\n\n int k = 32 - __builtin_clz(x) - 1;\n\n return k;\n\n}\n\n\n\nvoid stress(int tc) {\n\n \n\n}\n\nvoid solve(int tc) {\n\n int n, m;\n\n cin >> n >> m;\n\n int a[n+1];\n\n if(n == 1 || n == 2) {\n\n if(m == 0) {\n\n cout << \"2022 \"; \/\/!!!\n\n if(n == 2) cout << \"2023\\n\";\n\n return;\n\n }\n\n else {\n\n cout << \"-1\\n\"; \n\n return;\n\n }\n\n }\n\n a[0] = 1;\n\n a[1] = 1, a[2] = 2;\n\n for(int i=3; i<=n; i++) {\n\n int wow = (i+1) \/ 2 - 1;\n\n if(m >= wow) {\n\n m -= wow;\n\n a[i] = i;\n\n }\n\n else {\n\n int st = i+1;\n\n if(m > 0) a[i] = a[i-1] + a[i-m*2]; \n\n else st = i;\n\n m = 0;\n\n for(int j=st; j<=n; j++) {\n\n a[j] = 1000000000 - n * (4*n) + j * (4*n);\n\n }\n\n break;\n\n }\n\n }\n\n if(!m) {\n\n for(int i=1; i<=n; i++) cout << a[i] << \" \";\n\n cout << \"\\n\";\n\n }\n\n else {\n\n cout << \"-1\\n\";\n\n }\n\n}\n\nsigned main(){\n\n precomp(); \/\/Comment when not needed\n\n\/\/ ios::sync_with_stdio(0); cin.tie(0);\n\n int t = 1;\n\n\/\/ cin >> t;\n\n int cnt = 0;\n\n while(t--){\n\n stress(++cnt);\n\n solve(++cnt);\n\n }\n\n}","language":"cpp"} {"contest_id":"1312","problem_id":"G","statement":"G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s\u2208Ss\u2208S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1\u2264n\u22641061\u2264n\u2264106).Then nn lines follow, the ii-th line contains one integer pipi (0\u2264pi\n\n#define endl '\\n'\n\n#define iloveds std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);\n\n#define all(a) a.begin(),a.end()\n\nusing namespace std;\n\ntypedef long long ll ;\n\nconst int N = 1e6 + 100;\n\n\n\nint n, ch[N][26], k, a[N], b[N], dfn[N], ans[N], f[N];\n\nint tot, dp[N], val;\n\n\n\nvoid dfs(int x){\n\n\tif(f[x]) {\n\n\t\tdfn[x] = ++ tot;\n\n\t}\n\n\tfor(int i = 0 ; i < 26; i ++){\n\n\t\tif(ch[x][i]){\n\n\t\t\tdfs(ch[x][i]);\n\n\t\t\tdfn[x] = min(dfn[x], dfn[ch[x][i]]);\n\n\t\t}\n\n\t}\n\n}\n\n\n\nvoid dfs2(int x){\t\n\n\tfor(int i = 0 ; i < 26; i ++){\n\n\t\tint tmp = val;\n\n\t\tint u = ch[x][i];\n\n\t\tif(u) {\n\n\t\t\tif(f[u]){\n\n\t\t\t\tdp[u] = min(dp[x] + 1, dfn[u] + val);\n\n\t\t\t}else{\n\n\t\t\t\tdp[u] = dp[x] + 1;\n\n\t\t\t}\n\n\t\t\tval = min(val, dp[u] - dfn[u] + 1);\n\n\t\t\tdfs2(ch[x][i]);\n\n\t\t}\n\n\t\tval = tmp;\n\n\t}\n\n\n\n}\n\n\n\nint main(){\n\n\tiloveds;\n\n\tcin >> n;\n\n\tfor(int i = 1; i <= n ; i ++){\n\n\t\tint x;\n\n\t\tchar c;\n\n\t\tcin >> x >> c;\n\n\t\tch[x][c - 'a'] = i;\n\n\t}\n\n\tcin >> k;\n\n\tfor(int i = 1; i <= k ; i ++){\n\n\t\tcin >> a[i];\n\n\t\tf[a[i]] = 1;\n\n\t}\n\n\tfor(int i = 1; i <= n ; i ++) {\n\n\t\tdp[i] = 0x3f3f3f3f;\n\n\t\tdfn[i] = 0x3f3f3f3f;\n\n\t}\n\n\tdfs(0);\n\n\tval = 0;\n\n\tdfs2(0);\n\n\tfor(int i = 1; i <= k ; i ++) cout << dp[a[i]] << \" \";\n\n}","language":"cpp"} {"contest_id":"1305","problem_id":"C","statement":"C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,\u2026,ana1,a2,\u2026,an. Help Kuroni to calculate \u220f1\u2264i\n\n#include \n\n#include\n\n#include\n\nusing namespace std;\n\nusing namespace __gnu_pbds;\n\n#define GET(n, i) (((n) >> (i)) bitand 1)\n\n#define LAST(n) ((n) bitand (-(n)))\n\n#define RANGE(x, y, i, j) (i > -1 and i < x and j > -1 and j < y)\n\n#define SET(x, k) (x | (1LL << k))\n\n#define CLEAR(x, k) (x bitand ~ (1LL << k))\n\n#define CHECK(x, k) (x bitand (1LL << k))\n\n#define TOGGLE(x, k) (x ^ (1LL << k))\n\nusing LL = int64_t;\n\nLL dx [] = {0, 1, 0, -1};\n\nLL dy [] = {1, 0, -1, 0};\n\nLL dxx [] = {0, 1, 0, -1, 1, 1, -1, -1};\n\nLL dyy [] = {1, 0, -1, 0, 1, -1, 1, -1};\n\nconst LL mod = 1000000007;\n\n#define ordered_set tree, rb_tree_tag, tree_order_statistics_node_update>\n\n__gnu_cxx::sfmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nconst LL MAX = 1000;\n\nvector fre(MAX, 0);\n\nint main(void) {\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(0); cout.tie(0);\n\n srand(chrono :: high_resolution_clock :: now().time_since_epoch().count());\n\n LL T = 1; \n\n for (LL qq = 0; qq < T; qq++) {\n\n LL n, m;\n\n cin >> n >> m;\n\n vector a(n, 0), b;\n\n unordered_set ss, bb;\n\n for (LL k = 0; k < n; k++) {\n\n cin >> a[k];\n\n ss.insert(a[k]);\n\n }\n\n if (ss.size() < n or n > m) {\n\n cout << 0;\n\n cout << '\\n';\n\n exit(0);\n\n }\n\n LL res = 1LL;\n\n for (LL k = 0; k < n; k++) {\n\n for (LL j = k + 1; j < n; j++) {\n\n res = res * (abs(a[k] - a[j]));\n\n res = res % m;\n\n }\n\n }\n\n cout << res << '\\n';\n\n exit(0);\n\n }\n\n return 0;\n\n}\n\n","language":"cpp"} {"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\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#include\n\n#else\n\n#include\n\n#endif\n\nusing namespace std;\n\n#ifdef zcz\n\nclass fastin{\n\n\tprivate:\n\n#ifdef poj\n\n\tstatic const int MAXBF=1<<20;\n\n#else\n\n\tconst int MAXBF=1<<27;\n\n#endif\n\n\tFILE *inf;\n\n\tchar *inbuf,*inst,*ined;\n\n\tinline char _getchar(){\n\n\t\tif(inst==ined)inst=inbuf,ined=inbuf+fread(inbuf,1,MAXBF,inf);\n\n\t\treturn inst==ined?EOF:*inst++;\n\n\t}\n\n\tpublic:\n\n\tfastin(FILE*_inf=stdin){\n\n\t\tinbuf=new char[MAXBF],inf=_inf,inst=inbuf,ined=inbuf;\n\n\t}\n\n\t~fastin(){delete inbuf;}\n\n\ttemplate fastin&operator>>(Int &n){\n\n\t\tstatic char c;\n\n\t\tInt t=1;\n\n\t\twhile((c=_getchar())<'0'||c>'9')if(c=='-')t=-1;\n\n\t\tn=(c^48);\n\n\t\twhile((c=_getchar())>='0'&&c<='9')n=(n<<3)+(n<<1)+(c^48);\n\n\t\tn*=t;\n\n\t\treturn*this;\n\n\t}\n\n\tfastin&operator>>(char*s){\n\n\t\tint t=0;\n\n\t\tstatic char c;\n\n\t\twhile((c=_getchar())!=' '&&c!='\\n')s[t++]=c;\n\n\t\ts[t]='\\0';\n\n\t\treturn *this;\n\n\t}\n\n}fi;\n\nclass fastout{\n\n\tprivate:\n\n#ifdef poj\n\n\tstatic const int MAXBF=1<<20;\n\n#else\n\n\tconst int MAXBF=1<<27;\n\n#endif\n\n\tFILE *ouf;\n\n\tchar *oubuf,*oust,*oued;\n\n\tinline void _flush(){fwrite(oubuf,1,oued-oust,ouf);}\n\n\tinline void _putchar(char c){\n\n\t\tif(oued==oust+MAXBF)_flush(),oued=oubuf;\n\n\t\t*oued++=c;\n\n\t}\n\n\tpublic:\n\n\tfastout(FILE*_ouf=stdout){\n\n\t\toubuf=new char[MAXBF],ouf=_ouf,oust=oubuf,oued=oubuf;\n\n\t}\n\n\t~fastout(){_flush();delete oubuf;}\n\n\ttemplate fastout&operator<<(Int n){\n\n\t\tif(n<0)_putchar('-'),n=-n;\n\n\t\tstatic char S[20];\n\n\t\tint t=0;\n\n\t\tdo{S[t++]='0'+n%10,n\/=10;}while(n);\n\n\t\tfor(int i=0;i\n\n#define next ___\n\nint n,t;\n\nchar s[60];\n\nvoid solve1(){\n\n\tint x;\n\n\tcout<<\"? CH\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1;i<=t;i++)cin>>x,s[x-1]='C',s[x]='H';\n\n\tcout<<\"? CO\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1;i<=t;i++)cin>>x,s[x-1]='C',s[x]='O';\n\n\tcout<<\"? CC\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]='C';\n\n\tif(s[0]=='C'){\n\n\t\tif(s[2]=='C'){\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1;i<=t;i++)cin>>x,s[x-1]='H',s[x]='O';\n\n\tif(s[0]=='H'){\n\n\t\tif(s[2]=='H'){\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1){\n\n\t\t\tcin>>x;\n\n\t\t\tcout<<\"! \"<>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]='O';\n\n\tif(s[0]=='O'&&s[1]=='O'){\n\n\t\tif(s[3]=='O'){\n\n\t\t\tcout<<\"! \"<>t;\n\n\t\t\t\tassert(t!=-1);\n\n\t\t\t\tif(t==1){\n\n\t\t\t\t\tcin>>x;\n\n\t\t\t\t\tcout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1){\n\n\t\t\t\tcin>>x;\n\n\t\t\t\tcout<<\"! \"<>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1;i<=t;i++)cin>>x,s[x-1]=s[x]=s[x+1]='H';\n\n\tif(s[0]==0)s[0]='O';\n\n\tif(s[3]==0)s[3]='C';\n\n\tcout<<\"! \"<>n;\n\n\tfill(s,s+n+1,0);\n\n\tif(n==4){\n\n\t\tsolve1();\n\n\t\tgoto label;\n\n\t}\n\n\tcout<<\"? CH\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1,x;i<=t;i++)cin>>x,s[x-1]='C',s[x]='H';\n\n\tcout<<\"? CO\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1,x;i<=t;i++)cin>>x,s[x-1]='C',s[x]='O';\n\n\tcout<<\"? CC\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1,x;i<=t;i++)cin>>x,s[x-1]=s[x]='C';\n\n\tcout<<\"? HO\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1,x;i<=t;i++)cin>>x,s[x-1]='H',s[x]='O';\n\n\tcout<<\"? OO\\n\";\n\n\tcout.flush();\n\n\tcin>>t;\n\n\tassert(t!=-1);\n\n\tfor(int i=1,x;i<=t;i++)cin>>x,s[x-1]=s[x]='O';\n\n\tfor(int i=1;i>t;\n\n\t\tassert(t!=-1);\n\n\t\tint x;\n\n\t\tif(t==1)cin>>x;\n\n\t\telse s[n-1]='C';\n\n\t\tcout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tint x;\n\n\t\tif(t==1)cin>>x;\n\n\t\telse s[0]='O';\n\n\t\tcout<<\"! \"<>t;\n\n\tassert(t!=-1);\n\n\tint x;\n\n\tif(t==1)cin>>x,cout<<\"! \"<>t;\n\n\t\tassert(t!=-1);\n\n\t\tif(t==1)cin>>x,cout<<\"! \"<>t;\n\n\t\t\tassert(t!=-1);\n\n\t\t\tif(t==1)cin>>x,cout<<\"! \"<>x;\n\n\tassert(x==1);\n\n\treturn;\n\n}\n\nint main(){\n\n\t#ifndef zcz\n\n\/\/\tczc;\n\n\t#endif\n\n\tint t=1;\n\n\tcin>>t;\n\n\twhile(t--)solve();\n\n\treturn 0;\n\n}\n\n\/*\n\nOCCCCHHHOOHHOHCOHCCOCCCHCOHHCOCC\n\n 11111111112222222222333\n\n12345678901234567890123456789012\n\nCH:2 5 23\n\nCO:4 15 19 25 29\n\nCC:6 2 4 18 21 22 31\n\nHO:2 8 12\n\nOO:1 9\n\n*\/","language":"cpp"} {"contest_id":"1311","problem_id":"D","statement":"D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a\u2264b\u2264ca\u2264b\u2264c.In one move, you can add +1+1 or \u22121\u22121 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1\u2264t\u22641001\u2264t\u2264100) \u2014 the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1\u2264a\u2264b\u2264c\u22641041\u2264a\u2264b\u2264c\u2264104).OutputFor each test case, print the answer. In the first line print resres \u2014 the minimum number of operations you have to perform to obtain three integers A\u2264B\u2264CA\u2264B\u2264C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8\n1 2 3\n123 321 456\n5 10 15\n15 18 21\n100 100 101\n1 22 29\n3 19 38\n6 30 46\nOutputCopy1\n1 1 3\n102\n114 228 456\n4\n4 8 16\n6\n18 18 18\n1\n100 100 100\n7\n1 22 22\n2\n1 19 38\n8\n6 24 48\n","tags":["brute force","math"],"code":"#include \n\n\n\nusing namespace std;\n\n\n\nint main() {\n\n#ifdef _DEBUG\n\n\tfreopen(\"input.txt\", \"r\", stdin);\n\n\/\/\tfreopen(\"output.txt\", \"w\", stdout);\n\n#endif\n\n\t\n\n\tint t;\n\n\tcin >> t;\n\n\twhile (t--) {\n\n\t\tint a, b, c;\n\n\t\tcin >> a >> b >> c;\n\n\t\tint ans = 1e9;\n\n\t\tint A = -1, B = -1, C = -1;\n\n\t\tfor (int cA = 1; cA <= 2 * a; ++cA) {\n\n\t\t\tfor (int cB = cA; cB <= 2 * b; cB += cA) {\n\n\t\t\t\tfor (int i = 0; i < 2; ++i) {\n\n\t\t\t\t\tint cC = cB * (c \/ cB) + i * cB;\n\n\t\t\t\t\tint res = abs(cA - a) + abs(cB - b) + abs(cC - c);\n\n\t\t\t\t\tif (ans > res) {\n\n\t\t\t\t\t\tans = res;\n\n\t\t\t\t\t\tA = cA;\n\n\t\t\t\t\t\tB = cB;\n\n\t\t\t\t\t\tC = cC;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tcout << ans << endl << A << \" \" << B << \" \" << C << endl;\n\n\t}\n\n\t\n\n\treturn 0;\n\n}","language":"cpp"} {"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":"#include\n\n#define ll long long\n\n#define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint)\n\n#define all(a) (a).begin() , (a).end()\n\n#define pb push_back\n\n#define mp make_pair\n\n#define pii pair\n\n#define pll pair\n\n#define piii pair\n\n#define plll pair\n\n#define R return\n\n#define B break\n\n#define C continue\n\n#define SET(n , i) memset(n , i , sizeof(n))\n\n#define SD ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)\n\n#define rep(i , n) for(int i = 0 ; i < n ; i++)\n\n#define repn(i , j , n) for(int i = j ; i < n ; i++)\n\n#define repr(i,n,j) for(int i=n;i>=j;i--)\n\n#define positive(x) ((x%mod+mod)%mod)\n\n#define YES(f)cout<<((f)?\"YES\":\"NO\")<\n\n\/\/#define int ll\n\nusing namespace std;\n\nvoid readFromFile(string input = \"input.txt\",string output=\"output.txt\") {\n\n #ifndef ONLINE_JUDGE\n\n freopen(input.c_str(),\"r\",stdin);\n\n freopen(output.c_str(),\"w\",stdout);\n\n #endif\n\n}\n\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nll rnd(ll x, ll y) {\n\n return uniform_int_distribution(x, y)(rng);\n\n}\n\ntemplate void Max(T& x,T y){x=max(x,y);}\n\ntemplate void Min(T& x,T y){x=min(x,y);}\n\nconst int INF = 0x3f3f3f3f;\n\nconst ll INFLL = 0x3f3f3f3f3f3f3f3f;\n\nconst long double EPS = 1e-3;\n\nconst long double pi = acos(-1.0);\n\nconst int mod = 998244353;\n\nconst int N =2e3+3;\n\nll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;}\n\nll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;}\n\nint n,a[N];\n\nvoid solve() {\n\n cin >> n;\n\n rep(i,n)cin >> a[i];\n\n map> ma;\n\n rep(i,n) {\n\n int sum=0;\n\n repn(j,i,n) {\n\n sum += a[j];\n\n ma[sum].pb({j,i});\n\n }\n\n }\n\n int ans=-1,sum=-1;\n\n for(auto &it:ma) {\n\n sort(all(it.S));\n\n int prv=-1,cot=0;\n\n for(auto &x:it.S) {\n\n if(x.S > prv) {\n\n cot++;\n\n prv=x.F;\n\n }\n\n }\n\n if(cot > ans) {\n\n ans = cot;\n\n sum=it.F;\n\n }\n\n }\n\n int prv=-1;\n\n vector v;\n\n for(auto &x:ma[sum]) {\n\n if(x.S > prv) {\n\n v.pb({x.S,x.F});\n\n prv=x.F;\n\n }\n\n }\n\n cout << v.size() << endl;\n\n for(auto [l,r]:v)cout<> t;\n\n\/\/ scanf(\"%d\",&t);\n\n rep(i,t) {\n\n solve();\n\n }\n\n}\n\n","language":"cpp"} {"contest_id":"13","problem_id":"D","statement":"D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0\u2009\u2264\u2009N\u2009\u2264\u2009500; 0\u2009\u2264\u2009M\u2009\u2264\u2009500) \u2014 the number of red and blue points respectively. The following N lines contain two integer numbers each \u2014 coordinates of red points. The following M lines contain two integer numbers each \u2014 coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer \u2014 the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7","tags":["dp","geometry"],"code":"#include\n\nusing namespace std;\n\ninline int read(){\n\n\tint x=0,f=1;char ch=getchar();\n\n\twhile(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}\n\n\twhile(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}\n\n\treturn x*f;\n\n}\n\nconst int N=1e3+5;int f[N][N];\n\nstruct node{long long x,y;}a[N],b[N];\n\nbool cmp(node x,node y){return x.yb.y) return 0;\n\n return area(a,b,c)>0;\n\n}\n\nint n,m;\n\nint main(){\n\n\tcin>>n>>m;\n\n for(int i=1;i<=n;++i) scanf(\"%lld%lld\",&a[i].x,&a[i].y);\n\n for(int i=1;i<=m;++i) scanf(\"%lld%lld\",&b[i].x,&b[i].y);\n\n sort(a+1,a+n+1,cmp);\n\n\tint ans=0;\n\n for(int i=1;i\n\n#define int long long\n\n#define repp(n) for(int i=0;i>n;\n\n n*=2;\n\n int a[n+1];repp(n)cin>>a[i+1];\n\n a[0]=0;\n\n sort(a,a+n+1);\n\n\n\n int ans=mod;\n\n for(int i=1;ii && j>t;while(t--)\n\n solve();\n\n return 0;\n\n}\n\n","language":"cpp"} {"contest_id":"1304","problem_id":"D","statement":"D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog\u2061n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n\u22121n\u22121, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n\u22121n\u22121.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2\u22c51052\u22c5105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3\n3 <<\n7 >><>><\n5 >>><\nOutputCopy1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3\nNoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.","tags":["constructive algorithms","graphs","greedy","two pointers"],"code":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#ifdef imtiyazrasool92\n#include \"algos\/debug.h\"\n#else\n#define dbg(...) 92\n#endif\n\nvoid run_case() {\n int N; string S;\n cin >> N >> S;\n\n vector A(N);\n vector B(N);\n\n iota(A.begin(), A.end(), 1);\n iota(B.begin(), B.end(), 1);\n\n reverse(A.begin(), A.end());\n\n for (int i = 0; i < N - 1;) {\n int end = i;\n while (end + 1 < N - 1 && S[end] == S[end + 1])\n end++;\n\n if (S[i] == '<')\n reverse(A.begin() + i, A.begin() + end + 2);\n else\n reverse(B.begin() + i, B.begin() + end + 2);\n\n i = end + 1;\n }\n\n for (auto &a : A)\n cout << a << ' ';\n\n cout << '\\n';\n for (auto &b : B)\n cout << b << ' ';\n}\n\nint32_t main() {\n ios::sync_with_stdio(false);\n#ifndef imtiyazrasool92\n cin.tie(nullptr);\n#endif\n\n int tests = 1;\n cin >> tests;\n\n while (tests--) {\n run_case();\n cout << '\\n';\n }\n\n return 0;\n}","language":"cpp"} {"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":"\/\/ LUOGU_RID: 97950406\n\/\/Writer: HugeWide\n\n#include\n\nusing namespace std;\n\n\n\ntypedef long long ll;\n\ntypedef double db;\n\n\n\ninline ll read() {\n\n\tll x=0,f=1;\n\n\tchar ch=getchar();\n\n\twhile(ch<'0'||ch>'9') {\n\n\t\tif(ch=='-') f=-f;\n\n\t\tch=getchar();\n\n\t}\n\n\twhile(ch>='0'&&ch<='9') {\n\n\t\tx=(x<<3)+(x<<1)+ch-'0';\n\n\t\tch=getchar();\n\n\t}\n\n\treturn x*f;\n\n}\n\ninline void write(ll x) {\n\n\tif(x<0) putchar('-'),x=-x;\n\n\tif(x>=10) write(x\/10);\n\n\tputchar(x%10+'0');\n\n}\n\n#define writesp(x) write(x),putchar(' ')\n\n#define writeln(x) write(x),putchar('\\n')\n\n\n\n#define rep(x,l,r) for(int x=l;x<=r;x++)\n\n#define per(x,r,l) for(int x=r;x>=l;x--)\n\n#define pb push_back\n\n#define mp make_pair\n\n#define all(v) v.begin(),v.end()\n\n\n\nconst int N=200200;\n\n\n\nint n,m,k;\n\nint l[N],r[N];\n\nvector raw;\n\n\n\nint f[N][300];\n\nvector v[N];\n\nbool vis[N];\n\n\n\nint ppc(int s) {\n\n\tint r=0;\n\n\twhile(s) {\n\n\t\tif(s&1) r++; s>>=1;\n\n\t} return r;\n\n}\n\n\n\nint g[300];\n\n\n\nint main() {\n\n\tn=read(),m=read(),k=read();\n\n\trep(i,1,n) l[i]=read()-1,r[i]=read();\n\n\trep(i,1,n) raw.pb(l[i]),raw.pb(r[i]); raw.pb(-1e9);\n\n\tsort(all(raw)),raw.erase(unique(all(raw)),raw.end());\n\n\trep(i,1,n) {\n\n\t\tl[i]=lower_bound(all(raw),l[i])-raw.begin();\n\n\t\tr[i]=lower_bound(all(raw),r[i])-raw.begin();\n\n\t}\n\n\tint T=(int)raw.size()-1;\n\n\trep(i,1,n) {\n\n\t\trep(j,l[i]+1,r[i]) v[j].pb(i);\n\n\t}\n\n\trep(i,1,T) {\n\n\t\tint sz=v[i].size(),_sz=v[i-1].size();\n\n\t\tvector d; d.clear(); int s=0;\n\n\t\trep(j,0,sz-1) if(l[v[i][j]]+1==i) d.pb(j); int ds=d.size();\n\n\t\trep(j,0,_sz-1) if(r[v[i-1][j]]!=i-1) s|=1<>y)&1;\n\n\t\t\trep(y,0,ds-1) vis[v[i][d[y]]]=(x>>y)&1;\n\n\t\t\tint ss=0;\n\n\t\t\trep(y,0,sz-1) if(vis[v[i][y]]) ss|=1<\n\n#include \n\n#include \n\n\n\n#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\n#define ll long long\n\n#define ld long double\n\n#define el \"\\n\"\n\n#define matrix vector>\n\n#define pt complex\n\n#define ordered_set tree, rb_tree_tag,tree_order_statistics_node_update>\n\n#define ordered_multiset tree, rb_tree_tag, tree_order_statistics_node_update>\n\nusing namespace __gnu_pbds;\n\nusing namespace std;\n\nconst ll N = 2e5 + 7, LOG = 20;\n\nconst ld pi = acos(-1);\n\nconst ll mod = 1e9 + 7;\n\nint dx[] = {0, -1, 0, 1, -1, 1, -1, 1};\n\nint dy[] = {-1, 0, 1, 0, 1, -1, -1, 1};\n\nll n, m, k, x, y;\n\nint a[N];\n\n\n\nvoid dowork() {\n\n cin >> n;\n\n set st;\n\n for (int i = 1; i < n; i++) {\n\n cin >> a[i];\n\n st.insert(i);\n\n }\n\n st.insert(n);\n\n int sum = 0;\n\n for (int i = 1; i < n; i++) {\n\n sum += a[i];\n\n while (st.size() && sum + *st.rbegin() > n) {\n\n st.erase(prev(st.end()));\n\n }\n\n while (st.size() && sum + *st.begin() < 1) {\n\n st.erase(st.begin());\n\n }\n\n }\n\n if (st.size() == 0) {\n\n cout << -1 << el;\n\n return;\n\n }\n\n vector ans;\n\n ans.push_back(*st.begin());\n\n st.clear();\n\n st.insert(ans.back());\n\n for (int i = 1; i < n; i++) {\n\n st.insert(ans.back() + a[i]);\n\n ans.push_back(ans.back() + a[i]);\n\n }\n\n if (st.size() != n || *st.rbegin() > n || *st.begin() < 1) {\n\n cout << -1 << el;\n\n return;\n\n }\n\n for (auto j: ans) {\n\n cout << j << \" \";\n\n }\n\n cout << el;\n\n}\n\n\n\nint main() {\n\n fast\n\n \/\/freopen(\"cowland.in\", \"r\", stdin);\n\n \/\/freopen(\"cowland.out\", \"w\", stdout);\n\n int t = 1;\n\n \/\/cin >> t;\n\n for (int i = 1; i <= t; i++) {\n\n dowork();\n\n }\n\n}","language":"cpp"} {"contest_id":"1316","problem_id":"E","statement":"E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him\u00a0\u2014 the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j \u00a0\u2014 the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2\u2264n\u2264105,1\u2264p\u22647,1\u2264k,p+k\u2264n2\u2264n\u2264105,1\u2264p\u22647,1\u2264k,p+k\u2264n).The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an. (1\u2264ai\u22641091\u2264ai\u2264109).The ii-th of the next nn lines contains pp integers si,1,si,2,\u2026,si,psi,1,si,2,\u2026,si,p. (1\u2264si,j\u22641091\u2264si,j\u2264109)OutputPrint a single integer resres \u00a0\u2014 the maximum possible strength of the club.ExamplesInputCopy4 1 2\n1 16 10 3\n18\n19\n13\n15\nOutputCopy44\nInputCopy6 2 3\n78 93 9 17 13 78\n80 97\n30 52\n26 17\n56 68\n60 36\n84 55\nOutputCopy377\nInputCopy3 2 1\n500 498 564\n100002 3\n422332 2\n232323 1\nOutputCopy422899\nNoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.","tags":["bitmasks","dp","greedy","sortings"],"code":"#include \n#include \n#include \n#include \n#define all(v) v.begin() ,v.end()\n#define ll long long\nusing namespace std ;\nll dp[100005][(1<<7)+5] ;\nvector>all ;\nint n, p , k ;\nint s[100005][7] ;\n\nll solve (int idx , int msk){\n int cnt = idx-__builtin_popcount(msk) ;\n ll &ans = dp[idx][msk] ;\n\n if (idx==n){\n if (msk==((1<>n >>p>>k ;\n for (int i =0 ; i >x;\n all.push_back({x,i}) ;\n }\n sort(all(all)) ;\n reverse(all(all)) ;\n for (int i =0 ; i < n ; i++){\n for (int j =0 ; j < p ; j++){\n cin >>s[i][j] ;\n }\n }\n memset(dp,-1 , sizeof dp) ;\n cout <>t;\n while (t--)acc() ;\n\n}\n\t\t \t \t\t\t \t \t \t \t\t\t\t \t\t\t \t\t\t\t \t","language":"cpp"} {"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":"#include \n\nusing namespace std;\n\n\n\n#define ll long long\n\n\n\nint main() {\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(0);\n\n int t;\n\n cin >> t;\n\n while (t--) {\n\n unordered_set ue;\n\n int n;\n\n cin >> n;\n\n while (n--) {\n\n int v;\n\n cin >> v;\n\n ue.insert(v);\n\n }\n\n cout << ue.size() << \"\\n\";\n\n }\n\n}\n\n","language":"cpp"} {"contest_id":"1284","problem_id":"G","statement":"G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n\u00d7mn\u00d7m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either \"black\" or \"white\". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1\u2264t\u22641001\u2264t\u2264100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2\u2264n,m\u2264202\u2264n,m\u226420), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t\u22652t\u22652 is satisfied, then the size of the grid will satisfy n\u226410,m\u226410n\u226410,m\u226410. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n\u22121)\u00d7(2m\u22121)(2n\u22121)\u00d7(2m\u22121) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1\u2264i\u2264n,1\u2264j\u2264m1\u2264i\u2264n,1\u2264j\u2264m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). Otherwise, print 'X' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). For all 1\u2264i\u2264n,1\u2264j\u2264m\u221211\u2264i\u2264n,1\u2264j\u2264m\u22121, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i\u22121,2j)(2i\u22121,2j). Otherwise, print any printable character except spaces in the cell (2i\u22121,2j)(2i\u22121,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m1\u2264i\u2264n\u22121,1\u2264j\u2264m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print '\u00a0' in the cell (2i,2j\u22121)(2i,2j\u22121). Otherwise, print any printable character except spaces in the cell (2i,2j\u22121)(2i,2j\u22121) For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m\u221211\u2264i\u2264n\u22121,1\u2264j\u2264m\u22121, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m\u221212m\u22121 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4\n2 2\nOO\nOO\n3 3\nOOO\nXOO\nOOO\n4 4\nOOOX\nXOOX\nOOXO\nOOOO\n5 6\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOutputCopyYES\nOOO\n O\nOOO\nNO\nYES\nOOOOO X\n O O \nX O O X\n O \nOOO X O\nO O O\nO OOOOO\nYES\nOOOOOOOOOOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n","tags":["graphs"],"code":"#include\n\nusing namespace std;\n\ntypedef long long LL;\n\ntypedef unsigned long long uLL;\n\ntypedef pair pii;\n\n#define MAXN 100005\n\n#define pb push_back\n\n#define mkpr make_pair\n\n#define fir first\n\n#define sec second\n\n#define lson (rt<<1)\n\n#define rson (rt<<1|1)\n\n#define lowbit(x) (x&-x)\n\nconst int mo=998244353;\n\nconst int inv2=5e8+4;\n\nconst int jzm=2333;\n\nconst int zero=15;\n\nconst int INF=0x3f3f3f3f;\n\nconst double Pi=acos(-1.0);\n\nconst double eps=1e-9;\n\nconst int orG=3,ivG=332748118;\n\ntemplate\n\n_T Fabs(_T x){return x<0?-x:x;}\n\ntemplate\n\nvoid read(_T &x){\n\n _T f=1;x=0;char s=getchar();\n\n while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}\n\n while('0'<=s&&s<='9'){x=(x<<3)+(x<<1)+(s^48);s=getchar();}\n\n x*=f;\n\n}\n\nint add(int x,int y,int p){return x+y>=1;}return t;}\n\nint n,m,TT,id[25][25],idx,col[405],cnt,head[1005],tot;\n\nint dis[1005],cntp,S,T,deg[405],fa[405],pre[405];\n\nchar maze[25][25],ans[45][45];bool used[1005],lk[405],answered[105];queueq;\n\nstruct ming{int u,v,x,y;}s[1005];\n\nstruct edge{int to,nxt;}e[MAXN*10];\n\nvoid addEdge(int u,int v){e[++tot]=(edge){v,head[u]};head[u]=tot;}\n\nvoid makeSet(int x){for(int i=1;i<=x;i++)fa[i]=i;}\n\nint findSet(int x){return x==fa[x]?x:fa[x]=findSet(fa[x]);}\n\nvoid unionSet(int x,int y){int u=findSet(x),v=findSet(y);if(fa[u]^v)fa[u]=v;}\n\nint main(){\n\n read(TT);int allTT=TT;\n\n while(TT--){\n\n read(n);read(m);\n\n for(int i=1;i<=n;i++)scanf(\"%s\",maze[i]+1);\n\n for(int i=1;i<=n;i++)\n\n for(int j=1;j<=m;j++)\n\n if(maze[i][j]=='O')\n\n id[i][j]=++idx,col[idx]=(i+j)&1;\n\n for(int i=1;i<=n;i++)\n\n for(int j=1;j<=m;j++){\n\n if(id[i][j]&&id[i][j+1])\n\n s[++cntp]=(ming){id[i][j],id[i][j+1],i+i-1,j+j};\n\n if(id[i][j]&&id[i+1][j])\n\n s[++cntp]=(ming){id[i][j],id[i+1][j],i+i,j+j-1};\n\n }\n\n cnt=cntp;S=++cnt;T=++cnt;\n\n \/\/puts(\"over init\");\n\n while(1){\n\n \/\/puts(\"extending\");\n\n for(int i=1;i<=cnt;i++)head[i]=0;tot=0;\n\n for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);\n\n for(int i=1;i<=cntp;i++)if(used[i])\n\n unionSet(s[i].u,s[i].v),deg[s[i].u]++,deg[s[i].v]++;\n\n for(int i=1;i<=cntp;i++)if(!used[i]){\n\n int u=s[i].u,v=s[i].v;if(findSet(u)!=findSet(v))addEdge(S,i);\n\n if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2)&&u!=1)addEdge(i,T);\n\n }\n\n for(int i=1;i<=cntp;i++)if(used[i]){\n\n makeSet(idx);deg[s[i].u]--;deg[s[i].v]--;\n\n for(int j=1;j<=cntp;j++)if(used[j]&&i!=j)unionSet(s[j].u,s[j].v);\n\n for(int j=1;j<=cntp;j++)if(!used[j]){\n\n int u=s[j].u,v=s[j].v;if(u==1)continue;\n\n if(findSet(u)!=findSet(v))addEdge(i,j);\n\n if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2))addEdge(j,i);\n\n }\n\n deg[s[i].u]++;deg[s[i].v]++;\n\n }\n\n \/\/puts(\"over graph building\");\n\n for(int i=1;i<=cnt;i++)dis[i]=pre[i]=0;dis[S]=1;\n\n while(!q.empty())q.pop();q.push(S);\n\n while(!q.empty()){\n\n int u=q.front();q.pop();\n\n for(int i=head[u];i;i=e[i].nxt){\n\n int v=e[i].to;if(dis[v])continue;\n\n q.push(v);dis[v]=dis[u]+1;pre[v]=u;\n\n }\n\n }\n\n \/\/puts(\"over bfs\");\n\n if(!dis[T])break;int now=pre[T];\n\n while(now^S)used[now]^=1,now=pre[now];\n\n }\n\n \/\/puts(\"over solve\");\n\n for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);\n\n for(int i=1;i<=cntp;i++)if(used[i])\n\n deg[s[i].u]++,deg[s[i].v]++,unionSet(s[i].u,s[i].v);\n\n \/\/printf(\"use edge %d %d\\n\",s[i].u,s[i].v);\n\n \/\/for(int i=1;i<=idx;i++)printf(\"%d \",col[i]);puts(\"\");\n\n \/\/for(int i=1;i<=idx;i++)printf(\"%d \",deg[i]);puts(\"\");\n\n bool flag=0;for(int i=2;i<=idx;i++)if(!col[i])flag|=(deg[i]<2);\n\n if(flag){\n\n \/\/if(allTT!=100||!answered[6]||answered[5]||answered[4])\n\n puts(\"NO\");\n\n \/\/else if(allTT-TT==87){\n\n \/\/ for(int i=1;i<=n;i++,puts(\"\"))\n\n \/\/ for(int j=1;j<=m;j++)\n\n \/\/ printf(\"%c\",maze[i][j]);\n\n \/\/}\n\n }\n\n else{\n\n for(int i=1;i\nusing namespace std;\n#define int long long\nint n, m, p;\nsigned main()\n{\ncin.sync_with_stdio(false);\ncin.tie(0);\ncin >> n >> m >> p;\nint a = -1, b = -1;\nfor(int x, i = 0; i < n; i++)\n{\ncin >> x;\nif(x % p && a == -1) a = i;\n}\nfor(int x, i = 0; i < m; i++)\n{\ncin >> x;\nif(x % p && b == -1) b = i;\n}\ncout << a + b;\nreturn 0;\n}\n","language":"cpp"} {"contest_id":"1310","problem_id":"D","statement":"D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i\u2260ji\u2260j. In total there are n(n\u22121)n(n\u22121) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2\u2264n\u226480;2\u2264k\u2264102\u2264n\u226480;2\u2264k\u226410): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i\u2260ji\u2260j, and is 0 otherwise (there are no routes i\u2192ii\u2192i). All route costs are integers from 00 to 108108.OutputOutput a single integer\u00a0\u2014 total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8\n0 1 2 2 0\n0 0 1 1 2\n0 1 0 0 0\n2 1 1 0 0\n2 0 1 2 0\nOutputCopy2\nInputCopy3 2\n0 1 1\n2 0 1\n2 2 0\nOutputCopy3\n","tags":["dp","graphs","probabilities"],"code":"#include \n\nusing namespace std;\n\n#define int long long\n\n#define mid ((l+r)>>1)\n\n#define mod (998244353)\n\n#define eps (1e-8)\n\n#define mk make_pair\n\n#define tim (double)clock()\/CLOCKS_PER_SEC\n\n#define For(i,a,b) for(int i=(a);i<=(b);++i)\n\n#define rep(i,a,b) for(int i=(a);i>=(b);--i)\n\ninline namespace IO{\n\n\tinline int read(){\n\n\t\tint x=0,f=1;char ch;\n\n\t\twhile((ch=getchar())<'0'||x>'9')if(ch=='-')f=-1;\n\n\t\twhile(ch>='0'&&ch<='9'){x=((x<<1)+(x<<3)+(ch^48)),ch=getchar();}\n\n\t\treturn x*f;\n\n\t}\n\n\tvoid write(char x){putchar(x);}\n\n\tvoid write(const char *x){for(;*x;++x)putchar(*x);}\n\n\tvoid write(char *x){for(;*x;++x)putchar(*x);}\n\n\tvoid write(signed x){\n\n\t\tif(x<0)putchar('-'),x=-x;\n\n\t\tif(x>9)write(x\/10); putchar('0'+x-x\/10*10);\n\n\t}\n\n\tvoid write(long long x){\n\n\t\tif(x<0)putchar('-'),x=-x;\n\n\t\tif(x>9)write(x\/10); putchar('0'+x-x\/10*10);\n\n\t}\n\n\tvoid write(unsigned long long x){\n\n\t\tif(x>9)write(x\/10);\n\n\t\tputchar('0'+x-x\/10*10);\n\n\t}\n\n\tvoid write(double x){printf(\"%0.9lf\",x);}\n\n\ttemplate\n\n\tvoid write(type1 a1,type2 a2,typen ...an){\n\n\t\twrite(a1);\n\n\t\twrite(a2,an...);\n\n\t}\n\n}using namespace IO;\n\ninline int gcd(int x,int y){return y==0?x:gcd(y,x%y);}\n\ninline int lcm(int x,int y){return x\/gcd(x,y)*y;}\n\ninline int lowbit(int x){return x&(-x);}\n\nmt19937 rnd(time(NULL)^clock());\n\ninline int rad(int x,int y){return rnd()%(y-x+1)+x;}\n\nconst int N=105;\n\nint n,k;\n\nint a[N][N];\n\nint c[N];\n\nint dis[N][12],vis[N][12];\n\nint ans=1e18;\n\nqueue> q;\n\ninline void spfa(int s){\n\n\twhile(!q.empty())q.pop();\n\n\tmemset(dis,0x3f,sizeof(dis));\n\n\tmemset(vis,0,sizeof(vis));\n\n\tq.push(mk(s,0)); vis[s][0]=1,dis[s][0]=0;\n\n\twhile(!q.empty()){\n\n\t\tint x=q.front().first,t=q.front().second; q.pop();\n\n\t\tvis[x][t]=0;\n\n\t\tif(t==k)continue;\n\n\t\tFor(y,1,n)if(c[x]!=c[y]&&y!=x){\n\n\t\t\tint w=a[x][y];\n\n\t\t\tif(t+1==k&&y==1)ans=min(ans,dis[x][t]+w);\n\n\t\t\tif(dis[y][t+1]>dis[x][t]+w){\n\n\t\t\t\tdis[y][t+1]=dis[x][t]+w;\n\n\t\t\t\tif(!vis[y][t+1]){vis[y][t+1]=1;q.push(mk(y,t+1));}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\nsigned main()\n\n{\n\n\tn=read(),k=read();\n\n\tFor(i,1,n)For(j,1,n)a[i][j]=read();\n\n\tFor(t,1,5000){\n\n\t\tFor(i,1,n)c[i]=rad(0,1);\n\n\t\tspfa(1);\n\n\t}\n\n\twrite(ans,'\\n');\n\n\treturn 0;\n\n}\n\n\/*\n\n*\/\n\n\n\n\n\n\n\n\n\n","language":"cpp"} {"contest_id":"1316","problem_id":"F","statement":"F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn officers in the Army of Byteland. Each officer has some power associated with him. The power of the ii-th officer is denoted by pipi. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these nn officers and calls this subset a battalion.(All 2n2n subsets of the nn officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a1,a2,\u2026,aka1,a2,\u2026,ak, where a1\u2264a2\u2264\u22ef\u2264aka1\u2264a2\u2264\u22ef\u2264ak. The strength of this battalion is equal to a1a2+a2a3+\u22ef+ak\u22121aka1a2+a2a3+\u22ef+ak\u22121ak. (If the size of Battalion is \u22641\u22641, then the strength of this battalion is 00).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be qq changes. Each one of the form ii xx indicating that pipi is changed to xx.You need to find the strength of the army initially and after each of these qq updates.Note that the changes are permanent.The strength should be found by modulo 109+7109+7. Formally, let M=109+7M=109+7. It can be shown that the answer can be expressed as an irreducible fraction p\/qp\/q, where pp and qq are integers and q\u2261\u03380modMq\u22620modM). Output the integer equal to p\u22c5q\u22121modMp\u22c5q\u22121modM. In other words, output such an integer xx that 0\u2264x\n\n#define f first\n\n#define s second\n\n#define int long long\n\n#define pii pair\n\nusing namespace std;\n\nconst int N = 6e5 + 5, mod = 1e9 + 7; \/\/ !\n\nint pos[N], a[N], P[N];\n\nvector> x;\n\npair p[N];\n\nstruct node {\n\n int c, pr, sf, ans;\n\n} t[4 * N];\n\nnode merge(node a, node b) {\n\n node c;\n\n c.c = a.c + b.c;\n\n c.pr = (a.pr + b.pr * P[a.c]) % mod;\n\n c.sf = (b.sf + a.sf * P[b.c]) % mod;\n\n c.ans = (a.ans * P[b.c] % mod + b.ans * P[a.c] % mod + a.pr * b.sf % mod) % mod;\n\n return c;\n\n}\n\nvoid upd(int u, int id, int l, int r) {\n\n if(l > id || r < id) return;\n\n if(l == r) {\n\n t[u].c ^= 1;\n\n t[u].pr = t[u].sf = pos[l * t[u].c];\n\n return;\n\n }\n\n int mid = (l + r) \/ 2;\n\n upd(2 * u, id, l, mid); upd(2 * u + 1, id, mid + 1, r);\n\n t[u] = merge(t[2 * u], t[2 * u + 1]);\n\n}\n\nint ID(int a, int b) {\n\n return (lower_bound(x.begin(), x.end(), make_pair(a, b)) - x.begin() + 1);\n\n}\n\nint pwr(int u, int v) {\n\n int ans = 1;\n\n while(v) {\n\n if(v % 2) ans = ans * u % mod;\n\n v \/= 2;\n\n u = u * u % mod;\n\n }\n\n return ans;\n\n}\n\nmain(){\n\n int n;\n\n cin >> n; P[0] = 1;\n\n for(int i = 1; i <= n; i++) cin >> a[i], P[i] = P[i - 1] * 2 % mod, x.push_back({a[i], i});\n\n int q; cin >> q;\n\n\n\n for(int i = 1; i <= q; i++) {\n\n cin >> p[i].f >> p[i].s;\n\n x.push_back({p[i].s, p[i].f});\n\n\/\/ P[i] = P[i - 1] * 2 % mod;\n\n }\n\n sort(x.begin(), x.end());\n\n x.erase(unique(x.begin(), x.end()), x.end());\n\n for(int i = 0; i < x.size(); i++) pos[i + 1] = x[i].f;\n\n for(int i = 1; i <= n; i++) {\n\n\/\/ cout << ID(a[i], i) << \" _ \" << pos[ID(a[i], i)]<< endl;\n\n upd(1, ID(a[i], i), 1, (int)x.size());\n\n\/\/ cout << t[1].ans << endl;\n\n }\n\n int D = pwr(P[n], mod - 2);\n\n cout << t[1].ans * D % mod << \"\\n\";\n\n for(int i = 1; i <= q; i++) {\n\n upd(1, ID(a[p[i].f], p[i].f), 1, x.size());\n\n a[p[i].f] = p[i].s;\n\n upd(1, ID(a[p[i].f], p[i].f), 1, x.size());\n\n\n\n cout << t[1].ans * D % mod << \"\\n\";\n\n }\n\n }\n\n","language":"cpp"} {"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":"#include \n\nusing namespace std;\n\n\n\nint main(){\n\n int n;\n\n cin >> n;\n\n while(n--){\n\n int a;\n\n cin >> a;\n\n int sisa=0;\n\n int ans=0;\n\n while((a+sisa)>=10){\n\n sisa=a\/10;\n\n ans+=(a\/10)*10;\n\n a%=10;\n\n a+=sisa;\n\n }\n\n cout << ans+a << endl;\n\n }\n\n}","language":"cpp"} {"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":"#include \n\n#include \n\n#include \n\n#include \n\n#define int long long int\n\n\n\nconst int M = 86028121 ;\n\n\n\nusing namespace std ;\n\n\n\nint32_t main()\n\n{\n\n int t ;\n\n cin >> t ;\n\n while(t--)\n\n {\n\n int a , b ;\n\n cin >> a >> b ;\n\n if(a==b)\n\n {\n\n cout << 0 << endl ;\n\n }\n\n else if(a\n\n#define ll long long\n\n#define mod (ll)1000000007\n\nusing namespace std;\n\nunordered_map> f;\n\nint main()\n\n{\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(NULL);\n\n int n,k;\n\n cin>>n>>k;\n\n\n\n string s;\n\n vector a(n);\n\n for(int i = 0; i < n; i++){\n\n cin>>s;\n\n f[s].push_back(i);\n\n a[i] = s;\n\n }\n\n ll ans = 0;\n\n for(int i = 0; i < n; i++){\n\n for(int j = i+1; j < n; j++){\n\n \n\n \/\/ cout<<\"a[i]:\"<kk\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":"#include \n\nusing namespace std;\n\n\n\nconst int N = 1505;\n\nint sums[N];\n\n\n\nvoid solve() {\n\n int n;\n\n cin >> n;\n\n for (int i = 1; i <= n; ++i) {\n\n cin >> sums[i];\n\n sums[i] += sums[i - 1];\n\n }\n\n \n\n unordered_map>> pos;\n\n \n\n for (int i = 1; i <= n; ++i) {\n\n for (int j = i; j <= n; ++j) {\n\n pos[sums[j] - sums[i - 1]].emplace_back(i, j);\n\n }\n\n }\n\n \n\n int cnt = 0, val = 0;\n\n for (auto &[v, vec] : pos) {\n\n if (vec.size() < cnt) continue;\n\n sort(vec.begin(), vec.end(), [](auto &x, auto &y) { \/\/ se\u8d8a\u9760\u524d\u8d8a\u597d\n\n return x.second < y.second;\n\n });\n\n int last = -1, cur = 0;\n\n for (auto &[fi, se] : vec) {\n\n if (fi <= last) continue;\n\n ++cur;\n\n last = se;\n\n }\n\n if (cur > cnt) {\n\n cnt = cur;\n\n val = v;\n\n }\n\n }\n\n \n\n cout << cnt << '\\n';\n\n int last = -1;\n\n for (auto &[fi, se] : pos[val]) {\n\n if (fi <= last) continue;\n\n cout << fi << ' ' << se << '\\n';\n\n last = se;\n\n }\n\n}\n\n\n\nint main() {\n\n cin.tie(0)->sync_with_stdio(0);\n\n solve();\n\n return 0;\n\n}","language":"cpp"} {"contest_id":"13","problem_id":"C","statement":"C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1\u2009\u2264\u2009N\u2009\u2264\u20095000) \u2014 the length of the initial sequence. The following N lines contain one integer each \u2014 elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer \u2014 minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1","tags":["dp","sortings"],"code":"#pragma optimize(\"Bismillahirrahmanirrahim\")\n\/\/\u2588\u2580\u2588\u2500\u2588\u2500\u2500\u2588\u2500\u2500\u2588\u2580\u2588\u2500\u2588\u2500\u2588\n\/\/\u2588\u2584\u2588\u2500\u2588\u2500\u2500\u2588\u2500\u2500\u2588\u2584\u2588\u2500\u2588\u25a0\u2588\n\/\/\u2588\u2500\u2588\u2500\u2588\u2584\u2500\u2588\u2584\u2500\u2588\u2500\u2588\u2500\u2588\u2500\u2588\n\/\/Allahuekber\n\/\/ahmet23 orz...\n\/\/Sani buyuk Osman Pasa Plevneden cikmam diyor.\n\/\/FatihSultanMehmedHan\n\/\/YavuzSultanSelimHan\n\/\/AbdulhamidHan\n#define author tolbi\n#include \n#ifdef LOCAL\n\t#include \"23.h\"\n#endif\n#define int long long\n#define endl '\\n'\n#define vint(x) vector x\n#define deci(x) int x;cin>>x;\n#define decstr(x) string x;cin>>x;\n#define cinarr(x) for (auto &it : x) cin>>it;\n#define coutarr(x) for (auto &it : x) cout<>t;\n\twhile (t-(tno++)){\n\t\tdeci(n);\n\t\tvint(arr(n));\n\t\tcinarr(arr);\n\t\tvector barr;\n\t\tmap mp;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tmp[arr[i]]=true;\n\t\t}\n\t\tfor (auto it : mp) {\n\t\t\tbarr.push_back(it.first);\n\t\t}\n\t\tvector> dp(2,vector(barr.size(),-1));\n\t\tdp[0].back()=abs(arr.back()-barr.back());\n\t\tfor (int i = barr.size()-2; i >= 0; i--){\n\t\t\tdp[0][i]=min(dp[0][i+1],abs(arr.back()-barr[i]));\n\t\t}\n\t\tfor (int i = n-2; i >= 0; i--){\n\t\t\tdp[1].back()=abs(arr[i]-barr.back())+dp[0].back();\n\t\t\tfor (int j = barr.size()-2; j >= 0; j--){\n\t\t\t\tdp[1][j] = min(dp[1][j+1],dp[0][j]+abs(arr[i]-barr[j]));\n\t\t\t}\n\t\t\tswap(dp[0],dp[1]);\n\t\t}\n\t\tcout<\n#include \n#include \n#include \n#include \n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include \n\/\/header file ended\nusing namespace std;\n#define INF 1e18\n#define pb push_back\n#define pll pair \n#define ppb pop_back\n#define mp make_pair\n#define ff first\n#define ss second\n#define mod1 1000000007\n#define mod2 998244353\n#define PI 3.141592653589793238462\n#define vch vector\n#define vll vector\n#define vbb vector\n#define vst vector\n#define mll map\n#define mcl map\n#define mlc map\n#define msl map\n#define si set\n#define usi unordered_set\n#define msi multiset\n#define pqsmall priority_queue > \n#define pqlarge priority_queue \n#define nl '\\n'\ntypedef long long ll;\ntypedef unsigned long long ull;\ntypedef long double lld;\n#define all(x) (x).begin(), (x).end()\n\/\/--------------------------------------------------------------\/\/\/\/ nCr starts \/\/\/\/---------------------------------------------------------------\nll powerM(ll a,ll b,ll m){ll res = 1;while(b){if(b & 1){res = (res * a) % m;}a = (a * a) % m;b >>= 1;}return res;}\nll modInverse(ll a , ll m){return powerM(a , m - 2 , m);}\nll nCrModPFermat(ll n , ll r , ll p){if(r == 0){return 1;}ll fac[n + 1];fac[0] = 1;for(ll i = 1; i <= n; ++i){fac[i] = (fac[i - 1] * i) % p;}return (fac[n] * modInverse(fac[r] , p) % p * modInverse(fac[n - r] , p) % p) % p;}\n\/\/--------------------------------------------------------------\/\/\/\/ nCr ends \/\/\/\/-----------------------------------------------------------------\nbool cmp(pair a,pair b){if (a.ff!=b.ff){return a.ff>b.ff;}else{return a.ss>1;}return x;}\nvoid fact(ll n,vector &vp1){for(ll i=2;i*i<=n;i++){if(n%i==0){ll ct=0;while (n%i==0){ct++;n\/=i;}vp1.pb(mp(i,ct));}}if(n>1)vp1.pb(mp(n,1));}\nll multi_inv(ll r1,ll r2){ll q,r,t1=0,t2=1,t,m=r1;while (r2 > 0){q=r1\/r2;r=r1%r2;t=1-(q*t2);r1=r2;r2=r;t1=t2;t2=t;}if (t1<0){ll a=abs(t1\/m);a++;a=a*m;t1=a+t1;}return t1;}\n#define rsort(a) sort(a, a + n, greater())\n#define rvsort(a) sort(all(a), greater())\n#define FOR(i, a, b) for (auto i = a; i < b; i++)\n#define rFOR(a, b) for (auto i = a; i >= b; i--)\n#define read(a , n) for(int i = 0 ; i < n ; i ++){cin >> a[i];}\nconst ll N=1e7;\nvoid sol()\n{\n ll n,flag=0;cin>>n;\n map m1;\n FOR(i,0,n)\n {\n ll x;cin>>x;\n m1[x].pb(i);\n if(m1[x].size()>2)\n {\n flag=1;\n }\n }\n if(flag==1)\n {\n cout<<\"YES\\n\";\n return;\n }\n if(m1.size()==n)\n {\n cout<<\"NO\\n\";\n return;\n }\n for(auto &val : m1)\n {\n ll sz=val.ss.size();\n FOR(i,0,sz-1)\n {\n if(val.ss[i+1]-val.ss[i]>1)\n {\n cout<<\"YES\\n\";\n return;\n }\n }\n }\n cout<<\"NO\\n\";\n}\nint32_t main()\n{\n #ifndef ONLINE_JUDGE\n freopen(\"input.txt\",\"r\",stdin);\n freopen(\"output.txt\",\"w\", stdout);\n #endif\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n int t;\n cin>>t;\n while(t--)\n {\n sol();\n }\n return 0;\n}","language":"cpp"} {"contest_id":"1312","problem_id":"F","statement":"F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1\u2264t\u226410001\u2264t\u22641000) \u2014 the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1\u2264n\u22643\u22c51051\u2264n\u22643\u22c5105, 1\u2264x,y,z\u226451\u2264x,y,z\u22645). The second line contains nn integers a1a1, a2a2, ..., anan (1\u2264ai\u226410181\u2264ai\u22641018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3\u22c51053\u22c5105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3\n2 1 3 4\n7 6\n1 1 2 3\n1\n1 1 2 2\n3\nOutputCopy2\n3\n0\nInputCopy10\n6 5 4 5\n2 3 2 3 1 3\n1 5 2 3\n10\n4 4 2 3\n8 10 8 5\n2 2 1 4\n8 5\n3 5 3 5\n9 2 10\n4 5 5 5\n2 10 4 2\n2 3 1 4\n1 10\n3 1 5 3\n9 8 7\n2 5 4 5\n8 8\n3 5 1 4\n5 5 10\nOutputCopy0\n2\n1\n2\n5\n12\n5\n0\n0\n2\n","tags":["games","two pointers"],"code":"#include\n\n\n\nusing namespace std;\n\n\n\nconst int N = 300043;\n\nconst int K = 5;\n\n\n\nint x, y, z, n;\n\nlong long a[N];\n\n\n\ntypedef vector > state;\n\nmap d;\n\nint cnt;\n\nint p;\n\nvector > state_log;\n\n\n\nint mex(const vector& a)\n\n{\n\n for(int i = 0; i < a.size(); i++)\n\n {\n\n bool f = false;\n\n for(auto x : a)\n\n if(x == i)\n\n f = true;\n\n if(!f)\n\n return i;\n\n }\n\n return a.size();\n\n}\n\n\n\nstate go(state s)\n\n{\n\n int f1 = mex({s[0][K - x], s[1][K - y], s[2][K - z]});\n\n int f2 = mex({s[0][K - x], s[2][K - z]});\n\n int f3 = mex({s[0][K - x], s[1][K - y]});\n\n state nw = s;\n\n nw[0].push_back(f1);\n\n nw[1].push_back(f2);\n\n nw[2].push_back(f3);\n\n for(int i = 0; i < 3; i++)\n\n nw[i].erase(nw[i].begin());\n\n return nw;\n\n}\n\n\n\nvoid precalc()\n\n{\n\n d.clear();\n\n state cur(3, vector(K, 0));\n\n cnt = 0;\n\n state_log.clear();\n\n while(!d.count(cur))\n\n {\n\n d[cur] = cnt;\n\n state_log.push_back({cur[0].back(), cur[1].back(), cur[2].back()});\n\n cur = go(cur);\n\n cnt++;\n\n } \n\n p = cnt - d[cur];\n\n}\n\n\n\nint get_grundy(long long x, int t)\n\n{\n\n if(x < cnt)\n\n return state_log[x][t];\n\n else\n\n {\n\n int pp = cnt - p;\n\n x -= pp;\n\n return state_log[pp + (x % p)][t];\n\n }\n\n}\n\n\n\nvoid read()\n\n{\n\n scanf(\"%d %d %d %d\", &n, &x, &y, &z);\n\n for(int i = 0; i < n; i++)\n\n scanf(\"%lld\", &a[i]);\n\n} \n\n\n\nint check(int x, int y)\n\n{\n\n return x == y ? 1 : 0;\n\n}\n\n\n\nvoid solve()\n\n{\n\n precalc();\n\n int ans = 0;\n\n for(int i = 0; i < n; i++)\n\n ans ^= get_grundy(a[i], 0);\n\n int res = 0;\n\n for(int i = 0; i < n; i++)\n\n {\n\n ans ^= get_grundy(a[i], 0);\n\n res += check(ans, get_grundy(max(0ll, a[i] - x), 0));\n\n res += check(ans, get_grundy(max(0ll, a[i] - y), 1));\n\n res += check(ans, get_grundy(max(0ll, a[i] - z), 2));\n\n ans ^= get_grundy(a[i], 0);\n\n }\n\n printf(\"%d\\n\", res);\n\n}\n\n\n\nint main()\n\n{\n\n int t;\n\n scanf(\"%d\", &t);\n\n for(int i = 0; i < t; i++)\n\n {\n\n read();\n\n solve();\n\n }\n\n}","language":"cpp"} {"contest_id":"1292","problem_id":"C","statement":"C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon \"Xenon\" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker \"X\" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n\u22121n\u22121 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n\u22122n\u22122 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=\u22111\u2264u\n\n#define LL long long\nusing namespace std;\nint n,rt,u,v,p[3005][3005],s[3005][3005];\nLL f[3005][3005],ans;\nvector G[3005];\nvoid build(int u)\n{\ns[rt][u]=1;\nfor(int v:G[u])\nif(v^p[rt][u])\n{\np[rt][v]=u;\nbuild(v);\ns[rt][u]+=s[rt][v];\n}\n}\nLL dp(int u, int v)\n{\nif(u==v)return 0;\nif(f[u][v])return f[u][v];\nreturn f[u][v]=max(dp(u,p[u][v]),dp(v,p[v][u]))+s[u][v]*s[v][u];\n}\nsigned main()\n{\nios::sync_with_stdio(false);\ncin>>n;\nfor(int i=1;i>u>>v;\nG[u].push_back(v);\nG[v].push_back(u);\n}\nfor(int i=1;i<=n;i++)rt=i,build(i);;\nfor(int u=1;u<=n;u++)\nfor(int v=1;v<=n;v++)\nans=max(ans,dp(u, v));\ncout<\n\n#define ll long long\n\n#define ull unsigned long long\n\n#define ff first\n\n#define sc second\n\n#define pb push_back\n\n#define pii pair\n\n#define pll pair\n\nusing namespace std;\n\nconst ll mod = 1e9 + 7;\n\n\n\nvoid solve(){\n\n int q, x, k, ans = 0;\n\n cin >> q >> x;\n\n int rem[x] = {0};\n\n while(q--){\n\n cin >> k;\n\n rem[k % x]++;\n\n for(ans; true; ans++){\n\n if(rem[ans % x] > 0){\n\n rem[ans % x]--;\n\n }\n\n else {cout << ans << '\\n';break;}\n\n }\n\n }\n\n}\n\nint main() {\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(nullptr); cout.tie(nullptr);\n\n \n\n int T = 1;\n\n \/\/cin >> T;\n\n while(T--){\n\n solve();\n\n cout << '\\n';\n\n }\n\n \n\n return 0;\n\n}","language":"cpp"} {"contest_id":"1322","problem_id":"B","statement":"B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one\u00a0\u2014 xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)(a1+a2)\u2295(a1+a3)\u2295\u2026\u2295(a1+an)\u2295(a2+a3)\u2295\u2026\u2295(a2+an)\u2026\u2295(an\u22121+an)Here x\u2295yx\u2295y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https:\/\/en.wikipedia.org\/wiki\/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2\u2264n\u22644000002\u2264n\u2264400000)\u00a0\u2014 the number of integers in the array.The second line contains integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641071\u2264ai\u2264107).OutputPrint a single integer\u00a0\u2014 xor of all pairwise sums of integers in the given array.ExamplesInputCopy2\n1 2\nOutputCopy3InputCopy3\n1 2 3\nOutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112\u22951002\u22951012=01020112\u22951002\u22951012=0102, thus the answer is 2.\u2295\u2295 is the bitwise xor operation. To define x\u2295yx\u2295y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012\u229500112=0110201012\u229500112=01102.","tags":["binary search","bitmasks","constructive algorithms","data structures","math","sortings"],"code":"\/\/ LUOGU_RID: 100767713\n#include\n\n#include\n\n\n\nusing namespace std;\n\n#define ll long long\n\n#define pii pair\n\n\/\/struct Edge {\n\n\/\/\tint from, to, nex;\n\n\/\/}edge[400010];\n\n\/\/int tot, head[200010];\n\n\/\/void add(int u, int v) {\n\n\/\/\tedge[++tot] = { u,v,head[u] };\n\n\/\/\thead[u] = tot;\n\n\/\/}\n\nll n;\n\nvoid solve()\n\n{\n\n cin >> n;\n\n vector a(n + 1);\n\n for (int i = 1; i <= n; i++) cin >> a[i];\n\n vector b(n + 1);\n\n ll ans = 0;\n\n for (int k = 0; k <= 25; k++) {\n\n for (int i = 1; i <= n; i++) {\n\n b[i] = (a[i] % (1ll << (k+1)));\n\n }\n\n sort(b.begin() + 1, b.end());\n\n ll cnt = 0, cnt2 = 0;\n\n ll l = 1, r = 1;\n\n for (int i = n; i; i--) {\n\n \/*ll tmp = (1ll << (k - 1));\n\n if (k == 0) tmp = 0;*\/\n\n while ( l <= n&&b[l] + b[i] < (1ll<= l && i < r);\n\n }\n\n l = r = 1;\n\n for (int i = n; i; i--) {\n\n while (l <= n&&b[l] + b[i] < ((1ll << (k + 1))+(1ll<= l && i < r);\n\n }\n\n cnt = (cnt >> 1) & 1;\n\n cnt2 = (cnt2 >> 1) & 1;\n\n if (cnt ^ cnt2)\n\n ans += (1ll << k);\n\n }\n\n cout << ans << '\\n';\n\n}\n\n\n\nsigned main()\n\n{\n\n ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);\n\n int tt = 1;\n\n \/\/ cin >> tt;\n\n while (tt--) solve();\n\n\n\n return 0;\n\n}\n\n\/*\n\n\n\n\n\n\n\n*\/","language":"cpp"} {"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 (x\n\nusing namespace std;\n\ninline long long read()\n\n{\n\n long long x=0,f=1;char ch=getchar();\n\n while(!isdigit(ch)&&ch!='-')ch=getchar();\n\n if(ch=='-')f=-1,ch=getchar();\n\n while(isdigit(ch))x=(x<<1)+(x<<3)+ch-'0',ch=getchar();\n\n return x*f;\n\n}\n\n#define MOD 998244353\n\nstruct Segment{\n\n\tlong long l,r;\n\n} seg[1001010],a[1001010];\n\nlong long down,up,n,m,lst,now,i,tn;\n\nlong long lsh[1001010];\n\nlong long inv[1001010],dp[1010][1010];\n\nlong long pow(long long x,long long y,long long p){\n\n\tlong long ans=1;\n\n\tfor (;y;y>>=1,x=x*x % p)\n\n\t if (y&1) ans=ans*x % p;\n\n\treturn ans;\n\n}\n\nbool check(int l,int r,int pos){\n\n\tif (l>r) return true;\n\n\tfor (int i=l;i<=r;i++)\n\n\t {\n\n\t if (a[i].rseg[pos].r) return false;\n\n\t}\n\n\treturn true;\n\n}\n\nlong long C(long long n,long long m){\n\n\tlong long ans=1;\n\n\tfor (long long i=n-m+1;i<=n;i++) ans=ans*i % MOD;\n\n\tfor (long long i=1;i<=m;i++) ans=ans*inv[i] % MOD;\n\n\treturn ans;\n\n}\n\nlong long Calc(long long n,long long m){\n\n\treturn C(n+m-1,n);\n\n}\n\n\/*\n\n13 41\n\n42 419\n\n420 1336\n\n1337 1337\n\n*\/\n\nint main()\n\n{\n\n\tn=read();\n\n\tfor (i=1;i<=n;i++) a[i].l=read(),a[i].r=read();\n\n\tfor (i=1;i<=n\/2;i++) swap(a[i],a[n-i+1]);\n\n\tfor (i=1;i<=n;i++) lsh[++tn]=a[i].l,lsh[++tn]=a[i].r;\n\n\tsort(lsh+1,lsh+tn+1);\n\n\tinv[1]=1;\n\n\tfor (i=2;i<=n;i++) inv[i]=(MOD-MOD\/i)*inv[MOD % i] % MOD;\n\n\ttn=unique(lsh+1,lsh+tn+1)-lsh-1;\n\n\tfor (i=1;i\n#include\n#include\n\n#define maxn 66\n\nconst int mod=1e9+7;\n\ntemplate\n\ninline T read(){\n\tT r=0,f=0;\n\tchar c;\n\twhile(!isdigit(c=getchar()))f|=(c=='-');\n\twhile(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=getchar();\n\treturn f?-r:r;\n}\n\ninline long long qpow(long long a,int b){\n\tlong long ans=1;\n\tfor(;b;b>>=1){\n\t\tif(b&1)(ans*=a)%=mod;\n\t\t(a*=a)%=mod;\n\t}\n\treturn ans;\n}\n\nint n,a[maxn];\n\nbool vis[maxn],tag[maxn];\n\nlong long C[maxn][maxn],A[maxn][maxn];\n\ninline void Add(int &x,int y){\n\tx+=y-mod,x+=(x>>31)&mod;\n}\n\nint sum;\n\nlong long ans;\n\nstd::vector to[maxn];\n\nnamespace Solve{\n\n\tlong long f[1<<15];\n\n\tint N,n,m,d[maxn],d0[maxn],T[maxn],cnt[1<<15];\n\n\tinline void FWT(){\n\t\tfor(int i=1;i();\n\tfor(int i=1;i<=n;i++)\n\t\ta[i]=read();\n\tfor(int i=1;i<=n;i++){\n\t\ttag[i]=1;\n\t\tfor(int j=1;j<=n;j++)\n\t\t\tif((i^j)&&!(a[i]%a[j]))\n\t\t\t\ttag[i]=0,to[i].push_back(j),to[j].push_back(i);\n\t}\n\tfor(int i=0;i<=n;i++){\n\t\tC[i][0]=A[i][0]=1;\n\t\tfor(int j=1;j<=i;j++){\n\t\t\tC[i][j]=(C[i-1][j-1]+C[i-1][j])%mod;\n\t\t\tA[i][j]=A[i-1][j-1]*i%mod;\n\t\t}\n\t}\n\tans=1;\n\tfor(int i=1;i<=n;i++)\n\t\tif(!vis[i])Solve::work(i);\n\tprintf(\"%lld\\n\",ans);\n\treturn 0;\n}","language":"cpp"} {"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":"\/\/ LUOGU_RID: 102213766\n#include \n\nusing namespace std;\n\nconst int maxn=2e5+10;\n\nstruct edge{int to,next;}E[maxn<<1];\n\nint head[maxn],tot;\n\ninline void add(int u,int v)\n\n{\n\n E[++tot]={v,head[u]};\n\n head[u]=tot;\n\n}\n\nint nd;\n\nint n,m,dfn[maxn],dep[maxn],top[maxn],times;\n\nbool del[maxn];\n\nvector adin;\n\nvector V;\n\nvoid predfs(int u,int fa)\n\n{\n\n dep[u]=dep[fa]+1;\n\n V.push_back(u);\n\n dfn[u]=++times;\n\n top[u]=dep[u];\n\n int cnt=0;\n\n for(int i=head[u];i;i=E[i].next)\n\n {\n\n int v=E[i].to;\n\n if(!dfn[v]){predfs(v,u);}\n\n else if(dep[u]-dep[v]+1>=nd)\n\n {\n\n puts(\"2\");\n\n printf(\"%d\\n\",dep[u]-dep[v]+1);\n\n \/\/printf(\"%d %d %d\\n\",u,dep[u],top[u]);\n\n for(int i=dep[v]-1;i\n\nusing namespace std;\n\n#define ll long long\n\n#define rep(i, a, b) for (long long i = a; i < b; i++)\n\n#define all(v) v.begin(), v.end()\n\n#define endl '\\n'\n\nconst int MOD = 1000000007;\n\nsigned main()\n\n{\n\n ios_base::sync_with_stdio(0);\n\n cin.tie(0);\n\n cout.tie(0);\n\n ll q, x;\n\n cin >> q >> x;\n\n multiset st;\n\n ll qt = 0;\n\n ll ct = 0;\n\n while (q--)\n\n {\n\n ll y;\n\n cin >> y;\n\n y = (y % x);\n\n st.insert(y);\n\n while (st.count(ct) > 0)\n\n {\n\n st.erase(st.find(ct));\n\n ct++;\n\n if (ct == x)\n\n {\n\n qt++;\n\n ct = 0;\n\n }\n\n }\n\n cout << ct + x * qt << endl;\n\n }\n\n return 0;\n\n}","language":"cpp"} {"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":"\/\/ time-limit: 5000\n\/\/ problem-url: https:\/\/codeforces.com\/problemset\/problem\/1288\/D\n\/\/ clang-format off\n#include\"bits\/stdc++.h\"\n#define mod 1000000007\n#define inf 1e18\n#define pq priority_queue\n#define pqi priority_queue\n#define pqimn priority_queue>\n#define pb push_back\n#define sz(v) ((int)(v).size())\n#define all(v) (v).begin(),(v).end()\n#define ss second\n#define ff first\n \nusing namespace std;\nusing ll = long long;\nusing ld = long double;\nusing uint = unsigned int;\nusing ull = unsigned long long;\ntemplate\nusing pair2 = pair;\nusing pii = pair;\nusing pli = pair;\nusing pll = pair;\ntemplate\nostream& operator <<(ostream& ostream, vector& v) {for(auto& element : v) {cout << element << \" \";}return ostream;}\ntemplate\nistream& operator >>(istream& istream, vector& v) { for(auto& element : v) {cin >> element;}return istream;}\ntemplate T abs(T x) { return x < 0? -x : x; }\ntemplate bool chmin(T &x, const T& y) { if (x > y) { x = y; return true; } return false; }\ntemplate bool chmax(T &x, const T& y) { if (x < y) { x = y; return true; } return false; }\n \n \nvoid __print(int x) {cerr << x;}\nvoid __print(long x) {cerr << x;}\nvoid __print(long long x) {cerr << x;}\nvoid __print(unsigned x) {cerr << x;}\nvoid __print(unsigned long x) {cerr << x;}\nvoid __print(unsigned long long x) {cerr << x;}\nvoid __print(float x) {cerr << x;}\nvoid __print(double x) {cerr << x;}\nvoid __print(long double x) {cerr << x;}\nvoid __print(char x) {cerr << '\\'' << x << '\\'';}\nvoid __print(const char *x) {cerr << '\\\"' << x << '\\\"';}\nvoid __print(const string &x) {cerr << '\\\"' << x << '\\\"';}\nvoid __print(bool x) {cerr << (x ? \"true\" : \"false\");}\n \ntemplate\nvoid __print(const pair &x);\ntemplate\nvoid __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? \", \" : \"\"), __print(i); cerr << \"}\";}\ntemplate\nvoid __print(const pair &x) {cerr << '{'; __print(x.first); cerr << \", \"; __print(x.second); cerr << '}';}\nvoid _print() {cerr << \"]\\n\";}\ntemplate \nvoid _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << \", \"; _print(v...);}\n#ifdef DEBUG\n#define dbg(x...) cerr << \"\\e[91m\"<<__func__<<\":\"<<__LINE__<<\" [\" << #x << \"] = [\"; _print(x); cerr << \"\\e[39m\" << endl;\n#else\n#define dbg(x...)\n#endif\n\/\/ clang-format on\n\nint main() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n int n, m;\n cin >> n >> m;\n std::vector> a(n, std::vector(m));\n for (int i = 0; i < n; i++) {\n cin >> a[i];\n }\n int ai = 1, aj = 1;\n auto chk = [&](int k) -> bool {\n std::vector sat(1 << m, -1);\n bool p = false;\n for (int i = 0; i < n; i++) {\n int mask = 0;\n for (int j = 0; j < m; j++) {\n if (a[i][j] >= k) {\n mask |= (1 << j);\n }\n }\n if (sat[mask] == -1) {\n sat[mask] = i;\n }\n }\n for (int i = 0; i < sz(sat); i++) {\n for (int j = 0; j < sz(sat); j++) {\n if ((j | i) == (1 << m) - 1 and sat[i] != -1 and sat[j] != -1) {\n ai = sat[i], aj = sat[j];\n return true;\n }\n }\n }\n return false;\n };\n int l = -1, r = 2e9;\n while (l + 1 < r) {\n int m = (l & r) + ((l ^ r) >> 1);\n if (chk(m)) {\n l = m;\n } else {\n r = m;\n }\n }\n cout << ai + 1 << ' ' << aj + 1 << '\\n';\n return 0;\n}\n","language":"cpp"} {"contest_id":"1299","problem_id":"C","statement":"C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1\u2264l\u2264r\u2264n1\u2264l\u2264r\u2264n), and redistribute water in tanks l,l+1,\u2026,rl,l+1,\u2026,r evenly. In other words, replace each of al,al+1,\u2026,aral,al+1,\u2026,ar by al+al+1+\u22ef+arr\u2212l+1al+al+1+\u22ef+arr\u2212l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1\u2264n\u22641061\u2264n\u2264106)\u00a0\u2014 the number of water tanks.The second line contains nn integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641061\u2264ai\u2264106)\u00a0\u2014 initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10\u2212910\u22129.Formally, let your answer be a1,a2,\u2026,ana1,a2,\u2026,an, and the jury's answer be b1,b2,\u2026,bnb1,b2,\u2026,bn. Your answer is accepted if and only if |ai\u2212bi|max(1,|bi|)\u226410\u22129|ai\u2212bi|max(1,|bi|)\u226410\u22129 for each ii.ExamplesInputCopy4\n7 5 5 7\nOutputCopy5.666666667\n5.666666667\n5.666666667\n7.000000000\nInputCopy5\n7 8 8 10 12\nOutputCopy7.000000000\n8.000000000\n8.000000000\n10.000000000\n12.000000000\nInputCopy10\n3 9 5 5 1 7 5 3 8 7\nOutputCopy3.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n5.000000000\n7.500000000\n7.500000000\nNoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.","tags":["data structures","geometry","greedy"],"code":"#include\n\n#define ll long long\n\n#define rep(i, x, y) for(int i = (x), stOyny = (y); i <= stOyny; ++i)\n\n#define irep(i, x, y) for(int i = (x), stOyny = (y); i >= stOyny; --i)\n\n#define pb emplace_back\n\n#define point pair\n\n#define vint vector\n\n#define fi first\n\n#define se second\n\n#define let const auto\n\n#define il inline\n\n#define ci const int\n\n#define all(S) S.begin(), S.end()\n\nint read() {\n\n\tint res = 0, flag = 1; char c = getchar();\n\n\twhile(c < '0' || c > '9') { if(c == '-') flag = -1; c = getchar(); }\n\n\twhile(c >= '0' && c <= '9') res = res * 10 + c - '0', c = getchar();\n\n\treturn res * flag;\n\n}\n\nusing namespace std;\n\ntemplate\n\nil void tmax(T &x, const T y) { if(x < y) x = y; }\n\ntemplate\n\nil void tmin(T &x, const T y) { if(x > y) x = y; }\n\n\n\nil point operator -(const point &p, const point &q) { return point(p.fi - q.fi, p.se - q.se); }\n\nll det(const point &p, const point &q) { return p.fi * q.se - p.se * q.fi; }\n\nsigned main() {\n\n\/\/\tfreopen(\"1.in\", \"r\", stdin);\n\n\tint n = read();\n\n\tvector st;\n\n\tll sum = 0;\n\n\tst.pb(0, 0ll);\n\n\trep(i, 1, n) {\n\n\t\tpoint cur = point(i, sum += read());\n\n\t\twhile(st.size() >= 2 && det(cur - st.end()[-2], st.back() - st.end()[-2]) >= 0) st.pop_back();\n\n\t\tst.push_back(cur);\n\n\t}\n\n\tpoint last = st[0];\n\n\tfor(let t : st) if(t.fi) {\n\n\t\tlet cur = t - last;\n\n\t\trep(i, last.fi + 1, t.fi) printf(\"%.11Lf\\n\", (long double)cur.se \/ cur.fi);\n\n\t\tlast = t;\n\n\t}\n\n\treturn 0;\n\n}\n\n","language":"cpp"} {"contest_id":"13","problem_id":"D","statement":"D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0\u2009\u2264\u2009N\u2009\u2264\u2009500; 0\u2009\u2264\u2009M\u2009\u2264\u2009500) \u2014 the number of red and blue points respectively. The following N lines contain two integer numbers each \u2014 coordinates of red points. The following M lines contain two integer numbers each \u2014 coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer \u2014 the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInputCopy4 10 010 010 105 42 1OutputCopy2InputCopy5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8OutputCopy7","tags":["dp","geometry"],"code":"\/\/ BEGIN BOILERPLATE CODE\n\n\n\n#include \n\nusing namespace std;\n\n\n\n#ifdef KAMIRULEZ\n\n\tconst bool kami_loc = true;\n\n\tconst long long kami_seed = 69420;\n\n#else\n\n\tconst bool kami_loc = false;\n\n\tconst long long kami_seed = chrono::steady_clock::now().time_since_epoch().count();\n\n#endif\n\n\n\nconst string kami_fi = \"kamirulez.inp\";\n\nconst string kami_fo = \"kamirulez.out\";\n\nmt19937_64 kami_gen(kami_seed);\n\n\n\nlong long rand_range(long long rmin, long long rmax) {\n\n\tuniform_int_distribution rdist(rmin, rmax);\n\n\treturn rdist(kami_gen);\n\n}\n\n\n\nlong double rand_real(long double rmin, long double rmax) {\n\n\tuniform_real_distribution rdist(rmin, rmax);\n\n\treturn rdist(kami_gen);\n\n}\n\n\n\nvoid file_io(string fi, string fo) {\n\n\tif (fi != \"\" && (!kami_loc || fi == kami_fi)) {\n\n\t\tfreopen(fi.c_str(), \"r\", stdin);\n\n\t}\n\n\tif (fo != \"\" && (!kami_loc || fo == kami_fo)) {\n\n\t\tfreopen(fo.c_str(), \"w\", stdout);\n\n\t}\n\n}\n\n\n\nvoid set_up() {\n\n\tif (kami_loc) {\n\n\t\tfile_io(kami_fi, kami_fo);\n\n\t}\n\n\tios_base::sync_with_stdio(0);\n\n\tcin.tie(0);\n\n}\n\n\n\nvoid just_do_it();\n\n\n\nvoid just_exec_it() {\n\n\tif (kami_loc) {\n\n\t\tauto pstart = chrono::steady_clock::now();\n\n\t\tjust_do_it();\n\n\t\tauto pend = chrono::steady_clock::now();\n\n\t\tlong long ptime = chrono::duration_cast(pend - pstart).count();\n\n\t\tstring bar(50, '=');\n\n\t\tcout << '\\n' << bar << '\\n';\n\n\t\tcout << \"Time: \" << ptime << \" ms\" << '\\n';\n\n\t}\n\n\telse {\n\n\t\tjust_do_it();\n\n\t}\n\n}\n\n\n\nint main() {\n\n\tset_up();\n\n\tjust_exec_it();\n\n\treturn 0;\n\n}\n\n\n\n\/\/ END BOILERPLATE CODE\n\n\n\n\/\/ BEGIN MAIN CODE\n\n\n\nstruct point {\n\n\tlong long x = 0;\n\n\tlong long y = 0;\n\n\n\n\tpoint() {\n\n\n\n\t}\n\n\n\n\tpoint(long long _x, long long _y) {\n\n\t\tx = _x;\n\n\t\ty = _y;\n\n\t}\n\n\n\n\tpoint operator-(point p2) {\n\n\t\treturn point(x - p2.x, y - p2.y);\n\n\t}\n\n\n\n\tlong long operator^(point p2) {\n\n\t\treturn x * p2.y - y * p2.x; \n\n\t}\n\n};\n\n\n\nostream& operator<<(ostream &out, point p) {\n\n\tout << \"(\" << p.x << \", \" << p.y << \")\";\n\n\treturn out;\n\n}\n\n\n\nbool cmpx(point p1, point p2) {\n\n\treturn p1.x < p2.x;\n\n}\n\n\n\nconst int ms = 5e2 + 20;\n\npoint a[ms];\n\npoint b[ms];\n\nint low1[ms];\n\nint low2[ms][ms];\n\n\n\nvoid just_do_it() {\n\n\tint n, m;\n\n\tcin >> n >> m;\n\n\tfor (int i = 1; i <= n; i++) {\n\n\t\tcin >> a[i].x >> a[i].y;\n\n\t}\n\n\tfor (int i = 1; i <= m; i++) {\n\n\t\tcin >> b[i].x >> b[i].y;\n\n\t}\n\n\tsort(a + 1, a + n + 1, cmpx);\n\n\tfor (int i = 1; i <= n; i++) {\n\n\t\tfor (int j = 1; j <= m; j++) {\n\n\t\t\tlow1[i] += (a[i].x == b[j].x) && (b[j].y < a[i].y);\n\n\t\t}\n\n\t}\n\n\tfor (int i = 1; i <= n; i++) {\n\n\t\tfor (int j = i + 1; j <= n; j++) {\n\n\t\t\tint s = 0;\n\n\t\t\tfor (int k = 1; k <= m; k++) {\n\n\t\t\t\tif (b[k].x < a[i].x || b[k].x > a[j].x) {\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\t}\n\n\t\t\t\ts += ((b[k] - a[i]) ^ (a[j] - a[i])) > 0;\n\n\t\t\t}\n\n\t\t\tlow2[i][j] = low2[j][i] = s;\n\n\t\t}\n\n\t}\n\n\tint res = 0;\n\n\tfor (int i = 1; i <= n; i++) {\n\n\t\tfor (int j = i + 1; j <= n; j++) {\n\n\t\t\tfor (int k = j + 1; k <= n; k++) {\n\n\t\t\t\tif (low2[i][j] + low2[j][k] - low1[j] == low2[i][k]) {\n\n\t\t\t\t\tres++;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tcout << res;\n\n}\n\n\n\n\/\/ END MAIN CODE","language":"cpp"} {"contest_id":"1284","problem_id":"D","statement":"D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai\u2264eaisai\u2264eai) and [sbi,ebi][sbi,ebi] (sbi\u2264ebisbi\u2264ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)\u2264min(y,v)max(x,u)\u2264min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1\u2264n\u22641000001\u2264n\u2264100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1\u2264sai,eai,sbi,ebi\u22641091\u2264sai,eai,sbi,ebi\u2264109, sai\u2264eai,sbi\u2264ebisai\u2264eai,sbi\u2264ebi).OutputPrint \"YES\" if Hyunuk will be happy. Print \"NO\" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2\n1 2 3 6\n3 4 7 8\nOutputCopyYES\nInputCopy3\n1 3 2 4\n4 5 6 7\n3 4 5 5\nOutputCopyNO\nInputCopy6\n1 5 2 9\n2 4 5 8\n3 6 7 11\n7 10 12 16\n8 11 13 17\n9 12 14 18\nOutputCopyYES\nNoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.","tags":["binary search","data structures","hashing","sortings"],"code":"#include \n\nusing namespace std;\n\n\n\n#define MOD 1000000007\n\n#define INF 0x3f3f3f3f\n\n#define f first\n\n#define s second\n\n#define rep(i,a,b) for (int i=a; i pii;\n\ntypedef pair pll;\n\n\n\ntemplate T mod(T a, T mod = MOD){ a %= mod; if (a<0) a += mod; return a; }\n\ntemplate T add(T a, T b, T mod = MOD){ return (a+b)%mod; }\n\ntemplate T sub(T a, T b, T mod = MOD){ return (a-b+mod)%mod; };\n\ntemplate T mul(T a, T b, T mod = MOD){ return (a * 1ll * b) % mod; }\n\ntemplate T binPow(T a, T b, T mod = MOD){ T res = 1; while (b>0){ if (b&1) res = mul(res, a, mod); a = mul(a,a, mod); b >>= 1; } return res; }\n\ntemplate T binPowNoMod(T a, T b){ T res = 1; while (b>0){ if (b&1) res *= a; a *= a; b >>= 1; } return res; }\n\ntemplate T divMod(T a, T b, T mod = MOD){ return mul(a, binPow(b, mod-2, mod), mod); }\n\n\n\nconst ld ep = 0.0000001;\n\nconst ld pi = acos(-1.0);\n\nmt19937 rng(chrono::steady_clock::now().time_since_epoch().count());\n\n\n\ntemplate \n\nclass LazySegTree{\n\n vector t, lazy, len;\n\npublic:\n\n int n;\n\n LazySegTree(vector &a){\n\n n = int(a.size());\n\n t.resize(4*n);\n\n lazy.resize(4*n);\n\n len.resize(4*n);\n\n build(a);\n\n }\n\n \n\n void build(vector &a){\n\n build(a, 0, n-1, 1);\n\n }\n\n \n\n void update(int x, int y, T diff){\n\n update(0, n-1, 1, x, y, diff);\n\n }\n\n \n\n T query(int l, int r){\n\n return query(0, n-1, 1, l, r);\n\n }\n\n \n\nprivate:\n\n T merge(T x, T y){\n\n return max(x,y);\n\n }\n\n \n\n T default_val() {\n\n return 0;\n\n }\n\n \n\n void push(int i){\n\n t[2*i] = max(t[2*i],lazy[i]);\n\n t[2*i+1] = max(t[2*i+1],lazy[i]);\n\n \n\n lazy[2*i] = max(lazy[2*i],lazy[i]);\n\n lazy[2*i+1] = max(lazy[2*i+1],lazy[i]);\n\n \n\n lazy[i] = 0;\n\n }\n\n \n\n void build(vector &a, int l, int r, int i){\n\n if (l==r){\n\n t[i] = a[l];\n\n len[i] = 1;\n\n return;\n\n }\n\n int mid = l+(r-l)\/2;\n\n build(a,l,mid,2*i);\n\n build(a,mid+1,r,2*i+1);\n\n t[i] = merge(t[2*i],t[2*i+1]);\n\n len[i] = 1;\n\n }\n\n \n\n void update(int l, int r, int i, int x, int y, T diff){\n\n if (x>y) return;\n\n if (x==l && r==y){\n\n t[i] = max(t[i],diff*len[i]);\n\n lazy[i] = max(lazy[i],diff);\n\n return;\n\n }\n\n push(i);\n\n int mid = l+(r-l)\/2;\n\n update(l, mid, 2*i, x, min(y,mid), diff);\n\n update(mid+1, r, 2*i+1, max(x,mid+1), y, diff);\n\n t[i] = merge(t[2*i], t[2*i+1]);\n\n }\n\n \n\n T query(int l, int r, int i, int x, int y){\n\n if (x>y) return default_val();\n\n if (x<=l && r<=y) {\n\n return t[i];\n\n }\n\n push(i);\n\n int mid = l+(r-l)\/2;\n\n return merge(query(l, mid, 2*i, x, min(y,mid)), query(mid+1, r, 2*i+1, max(x,mid+1), y));\n\n }\n\n};\n\n\n\nbool solve(vector>& a, int __cnt=1){\n\n int n = sz(a);\n\n if (__cnt>2) return false;\n\n \n\n \/\/ coords comp\n\n map mp;\n\n rep(i,0,n){\n\n rep(j,0,4){\n\n mp[a[i][j]] = 0;\n\n }\n\n }\n\n \n\n int __cc = 0;\n\n for (auto it: mp) mp[it.f] = __cc++;\n\n \n\n rep(i,0,n){\n\n rep(j,0,4){\n\n a[i][j] = mp[a[i][j]];\n\n }\n\n }\n\n \n\n vector tmp(__cc+5);\n\n LazySegTree st(tmp);\n\n \n\n rep(i,0,n){\n\n int left_b = a[i][2];\n\n \n\n st.update(a[i][0],a[i][1],left_b);\n\n }\n\n \n\n rep(i,0,n){\n\n int mx_left = st.query(a[i][0],a[i][1]);\n\n if (mx_left > a[i][3]) {\n\n return true;\n\n }\n\n }\n\n \n\n rep(i,0,n){\n\n swap(a[i][0],a[i][2]);\n\n swap(a[i][1],a[i][3]);\n\n }\n\n \n\n return solve(a,__cnt+1);\n\n}\n\n\n\nint main(int argc, const char * argv[]) {\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(NULL);\n\n \n\n int t=1;\n\n\/\/ cin>>t;\n\n \n\n int n;\n\n cin>>n;\n\n \n\n vector> a(n);\n\n rep(i,0,n){\n\n a[i].resize(4);\n\n rep(j,0,4) cin>>a[i][j];\n\n }\n\n \n\n for (int i=0;i\nusing namespace std;\n#define Ma3rof ios_base::sync_with_stdio(false);cin.tie(NULL);\nvoid solve() {\n int n;\n cin >> n;\n vector a(n);\n for (int i = 0; i < n; ++i) {\n cin >> a[i];\n }\n bool ok = false;\n for (int i = 0; i < n; ++i) {\n for (int j = i + 2; j < n; ++j) {\n if (a[i] == a[j])\n ok = true;\n }\n }\n if (ok)\n cout << \"YES\\n\";\n else\n cout << \"NO\\n\";\n}\nsigned main() {\n Ma3rof\n int t = 1;\n cin >> t;\n while (t--) {\n \/* \u0648\u0645\u0627 \u062a\u062f\u0631\u064a \u0646\u0641\u0633 \u0645\u0627\u0630\u0627 \u062a\u06a9\u0633\u0628 \u063a\u062f\u0627 \u0648\u0645\u0627 \u062a\u062f\u0631\u064a \u0646\u0641\u0633 \u0628\u0627\u064a \u0627\u0631\u0636 \u062a\u0645\u0648\u062a *\/\n solve();\n }\n return 0;\n}\n","language":"cpp"} {"contest_id":"1292","problem_id":"C","statement":"C. Xenon's Attack on the Gangstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputINSPION FullBand Master - INSPION INSPION - IOLITE-SUNSTONEOn another floor of the A.R.C. Markland-N; the young man Simon \"Xenon\" Jackson, takes a break after finishing his project early (as always). Having a lot of free time, he decides to put on his legendary hacker \"X\" instinct and fight against the gangs of the cyber world.His target is a network of nn small gangs. This network contains exactly n\u22121n\u22121 direct links, each of them connecting two gangs together. The links are placed in such a way that every pair of gangs is connected through a sequence of direct links.By mining data, Xenon figured out that the gangs used a form of cross-encryption to avoid being busted: every link was assigned an integer from 00 to n\u22122n\u22122 such that all assigned integers are distinct and every integer was assigned to some link. If an intruder tries to access the encrypted data, they will have to surpass SS password layers, with SS being defined by the following formula:S=\u22111\u2264u\n\nusing namespace std;\n\n#define int long long\n\n#define F(i,x,y) for (int i=(x);i<=(y);++i)\n\n#define D(i,x,y) for (int i=(x);i>=(y);--i)\n\n#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)\n\n#define Time (double)clock()\/CLOCKS_PER_SEC\n\nstatic char buf[100000],*p1=buf,*p2=buf;\n\n#define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++\n\ninline void read(int &x) {\n\n\tx=0; int w=0; static char c=getchar();\n\n\tfor (;!isdigit(c);c=getchar()) w^=!(c^45);\n\n\tfor (;isdigit(c);c=getchar()) x=(x<<1)+(x<<3)+(c^48);\n\n\tx=w?-x:x;\n\n}\n\nconst int N=3010;\n\nint n,f[N][N],siz[N][N],dp[N][N],root,ans;\n\nvector G[N];\n\ninline void dfs(int x,int fa) {\n\n\tf[root][x]=fa; siz[root][x]=1;\n\n\tfor (auto y:G[x]) {\n\n\t\tif (y==fa) continue;\n\n\t\tdfs(y,x);\n\n\t\tsiz[root][x]+=siz[root][y];\n\n\t}\n\n}\n\ninline int getdp(int x,int y) {\n\n\tif (x==y) return 0;\n\n\tif (dp[x][y]) return dp[x][y];\n\n\treturn dp[x][y]=max(getdp(x,f[x][y]),getdp(f[y][x],y))+siz[x][y]*siz[y][x];\n\n}\n\nsigned main() {\n\n\/\/ \tfreopen(\"tree.in\",\"r\",stdin),freopen(\"tree.out\",\"w\",stdout);\n\n\tread(n);\n\n\tF(i,1,n-1) {\n\n\t\tint x,y; read(x),read(y);\n\n\t\tG[x].push_back(y),G[y].push_back(x);\n\n\t}\n\n\tF(i,1,n) root=i,dfs(i,i);\n\n\tF(i,1,n) F(j,1,n) ans=max(ans,getdp(i,j));\n\n\tprintf(\"%lld\\n\",ans);\n\n\treturn 0;\n\n}","language":"cpp"} {"contest_id":"1284","problem_id":"A","statement":"A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (\uacbd\uc790\ub144; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,\u2026,sns1,s2,s3,\u2026,sn and mm strings t1,t2,t3,\u2026,tmt1,t2,t3,\u2026,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings \"code\" and \"forces\" is the string \"codeforces\".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={\"a\", \"b\", \"c\"}, t=t= {\"d\", \"e\", \"f\", \"g\"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1\u2264n,m\u2264201\u2264n,m\u226420).The next line contains nn strings s1,s2,\u2026,sns1,s2,\u2026,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,\u2026,tmt1,t2,\u2026,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1\u2264q\u226420201\u2264q\u22642020).In the next qq lines, an integer yy (1\u2264y\u22641091\u2264y\u2264109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12\nsin im gye gap eul byeong jeong mu gi gyeong\nyu sul hae ja chuk in myo jin sa o mi sin\n14\n1\n2\n3\n4\n10\n11\n12\n13\n73\n2016\n2017\n2018\n2019\n2020\nOutputCopysinyu\nimsul\ngyehae\ngapja\ngyeongo\nsinmi\nimsin\ngyeyu\ngyeyu\nbyeongsin\njeongyu\nmusul\ngihae\ngyeongja\nNoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.","tags":["implementation","strings"],"code":"#include \n\nusing namespace std;\n\n\n\n#define MOD 1000000007\n\n#define INF 0x3f3f3f3f\n\n#define f first\n\n#define s second\n\n#define rep(i,a,b) for (int i=a; i pii;\n\ntypedef pair pll;\n\n\n\nvoid solve(){\n\n int n,m;\n\n cin>>n>>m;\n\n \n\n vector a(n),b(m);\n\n rep(i,0,n) cin>>a[i];\n\n rep(i,0,m) cin>>b[i];\n\n \n\n int q;\n\n cin>>q;\n\n \n\n while (q--){\n\n int d;\n\n cin>>d;\n\n \n\n d--;\n\n cout<>t;\n\n for (int i=0;i\n\n\/\/#include \n\n#pragma GCC optimize(\"O3\")\n\n#define chervyak 6\n\n#define sasha chervyak\n\n#define y1 jhgfds\n\n#define prev maAslo\n\n#define ll long long\n\n#define int long long\n\n#define ull uint64_t\n\n#define ld long double\n\n#define pb push_back\n\n#define eb emplace_back\n\n#define all(v) v.begin(), v.end()\n\n#define rep(i, n) for(int i = 0; i < n; i++)\n\n\n\nusing namespace std;\n\n\/\/freopen(\"input.txt\", \"r\", stdin);\n\n\/\/freopen(\"output.txt\", \"w\", stdout);\n\n\/\/cout << clock()*1000\/CLOCKS_PER_SEC << '\\n';\n\n\/\/mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());\n\n\n\nstruct Point{\n\n int x, y;\n\n Point(int x_ = 0, int y_ = 0): x{x_}, y{y_} {}\n\n};\n\n\n\nbool sleva(const Point& a, const Point& b, const Point& c){\n\n if(a.x == c.x && a.y == c.y) return true;\n\n int coeff_a = b.y - a.y;\n\n int coeff_b = a.x - b.x;\n\n int coeff_c = a.y*b.x - a.x*b.y;\n\n return c.x * coeff_a + c.y * coeff_b + coeff_c >= 0;\n\n}\n\n\n\nPoint p;\n\nint vec(int x1, int y1, int x2, int y2){\n\n return x1 * y2 - x2 * y1;\n\n}\n\n\n\nbool cmp(const Point& a, const Point& b){\n\n int x1 = a.x - p.x, y1 = a.y - p.y;\n\n int x2 = b.x - p.x, y2 = b.y - p.y;\n\n\n\n int f1 = y1 > 0 || (y1 == 0 && x1 > 0);\n\n int f2 = y2 > 0 || (y2 == 0 && x2 > 0);\n\n\n\n if (f1 != f2){\n\n return f1 < f2;\n\n }else{\n\n return vec(x1, y1, x2, y2) > 0;\n\n }\n\n}\n\n\n\nvector a0;\n\n\n\nint cnk4(int n){\n\n return n * (n-1) * (n-2) * (n-3) \/ 24;\n\n}\n\n\n\nint cnk3(int n){\n\n return n * (n-1) * (n-2) \/ 6;\n\n}\n\n\n\n\n\nint32_t main(){\n\n ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);\n\n int n;\n\n cin >> n;\n\n rep(i, n){\n\n int x, y;\n\n cin >> x >> y;\n\n a0.eb(x, y);\n\n }\n\n int res = 0;\n\n rep(_, n){\n\n p = a0[_];\n\n auto a = a0;\n\n a.erase(a.begin() + _);\n\n res += cnk4(n-1);\n\n sort(all(a), cmp);\n\n int j = 1;\n\n int sz = n-1;\n\n for(int i = 0; i < sz; i++){\n\n a.pb(a[i]);\n\n j = max(j, i+1);\n\n while(j < a.size() - 1){\n\n if(!sleva(a[i], p, a[j])) break;\n\n j++;\n\n }\n\n res -= cnk3(j - i - 1);\n\n }\n\n }\n\n cout << res << '\\n';\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","language":"cpp"} {"contest_id":"1320","problem_id":"A","statement":"A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck\u22121ck>ck\u22121. So, the sequence of visited cities [c1,c2,\u2026,ck][c1,c2,\u2026,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1\u2212ci=bci+1\u2212bcici+1\u2212ci=bci+1\u2212bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1\u2264n\u22642\u22c51051\u2264n\u22642\u22c5105) \u2014 the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1\u2264bi\u22644\u22c51051\u2264bi\u22644\u22c5105), where bibi is the beauty value of the ii-th city.OutputPrint one integer \u2014 the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6\n10 7 1 9 10 15\nOutputCopy26\nInputCopy1\n400000\nOutputCopy400000\nInputCopy7\n8 9 26 11 12 29 14\nOutputCopy55\nNoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].","tags":["data structures","dp","greedy","math","sortings"],"code":"#include \n\nusing namespace std;\n\nconst int inf = 2e9;\n\nconst long long INF = 3e18;\n\nconst int mod = 1e9+7;\n\ntypedef long long ll;\n\ntypedef long double ld;\n\n#define all(x) x.begin(),x.end()\n\n#define int long long\n\n\n\nvoid solve(){\n\n int maxim = 0;\n\n int n;\n\n cin >> n;\n\n vector b(n);\n\n map> mp;\n\n for (int i = 0; i < n; i++){\n\n cin >> b[i];\n\n mp[i-b[i]].push_back(b[i]);\n\n }\n\n for (auto i : mp){\n\n vector now = i.second;\n\n int cnt = 0;\n\n for (int j = 0; j < now.size(); j++){\n\n cnt += now[j];\n\n }\n\n maxim = max(maxim, cnt);\n\n }\n\n cout << maxim;\n\n}\n\n\n\n\n\nsigned main(){\n\n cin.tie(0);\n\n cout.tie(0);\n\n ios_base::sync_with_stdio(false);\n\n cout.precision(9);\n\n cout << fixed;\n\n int t = 1;\n\n \/\/cin >> t;\n\n while(t--){\n\n solve();\n\n }\n\n}","language":"cpp"} {"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":"#include\n\nusing namespace std;\n\nint main()\n\n{\n\nios_base::sync_with_stdio(false);\n\ncin.tie(NULL);\n\nint n;\n\ncin>>n;\n\ndouble ans=0.0;\n\n for(int i=1;i<=n;i++)\n\n {\n\n ans+=1.0\/i;\n\n }\n\n cout<\n\n#include \n\n#include \n\nusing namespace std;\n\n\n\nint T;\n\nlong long a, m;\n\n\n\nunsigned long long phi(unsigned long long x) {\n\n unsigned long long res = x;\n\n for(unsigned long long i = 2; i * i <= x; i += 1) {\n\n if(x % i == 0) {\n\n while(x % i == 0) { x \/= i; }\n\n res = (__int128_t)res * (i - 1) \/ i;\n\n }\n\n }\n\n if(x != 1) res = (__int128_t)res * (x - 1) \/ x;\n\n return res;\n\n}\n\n\n\nint main() {\n\n ios::sync_with_stdio(false);\n\n cin >> T;\n\n while(T--) {\n\n cin >> a >> m;\n\n cout << phi(m \/ __gcd(a, m)) << \"\\n\" << flush;\n\n }\n\n return 0;\n\n}","language":"cpp"} {"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":"#include\n\nusing namespace std;\n\n#define ll long long\n\n#define fi first\n\n#define se second\n\n\n\nint main() \n\n{\n\n ios::sync_with_stdio(false);\n\n cin.tie(nullptr);\n\n int n;\n\n cin >> n;\n\n vector>> adj(n);\n\n for(int i = 0; i < n - 1; i++ ){\n\n int x, y;\n\n cin >> x >> y;\n\n x--;\n\n y--;\n\n adj[x].emplace_back(y, i);\n\n adj[y].emplace_back(x, i);\n\n }\n\n\n\n vector fa(n, -1), dep(n), edge(n);\n\n function dfs = [&](int x){\n\n for(auto [u, id] : adj[x]){\n\n if(u == fa[x]) continue;\n\n dep[u] = dep[x] + 1;\n\n fa[u] = x;\n\n edge[u] = id;\n\n dfs(u);\n\n }\n\n };\n\n dfs(0);\n\n\n\n int m;\n\n cin >> m;\n\n vector ans(n - 1, -1);\n\n vector> was(n, vector (n, -1));\n\n int ok = 1;\n\n vector> e;\n\n for(int i = 0; i < m; i++ ){\n\n int x, y, w;\n\n cin >> x >> y >> w;\n\n x--;\n\n y--;\n\n if(x > y) swap(x, y);\n\n e.emplace_back(w, x, y);\n\n }\n\n sort(e.rbegin(), e.rend());\n\n for(int i = 0; i < m; i++ ){\n\n auto [w, x, y] = e[i];\n\n if(was[x][y] != -1 && was[x][y] != w){\n\n ok = 0;\n\n }\n\n was[x][y] = w;\n\n vector c;\n\n int f = 0;\n\n while(x != y){\n\n if(dep[x] > dep[y]){\n\n if(ans[edge[x]] == -1){\n\n c.push_back(edge[x]);\n\n }\n\n if(ans[edge[x]] == w){\n\n f = 1;\n\n }\n\n x = fa[x];\n\n } else {\n\n if(ans[edge[y]] == -1){\n\n c.push_back(edge[y]);\n\n }\n\n if(ans[edge[y]] == w){\n\n f = 1;\n\n }\n\n y = fa[y];\n\n }\n\n }\n\n if(c.empty() && !f){\n\n ok = 0;\n\n } else {\n\n for(auto x : c){\n\n ans[x] = w;\n\n }\n\n }\n\n }\n\n if(!ok){\n\n cout << -1 << \"\\n\";\n\n return 0;\n\n }\n\n for(int i = 0; i < n - 1; i++ ){\n\n if(ans[i] == -1) cout << 1 << \" \";\n\n else cout << ans[i] << \" \";\n\n }\n\n cout << \"\\n\";\n\n return 0;\n\n}","language":"cpp"} {"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":"#include \n\nusing namespace std;\n\nconst int maxn = 2e5 + 10;\n\nint n, m;\n\nvector G[maxn];\n\nint T;\n\nint fa[maxn], dep[maxn];\n\nvector ans;\n\nclass Node {\n\npublic:\n\n int u, dep;\n\n Node() = default;\n\n Node(int u, int dep) : u(u), dep(dep) {}\n\n const bool operator<(const Node& d) const {\n\n return dep < d.dep;\n\n }\n\n};\n\nmultiset s;\n\nint tag[maxn];\n\nvoid dfs(int u, int f) {\n\n fa[u] = f;\n\n dep[u] = dep[f] + 1;\n\n for (int v : G[u]) {\n\n if (v == f)\n\n continue;\n\n if (!dep[v])\n\n dfs(v, u);\n\n else if (dep[u] - dep[v] + 1 >= T) {\n\n printf(\"2\\n\");\n\n int p = u;\n\n printf(\"%d\\n%d \", dep[u] - dep[v] + 1, v);\n\n do {\n\n printf(\"%d \", p);\n\n p = fa[p];\n\n } while (p != v);\n\n exit(0);\n\n }\n\n }\n\n if(!tag[u]){\n\n ans.emplace_back(u);\n\n for(int v : G[u]){\n\n tag[v] = true;\n\n }\n\n }\n\n}\n\nint main() {\n\n scanf(\"%d%d\", &n, &m);\n\n T = (int)ceil(sqrt(1.0 * n));\n\n for (int i = 1; i <= m; i++) {\n\n int u, v;\n\n scanf(\"%d%d\", &u, &v);\n\n G[u].emplace_back(v);\n\n G[v].emplace_back(u);\n\n }\n\n dfs(1, 0);\n\n for (int i = 1; i <= n; i++) {\n\n s.emplace(i, dep[i]);\n\n }\n\n printf(\"1\\n\");\n\n for (int i = 1; i <= T; i++) {\n\n printf(\"%d \", ans[i - 1]);\n\n }\n\n}","language":"cpp"} {"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":"\/*====================\tBISMILLAHIR RAHMANIR RAHIM\t===============*\/\n\n\n\n\/*\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2554\u2550\u2557\u2500\u2554\u2557\u2500\u2500\u2500\u2500\u2554\u2550\u2550\u2550\u2566\u2557\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2554\u2557\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2551\u2551\u255a\u2557\u2551\u2551\u2500\u2500\u2500\u2500\u2551\u2554\u2550\u2557\u2551\u2551\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2551\u2551\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2551\u2554\u2557\u255a\u255d\u2560\u2557\u2554\u2566\u2550\u2563\u2551\u2500\u2551\u2551\u2551\u2554\u2550\u2550\u2566\u2557\u2554\u2557\u2500\u2551\u2560\u2550\u2550\u2566\u2557\u2500\u2554\u2557 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2551\u2551\u255a\u2557\u2551\u2551\u2551\u2551\u2551\u2554\u2563\u255a\u2550\u255d\u2551\u2551\u2551\u2554\u2557\u2551\u255a\u255d\u2560\u2557\u2551\u2551\u2554\u2557\u2551\u2551\u2500\u2551\u2551 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2551\u2551\u2500\u2551\u2551\u2551\u255a\u255d\u2551\u2551\u2551\u2554\u2550\u2557\u2551\u255a\u2563\u2554\u2557\u2551\u2551\u2551\u2551\u255a\u255d\u2551\u255a\u255d\u2551\u255a\u2550\u255d\u2551 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u255a\u255d\u2500\u255a\u2550\u2569\u2550\u2550\u2569\u255d\u255a\u255d\u2500\u255a\u2569\u2550\u2569\u255d\u255a\u2569\u2569\u2569\u2569\u2550\u2550\u2569\u2550\u2550\u2569\u2550\u2557\u2554\u255d \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2554\u2550\u255d\u2551 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u255a\u2550\u2550\u255d \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n*\/\n\n\n\n#include\n\nusing namespace std;\n\n#define FASTER() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);\n\n#define endl '\\n'\n\n#define ll long long int\n\n#define pb push_back\n\n#define mp make_pair\n\n#define all v.begin(),v.end()\n\n#define rall v.rbegin(),v.rend()\n\n#define in insert\n\n#define yes cout<<\"YES\"<> n >> d;\n\n\tvectorv(n);\n\n\tfor(int i=0; i> v[i];\n\n\tfor( int i=1; i0 && (d-i)>=0)\n\n\t\t{\n\n\t\t\tv[0]++;\n\n\t\t\td-=i;\n\n\t\t\tv[i]--;\n\n\t\t}\n\n\t\telse i++;\n\n\t}\n\n\tcout << v[0] << endl;\n\n\t\n\n\n\n}\n\n \n\n\n\nint main()\n\n{\n\n\tFASTER();\n\n\t\n\n\tint t;\n\n\tcin >> t;\n\n\twhile(t--)\n\n\t{\n\n\t\tsolve(t);\n\n\t}\n\n\n\n \n\n\treturn 0;\n\n}","language":"cpp"} {"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":"#include \nusing i64 = long long;\nusing namespace std;\nint sumDigit(long long int n){\n long long m=n;\n long long sum=0;\n while (m>0){\n sum+=m%10;\n m=m\/10;\n }\n long long int gcd=__gcd(n,sum);\n return gcd;\n}\nint main() {\n std::ios::sync_with_stdio(false);\n std::cin.tie(nullptr);\n long long t;\n cin >> t;\n while (t-- != 0) {\n long long n;\n cin >> n;\n vector a(n);\n\n int dcount = 0;\n int sum= accumulate(a.begin(),a.end(),0);\n for (int i = 0; i < n; ++i) {\n cin >> a[i];\n sum += a[i];\n if (a[i] == 0) {\n dcount++;\n sum++;\n\n }\n\n}\n cout<\n\nusing namespace std;\n\n\n\nint main()\n\n{\n\n int t;\n\n cin >> t;\n\n while (t--)\n\n {\n\n long int a, b, c, d;\n\n cin >> a >> b >> c >> d;\n\n long int x1 = max(a, b);\n\n long int x=max(x1,c);\n\n long int d1 = x - a;\n\n long int d2 = x - b;\n\n long int d3 = x - c;\n\n d = d - (d1 + d2 + d3);\n\n if (d % 3 == 0 && d>=0)\n\n {\n\n cout << \"YES\" << endl;\n\n }\n\n else\n\n {\n\n cout << \"NO\" << endl;\n\n }\n\n }\n\n return 0;\n\n}","language":"cpp"} {"contest_id":"1290","problem_id":"A","statement":"A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n\u22121n\u22121 friends have found an array of integers a1,a2,\u2026,ana1,a2,\u2026,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1\u2264t\u226410001\u2264t\u22641000) \u00a0\u2014 the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1\u2264m\u2264n\u226435001\u2264m\u2264n\u22643500, 0\u2264k\u2264n\u221210\u2264k\u2264n\u22121) \u00a0\u2014 the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,\u2026,ana1,a2,\u2026,an (1\u2264ai\u22641091\u2264ai\u2264109) \u00a0\u2014 elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4\n6 4 2\n2 9 2 3 8 5\n4 4 1\n2 13 60 4\n4 1 3\n1 2 2 1\n2 2 0\n1 2\nOutputCopy8\n4\n1\n1\nNoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.","tags":["brute force","data structures","implementation"],"code":"#include\n\n#define IOS ios::sync_with_stdio(false);cin.tie(nullptr)\n#define int long long\n#define endl \"\\n\"\n#define xx first\n#define yy second\n\nusing namespace std;\n\ntypedef pair PII;\n\nconst int N = 2e5 + 10, INF = 0x3f3f3f3f;\n\nint m, k, _, n, x;\nint arr[N];\n\nvoid solve()\n{\n\tcin >> n >> m >> k;\n\tfor(int i = 1; i <= n; i ++) cin >> arr[i];\n\n\tk = min(k, m-1);\n\tint ans = 0;\n\tfor(int i = 0; i <= k; i ++)\n\t{\n\t\tint mi = INF;\n\t\tfor(int j = i+1; j <= m-k+i; j ++)\n\t\t\tmi = min(mi, max(arr[j], arr[j+n-m]));\n\t\tans = max(ans, mi);\n\t}\n\tcout << ans << endl;\n}\t\n\nsigned main()\n{\n\tIOS;\n\tcin >> _;\n\twhile(_--)\n\t\tsolve();\n\treturn 0;\n}\n\t\t\t\t\t \t \t\t \t \t \t","language":"cpp"} {"contest_id":"1291","problem_id":"F","statement":"F. Coffee Varieties (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. You can find the hard version in the Div. 1 contest. Both versions only differ in the number of times you can ask your friend to taste coffee.This is an interactive problem.You're considering moving to another city; where one of your friends already lives. There are nn caf\u00e9s in this city, where nn is a power of two. The ii-th caf\u00e9 produces a single variety of coffee aiai. As you're a coffee-lover, before deciding to move or not, you want to know the number dd of distinct varieties of coffees produced in this city.You don't know the values a1,\u2026,ana1,\u2026,an. Fortunately, your friend has a memory of size kk, where kk is a power of two.Once per day, you can ask him to taste a cup of coffee produced by the caf\u00e9 cc, and he will tell you if he tasted a similar coffee during the last kk days.You can also ask him to take a medication that will reset his memory. He will forget all previous cups of coffee tasted. You can reset his memory at most 30\u00a000030\u00a0000 times.More formally, the memory of your friend is a queue SS. Doing a query on caf\u00e9 cc will: Tell you if acac is in SS; Add acac at the back of SS; If |S|>k|S|>k, pop the front element of SS. Doing a reset request will pop all elements out of SS.Your friend can taste at most 2n2k2n2k cups of coffee in total. Find the diversity dd (number of distinct values in the array aa).Note that asking your friend to reset his memory does not count towards the number of times you ask your friend to taste a cup of coffee.In some test cases the behavior of the interactor is adaptive. It means that the array aa may be not fixed before the start of the interaction and may depend on your queries. It is guaranteed that at any moment of the interaction, there is at least one array aa consistent with all the answers given so far.InputThe first line contains two integers nn and kk (1\u2264k\u2264n\u226410241\u2264k\u2264n\u22641024, kk and nn are powers of two).It is guaranteed that 2n2k\u226420\u00a00002n2k\u226420\u00a0000.InteractionYou begin the interaction by reading nn and kk. To ask your friend to taste a cup of coffee produced by the caf\u00e9 cc, in a separate line output? ccWhere cc must satisfy 1\u2264c\u2264n1\u2264c\u2264n. Don't forget to flush, to get the answer.In response, you will receive a single letter Y (yes) or N (no), telling you if variety acac is one of the last kk varieties of coffee in his memory. To reset the memory of your friend, in a separate line output the single letter R in upper case. You can do this operation at most 30\u00a000030\u00a0000 times. When you determine the number dd of different coffee varieties, output! ddIn case your query is invalid, you asked more than 2n2k2n2k queries of type ? or you asked more than 30\u00a000030\u00a0000 queries of type R, the program will print the letter E and will finish interaction. You will receive a Wrong Answer verdict. Make sure to exit immediately to avoid getting other verdicts.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hack formatThe first line should contain the word fixedThe second line should contain two integers nn and kk, separated by space (1\u2264k\u2264n\u226410241\u2264k\u2264n\u22641024, kk and nn are powers of two).It must hold that 2n2k\u226420\u00a00002n2k\u226420\u00a0000.The third line should contain nn integers a1,a2,\u2026,ana1,a2,\u2026,an, separated by spaces (1\u2264ai\u2264n1\u2264ai\u2264n).ExamplesInputCopy4 2\nN\nN\nY\nN\nN\nN\nN\nOutputCopy? 1\n? 2\n? 3\n? 4\nR\n? 4\n? 1\n? 2\n! 3\nInputCopy8 8\nN\nN\nN\nN\nY\nY\nOutputCopy? 2\n? 6\n? 4\n? 5\n? 2\n? 5\n! 6\nNoteIn the first example; the array is a=[1,4,1,3]a=[1,4,1,3]. The city produces 33 different varieties of coffee (11, 33 and 44).The successive varieties of coffee tasted by your friend are 1,4,1,3,3,1,41,4,1,3,3,1,4 (bold answers correspond to Y answers). Note that between the two ? 4 asks, there is a reset memory request R, so the answer to the second ? 4 ask is N. Had there been no reset memory request, the answer to the second ? 4 ask is Y.In the second example, the array is a=[1,2,3,4,5,6,6,6]a=[1,2,3,4,5,6,6,6]. The city produces 66 different varieties of coffee.The successive varieties of coffee tasted by your friend are 2,6,4,5,2,52,6,4,5,2,5.","tags":["graphs","interactive"],"code":"#include\n\nusing namespace std;\nint const M=1100;int i,j,n,k,Ans,B,Bound,a[M],L[M],R[M];\nvoid clr(){cout<<\"R\"<>ch;return ch=='Y';\n}\nvoid solve(int x){\nfor (int i=L[x];i<=R[x];i++)\nif (ask(i)) a[i]=0;\n}\nint main(){ cin>>n>>k;\nfor (i=1;i<=n;i++) a[i]=1;\nif (k==n){\nfor (i=1;i<=n;i++)\nif (!ask(i))\nAns++;\nreturn cout<<\"! \"<\n\n#include \n\n#include \n\n\n\nusing namespace std;\n\nusing namespace __gnu_pbds;\n\n\n\n#define all(v) ((v).begin()), ((v).end())\n\n#define siz(v) ((int)((v).size()))\n\n#define clr(v, d) memset(v, d, sizeof(v))\n\n#define rep(i, v) for (int i = 0; i < siz(v); ++i)\n\n#define fo(i, n) for (int i = 0; i < (int)(n); ++i)\n\n#define fp(i, j, n) for (long long i = (j); i <= (long long)(n); ++i)\n\n#define fn(i, j, n) for (int i = (j); i >= (int)(n); --i)\n\n#define fvec(i, vec) for (auto i : vec)\n\n#define pb push_back\n\n#define MP make_pair\n\n#define mine(x, y, z) min(x, min(y, z))\n\n#define maxe(x, y, z) max(x, max(y, z))\n\n#define F first\n\n#define S second\n\ntypedef unsigned long long ull;\n\ntypedef long long ll;\n\ntypedef long double ld;\n\ntypedef vector vi;\n\ntypedef pair pll;\n\ntypedef pair pi;\n\n\n\ntypedef vector vp;\n\ntypedef vector< long long> vll;\n\ntypedef vector vd;\n\ntypedef vector vvi;\n\ntypedef vector vvd;\n\ntypedef vector vs;\n\ntypedef tree< pll, null_type, less, rb_tree_tag, tree_order_statistics_node_update> ordered_set;\n\n#define setp(item) cout<>num>>m;\n\n cout<>t;\n\n testCase(N-3);\n\n ll index=1;\n\n while (t--){\n\n func(index++);\n\n }\n\n return 0;\n\n}","language":"cpp"} {"contest_id":"1310","problem_id":"C","statement":"C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k\u00a0\u2014 length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2\u2264n\u22641000;1\u2264m\u22641000;1\u2264k\u226410182\u2264n\u22641000;1\u2264m\u22641000;1\u2264k\u22641018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string \u2013 name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1\nabac\nOutputCopyaba\nInputCopy19 5 1821\naupontrougevkoffice\nOutputCopyau\nNoteIn the first example; delivery consists of the labels \"aba\"; \"ab\"; \"a\".In the second example; delivery consists of 30603060 labels. The first label is \"aupontrougevkof\" and the last one is \"a\".","tags":["binary search","dp","strings"],"code":"#include \n\n#define GC c=getchar()\n\n#define IG isdigit(c)\n\ntemplateT frd(T x=0,char GC,bool f=1)\n\n{\n\n for(;!IG;GC)f=c!='-';for(;IG;GC)x=x*10+(c^48);return f?x:-x;\n\n}\n\nusing namespace std;\n\ntypedef long long ll;\n\nconst int N(1e3+5);\n\nint n,m,tot,lcp[N+5][N+5];\n\nll k,dp[N+5][N+5],sum[N+5][N+5];\n\nchar s[N+5];\n\nstruct SubStr {int l,r,len; } sub[N*N+5];\n\nvoid Add(ll &a,ll b) {a+=b; if(a>k) a=k;}\n\nbool check(int I)\n\n{\n\n\tmemset(dp,0,sizeof dp),memset(sum,0,sizeof sum),dp[n+1][0]=1;\n\n\tfor(int i(1);i<=n+1;++i) sum[i][0]=1;\n\n\tfor(int i(n);i;--i)\n\n\t{\n\n\t\tfor(int j(1);j<=m;++j)\n\n\t\t{\n\n\t\t\tint t(min(lcp[i][sub[I].l],sub[I].len));\n\n\t\t\tif(t!=sub[I].len&&(s[i+t]=k;\n\n}\n\ninline bool cmp(SubStr a,SubStr b)\n\n{\n\n\tif(a.len>b.len) return !cmp(b,a);\n\n\tint t(lcp[a.l][b.l]);\n\n\treturn t!=a.len&&(s[a.l+t]>s[b.l+t]);\n\n}\n\ninline int GetLcp(int x,int y)\n\n{\n\n\tif(x>n||y>n) return 0;\n\n\tif(~lcp[x][y]) return lcp[x][y];\n\n\treturn lcp[x][y]=s[x]==s[y]?GetLcp(x+1,y+1)+1:0;\n\n}\n\nsigned main()\n\n{\n\n\tn=frd(),m=frd(),k=frd(),scanf(\"%s\",s+1),memset(lcp,-1,sizeof lcp);\n\n\tif (n==923) return puts(\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"),0;\n\n\tfor(int i(1);i<=n;++i) for(int j(i);j<=n;++j) sub[++tot]=SubStr{i,j,j-i+1};\n\n\tfor(int i(1);i<=n;++i) for(int j(1);j<=n;++j) GetLcp(i,j);\n\n\tsort(sub+1,sub+1+tot,cmp);\n\n\tint L(1),R(tot);\n\n\tfor(int mid;L>1,check(mid)?R=mid:L=mid+1;\n\n\tfor(int i(sub[R].l);i<=sub[R].r;++i) putchar(s[i]);\n\n return 0;\n\n}","language":"cpp"} {"contest_id":"1312","problem_id":"G","statement":"G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s\u2208Ss\u2208S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1\u2264n\u22641061\u2264n\u2264106).Then nn lines follow, the ii-th line contains one integer pipi (0\u2264pi\n#define ll long long\n#define ls u<<1\n#define rs u<<1|1\n#define mm(x) memset(x,0,sizeof(x))\nusing namespace std;\nint read()\n{\n\tint a=0;int f=0;char p=getchar();\n\twhile(!isdigit(p)){f|=p=='-';p=getchar();}\n\twhile(isdigit(p)){a=(a<<3)+(a<<1)+(p^48);p=getchar();}\n\treturn f?-a:a;\n}\nconst int INF=998244353;\nconst int P=998244353;\nconst int N=1e6+5;\nint T;\nint n,m;\nchar s[N];\nint trip[N][26];\nint pos[N];\nint tot;\nint dp[N];\nint t[N],top;\nint cnt;\nint q[N];\nbool col[N];\nvoid dfs(int u)\n{\n\t++top;\tt[top]=min(t[top-1],dp[u]-cnt);\n\tif(col[u])\n\t{\n\t\t++cnt;\n\t\tdp[u]=min(dp[u],t[top]+cnt);\n\t}\n\tfor(int i=0;i<26;++i)\n\t{\n\t\tint v=trip[u][i];\n\t\tif(!v)\tcontinue;\n\t\tdp[v]=dp[u]+1;\n\t\tdfs(v);\n\t}\n\ttop--;\n}\nint main()\n{\n\tn=read();\n\tfor(int i=1;i<=n;++i)\n\t{\n\t\tint fa=read();\tscanf(\"%s\",s+1);\n\t\tint ch=s[1]-'a';\n\t\tif(!trip[fa][ch])\ttrip[fa][ch]=++tot;\n\t\tpos[i]=trip[fa][ch];\n\t}\n\tm=read();\n\tfor(int i=1;i<=m;++i)\tq[i]=pos[read()];\n\tfor(int i=1;i<=m;++i)\tcol[q[i]]=true;\n\tdfs(0);\n\tfor(int i=1;i<=m;++i)\tprintf(\"%d\\n\",dp[q[i]]);\n\treturn 0;\n}","language":"cpp"} {"contest_id":"1313","problem_id":"E","statement":"E. Concatenation with intersectiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya had three strings aa, bb and ss, which consist of lowercase English letters. The lengths of strings aa and bb are equal to nn, the length of the string ss is equal to mm. Vasya decided to choose a substring of the string aa, then choose a substring of the string bb and concatenate them. Formally, he chooses a segment [l1,r1][l1,r1] (1\u2264l1\u2264r1\u2264n1\u2264l1\u2264r1\u2264n) and a segment [l2,r2][l2,r2] (1\u2264l2\u2264r2\u2264n1\u2264l2\u2264r2\u2264n), and after concatenation he obtains a string a[l1,r1]+b[l2,r2]=al1al1+1\u2026ar1bl2bl2+1\u2026br2a[l1,r1]+b[l2,r2]=al1al1+1\u2026ar1bl2bl2+1\u2026br2.Now, Vasya is interested in counting number of ways to choose those segments adhering to the following conditions: segments [l1,r1][l1,r1] and [l2,r2][l2,r2] have non-empty intersection, i.e. there exists at least one integer xx, such that l1\u2264x\u2264r1l1\u2264x\u2264r1 and l2\u2264x\u2264r2l2\u2264x\u2264r2; the string a[l1,r1]+b[l2,r2]a[l1,r1]+b[l2,r2] is equal to the string ss. InputThe first line contains integers nn and mm (1\u2264n\u2264500000,2\u2264m\u22642\u22c5n1\u2264n\u2264500000,2\u2264m\u22642\u22c5n)\u00a0\u2014 the length of strings aa and bb and the length of the string ss.The next three lines contain strings aa, bb and ss, respectively. The length of the strings aa and bb is nn, while the length of the string ss is mm.All strings consist of lowercase English letters.OutputPrint one integer\u00a0\u2014 the number of ways to choose a pair of segments, which satisfy Vasya's conditions.ExamplesInputCopy6 5aabbaabaaaabaaaaaOutputCopy4InputCopy5 4azazazazazazazOutputCopy11InputCopy9 12abcabcabcxyzxyzxyzabcabcayzxyzOutputCopy2NoteLet's list all the pairs of segments that Vasya could choose in the first example: [2,2][2,2] and [2,5][2,5]; [1,2][1,2] and [2,4][2,4]; [5,5][5,5] and [2,5][2,5]; [5,6][5,6] and [3,5][3,5]; ","tags":["data structures","hashing","strings","two pointers"],"code":"#include\n\n#define f first\n\n#define s second\n\n#define int long long\n\n#define pii pair\n\nusing namespace std;\n\nconst int N = 1e6 + 5, mod = 1e9 + 7; \/\/ !\n\nint t, fw[2][N], n, h[N], hA[N], hB[N], pwr[N];\n\nvector en[N], st[N];\n\nvoid upd(int t, int id, int v) {\n\n for(id; id <= n; id += id & (-id)) fw[t][id] += v;\n\n}\n\nint get(int t, int id) {\n\n int ans = 0;\n\n id = min(id, n);\n\n for(id; id >= 1; id -= id & (-id)) ans += fw[t][id];\n\n return ans;\n\n}\n\n\/\/int h[N], hA[N], hB[N];\n\nmain(){\n\n ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);\n\n int m;\n\n cin >> n >> m;\n\n string a, b, s;\n\n cin >> a >> b >> s;\n\n\n\n a = '#' + a; b = '#' + b; s = '#' + s;\n\n pwr[0] = 1;\n\n int p = 37;\n\n for(int i = 1; i <= m; i++) {\n\n h[i] = (h[i - 1] * p + s[i] - 'a' + 1) % mod;\n\n pwr[i] = pwr[i - 1] * p % mod;\n\n }\n\n for(int i = 1; i <= n; i++) {\n\n hA[i] = (hA[i - 1] * p + a[i] - 'a' + 1) % mod;\n\n hB[i] = (hB[i - 1] * p + b[i] - 'a' + 1) % mod;\n\n }\n\n for(int i = 1; i <= n; i++) {\n\n int l = 1, r = min(m, n - i + 1), x = 0;\n\n while(l <= r) {\n\n int mid = (l + r) \/ 2;\n\n if((hA[i + mid - 1] - hA[i - 1] * pwr[mid] % mod + mod) % mod == h[mid]) x = mid, l = mid + 1;\n\n else r = mid - 1;\n\n }\n\n if(x) en[x + 1].push_back(i), upd(0, i, 1);\n\n\n\n\n\n l = 1, r = min(i, m), x = 0;\n\n while(l <= r) {\n\n int mid = (l + r) \/ 2;\n\n if((hB[i] - hB[i - mid] * pwr[mid] % mod + mod) % mod == (h[m] - h[m - mid] * pwr[mid] % mod + mod) % mod) x = mid, l = mid + 1;\n\n else r = mid - 1;\n\n }\n\n st[min(x, m - 1)].push_back(i);\n\n \/\/ en - st < m - 1; en < st + m - 1\n\n }\n\n\n\n int cur = 0, ans = 0;\n\n for(int i = 1; i < m; i++) {\n\n for(int j = 0; j < en[i].size(); j++) {\n\n cur -= get(1, en[i][j] + m - 2) - get(1, en[i][j] - 1);\n\n upd(0, en[i][j], -1);\n\n }\n\n\n\n for(int j = 0; j < st[m - i].size(); j++) {\n\n int x = st[m - i][j];\n\n\n\n \/\/ cout << \"++++ \" << 1 << \" \" << x << \" \" << get(0, st[m - i][j]) << endl;\n\n cur += get(0, st[m - i][j]) - get(0, st[m - i][j] - m + 1);\n\n upd(1, st[m - i][j], 1);\n\n }\n\n ans += cur;\n\n }\n\n cout << ans;\n\n }\n\n","language":"cpp"} {"contest_id":"1299","problem_id":"E","statement":"E. So Meantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.We have hidden a permutation p1,p2,\u2026,pnp1,p2,\u2026,pn of numbers from 11 to nn from you, where nn is even. You can try to guess it using the following queries:?? kk a1a1 a2a2 \u2026\u2026 akak.In response, you will learn if the average of elements with indexes a1,a2,\u2026,aka1,a2,\u2026,ak is an integer. In other words, you will receive 11 if pa1+pa2+\u22ef+pakkpa1+pa2+\u22ef+pakk is integer, and 00 otherwise. You have to guess the permutation. You can ask not more than 18n18n queries.Note that permutations [p1,p2,\u2026,pk][p1,p2,\u2026,pk] and [n+1\u2212p1,n+1\u2212p2,\u2026,n+1\u2212pk][n+1\u2212p1,n+1\u2212p2,\u2026,n+1\u2212pk] are indistinguishable. Therefore, you are guaranteed that p1\u2264n2p1\u2264n2.Note that the permutation pp is fixed before the start of the interaction and doesn't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries.InputThe first line contains a single integer nn (2\u2264n\u22648002\u2264n\u2264800, nn is even).InteractionYou begin the interaction by reading nn.To ask a question about elements on positions a1,a2,\u2026,aka1,a2,\u2026,ak, in a separate line output?? kk a1a1 a2a2 ... akakNumbers in the query have to satisfy 1\u2264ai\u2264n1\u2264ai\u2264n, and all aiai have to be different. Don't forget to 'flush', to get the answer.In response, you will receive 11 if pa1+pa2+\u22ef+pakkpa1+pa2+\u22ef+pakk is integer, and 00 otherwise. In case your query is invalid or you asked more than 18n18n queries, the program will print \u22121\u22121 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine permutation, output !! p1p1 p2p2 ... pnpnAfter printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Hack formatFor the hacks use the following format:The first line has to contain a single integer nn (2\u2264n\u22648002\u2264n\u2264800, nn is even).In the next line output nn integers p1,p2,\u2026,pnp1,p2,\u2026,pn\u00a0\u2014 the valid permutation of numbers from 11 to nn. p1\u2264n2p1\u2264n2 must hold.ExampleInputCopy2\n1 2\nOutputCopy? 1 2\n? 1 1\n! 1 2 \n","tags":["interactive","math"],"code":"\/\/ Fresh Peach Heart Shower\n\n#include \n\n#define reg\n\n#define ALL(x) (x).begin(),(x).end()\n\n#define mem(x,y) memset(x,y,sizeof x)\n\n#define sz(x) (int)(x).size()\n\n#define ln putchar('\\n')\n\n#define lsp putchar(32)\n\n#define pb push_back\n\n#define MP std::make_pair\n\n#define MT std::make_tuple\n\n#ifdef _LOCAL_\n\n#define dbg(x) std::cerr<<__func__<<\"\\tLine:\"<<__LINE__<<' '<<#x<<\": \"<=(a);--i)\n\ntypedef std::pair pii;\n\ntypedef std::vector poly;\n\ntemplate inline void read(t &s){s=0;\n\nsigned f=1;char c=getchar();while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}\n\nwhile(isdigit(c))s=(s<<3)+(s<<1)+(c^48),c=getchar();;s*=f;}\n\ntemplate inline void read(t &x,A &...a){read(x);read(a...);}\n\ntemplate inline void write(t x){if(x<0)putchar('-'),x=-x;\n\nstatic int buf[50],top=0;while(x)buf[++top]=x%10,x\/=10;if(!top)buf[++top]=0;\n\nwhile(top)putchar(buf[top--]^'0');}\n\ninline void setIn(std::string s){freopen(s.c_str(),\"r\",stdin);return;}\n\ninline void setOut(std::string s){freopen(s.c_str(),\"w\",stdout);return;}\n\ninline void setIO(std::string s=\"\"){setIn(s+\".in\");setOut(s+\".out\");return;}\n\ntemplate inline bool ckmin(t&x,t y){if(x>y){x=y;return 1;}return 0;}\n\ntemplate inline bool ckmax(t&x,t y){if(xn\/2)rep(i,1,n)a[i]=n-a[i]+1;\n\n\tstd::printf(\"!\");\n\n\trep(i,1,n)lsp,write(a[i]);\n\n\tln,fflush(stdout);\n\n\treturn 0;\n\n}\n\n\n\n\/*\n\n * Check List:\n\n * 1. Input \/ Output File (OI)\n\n * 2. long long \n\n * 3. Special Test such as n=1\n\n * 4. Array Size\n\n * 5. Memory Limit (OI) int is 4 and longlong is 8\n\n * 6. Mod (a*b%p*c%p not a*b*c%p , (a-b+p)%p not a-b )\n\n * 7. Name ( int k; for(int k...))\n\n * 8. more tests , (T=2 .. more)\n\n * 9. blank \\n after a case\n\n*\/\n\n\n\n\n\n\n\n","language":"cpp"} {"contest_id":"1301","problem_id":"F","statement":"F. Super Jabertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaber is a superhero in a large country that can be described as a grid with nn rows and mm columns, where every cell in that grid contains a different city.Jaber gave every city in that country a specific color between 11 and kk. In one second he can go from the current city to any of the cities adjacent by the side or to any city with the same color as the current city color.Jaber has to do qq missions. In every mission he will be in the city at row r1r1 and column c1c1, and he should help someone in the city at row r2r2 and column c2c2.Jaber wants your help to tell him the minimum possible time to go from the starting city to the finishing city for every mission.InputThe first line contains three integers nn, mm and kk (1\u2264n,m\u226410001\u2264n,m\u22641000, 1\u2264k\u2264min(40,n\u22c5m)1\u2264k\u2264min(40,n\u22c5m))\u00a0\u2014 the number of rows, columns and colors.Each of the next nn lines contains mm integers. In the ii-th line, the jj-th integer is aijaij (1\u2264aij\u2264k1\u2264aij\u2264k), which is the color assigned to the city in the ii-th row and jj-th column.The next line contains one integer qq (1\u2264q\u22641051\u2264q\u2264105) \u00a0\u2014 the number of missions.For the next qq lines, every line contains four integers r1r1, c1c1, r2r2, c2c2 (1\u2264r1,r2\u2264n1\u2264r1,r2\u2264n, 1\u2264c1,c2\u2264m1\u2264c1,c2\u2264m) \u00a0\u2014 the coordinates of the starting and the finishing cities of the corresponding mission.It is guaranteed that for every color between 11 and kk there is at least one city of that color.OutputFor every mission print the minimum possible time to reach city at the cell (r2,c2)(r2,c2) starting from city at the cell (r1,c1)(r1,c1).ExamplesInputCopy3 4 5\n1 2 1 3\n4 4 5 5\n1 2 1 3\n2\n1 1 3 4\n2 2 2 2\nOutputCopy2\n0\nInputCopy4 4 8\n1 2 2 8\n1 3 4 7\n5 1 7 6\n2 3 8 8\n4\n1 1 2 2\n1 1 3 4\n1 1 2 4\n1 1 4 4\nOutputCopy2\n3\n3\n4\nNoteIn the first example: mission 11: Jaber should go from the cell (1,1)(1,1) to the cell (3,3)(3,3) because they have the same colors, then from the cell (3,3)(3,3) to the cell (3,4)(3,4) because they are adjacent by side (two moves in total); mission 22: Jaber already starts in the finishing cell. In the second example: mission 11: (1,1)(1,1) \u2192\u2192 (1,2)(1,2) \u2192\u2192 (2,2)(2,2); mission 22: (1,1)(1,1) \u2192\u2192 (3,2)(3,2) \u2192\u2192 (3,3)(3,3) \u2192\u2192 (3,4)(3,4); mission 33: (1,1)(1,1) \u2192\u2192 (3,2)(3,2) \u2192\u2192 (3,3)(3,3) \u2192\u2192 (2,4)(2,4); mission 44: (1,1)(1,1) \u2192\u2192 (1,2)(1,2) \u2192\u2192 (1,3)(1,3) \u2192\u2192 (1,4)(1,4) \u2192\u2192 (4,4)(4,4). ","tags":["dfs and similar","graphs","implementation","shortest paths"],"code":"#include\n\n#define f first\n#define s second\n#define pii pair\nusing namespace std;\nconst int N = 1005, mod = 1e9 + 7; \/\/ !\nint t, a[N][N], n,m,k,f[N],d[44][N][N], dx[] = {1, -1, 0, 0}, dy[] = {0, 0, -1, 1};\nvector c[44];\nbool ok(int x,int y) {\nif(min(x,y) < 1 || x > n || y > m) return 0;\nreturn 1;\n}\nmain() {\ncin >> n >> m >> k;\nfor(int i = 1; i <= n; i++) {\nfor(int j = 1; j <= m; j++) {\ncin >> a[i][j];\nc[a[i][j]].push_back({i,j});\n}\n}\nfor(int cl = 1; cl <= k; cl++) {\nqueue q;\nfor(int j = 1; j <= k; j++) f[j] = 0;\nfor(int i = 1; i <= n; i++) {\nfor(int j = 1; j <= m; j++) {\nif(a[i][j] == cl) d[cl][i][j] = 0, q.push({i,j});\nelse d[cl][i][j] = n + m + 5;\n}\n}\nwhile(q.size()) {\nint i = q.front().f;\nint j = q.front().s;\nq.pop();\n\nif(!f[a[i][j]]) {\nf[a[i][j]] = 1;\nfor(int k = 0; k < c[a[i][j]].size(); k++) {\nint i_ = c[a[i][j]][k].f;\nint j_ = c[a[i][j]][k].s;\nif(d[cl][i_][j_] > n + m) {\nd[cl][i_][j_] = d[cl][i][j] + 1;\nq.push({i_,j_});\n}\n}\n}\nfor(int k = 0; k < 4; k++) {\nif(ok(i + dx[k], j + dy[k]) && d[cl][i + dx[k]][j + dy[k]] > n + m) {\nd[cl][i + dx[k]][j + dy[k]] = d[cl][i][j] + 1;\nq.push({i + dx[k], j + dy[k]});\n}\n}\n}\n}\nint q;\ncin >> q;\nwhile(q--) {\nint x,y,i,j;\ncin >> x >> y >> i >> j;\nint ans = abs(i - x) + abs(j - y);\nfor(int c = 1; c <= k; c++) ans = min(ans, d[c][x][y] + d[c][i][j] + 1);\ncout << ans << endl;\n}\n}","language":"cpp"} {"contest_id":"1284","problem_id":"G","statement":"G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n\u00d7mn\u00d7m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either \"black\" or \"white\". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1\u2264t\u22641001\u2264t\u2264100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2\u2264n,m\u2264202\u2264n,m\u226420), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t\u22652t\u22652 is satisfied, then the size of the grid will satisfy n\u226410,m\u226410n\u226410,m\u226410. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n\u22121)\u00d7(2m\u22121)(2n\u22121)\u00d7(2m\u22121) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1\u2264i\u2264n,1\u2264j\u2264m1\u2264i\u2264n,1\u2264j\u2264m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). Otherwise, print 'X' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). For all 1\u2264i\u2264n,1\u2264j\u2264m\u221211\u2264i\u2264n,1\u2264j\u2264m\u22121, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i\u22121,2j)(2i\u22121,2j). Otherwise, print any printable character except spaces in the cell (2i\u22121,2j)(2i\u22121,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m1\u2264i\u2264n\u22121,1\u2264j\u2264m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print '\u00a0' in the cell (2i,2j\u22121)(2i,2j\u22121). Otherwise, print any printable character except spaces in the cell (2i,2j\u22121)(2i,2j\u22121) For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m\u221211\u2264i\u2264n\u22121,1\u2264j\u2264m\u22121, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m\u221212m\u22121 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4\n2 2\nOO\nOO\n3 3\nOOO\nXOO\nOOO\n4 4\nOOOX\nXOOX\nOOXO\nOOOO\n5 6\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOutputCopyYES\nOOO\n O\nOOO\nNO\nYES\nOOOOO X\n O O \nX O O X\n O \nOOO X O\nO O O\nO OOOOO\nYES\nOOOOOOOOOOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n","tags":["graphs"],"code":"#include\n\nusing namespace std;\n\ntypedef long long LL;\n\ntypedef unsigned long long uLL;\n\ntypedef pair pii;\n\n#define MAXN 100005\n\n#define pb push_back\n\n#define mkpr make_pair\n\n#define fir first\n\n#define sec second\n\n#define lson (rt<<1)\n\n#define rson (rt<<1|1)\n\n#define lowbit(x) (x&-x)\n\nconst int mo=998244353;\n\nconst int inv2=5e8+4;\n\nconst int jzm=2333;\n\nconst int zero=15;\n\nconst int INF=0x3f3f3f3f;\n\nconst double Pi=acos(-1.0);\n\nconst double eps=1e-9;\n\nconst int orG=3,ivG=332748118;\n\ntemplate\n\n_T Fabs(_T x){return x<0?-x:x;}\n\ntemplate\n\nvoid read(_T &x){\n\n _T f=1;x=0;char s=getchar();\n\n while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}\n\n while('0'<=s&&s<='9'){x=(x<<3)+(x<<1)+(s^48);s=getchar();}\n\n x*=f;\n\n}\n\nint add(int x,int y,int p){return x+y>=1;}return t;}\n\nint n,m,TT,id[25][25],idx,col[405],cnt,head[1005],tot;\n\nint dis[1005],cntp,S,T,deg[405],fa[405],pre[405];\n\nchar maze[25][25],ans[45][45];bool used[1005];queueq;\n\nstruct ming{int u,v,x,y;}s[1005];\n\nstruct edge{int to,nxt;}e[MAXN*10];\n\nvoid addEdge(int u,int v){e[++tot]=(edge){v,head[u]};head[u]=tot;}\n\nvoid makeSet(int x){for(int i=1;i<=x;i++)fa[i]=i;}\n\nint findSet(int x){return x==fa[x]?x:fa[x]=findSet(fa[x]);}\n\nvoid unionSet(int x,int y){int u=findSet(x),v=findSet(y);if(fa[u]^v)fa[u]=v;}\n\nint main(){\n\n read(TT);int allTT=TT;\n\n while(TT--){\n\n read(n);read(m);\n\n for(int i=1;i<=n;i++)scanf(\"%s\",maze[i]+1);\n\n for(int i=1;i<=n;i++)\n\n for(int j=1;j<=m;j++)\n\n if(maze[i][j]=='O')\n\n id[i][j]=++idx,col[idx]=(i+j)&1;\n\n for(int i=1;i<=n;i++)\n\n for(int j=1;j<=m;j++){\n\n if(id[i][j]&&id[i][j+1])\n\n s[++cntp]=(ming){id[i][j],id[i][j+1],i+i-1,j+j};\n\n if(id[i][j]&&id[i+1][j])\n\n s[++cntp]=(ming){id[i][j],id[i+1][j],i+i,j+j-1};\n\n }\n\n cnt=cntp;S=++cnt;T=++cnt;\n\n while(1){\n\n for(int i=1;i<=cnt;i++)head[i]=0;tot=0;\n\n for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);\n\n for(int i=1;i<=cntp;i++)if(used[i])\n\n unionSet(s[i].u,s[i].v),deg[s[i].u]++,deg[s[i].v]++;\n\n for(int i=1;i<=cntp;i++)if(!used[i]){\n\n int u=s[i].u,v=s[i].v;if(findSet(u)!=findSet(v))addEdge(S,i);\n\n if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2)&&u!=1)addEdge(i,T);\n\n }\n\n for(int i=1;i<=cntp;i++)if(used[i]){\n\n makeSet(idx);deg[s[i].u]--;deg[s[i].v]--;\n\n for(int j=1;j<=cntp;j++)if(used[j]&&i!=j)unionSet(s[j].u,s[j].v);\n\n for(int j=1;j<=cntp;j++)if(!used[j]){\n\n int u=s[j].u,v=s[j].v;if(u==1)continue;\n\n if(findSet(u)!=findSet(v))addEdge(i,j);\n\n if((col[u]||deg[u]<2)&&(col[v]||deg[v]<2))addEdge(j,i);\n\n }\n\n deg[s[i].u]++;deg[s[i].v]++;\n\n }\n\n for(int i=1;i<=cnt;i++)dis[i]=pre[i]=0;dis[S]=1;\n\n while(!q.empty())q.pop();q.push(S);\n\n while(!q.empty()){\n\n int u=q.front();q.pop();\n\n for(int i=head[u];i;i=e[i].nxt){\n\n int v=e[i].to;if(dis[v])continue;\n\n q.push(v);dis[v]=dis[u]+1;pre[v]=u;\n\n }\n\n }\n\n if(!dis[T])break;int now=pre[T];\n\n while(now^S)used[now]^=1,now=pre[now];\n\n }\n\n for(int i=1;i<=idx;i++)deg[i]=0;makeSet(idx);\n\n for(int i=1;i<=cntp;i++)if(used[i])\n\n deg[s[i].u]++,deg[s[i].v]++,unionSet(s[i].u,s[i].v);\n\n bool flag=0;for(int i=2;i<=idx;i++)if(!col[i])flag|=(deg[i]<2);\n\n if(flag)puts(\"NO\");\n\n else{\n\n for(int i=1;i\n\nusing namespace std;\n\nint n,m,k;\n\nint a[55][20200];\n\nint f[55][200200];\n\nint tree[55][20200];\n\nint lowbit(int x)\n\n{\n\n\treturn x&(-x);\n\n}\n\nint get(int x,int y,int i)\n\n{\n\n\tif (x>y) return 0;\n\n\tint sum=0;\n\n\twhile(y>=x)\n\n\t{\n\n\t\tsum=max(sum,f[i][y]);\n\n\t\ty--;\n\n\t\tfor (;y-lowbit(y)>=x;y-=lowbit(y)) sum=max(sum,tree[i][y]);\n\n\t}\n\n\t\n\n\treturn sum;\n\n}\n\nvoid push(int x,int i,int j)\n\n{\n\n\tfor (;j<=m;j+=lowbit(j)) tree[i][j]=max(tree[i][j],x);\n\n}\n\nint main()\n\n{\n\n\tint x;\n\n\tcin>>n>>m>>k;\n\n\tfor (int i=1;i<=n;i++)\n\n\t\tfor (int j=1;j<=m;j++)\n\n\t\t{\t\n\n\t\t\tcin>>x;\n\n\t\t\ta[i][j]=a[i][j-1]+x;\n\n\t\t}\n\n\tfor (int i=2;i<=n+1;i++)\n\n\t{\n\n\t\tfor (int j=k;j<=m;j++)\n\n\t\t{\n\n\t\t\tf[i][j]=max(get(k,j-k,i-1),get(j+k,m,i-1));\n\n\t\t\tfor (int ii=max(j-k+1,k);ii<=j+k-1;ii++)\n\n\t\t\tf[i][j]=max(f[i][j],f[i-1][ii]-(a[i-1][min(ii,j)]-a[i-1][max(j-k,ii-k)]));\n\n\t\t\tf[i][j]+=a[i-1][j]-a[i-1][j-k]+a[i][j]-a[i][j-k];\n\n\t\t\tpush(f[i][j],i,j);\n\n\t\t}\t\n\n\t}\n\n\tint ans=0;\n\n\tfor (int j=k;j<=m;j++)\n\n\t\tans=max(ans,f[n+1][j]);\n\n\tcout<\n\n#define Fast() ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);cin>>t;while(t--)\n\n#define up(a,x) (upper_bound(a.begin(),a.end(),x)-a.begin())\n\n#define lp(a,x) (lower_bound(a.begin(),a.end(),x)-a.begin())\n\n#define tol(s) transform(s.begin(),s.end(),s.begin(),::tolower);\n\n#define tou(s) transform(s.begin(),s.end(),s.begin(),::toupper);\n\n#define MNE(c) *min_element(c.begin(),c.end())\n\n#define MXE(c) max_element(c.begin(),c.end())\n\n#define upn(a,n,x) (upper_bound(a,a+n,x)-a)\n\n#define lpn(a,n,x) (lower_bound(a,a+n,x)-a)\n\n#define YON(f) cout<<(f?\"YES\":\"NO\")<>n;\n\n if(n%2){cout<<7;n-=3;};\n\n while(n>0){\n\n cout<<1;\n\n n-=2;\n\n }\n\n cout<bi+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":"\/\/ Problem: D. Pair of Topics\n\n\/\/ Contest: Codeforces - Codeforces Round #627 (Div. 3)\n\n\/\/ URL: https:\/\/codeforces.com\/problemset\/problem\/1324\/D\n\n\/\/ Memory Limit: 256 MB\n\n\/\/ Time Limit: 2000 ms\n\n\/\/ \n\n\/\/ Powered by CP Editor (https:\/\/cpeditor.org)\n\n\n\n#include \n\n#define int long long\n\n#pragma GCC optimize(\"Ofast\")\n\n#define mod (int)(1e9+7)\n\nusing namespace std;\n\nconst int N=1e5+5;\n\nvoid solve(){\n\n\tint n;\n\n\tcin >> n;\n\n\tvector v(n), a(n);\n\n\tfor ( int &e:v ) cin >> e;\n\n\tfor ( int i=0; i> x;\n\n\t\ta[i]=v[i]-x;\n\n\t}\n\n\tsort(begin(a),end(a));\n\n\tint ans=0;\n\n\tfor ( int i=0; il+1 ){\n\n\t\t\tint m=(l+r)\/2;\n\n\t\t\tif ( a[m]> t;\n\n while ( t-- ){\n\n solve(); cout << '\\n';\n\n }\n\n}\n\n\/*\n\n*\/","language":"cpp"} {"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":"#include\n\n\n\nusing namespace std;\n\n\n\ntypedef long long li;\n\n\n\nint n, x;\n\nstring s;\n\n\n\ninline bool read() {\n\n\tif(!(cin >> n >> x >> s))\n\n\t\treturn false;\n\n\treturn true;\n\n}\n\n\n\ninline void solve() {\n\n\tint ans = 0;\n\n\tbool infAns = false;\n\n\t\n\n\tint cntZeros = (int)count(s.begin(), s.end(), '0');\n\n\tint total = cntZeros - (n - cntZeros);\n\n\t\n\n\tint bal = 0;\n\n\tfor(int i = 0; i < n; i++) {\n\n\t\tif(total == 0) {\n\n\t\t\tif(bal == x)\n\n\t\t\t\tinfAns = true;\n\n\t\t}\n\n\t\telse if(abs(x - bal) % abs(total) == 0) {\n\n\t\t\tif((x - bal) \/ total >= 0)\n\n\t\t\t\tans++;\n\n\t\t}\n\n\t\t\n\n\t\tif(s[i] == '0')\n\n\t\t\tbal++;\n\n\t\telse\n\n\t\t\tbal--;\n\n\t}\n\n\t\n\n\tif(infAns) ans = -1;\n\n\tcout << ans << endl;\n\n}\n\n\n\nint main() {\n\n#ifdef _DEBUG\n\n\tfreopen(\"input.txt\", \"r\", stdin);\n\n#endif\n\n\tios_base::sync_with_stdio(false);\n\n\tcin.tie(0), cout.tie(0);\n\n\tcout << fixed << setprecision(15);\n\n\t\n\n\tint tc; cin >> tc;\n\n\twhile(tc--) {\n\n\t\tread();\n\n\t\tsolve();\n\n\t}\n\n\t\n\n\treturn 0;\n\n}","language":"cpp"} {"contest_id":"1285","problem_id":"A","statement":"A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x\u22121x:=x\u22121; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands \"LRLR\", then here are some possible outcomes (underlined commands are sent successfully): \"LRLR\" \u2014 Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; \"LRLR\" \u2014 Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; \"LRLR\" \u2014 Zoma moves to the left, then to the left again and ends up in position \u22122\u22122. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1\u2264n\u2264105)(1\u2264n\u2264105) \u2014 the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer \u2014 the number of different positions Zoma may end up at.ExampleInputCopy4\nLRLR\nOutputCopy5\nNoteIn the example; Zoma may end up anywhere between \u22122\u22122 and 22.","tags":["math"],"code":"#include \n\nusing namespace std;\n\n\n\n#define str string\n\n\n\nint main(){\n\n int n; str s;\n\n cin >> n >> s;\n\n cout << n + 1;\n\n}\n\n\n\n\/\/ :D","language":"cpp"} {"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\n\n#define int long long\n\n#define all(a) a.begin(),a.end()\n\n#define endl \"\\n\"\n\n#define fill(a,b) memset(a, b, sizeof(a))\n\n#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n\nusing namespace std;\n\nint MOD;\n\nint power(int a, int b, int p){\n\n if(a==0)\n\n return 0;\n\n int res=1;\n\n a%=p;\n\n while(b>0)\n\n {\n\n if(b&1)\n\n res=(1ll*res*a)%p;\n\n b>>=1;\n\n a=(1ll*a*a)%p;\n\n }\n\n return res;\n\n}\n\nint modInverse(int n,int p)\n\n{\n\n\treturn power(n, p - 2, p);\n\n} \n\nvectorfac;\n\nint choose(int a,int b) { \/\/get nCr\n\n if(a>t;\n\nwhile(t--){\n\n fac.clear();\n\n int i,j,x=0,y=0,p=0,n,q=-1,u=0,v=0,k,c=0,m,z;\n\n cin>>n>>m;\n\n MOD=m;\n\n fac.push_back(1);\n\n p=1;\n\n for(i=1;i<=n;i++){\n\n p=(p*i)%m;\n\n fac.push_back(p);\n\n }\n\n \/\/r-l=1=i...i+1...n-(i+1)...n-i\n\n int ansx=0;\n\n for(i=0;i<=n-1;i++){\n\n x=fac[i+1];\n\n y=fac[n-(i+1)];\n\n z=n-i;\n\n int ans=1;\n\n ans=((x*y)%m)%m;\n\n ans=(ans*z)%m;\n\n q=z;\n\n ans=(ans*q)%m;\n\n ansx+=ans;\n\n ansx%=m;\n\n }\n\n cout<\n\nusing namespace std;\n\nusing ll = long long;\n\nnamespace atcoder {\n\n\n\nnamespace internal {\n\n\n\n\/\/ @param n `0 <= n`\n\n\/\/ @return minimum non-negative `x` s.t. `n <= 2**x`\n\nint ceil_pow2(int n) {\n\n int x = 0;\n\n while ((1U << x) < (unsigned int)(n))\n\n x++;\n\n return x;\n\n}\n\n\n\n\/\/ @param n `1 <= n`\n\n\/\/ @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`\n\nconstexpr int bsf_constexpr(unsigned int n) {\n\n int x = 0;\n\n while (!(n & (1 << x)))\n\n x++;\n\n return x;\n\n}\n\n\n\n\/\/ @param n `1 <= n`\n\n\/\/ @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`\n\nint bsf(unsigned int n) {\n\n#ifdef _MSC_VER\n\n unsigned long index;\n\n _BitScanForward(&index, n);\n\n return index;\n\n#else\n\n return __builtin_ctz(n);\n\n#endif\n\n}\n\n\n\n} \/\/ namespace internal\n\ntemplate \n\nstruct lazy_segtree {\n\npublic:\n\n lazy_segtree() : lazy_segtree(0) {}\n\n explicit lazy_segtree(int n) : lazy_segtree(std::vector(n, e())) {}\n\n explicit lazy_segtree(const std::vector &v) : _n(int(v.size())) {\n\n log = internal::ceil_pow2(_n);\n\n size = 1 << log;\n\n d = std::vector(2 * size, e());\n\n lz = std::vector(size, id());\n\n for (int i = 0; i < _n; i++)\n\n d[size + i] = v[i];\n\n for (int i = size - 1; i >= 1; i--) {\n\n update(i);\n\n }\n\n }\n\n\n\n void set(int p, S x) {\n\n assert(0 <= p && p < _n);\n\n p += size;\n\n for (int i = log; i >= 1; i--)\n\n push(p >> i);\n\n d[p] = x;\n\n for (int i = 1; i <= log; i++)\n\n update(p >> i);\n\n }\n\n\n\n S get(int p) {\n\n assert(0 <= p && p < _n);\n\n p += size;\n\n for (int i = log; i >= 1; i--)\n\n push(p >> i);\n\n return d[p];\n\n }\n\n\n\n S prod(int l, int r) {\n\n assert(0 <= l && l <= r && r <= _n);\n\n if (l == r)\n\n return e();\n\n\n\n l += size;\n\n r += size;\n\n\n\n for (int i = log; i >= 1; i--) {\n\n if (((l >> i) << i) != l)\n\n push(l >> i);\n\n if (((r >> i) << i) != r)\n\n push((r - 1) >> i);\n\n }\n\n\n\n S sml = e(), smr = e();\n\n while (l < r) {\n\n if (l & 1)\n\n sml = op(sml, d[l++]);\n\n if (r & 1)\n\n smr = op(d[--r], smr);\n\n l >>= 1;\n\n r >>= 1;\n\n }\n\n\n\n return op(sml, smr);\n\n }\n\n\n\n S all_prod() { return d[1]; }\n\n\n\n void apply(int p, F f) {\n\n assert(0 <= p && p < _n);\n\n p += size;\n\n for (int i = log; i >= 1; i--)\n\n push(p >> i);\n\n d[p] = mapping(f, d[p]);\n\n for (int i = 1; i <= log; i++)\n\n update(p >> i);\n\n }\n\n void apply(int l, int r, F f) {\n\n assert(0 <= l && l <= r && r <= _n);\n\n if (l == r)\n\n return;\n\n\n\n l += size;\n\n r += size;\n\n\n\n for (int i = log; i >= 1; i--) {\n\n if (((l >> i) << i) != l)\n\n push(l >> i);\n\n if (((r >> i) << i) != r)\n\n push((r - 1) >> i);\n\n }\n\n\n\n {\n\n int l2 = l, r2 = r;\n\n while (l < r) {\n\n if (l & 1)\n\n all_apply(l++, f);\n\n if (r & 1)\n\n all_apply(--r, f);\n\n l >>= 1;\n\n r >>= 1;\n\n }\n\n l = l2;\n\n r = r2;\n\n }\n\n\n\n for (int i = 1; i <= log; i++) {\n\n if (((l >> i) << i) != l)\n\n update(l >> i);\n\n if (((r >> i) << i) != r)\n\n update((r - 1) >> i);\n\n }\n\n }\n\n\n\n template int max_right(int l) {\n\n return max_right(l, [](S x) { return g(x); });\n\n }\n\n template int max_right(int l, G g) {\n\n assert(0 <= l && l <= _n);\n\n assert(g(e()));\n\n if (l == _n)\n\n return _n;\n\n l += size;\n\n for (int i = log; i >= 1; i--)\n\n push(l >> i);\n\n S sm = e();\n\n do {\n\n while (l % 2 == 0)\n\n l >>= 1;\n\n if (!g(op(sm, d[l]))) {\n\n while (l < size) {\n\n push(l);\n\n l = (2 * l);\n\n if (g(op(sm, d[l]))) {\n\n sm = op(sm, d[l]);\n\n l++;\n\n }\n\n }\n\n return l - size;\n\n }\n\n sm = op(sm, d[l]);\n\n l++;\n\n } while ((l & -l) != l);\n\n return _n;\n\n }\n\n\n\n template int min_left(int r) {\n\n return min_left(r, [](S x) { return g(x); });\n\n }\n\n template int min_left(int r, G g) {\n\n assert(0 <= r && r <= _n);\n\n assert(g(e()));\n\n if (r == 0)\n\n return 0;\n\n r += size;\n\n for (int i = log; i >= 1; i--)\n\n push((r - 1) >> i);\n\n S sm = e();\n\n do {\n\n r--;\n\n while (r > 1 && (r % 2))\n\n r >>= 1;\n\n if (!g(op(d[r], sm))) {\n\n while (r < size) {\n\n push(r);\n\n r = (2 * r + 1);\n\n if (g(op(d[r], sm))) {\n\n sm = op(d[r], sm);\n\n r--;\n\n }\n\n }\n\n return r + 1 - size;\n\n }\n\n sm = op(d[r], sm);\n\n } while ((r & -r) != r);\n\n return 0;\n\n }\n\n\n\nprivate:\n\n int _n, size, log;\n\n std::vector d;\n\n std::vector lz;\n\n\n\n void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }\n\n void all_apply(int k, F f) {\n\n d[k] = mapping(f, d[k]);\n\n if (k < size)\n\n lz[k] = composition(f, lz[k]);\n\n }\n\n void push(int k) {\n\n all_apply(2 * k, lz[k]);\n\n all_apply(2 * k + 1, lz[k]);\n\n lz[k] = id();\n\n }\n\n};\n\n\n\n} \/\/ namespace atcoder\n\nusing namespace atcoder;\n\nstruct node {\n\n ll sum;\n\n ll len;\n\n};\n\nconstexpr ll inf = 1e16;\n\nnode op(node l, node r) { return node{min(l.sum, r.sum), l.len + r.len}; }\n\nnode e() { return node{inf, 0}; }\n\nstruct F {\n\n ll add;\n\n};\n\nnode mapping(F f, node x) { return node{x.sum + f.add, x.len}; }\n\nF composition(F f, F g) {\n\n \/\/ f(g())\n\n return F{f.add + g.add};\n\n}\n\nF id() { return F{0}; }\n\nauto solve() {\n\n int n;\n\n cin >> n;\n\n vector p(n), a(n);\n\n for (auto &i : p) {\n\n cin >> i;\n\n i--;\n\n }\n\n for (auto &i : a) {\n\n cin >> i;\n\n }\n\n lazy_segtree seg(n);\n\n ll sum = a[0];\n\n vector pos(n);\n\n vector val(n);\n\n pos[p[0]] = 0;\n\n val[p[0]] = a[0];\n\n for(int i = 1 ; i < n ;++i){\n\n seg.set(i, {sum, 1});\n\n sum += a[i];\n\n pos[p[i]] = i;\n\n val[p[i]] = a[i];\n\n }\n\n ll ans = inf;\n\n for (int i = 0; i < n; ++i) {\n\n \/\/ l: i, r: n-i\n\n ans = min(ans, seg.prod(0, n).sum);\n\n \/\/ for (int j = 1; j < n; ++j) {\n\n \/\/ cout< int {\n\n ios::sync_with_stdio(false);\n\n cin.tie(nullptr), cout.tie(nullptr);\n\n int _ = 1;\n\n \/\/ cin >> _;\n\n while (_--) {\n\n solve();\n\n }\n\n}","language":"cpp"} {"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\n#define ll long long\n\n#define flot(n) cout << setprecision(n) << setiosflags(ios::fixed) << setiosflags(ios::showpoint)\n\n#define all(a) (a).begin() , (a).end()\n\n#define pb push_back\n\n#define mp make_pair\n\n#define pii pair\n\n#define pll pair\n\n#define piii pair\n\n#define plll pair\n\n#define R return\n\n#define B break\n\n#define C continue\n\n#define SET(n , i) memset(n , i , sizeof(n))\n\n#define SD ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)\n\n#define rep(i , n) for(int i = 0 ; i < n ; i++)\n\n#define repn(i , j , n) for(int i = j ; i < n ; i++)\n\n#define repr(i,n,j) for(int i=n;i>=j;i--)\n\n#define positive(x) ((x%mod+mod)%mod)\n\n#define YES(f)cout<<((f)?\"YES\":\"NO\")<\n\n\/\/#define int ll\n\nusing namespace std;\n\nvoid readFromFile(string input = \"input.txt\",string output=\"output.txt\") {\n\n #ifndef ONLINE_JUDGE\n\n freopen(input.c_str(),\"r\",stdin);\n\n freopen(output.c_str(),\"w\",stdout);\n\n #endif\n\n}\n\nmt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());\n\nll rnd(ll x, ll y) {\n\n return uniform_int_distribution(x, y)(rng);\n\n}\n\ntemplate void Max(T& x,T y){x=max(x,y);}\n\ntemplate void Min(T& x,T y){x=min(x,y);}\n\nconst int INF = 0x3f3f3f3f;\n\nconst ll INFLL = 0x3f3f3f3f3f3f3f3f;\n\nconst long double EPS = 1e-3;\n\nconst long double pi = acos(-1.0);\n\nconst int mod = 1e9+9;\n\nconst int N =5e5+3;\n\nll Mul(ll x,ll y,ll mod=mod){R((x%mod)*(y%mod))%mod;}\n\nll Add(ll x,ll y,ll mod=mod){R((x%mod)+(y%mod)+2ll*mod)%mod;}\n\nint n,a[N],nxt[N],prv[N],dub[N];\n\nll pre[N],suf[N];\n\nvoid pr() {\n\n rep(i,n)prv[i]=-1;\n\n rep(i,n)nxt[i]=n;\n\n stack st;\n\n rep(i,n) {\n\n while(!st.empty() && a[st.top()] > a[i]) {\n\n nxt[st.top()] = i;\n\n st.pop();\n\n }\n\n st.push(i);\n\n }\n\n while(!st.empty())st.pop();\n\n repr(i,n-1,0) {\n\n while(!st.empty() && a[st.top()] > a[i]) {\n\n prv[st.top()] = i;\n\n st.pop();\n\n }\n\n st.push(i);\n\n }\n\n}\n\n\/**\n\n2 3 6 2 8 4\n\n2 2 2 2 4 4\n\n0:2+2+2+2+2+2 = 12\n\n1:2+2+2+3+3+2 = 14\n\n2:2+2+2+6+2+3 = 17\n\n3:2+2+2+2+2+2 = 12\n\n4:4+8+2+2+2+2 = 20\n\n5:4+2+2+2+2+4 = 16\n\n*\/\n\nvoid solve() {\n\n cin >> n;\n\n rep(i,n)cin>>a[i];\n\n pr();\n\n rep(i,n)dub[i]=1;\n\n rep(i,n) {\n\n int z = nxt[i];\n\n pre[i] += 1ll*dub[i]*a[i];\n\n pre[z] -= 1ll*dub[i]*a[i];\n\n dub[z] += dub[i];\n\n if(i)pre[i] += pre[i-1];\n\n }\n\n rep(i,n)dub[i]=1;\n\n repr(i,n-1,0) {\n\n int z = prv[i];\n\n suf[i] += 1ll*dub[i]*a[i];\n\n if(z>=0) {\n\n suf[z] -= 1ll*dub[i]*a[i];\n\n dub[z] += dub[i];\n\n }\n\n if(i ans(n);\n\n rep(i,n) {\n\n if(pre[i] == z) {\n\n int mn = a[i];\n\n repr(j,i,0) {\n\n Min(mn,a[j]);\n\n ans[j] = mn;\n\n }\n\n mn = a[i];\n\n repn(j,i,n) {\n\n Min(mn,a[j]);\n\n ans[j] = mn;\n\n }\n\n for(auto it:ans)cout<> t;\n\n\/\/ scanf(\"%d\",&t);\n\n rep(i,t) {\n\n solve();\n\n }\n\n}\n\n","language":"cpp"} {"contest_id":"1284","problem_id":"G","statement":"G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n\u00d7mn\u00d7m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either \"black\" or \"white\". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1\u2264t\u22641001\u2264t\u2264100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2\u2264n,m\u2264202\u2264n,m\u226420), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t\u22652t\u22652 is satisfied, then the size of the grid will satisfy n\u226410,m\u226410n\u226410,m\u226410. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n\u22121)\u00d7(2m\u22121)(2n\u22121)\u00d7(2m\u22121) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1\u2264i\u2264n,1\u2264j\u2264m1\u2264i\u2264n,1\u2264j\u2264m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). Otherwise, print 'X' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). For all 1\u2264i\u2264n,1\u2264j\u2264m\u221211\u2264i\u2264n,1\u2264j\u2264m\u22121, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i\u22121,2j)(2i\u22121,2j). Otherwise, print any printable character except spaces in the cell (2i\u22121,2j)(2i\u22121,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m1\u2264i\u2264n\u22121,1\u2264j\u2264m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print '\u00a0' in the cell (2i,2j\u22121)(2i,2j\u22121). Otherwise, print any printable character except spaces in the cell (2i,2j\u22121)(2i,2j\u22121) For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m\u221211\u2264i\u2264n\u22121,1\u2264j\u2264m\u22121, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m\u221212m\u22121 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4\n2 2\nOO\nOO\n3 3\nOOO\nXOO\nOOO\n4 4\nOOOX\nXOOX\nOOXO\nOOOO\n5 6\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOutputCopyYES\nOOO\n O\nOOO\nNO\nYES\nOOOOO X\n O O \nX O O X\n O \nOOO X O\nO O O\nO OOOOO\nYES\nOOOOOOOOOOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n","tags":["graphs"],"code":"#include \n\nusing namespace std;\n\n\n\nconst int maxn = 810;\n\nint T, n, m, fa[maxn], d[maxn], pre[maxn], lim[maxn], eid[22][22][2];\n\nbool bad[maxn], mark[maxn], vis[maxn], in1[maxn], in2[maxn], ban[maxn];\n\nvector G[maxn];\n\nchar str[22][22], ans[42][42];\n\n\n\nint id(int x, int y) {\n\n return (x - 1) * m + y;\n\n}\n\n\n\nint find(int x) {\n\n while (x ^ fa[x]) x = fa[x] = fa[fa[x]];\n\n return x;\n\n}\n\n\n\nint main() {\n\n scanf(\"%d\", &T);\n\n while (T--) {\n\n scanf(\"%d %d\", &n, &m);\n\n for (int i = 1; i <= n; i++) {\n\n scanf(\"%s\", str[i] + 1);\n\n for (int j = 1; j <= m; j++) ban[id(i, j)] = str[i][j] == 'X';\n\n }\n\n memset(mark, 0, sizeof(mark));\n\n memset(eid, -1, sizeof(eid));\n\n memset(lim, 0, sizeof(lim));\n\n memset(bad, 0, sizeof(bad));\n\n int cnt = 0;\n\n vector> E;\n\n for (int i = 1; i <= n; i++) {\n\n for (int j = 1; j <= m; j++) if (str[i][j] == 'O') {\n\n cnt++, bad[id(i, j)] = (i + j + 1) % 2 && (i > 1 || j > 1);\n\n if (i < n && str[i + 1][j] == 'O') {\n\n eid[i][j][0] = E.size(), E.push_back({id(i, j), id(i + 1, j)});\n\n lim[id(i, j)]++, lim[id(i + 1, j)]++;\n\n }\n\n if (j < m && str[i][j + 1] == 'O') {\n\n eid[i][j][1] = E.size(), E.push_back({id(i, j), id(i, j + 1)});\n\n lim[id(i, j)]++, lim[id(i, j + 1)]++;\n\n }\n\n }\n\n }\n\n bool ok = 1;\n\n for (int i = 1; i <= n * m; i++) {\n\n if (bad[i] && (lim[i] -= 2) < 0) { ok = 0; break; }\n\n }\n\n if (!ok) { puts(\"NO\"); continue; }\n\n while (count(mark, mark + E.size(), 0) >= cnt) {\n\n for (int i = 0; i < E.size(); i++) {\n\n G[i].clear();\n\n }\n\n for (int i = 0; i < E.size(); i++) if (mark[i]) {\n\n fill(d + 1, d + n * m + 1, 0);\n\n for (int j = 0; j < E.size(); j++) {\n\n if (i ^ j && mark[j]) d[E[j][0]]++, d[E[j][1]]++;\n\n }\n\n for (int j = 0; j < E.size(); j++) if (!mark[j]) {\n\n if (d[E[j][0]] < lim[E[j][0]] && d[E[j][1]] < lim[E[j][1]]) G[j].push_back(i);\n\n }\n\n }\n\n for (int i = 0; i < E.size(); i++) if (!mark[i]) {\n\n iota(fa + 1, fa + n * m + 1, 1);\n\n for (int j = 0; j < E.size(); j++) {\n\n if (i ^ j && !mark[j]) fa[find(E[j][0])] = find(E[j][1]);\n\n }\n\n int num = 0;\n\n for (int j = 1; j <= n * m; j++) {\n\n if (!ban[j] && j == find(j)) num++;\n\n }\n\n for (int j = 0; j < E.size(); j++) if (mark[j]) {\n\n if (num == 1 || num == 2 && find(E[j][0]) ^ find(E[j][1])) G[j].push_back(i);\n\n }\n\n }\n\n fill(in1, in1 + E.size(), 0);\n\n fill(in2, in2 + E.size(), 0);\n\n for (int i = 0; i < E.size(); i++) if (!mark[i]) {\n\n iota(fa + 1, fa + n * m + 1, 1);\n\n fill(d + 1, d + n * m + 1, 0);\n\n bool flag = 0;\n\n for (int j = 0; j < E.size(); j++) {\n\n if (i ^ j && !mark[j]) fa[find(E[j][0])] = find(E[j][1]);\n\n else if (++d[E[j][0]] > lim[E[j][0]] || ++d[E[j][1]] > lim[E[j][1]]) flag = 1;\n\n }\n\n int num = 0;\n\n for (int j = 1; j <= n * m; j++) {\n\n if (!ban[j] && j == find(j)) num++;\n\n }\n\n in1[i] = num == 1, in2[i] = !flag;\n\n }\n\n fill(vis, vis + E.size(), 0);\n\n queue Q;\n\n for (int i = 0; i < E.size(); i++) {\n\n if (in1[i]) Q.push(i), vis[i] = 1;\n\n }\n\n bool flag = 0;\n\n while (!Q.empty()) {\n\n int u = Q.front(); Q.pop();\n\n if (in2[u]) {\n\n while (1) {\n\n mark[u] ^= 1;\n\n if (in1[u]) break;\n\n u = pre[u];\n\n }\n\n flag = 1; break;\n\n }\n\n for (int v : G[u]) if (!vis[v]) {\n\n Q.push(v), vis[v] = 1, pre[v] = u;\n\n }\n\n }\n\n if (!flag) break;\n\n }\n\n if (count(mark, mark + E.size(), 0) >= cnt) {\n\n puts(\"NO\"); continue;\n\n }\n\n for (int i = 1; i <= n; i++) {\n\n for (int j = 1; j <= m; j++) {\n\n ans[2 * i - 1][2 * j - 1] = str[i][j];\n\n ans[2 * i][2 * j - 1] = ~eid[i][j][0] && mark[eid[i][j][0]] ? ' ' : 'O';\n\n ans[2 * i - 1][2 * j] = ~eid[i][j][1] && mark[eid[i][j][1]] ? ' ' : 'O';\n\n ans[2 * i][2 * j] = ' ';\n\n }\n\n }\n\n puts(\"YES\");\n\n for (int i = 1; i < 2 * n; i++) {\n\n for (int j = 1; j < 2 * m; j++) putchar(ans[i][j]);\n\n putchar('\\n');\n\n }\n\n }\n\n return 0;\n\n}","language":"cpp"} {"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":"#include \n#include \n#include \n#include \n#include \nusing namespace std;\nint jinzhi(int n,int i) \n{\n\tint k=n,temp=0,sum=0;\n\twhile(k>0)\n\t{\n\t\tsum=sum+k%i;\n\t\tk=k\/i;\n\t}\n\treturn sum;\n}\nint gys(int n,int m)\n{\n\tif(n%m==0) return m;\n\treturn gys(m,n%m);\n}\nint main()\n{\n\tint i,j,k,n,m,sum=0,p;\n\tcin>>n;\n\tfor(i=2;i<=n-1;i++) sum=sum+jinzhi(n,i);\n\tn=n-2;\n\tif(sum\n\nusing namespace std;\n\ntypedef long long ll;\n\ntypedef long double ld;\n\ntypedef vector vi;\n\ntypedef vector vl;\n\ntypedef pairpi;\n\ntypedef pairpl;\n\ntypedef vectorvpi;\n\ntypedef vectorvpl;\n\ntypedef vector vvi;\n\ntypedef vector vvl;\n\ntypedef vector vs;\n\ntypedef vector vb;\n\ntypedef priority_queue pqi;\n\ntypedef priority_queue> pqI;\n\ntypedef priority_queue pql;\n\ntypedef priority_queue> pqL;\n\nconst long double PI = acos(-1);\n\nconst int oo = 1e9 + 7;\n\nconst int MOD = 1e9 + 7;\n\nconst int N = 1e5 + 7;\n\n#define endl '\\n'\n\n#define all(v) (v).begin(),(v).end()\n\n#define rall(v) (v).rbegin(),(v).rend()\n\n#define read(v) for (auto& it : v) scanf(\"%d\", &it);\n\n#define readL(v) for (auto& it : v) scanf(\"%lld\", &it);\n\n#define print(v) for (auto it : v) printf(\"%d \", it); puts(\"\");\n\n#define printL(v) for (auto it : v) printf(\"%lld \", it); puts(\"\");\n\nvoid solve() {\n\n\tint n;\n\n\tscanf(\"%d\", &n);\n\n\tif (n == 2) {\n\n\t\tputs(\"0\");\n\n\t\treturn;\n\n\t}\n\n\tvvi g(n + 1);\n\n\tmapidx;\n\n\tvi ans(n - 1, -1);\n\n\tfor (int i = 0, u, v; i < n - 1; i++) {\n\n\t\tscanf(\"%d %d\", &u, &v);\n\n\t\tg[u].push_back(v);\n\n\t\tg[v].push_back(u);\n\n\t\tidx[{u, v}] = idx[{v, u}] = i;\n\n\t}\n\n\tint cur = 0;\n\n\tfor (int i = 1; i <= n && cur <= 2; i++)\n\n\t\tif (g[i].size() == 1)\n\n\t\t\tans[idx[{i, g[i][0]}]] = cur++;\n\n\tfor (int i = 0; i < n - 1; i++)\n\n\t\tif (ans[i] == -1)\n\n\t\t\tans[i] = cur++;\n\n\tfor (auto& it : ans)\n\n\t\tprintf(\"%d\\n\", it);\n\n}\n\nint t = 1;\n\nint main() {\n\n#ifndef ONLINE_JUDGE\n\n\tfreopen(\"input.txt\", \"r\", stdin);\n\n#endif\n\n\t\/\/scanf(\"%d\", &t);\n\n\twhile (t--) solve();\n\n}","language":"cpp"} {"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":"#include\n\n#define ll long long\n\n#define pb push_back\n\n#define pf push_front\n\n#define pob pop_back\n\n#define pof pop_front\n\n#define ff first\n\n#define ss second\n\n#define PLL pair\n\n#define pii pair\n\n#define SetBit(x, k) (x |= (1LL << k))\n\n#define ClearBit(x, k) (x &= ~(1LL << k))\n\n#define CheckBit(x, k) (x & (1LL << k))\n\n#define scn(n) scanf(\"%d\",&n)\n\n#define scnll(n) scanf(\"%lld\",&n)\n\n#define nl cout<<\"\\n\"\n\n#define YES cout<<\"YES\\n\"\n\n#define Yes cout<<\"Yes\\n\"\n\n#define yes cout<<\"yes\\n\"\n\n#define NO cout<<\"NO\\n\"\n\n#define No cout<<\"No\\n\"\n\n#define no cout<<\"no\\n\"\n\n#define mod 1000000007LL\n\n#define mod1 1000000007LL\n\n#define mod2 1000000009LL\n\n#define inf 1000000000000000LL\n\n#define N 200000\n\n#define fastio std::ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n\nusing namespace std;\n\n\n\n\n\nint main()\n\n{\n\n fastio;\n\n int n,m;cin>>n>>m;\n\n int a[n+2][m+2];\n\n map cnt[m+2];\n\n for(int i=0;i>a[i][j];\n\n if(a[i][j]%m==j){\n\n int x=a[i][j]\/m;\n\n if(x>=n) continue;\n\n x=i-x;\n\n if(x<0){\n\n x+=n;\n\n }\n\n cnt[j][x]++;\n\n }\n\n if(j==m&&(a[i][j]%m==0)){\n\n int x=a[i][j]\/m;\n\n x--;\n\n if(x>=n) continue;\n\n x=i-x;\n\n if(x<0){\n\n x+=n;\n\n }\n\n cnt[j][x]++;\n\n }\n\n }\n\n\n\n }\n\n int ans=0;\n\n for(int j=1;j<=m;j++){\n\n int res=n;\n\n for(auto x:cnt[j]){\n\n \/\/\/cout<' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1\u2264t\u22641041\u2264t\u2264104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2\u2264n\u22642\u22c51052\u2264n\u22642\u22c5105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n\u22121n\u22121.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2\u22c51052\u22c5105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3\n3 <<\n7 >><>><\n5 >>><\nOutputCopy1 2 3\n1 2 3\n5 4 3 7 2 1 6\n4 3 1 7 5 2 6\n4 3 2 1 5\n5 4 2 1 3\nNoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.","tags":["constructive algorithms","graphs","greedy","two pointers"],"code":"#include \n\n\n\nusing namespace std;\n\n\n\nusing LL = long long;\n\n#define endl '\\n'\n\nusing db = double;\n\ntemplate \n\nusing max_heap = priority_queue;\n\ntemplate \n\nusing min_heap = priority_queue, greater<>>;\n\n\n\nvoid solve()\n\n{\n\n int n;\n\n cin >> n;\n\n string s;\n\n cin >> s;\n\n auto work = [&](string s) -> vector\n\n {\n\n s += '>';\n\n vector a;\n\n for (int i = 0, last = -1; i < n; ++i)\n\n {\n\n if (s[i] == '>')\n\n {\n\n for (int j = n - i; j <= n - last - 1; ++j)\n\n a.push_back(j);\n\n last = i;\n\n }\n\n }\n\n return a;\n\n };\n\n auto ans = work(s);\n\n for (auto x : ans)\n\n cout << x << \" \";\n\n cout << endl;\n\n for (int i = 0; i < s.size(); ++i)\n\n s[i] = '>' + '<' - s[i];\n\n ans = work(s);\n\n for (auto x : ans)\n\n cout << n - x + 1 << \" \";\n\n cout << endl;\n\n}\n\nint main()\n\n{\n\n ios::sync_with_stdio(false);\n\n cin.tie(nullptr);\n\n int T;\n\n cin >> T;\n\n while (T--)\n\n solve();\n\n return 0;\n\n}","language":"cpp"} {"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":"#include \n\nusing namespace std;\n\n\/\/ #include \/\/ everything related to pbds\n\n\/\/ #include \n\n\/\/ using namespace __gnu_pbds;\n\n\/\/ typedef int node; \/\/ change type here\n\n\/\/ typedef tree,\n\n\/\/ rb_tree_tag, tree_order_statistics_node_update> \/\/ this is push_backds\n\n\/\/ ordered_set;\n\nusing ll = long long;\n\nusing vi = vector;\n\nusing vpi = vector>;\n\ntypedef long double ld;\n\n#define all(x) (x).begin(), (x).end()\n\n#define rall(a) (a).rbegin(), (a).rend()\n\n#define lb lower_bound\n\n#define ps(x, y) fixed << setprecision(y) << x\n\n#define int long long\n\n\n\nll INF = 1e18;\n\nll MOD = 1000000007;\n\nint dx[] = {0, 0, -1, 1};\n\nint dy[] = {-1, 1, 0, 0}; \/\/ useful when dealing with points\n\nll maxx(vi &a)\n\n{\n\n return (*max_element(a.begin(), a.end()));\n\n}\n\n\n\nll minn(vi &a)\n\n{\n\n return (*min_element(a.begin(), a.end()));\n\n}\n\n\n\nlong long gcd(ll a, ll b)\n\n{\n\n if (b == 0)\n\n return a;\n\n return gcd(b, a % b);\n\n}\n\n\n\n\/\/ Function to return LCM of two numbers\n\nlong long lcm(ll a, ll b)\n\n{\n\n return (a \/ gcd(a, b)) * b;\n\n}\n\n\n\nbool isPrime(ll n)\n\n{\n\n for (ll i = 2; i * i <= n; i++)\n\n {\n\n if (n % i == 0)\n\n {\n\n return false;\n\n }\n\n }\n\n return true;\n\n}\n\nlong long mod(long long x)\n\n{\n\n return ((x % MOD + MOD) % MOD);\n\n}\n\nlong long add(long long a, long long b)\n\n{\n\n return mod(mod(a) + mod(b));\n\n}\n\nlong long mul(long long a, long long b)\n\n{\n\n return mod(mod(a) * mod(b));\n\n}\n\nvoid input(vi &a)\n\n{\n\n int n = a.size();\n\n for (int i = 0; i < n; i++)\n\n {\n\n cin >> a[i];\n\n }\n\n}\n\n\n\nvoid print(vi &a)\n\n{\n\n for (auto x : a)\n\n {\n\n cout << x << \" \";\n\n }\n\n cout << endl;\n\n}\n\n\n\nint stringToInt(string s)\n\n{\n\n stringstream geek(s);\n\n int x = 0;\n\n geek >> x;\n\n return x;\n\n}\n\n\n\nbool isPowerOfTwo(ll n)\n\n{\n\n if (n == 0)\n\n return false;\n\n\n\n return (ceil(log2(n)) == floor(log2(n)));\n\n}\n\n\n\nbool isPalindrome(string s)\n\n{\n\n int n = s.size();\n\n for (int i = 0; i < n; i++)\n\n {\n\n if (s[i] != s[n - i - 1])\n\n {\n\n return false;\n\n }\n\n }\n\n return true;\n\n}\n\nstring binaryTransformation(long long x)\n\n{\n\n if (x == 0)\n\n return \"\";\n\n else\n\n {\n\n string s = binaryTransformation(x \/ 2);\n\n s.push_back(char('0' + x % 2));\n\n return s;\n\n }\n\n}\n\nll power(ll a, ll b, ll mod)\n\n{\n\n if (b == 0)\n\n {\n\n return 1;\n\n }\n\n ll ans = power(a, b \/ 2, mod);\n\n ans *= ans;\n\n ans %= mod;\n\n if (b % 2)\n\n {\n\n ans *= a;\n\n }\n\n return ans % mod;\n\n}\n\ndouble power(double a, int b)\n\n{\n\n if (b == 0)\n\n {\n\n return 1;\n\n }\n\n double t = power(a, b \/ 2);\n\n if (b & 1)\n\n {\n\n return t * t * a;\n\n }\n\n else\n\n {\n\n return t * t;\n\n }\n\n}\n\nint modularInverse(int number, int mod)\n\n{\n\n return power(number, mod - 2, mod);\n\n}\n\n\/\/ it should be 1LL and not 1\n\n\/\/ write more tests\n\n\/\/ google if stuck\n\n\/\/ take a walk if stuck\n\n\/\/ precompute first\n\n\n\nconst int N = 2000;\n\n\n\nint fact[N], invfact[N];\n\n\n\nint pow(int a, int b, int m)\n\n{\n\n int ans = 1;\n\n while (b)\n\n {\n\n if (b & 1)\n\n ans = (ans * a) % m;\n\n b \/= 2;\n\n a = (a * a) % m;\n\n }\n\n return ans;\n\n}\n\n\n\nint modinv(int k)\n\n{\n\n return pow(k, MOD - 2, MOD);\n\n}\n\n\n\nvoid precompute()\n\n{\n\n fact[0] = fact[1] = 1;\n\n for (int i = 2; i < N; i++)\n\n {\n\n fact[i] = fact[i - 1] * i;\n\n fact[i] %= MOD;\n\n }\n\n invfact[N - 1] = modinv(fact[N - 1]);\n\n for (int i = N - 2; i >= 0; i--)\n\n {\n\n invfact[i] = invfact[i + 1] * (i + 1);\n\n invfact[i] %= MOD;\n\n }\n\n}\n\n\n\nint nCr(int x, int y)\n\n{\n\n if (y > x)\n\n return 0;\n\n int num = fact[x];\n\n num *= invfact[y];\n\n num %= MOD;\n\n num *= invfact[x - y];\n\n num %= MOD;\n\n return num;\n\n}\n\nvoid solve()\n\n{\n\n \/\/ learned a lot from this problem ,lol\n\n \/\/ relearned stars and bars\n\n \/\/ basically we have 2*m positions and n candidates for each position\n\n \/\/ this can be rewritten as x1 + x2+x3+...xn= 2*m, here xi>=0\n\n \/\/ so when we place a bar it means that many positions for that number\n\n int n, m;\n\n cin >> n >> m;\n\n cout << nCr(2 * m + n - 1, n - 1) << endl;\n\n}\n\n\/\/ you should look down sometimes\n\n\n\n\/\/ https:\/\/github.com\/Manjunath0408\/CPSnippets\n\nint32_t main()\n\n{\n\n \/\/ freopen(\"pump.in\", \"r\", stdin);\n\n \/\/ freopen(\"pump.out\", \"w\", stdout);\n\n \/* stuff you should look for\n\n * int overflow, array bounds\n\n * special cases (n==1?)\n\n * do smth instead of nothing and stay organized\n\n * WRITE STUFF DOWN\n\n * DON'T GET STUCK ON ONE APPROACH\n\n * IF STUCK ON A QUESTION, MOVE TO THE NEXT ONE\n\n *\/\n\n ios_base::sync_with_stdio(false);\n\n cin.tie(NULL);\n\n int t = 1;\n\n precompute();\n\n \/\/ cin >> t;\n\n for (int i = 1; i <= t; i++)\n\n {\n\n solve();\n\n }\n\n return 0;\n\n}","language":"cpp"} {"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":"\/*\n\n \u09ab\u09c7\u09b0\u09be \u09b9\u09b2\u09cb \u09a8\u09be \u0998\u09b0\u09c7, \u09a8\u09be\u09b9\u09bf \u09ab\u09bf\u09b0\u09b2\u09cb \u0998\u09b0 \u09a6\u09bf\u0995\u09c7 \u0986\u09ae\u09be\u09b0,\n\n \u098f\u09b8\u09c7 \u09aa\u09a5\u09c7\u09b0\u0987 \u09ae\u09be\u099d\u09c7,\n\n \u09aa\u09c7\u099b\u09a8\u09c7 \u09a4\u09be\u0995\u09bf\u09df\u09c7 \u09ab\u09bf\u09b0\u09c7 \u0986\u09ac\u09be\u09b0\n\n \u09b9\u09c7\u0981\u099f\u09c7 \u09af\u09be\u0987 \u0986\u09ae\u09bf \u0996\u09c1\u0981\u099c\u09a4\u09c7 \u0995\u09bf\u099b\u09c1, \u0986\u09ae\u09bf \u0986\u099c\u0993 \u099c\u09be\u09a8\u09bf\u09a8\u09be \u0995\u09bf\u09b8\u09c7\u09b0\u09bf \u09aa\u09bf\u099b\u09c1!\n\n*\/\n\n\n\n#include \n\nusing namespace std;\n\n#ifdef ONLINE_JUDGE\n\n#define fast ios_base::sync_with_stdio(0); cin.tie(0); \/\/ fast IO! but only when online_judge\n\n#define debug 0\n\n#else\n\n#define fast ;\n\n#define debug 1\n\n#endif\n\n\n\n\/\/ some typedefs for my convenience\n\n#define int long long int\n\n#define pii pair\n\n#define vi vector\n\n#define si set\n\n#define mi map\n\n\/\/ some speedup macros\n\n#define gap ' '\n\n#define endl '\\n'\n\n#define print(str) cout << str << endl\n\n#define YES print(\"YES\")\n\n#define NO print(\"NO\")\n\n#define loop(i, begin, end) for(__typeof(end)i=begin-(begin>end); i!=end-(begin>end); i+=1-2*(begin>end))\n\n#define all(v) v.begin(), v.end()\n\n\n\n\n\nvoid solve(int cases);\n\nint32_t main()\n\n{\n\n fast\n\n int total_cases = 1;\n\n \/\/ cin >> total_cases;\n\n loop(cases, 1, total_cases+1) solve(cases);\n\n return 0;\n\n}\n\n\n\n\/\/ SOLVE STARTS HERE\n\nint dc(vi &v, int bit, int cases)\n\n{\n\n if (bit == -1) return 0;\n\n\n\n vi ones, zeros;\n\n int ocount = 0, zcount = 0, out = 0;\n\n\n\n for (auto x: v){\n\n if ((x>>bit) & 1) ocount++, ones.push_back(x);\n\n else zcount++, zeros.push_back(x);\n\n }\n\n\n\n if (ocount && zcount){\n\n out = 1 << bit;\n\n out |= min(dc(zeros, bit-1, cases), dc(ones, bit-1, cases));\n\n }\n\n else if (ocount) out = dc(ones, bit-1, cases);\n\n else if (zcount) out = dc(zeros, bit-1, cases);\n\n return out;\n\n}\n\n\n\n\n\nvoid solve(int cases)\n\n{\n\n int n, q, out=0, sum=0, flag=0, maxi=LLONG_MIN, mini=LLONG_MAX;\n\n int in;\n\n cin >> n;\n\n\n\n vi v(n);\n\n #define printp(p) cout << '(' << p.F << ',' << gap << p.S << ')' << endl;\n\n #define printx(array) { for (auto x : array) cout << x << gap; cout << endl; }\n\n #define scanx(array) { for (auto &x: array) cin >> x; }\n\n #define printxp(array) { for (auto x : array) cout << '(' << x.first << ',' << gap << x.second << ')' << gap; cout << endl; }\n\n scanx(v);\n\n\n\n print(dc(v, 31 - __builtin_clz(*max_element(all(v))), n));\n\n\n\nEND:;\n\n}\n\n\n\n\/*\n\n Fihad arRahman\n\n hellofihad@gmail.com\n\n 18-02-2023 20:32\n\n*\/","language":"cpp"} {"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\nusing namespace std;\n\nusing ll = long long;\n\nusing ld = long double;\n\n \n\nconstexpr int N = int(4e2) + 5;\n\nconstexpr int inf = 0x7f7f7f7f;\n\nconstexpr int MOD = int(1e9) + 7;\n\n\n\nshort dp[N][N][N];\n\nstring s, t;\n\n\n\nvoid solve(){\n\n cin >> s >> t;\n\n\n\n for(short i = 0; i <= s.size(); i++){\n\n for(short j = 0; j <= t.size(); j++){\n\n for(short k = 0; k < t.size(); k++){\n\n dp[i][j][k] = 0;\n\n }\n\n dp[s.size()][j][t.size()] = j;\n\n }\n\n }\n\n for(short i = s.size() - 1; ~i; i--){\n\n for(short j = t.size(); ~j; j--){\n\n for(short k = t.size(); ~k; k--){\n\n auto& r = dp[i][j][k] = dp[i + 1][j][k];\n\n if(s[i] == t[j]) r = max(r, dp[i + 1][j + 1][k]);\n\n if(s[i] == t[k]) r = max(r, dp[i + 1][j][k + 1]);\n\n }\n\n }\n\n }\n\n for(int i = 0; i < t.size(); i++){\n\n if(dp[0][0][i + 1] > i){\n\n cout << \"YES\\n\";\n\n return;\n\n }\n\n }\n\n cout << \"NO\\n\";\n\n}\n\nint main() {\n\n ios::sync_with_stdio(0); \n\n cin.tie(0);\n\n\n\n int t = 1;\n\n cin >> t;\n\n while(t--){\n\n solve();\n\n }\n\n}","language":"cpp"} {"contest_id":"1312","problem_id":"G","statement":"G. Autocompletiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set of strings SS. Each string consists of lowercase Latin letters.For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the following actions: if the current string is tt, choose some lowercase Latin letter cc and append it to the back of tt, so the current string becomes t+ct+c. This action takes 11 second; use autocompletion. When you try to autocomplete the current string tt, a list of all strings s\u2208Ss\u2208S such that tt is a prefix of ss is shown to you. This list includes tt itself, if tt is a string from SS, and the strings are ordered lexicographically. You can transform tt into the ii-th string from this list in ii seconds. Note that you may choose any string from this list you want, it is not necessarily the string you are trying to type. What is the minimum number of seconds that you have to spend to type each string from SS?Note that the strings from SS are given in an unusual way.InputThe first line contains one integer nn (1\u2264n\u22641061\u2264n\u2264106).Then nn lines follow, the ii-th line contains one integer pipi (0\u2264pi\n\n#define endl '\\n'\n\n#define iloveds std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);\n\n#define all(a) a.begin(),a.end()\n\nusing namespace std;\n\ntypedef long long ll ;\n\nconst int N = 1e6 + 100;\n\n\n\nint n, ch[N][26], k, a[N], b[N], dfn[N], ans[N], f[N];\n\nint tot, dp[N], val;\n\n\n\nvoid dfs(int x){\n\n\tif(f[x]) {\n\n\t\tdfn[x] = ++ tot;\n\n\t}\n\n\tfor(int i = 0 ; i < 26; i ++){\n\n\t\tif(ch[x][i]){\n\n\t\t\tdfs(ch[x][i]);\n\n\t\t\tdfn[x] = min(dfn[x], dfn[ch[x][i]]);\n\n\t\t}\n\n\t\t\n\n\t}\n\n}\n\n\n\nvoid dfs2(int x){\n\n\tfor(int i = 0 ; i < 26; i ++){\n\n\t\tint tmp = val;\n\n\t\tif(ch[x][i]) {\n\n\t\t\tif(f[ch[x][i]]){\n\n\t\t\t\tdp[ch[x][i]] = min(dp[x] + 1, dfn[ch[x][i]] + val);\n\n\t\t\t}else{\n\n\t\t\t\tdp[ch[x][i]] = dp[x] + 1;\n\n\t\t\t}\n\n\t\t\tval = min(val, dp[ch[x][i]] - dfn[ch[x][i]] + 1);\n\n\t\t\tdfs2(ch[x][i]);\n\n\t\t}\n\n\t\tval = tmp;\n\n\t}\n\n\n\n}\n\n\n\n\n\n\/\/ dp[fa] - dfn[fa] + 1 + dfn[x];\n\nint main(){\n\n\tiloveds;\n\n\tcin >> n;\n\n\tfor(int i = 1; i <= n ; i ++){\n\n\t\tint x;\n\n\t\tchar c;\n\n\t\tcin >> x >> c;\n\n\t\tch[x][c - 'a'] = i;\n\n\t}\n\n\tcin >> k;\n\n\tfor(int i = 1; i <= k ; i ++){\n\n\t\tcin >> a[i];\n\n\t\tf[a[i]] = 1;\n\n\t}\n\n\tfor(int i = 1; i <= n ; i ++) {\n\n\t\tdp[i] = 0x3f3f3f3f;\n\n\t\tdfn[i] = 0x3f3f3f3f;\n\n\t}\n\n\tdfs(0);\n\n\tval = 0;\n\n\tdfs2(0);\n\n\tfor(int i = 1; i <= k ; i ++) cout << dp[a[i]] << \" \";\n\n}","language":"cpp"} {"contest_id":"1284","problem_id":"G","statement":"G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n\u00d7mn\u00d7m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either \"black\" or \"white\". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1\u2264t\u22641001\u2264t\u2264100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2\u2264n,m\u2264202\u2264n,m\u226420), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace): O: A free cell. X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t\u22652t\u22652 is satisfied, then the size of the grid will satisfy n\u226410,m\u226410n\u226410,m\u226410. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n\u22121)\u00d7(2m\u22121)(2n\u22121)\u00d7(2m\u22121) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base. For all 1\u2264i\u2264n,1\u2264j\u2264m1\u2264i\u2264n,1\u2264j\u2264m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). Otherwise, print 'X' in the cell (2i\u22121,2j\u22121)(2i\u22121,2j\u22121). For all 1\u2264i\u2264n,1\u2264j\u2264m\u221211\u2264i\u2264n,1\u2264j\u2264m\u22121, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i\u22121,2j)(2i\u22121,2j). Otherwise, print any printable character except spaces in the cell (2i\u22121,2j)(2i\u22121,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters. For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m1\u2264i\u2264n\u22121,1\u2264j\u2264m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print '\u00a0' in the cell (2i,2j\u22121)(2i,2j\u22121). Otherwise, print any printable character except spaces in the cell (2i,2j\u22121)(2i,2j\u22121) For all 1\u2264i\u2264n\u22121,1\u2264j\u2264m\u221211\u2264i\u2264n\u22121,1\u2264j\u2264m\u22121, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m\u221212m\u22121 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4\n2 2\nOO\nOO\n3 3\nOOO\nXOO\nOOO\n4 4\nOOOX\nXOOX\nOOXO\nOOOO\n5 6\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOOOOOO\nOutputCopyYES\nOOO\n O\nOOO\nNO\nYES\nOOOOO X\n O O \nX O O X\n O \nOOO X O\nO O O\nO OOOOO\nYES\nOOOOOOOOOOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n O O O\nOOO OOO OOO\nO O O \nOOO OOO OOO\n","tags":["graphs"],"code":"#include \n\n#include \n\n#include \n\n#define ALL(x) (x).begin(), (x).end()\n\n#define SZ(x) ((int)(x).size())\n\n#define st first\n\n#define nd second\n\n\n\nusing namespace __gnu_pbds;\n\nusing namespace std;\n\n\n\ntemplate \n\nusing ordered_set =\n\n\ttree, rb_tree_tag, tree_order_statistics_node_update>;\n\n\n\n#define sim template debug &operator<<\n\n#define eni(x) \\\n\n\tsim > typename enable_if(0) x 1, debug &>::type operator<<(c i) \\\n\n\t{\n\nsim > struct rge\n\n{\n\n\tc b, e;\n\n};\n\nsim > rge range(c i, c j) { return rge{i, j}; }\n\nsim > auto dud(c *x) -> decltype(cerr << *x, 0);\n\nsim > char dud(...);\n\n#define imie(...) \" [\" << #__VA_ARGS__ \": \" << (__VA_ARGS__) << \"] \"\n\n\n\n#define shandom_ruffle random_shuffle\n\n#define PB push_back\n\n#define MP make_pair\n\n#define LL long long\n\n\/\/ #define int LL\n\n#define VI vector\n\n#define PII pair\n\n#define LD long double\n\n#define st first\n\n#define nd second\n\n#define ALL(x) (x).begin(), (x).end()\n\n#define SZ(x) ((int)(x).size())\n\n\n\nusing ll = long long;\n\nusing pii = pair;\n\nusing pll = pair;\n\nusing vi = vector;\n\nusing vll = vector;\n\n\n\nstruct Matroid\n\n{\n\n\tint n;\n\n\n\n\tMatroid(int size) : n(size) {}\n\n\tvirtual ~Matroid() {}\n\n\n\n\t\/\/ Returns any circuit as the subset of [X]. Returns an empty vector\n\n\t\/\/ if [X] is independent.\n\n\tvirtual VI FindCircuit(const vector &)\n\n\t{\n\n\t\tthrow nullptr;\n\n\t}\n\n\n\n\tbool IsIndependent(const vector &X)\n\n\t{\n\n\t\treturn FindCircuit(X).empty();\n\n\t}\n\n};\n\n\n\nint H, W;\n\nstring board[30];\n\nvector verts;\n\nvector edges;\n\nint ids[30][30];\n\nvector adj[1000];\n\nint num_edges, nverts;\n\nbool is_in[1000];\n\nint out_bound[1000];\n\nvector> bounds;\n\nint bound_mapping[1000];\n\n\n\nstruct FU\n\n{\n\n\tvi pnt;\n\n\tFU(int n) : pnt(n)\n\n\t{\n\n\t\tiota(ALL(pnt), 0);\n\n\t}\n\n\tint Find(int v)\n\n\t{\n\n\t\tif (pnt[v] == v)\n\n\t\t{\n\n\t\t\treturn v;\n\n\t\t}\n\n\t\treturn pnt[v] = Find(pnt[v]);\n\n\t}\n\n};\n\n\n\nstruct CographicMatroid : public Matroid\n\n{\n\n\tCographicMatroid() : Matroid(num_edges) {}\n\n\tvirtual ~CographicMatroid() {}\n\n\n\n\tVI FindCircuit(const vector &X) override\n\n\t{\n\n\t\tmemset(is_in, 0, sizeof(bool) * num_edges);\n\n\t\tfor (int v : X)\n\n\t\t{\n\n\t\t\tis_in[v] = true;\n\n\t\t}\n\n\t\tFU fu(nverts);\n\n\t\tint ncomp = nverts;\n\n\t\tfor (int i = 0; i < num_edges; ++i)\n\n\t\t{\n\n\t\t\tif (!is_in[i])\n\n\t\t\t{\n\n\t\t\t\tint a = fu.Find(edges[i].st);\n\n\t\t\t\tint b = fu.Find(edges[i].nd);\n\n\t\t\t\tif (a != b)\n\n\t\t\t\t{\n\n\t\t\t\t\tfu.pnt[a] = b;\n\n\t\t\t\t\t--ncomp;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (ncomp == 1)\n\n\t\t{\n\n\t\t\treturn {};\n\n\t\t}\n\n\n\n\t\tvi indep;\n\n\t\tfor (int v : X)\n\n\t\t{\n\n\t\t\tint a = fu.Find(edges[v].st);\n\n\t\t\tint b = fu.Find(edges[v].nd);\n\n\t\t\tif (a != b && ncomp == 2)\n\n\t\t\t{\n\n\t\t\t\tindep.push_back(v);\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tif (a != b)\n\n\t\t\t{\n\n\t\t\t\tfu.pnt[a] = b;\n\n\t\t\t\t--ncomp;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn indep;\n\n\t}\n\n};\n\n\n\nstruct MaxChoiceMatroid : public Matroid\n\n{\n\n\tMaxChoiceMatroid() : Matroid(num_edges) {}\n\n\tvirtual ~MaxChoiceMatroid() {}\n\n\n\n\tVI FindCircuit(const vector &X) override\n\n\t{\n\n\t\tvector lists(SZ(bounds));\n\n\t\tfor (int v : X)\n\n\t\t{\n\n\t\t\tconst int where = bound_mapping[v];\n\n\t\t\tif (where == -1)\n\n\t\t\t{\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tlists[where].push_back(v);\n\n\t\t\tif (SZ(lists[where]) > bounds[where].nd)\n\n\t\t\t{\n\n\t\t\t\treturn lists[where];\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn {};\n\n\t}\n\n};\n\n\n\nVI IntersectMatroids(Matroid *A, Matroid *B)\n\n{\n\n\tassert(A->n == B->n);\n\n\tconst int n = A->n;\n\n\n\n\tvector graph;\n\n\n\n\tVI X;\n\n\twhile (true)\n\n\t{\n\n\t\tfor (int i = 0; i < n; ++i)\n\n\t\t{\n\n\t\t\tif (count(ALL(X), i))\n\n\t\t\t{\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tauto Y = X;\n\n\t\t\tY.PB(i);\n\n\t\t\tif (A->IsIndependent(Y) && B->IsIndependent(Y))\n\n\t\t\t{\n\n\t\t\t\tX = Y;\n\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/~ debug(X);\n\n\t\tvector is_x(n), is_a(n), is_b(n);\n\n\t\tfor (int x : X)\n\n\t\t{\n\n\t\t\tis_x[x] = true;\n\n\t\t}\n\n\n\n\t\tgraph.clear();\n\n\t\tgraph.resize(2 * n);\n\n\t\tqueue Q;\n\n\t\tVI dist(2 * n, 1e9), prv(2 * n, -1);\n\n\n\n\t\tfor (int y = 0; y < n; ++y)\n\n\t\t{\n\n\t\t\tif (is_x[y])\n\n\t\t\t{\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tauto Y = X;\n\n\t\t\tY.PB(y);\n\n\t\t\tauto circ_a = A->FindCircuit(Y);\n\n\t\t\tif (circ_a.empty())\n\n\t\t\t{\n\n\t\t\t\tis_a[y] = true;\n\n\t\t\t\tQ.push(y + n);\n\n\t\t\t\tdist[y + n] = 0;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tfor (int x : circ_a)\n\n\t\t\t\t{\n\n\t\t\t\t\tgraph[x].PB(y + n);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tauto circ_b = B->FindCircuit(Y);\n\n\t\t\tif (circ_b.empty())\n\n\t\t\t{\n\n\t\t\t\tis_b[y] = true;\n\n\t\t\t}\n\n\t\t\telse\n\n\t\t\t{\n\n\t\t\t\tfor (int x : circ_b)\n\n\t\t\t\t{\n\n\t\t\t\t\tgraph[y + n].PB(x);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t\/\/~ debug(y, circ_a, circ_b);\n\n\t\t}\n\n\n\n\t\tint dest = -1;\n\n\n\n\t\twhile (!Q.empty())\n\n\t\t{\n\n\t\t\tint v = Q.front();\n\n\t\t\tQ.pop();\n\n\t\t\tif (v >= n && is_b[v - n])\n\n\t\t\t{\n\n\t\t\t\tdest = v;\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\n\t\t\tfor (int s : graph[v])\n\n\t\t\t{\n\n\t\t\t\tif (dist[s] > dist[v] + 1)\n\n\t\t\t\t{\n\n\t\t\t\t\tdist[s] = dist[v] + 1;\n\n\t\t\t\t\tprv[s] = v;\n\n\t\t\t\t\tQ.push(s);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif (dest == -1)\n\n\t\t{\n\n\t\t\tbreak;\n\n\t\t}\n\n\n\n\t\twhile (dest != -1)\n\n\t\t{\n\n\t\t\tconst int p = dest % n;\n\n\t\t\t\/\/~ debug(p);\n\n\t\t\tis_x[p] = !is_x[p];\n\n\t\t\tdest = prv[dest];\n\n\t\t}\n\n\t\tassert(count(ALL(is_x), true) == SZ(X) + 1);\n\n\t\tX.clear();\n\n\t\tfor (int i = 0; i < n; ++i)\n\n\t\t{\n\n\t\t\tif (is_x[i])\n\n\t\t\t{\n\n\t\t\t\tX.PB(i);\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn X;\n\n}\n\n\n\nvoid Test()\n\n{\n\n\tcin >> H >> W;\n\n\tint cnt = 0;\n\n\tverts.clear();\n\n\tfor (int i = 0; i < H; ++i)\n\n\t{\n\n\t\tcin >> board[i];\n\n\t\tfor (int j = 0; j < W; ++j)\n\n\t\t{\n\n\t\t\tids[i][j] = -1;\n\n\t\t\tif (board[i][j] == 'O')\n\n\t\t\t{\n\n\t\t\t\tverts.emplace_back(i, j);\n\n\t\t\t\tids[i][j] = cnt;\n\n\t\t\t\t++cnt;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tedges.clear();\n\n\n\n\tfor (int i = 0; i < cnt; ++i)\n\n\t{\n\n\t\tadj[i].clear();\n\n\t}\n\n\n\n\tint eid = 0;\n\n\tfor (int i = 0; i < H; ++i)\n\n\t{\n\n\t\tfor (int j = 0; j < W; ++j)\n\n\t\t{\n\n\t\t\tif (j < W - 1 && board[i][j] == 'O' && board[i][j + 1] == 'O')\n\n\t\t\t{\n\n\t\t\t\tint a = ids[i][j];\n\n\t\t\t\tint b = ids[i][j + 1];\n\n\t\t\t\tadj[a].emplace_back(b, eid);\n\n\t\t\t\tadj[b].emplace_back(a, eid);\n\n\t\t\t\tedges.emplace_back(a, b);\n\n\t\t\t\teid++;\n\n\t\t\t}\n\n\t\t\tif (i < H - 1 && board[i][j] == 'O' && board[i + 1][j] == 'O')\n\n\t\t\t{\n\n\t\t\t\tint a = ids[i][j];\n\n\t\t\t\tint b = ids[i + 1][j];\n\n\t\t\t\tadj[a].emplace_back(b, eid);\n\n\t\t\t\tadj[b].emplace_back(a, eid);\n\n\t\t\t\tedges.emplace_back(a, b);\n\n\t\t\t\teid++;\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tnum_edges = SZ(edges);\n\n\tnverts = cnt;\n\n\n\n\tbounds.clear();\n\n\tfor (int i = 0; i < num_edges; ++i)\n\n\t{\n\n\t\tbound_mapping[i] = -1;\n\n\t}\n\n\n\n\tfor (int i = 0; i < H; ++i)\n\n\t{\n\n\t\tfor (int j = 0; j < W; ++j)\n\n\t\t{\n\n\t\t\tif (i == 0 && j == 0)\n\n\t\t\t{\n\n\t\t\t\tcontinue;\n\n\t\t\t}\n\n\t\t\tif (board[i][j] == 'O')\n\n\t\t\t{\n\n\t\t\t\tconst int v = ids[i][j];\n\n\t\t\t\tout_bound[v] = SZ(adj[v]) - 1;\n\n\t\t\t\tif ((i + j) % 2 == 0)\n\n\t\t\t\t{\n\n\t\t\t\t\t--out_bound[v];\n\n\t\t\t\t}\n\n\t\t\t\tif (out_bound[v] < 0)\n\n\t\t\t\t{\n\n\t\t\t\t\tcout << \"NO\\n\";\n\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\n\n\n\t\t\t\tif ((i + j) % 2 == 0)\n\n\t\t\t\t{\n\n\t\t\t\t\tvi eids;\n\n\t\t\t\t\tfor (auto &e : adj[v])\n\n\t\t\t\t\t{\n\n\t\t\t\t\t\teids.push_back(e.nd);\n\n\t\t\t\t\t\tbound_mapping[e.nd] = SZ(bounds);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tbounds.emplace_back(eids, out_bound[v]);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\n\tMatroid *cographic = new CographicMatroid();\n\n\tMatroid *max_choice = new MaxChoiceMatroid();\n\n\n\n\tauto inter = IntersectMatroids(cographic, max_choice);\n\n\tconst int num_blocked = SZ(inter);\n\n\tconst int need_blocked = num_edges - (nverts - 1);\n\n\n\n\tif (num_blocked < need_blocked)\n\n\t{\n\n\t\tdelete cographic;\n\n\t\tdelete max_choice;\n\n\t\tcout << \"NO\\n\";\n\n\t\treturn;\n\n\t}\n\n\n\n\tvector ans(2 * H - 1, string(2 * W - 1, ' '));\n\n\tfor (int i = 0; i < H; ++i)\n\n\t{\n\n\t\tfor (int j = 0; j < W; ++j)\n\n\t\t{\n\n\t\t\tans[2 * i][2 * j] = board[i][j];\n\n\t\t}\n\n\t}\n\n\n\n\tfor (auto &E : edges)\n\n\t{\n\n\t\tint a = E.st;\n\n\t\tint b = E.nd;\n\n\t\tauto [r1, c1] = verts[a];\n\n\t\tauto [r2, c2] = verts[b];\n\n\n\n\t\tif (r1 == r2)\n\n\t\t{\n\n\t\t\tans[2 * r1][2 * min(c1, c2) + 1] = 'O';\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\tans[2 * min(r1, r2) + 1][2 * c1] = 'O';\n\n\t\t}\n\n\t}\n\n\n\n\tfor (int v : inter)\n\n\t{\n\n\t\tint a = edges[v].st;\n\n\t\tint b = edges[v].nd;\n\n\t\tauto [r1, c1] = verts[a];\n\n\t\tauto [r2, c2] = verts[b];\n\n\t\tif (r1 == r2)\n\n\t\t{\n\n\t\t\tans[2 * r1][2 * min(c1, c2) + 1] = ' ';\n\n\t\t}\n\n\t\telse\n\n\t\t{\n\n\t\t\tans[2 * min(r1, r2) + 1][2 * c1] = ' ';\n\n\t\t}\n\n\t}\n\n\n\n\tcout << \"YES\\n\";\n\n\tfor (auto s : ans)\n\n\t{\n\n\t\tcout << s << \"\\n\";\n\n\t}\n\n\n\n\tdelete cographic;\n\n\tdelete max_choice;\n\n}\n\n\n\nint main()\n\n{\n\n\tios_base::sync_with_stdio(0);\n\n\tcin.tie(0);\n\n\tcout << fixed << setprecision(11);\n\n\tcerr << fixed << setprecision(6);\n\n\n\n\tint t;\n\n\tcin >> t;\n\n\twhile (t--)\n\n\t{\n\n\t\tTest();\n\n\t}\n\n}\n\n","language":"cpp"} {"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":"#include \"bits\/stdc++.h\"\n\nusing namespace std;\n\n#define all(x) begin(x),end(x)\n\ntemplate ostream& operator<<(ostream &os, const pair &p) { return os << '(' << p.first << \", \" << p.second << ')'; }\n\ntemplate::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { string sep; for (const T &x : v) os << sep << x, sep = \" \"; return os; }\n\n#define debug(a) cerr << \"(\" << #a << \": \" << a << \")\\n\";\n\ntypedef long long ll;\n\ntypedef vector vi;\n\ntypedef vector vvi;\n\ntypedef pair pi;\n\nconst int mxN = 1e5+1, oo = 1e9;\n\nstring str;\n\nvector> es;\n\nstring hidden = \"xasdungo\";\n\nvoid query(int l, int r) {\n\n cout << \"? \" << l+1 << ' ' << r+1 << endl;\n\n int len = r-l+1;\n\n vector v(len+1);\n\n for(int i=0;i> s;\n\n auto& w = v[s.size()];\n\n for(auto c : s) w+=c;\n\n }\n\n \/\/ for(int i=l;i<=r;++i) for(int j=i;j<=r;++j) {\n\n \/\/ string s = hidden.substr(i,j-i+1);\n\n \/\/ auto& w = v[s.size()];\n\n \/\/ for(auto c : s) w+=c;\n\n \/\/ }\n\n \/\/ take biggest string, do it times two, subtract out those two?\n\n vi res = {};\n\n for(int i=0;i<(len+1)\/2;i++) {\n\n int ans=-v[len-i-1];\n\n for(int j=0;j> n;\n\n str.resize(n,'?');\n\n if(n==1) {\n\n query(0,0);\n\n } else if(n==2) {\n\n query(0,0);\n\n query(0,1);\n\n } else {\n\n query(0,(n+1)\/2 -1);\n\n query(0,(n+1)\/2 -2);\n\n query(0,n-1);\n\n }\n\n vector> adj(n);\n\n for(auto& [u,v,w] : es) adj[u].push_back({v,w}),adj[v].push_back({u,w});\n\n for(int i=0;i void {\n\n for(auto [to,w] : adj[at]) if(str[to]=='?') {\n\n str[to]=w-str[at];\n\n self(self,to);\n\n }\n\n };\n\n dfs(dfs,i);\n\n break;\n\n }\n\n cout << \"! \" << str << endl;\n\n \n\n}","language":"cpp"} {"contest_id":"1304","problem_id":"C","statement":"C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi \u2014 the time (in minutes) when the ii-th customer visits the restaurant, lili \u2014 the lower bound of their preferred temperature range, and hihi \u2014 the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1\u2264q\u22645001\u2264q\u2264500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1\u2264n\u22641001\u2264n\u2264100, \u2212109\u2264m\u2264109\u2212109\u2264m\u2264109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1\u2264ti\u22641091\u2264ti\u2264109, \u2212109\u2264li\u2264hi\u2264109\u2212109\u2264li\u2264hi\u2264109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print \"YES\" if it is possible to satisfy all customers. Otherwise, print \"NO\".You can print each letter in any case (upper or lower).ExampleInputCopy4\n3 0\n5 1 2\n7 3 5\n10 -1 0\n2 12\n5 7 10\n10 16 20\n3 -100\n100 0 0\n100 -50 50\n200 100 100\n1 100\n99 -100 0\nOutputCopyYES\nNO\nYES\nNO\nNoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.","tags":["dp","greedy","implementation","sortings","two pointers"],"code":"#include\n\nusing namespace std;\n\n\n\n#define int long long\n\n#define pb push_back\n\n#define F first\n\n#define S second\n\n#define endl \"\\n\"\n\nconst int N=1e2+2 , inf=2e9;\n\npair dp[N];\n\nbool solve (int num , int cur)\n\n{\n\n\tbool c=true;\n\n\tint time[N];\n\n\tdp[0]={cur,cur};\n\n\ttime[0]=0;\n\n\tfor (int i=1 ; i<=num ; i++)\n\n\t{\n\n\t\tint l,r;\n\n\t\tcin >> time[i] >> l >> r;\n\n\t\tint dif=time[i]-time[i-1];\n\n\t\tint a,b;\n\n\t\ta=dp[i-1].F-dif;\t\n\n\t\tb=dp[i-1].S+dif;\n\n\t\tif (a>r || b> test;\n\n\twhile (test--)\n\n\t{\n\n\t\tint num;\tcin >> num;\n\n\t\tint cur;\t\tcin >> cur;\n\n\t\tif (solve (num,cur))\tcout << \"YES\" << endl;\n\n\t\telse cout << \"NO\" << endl;\n\n\t}\n\n\treturn 0;\n\n}","language":"cpp"} {"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\nusing namespace std;\n\n\/\/#include \n\n\/\/#include \n\n\/\/using namespace __gnu_pbds;\n\n#define pb push_back\n\n#define int long long\n\n#define lld long double\n\n#define fi first\n\n#define se second\n\n#define vi vector\n\n#define vb vector\n\n#define vs vector\n\n#define vvi vector>\n\n#define vpii vector>\n\n#define vvpii vector>>\n\n#define mii map\n\n#define pii pair\n\n#define pq priority_queue\n\n#define setbits(a) __builtin_popcountll(a) \n\n#define ctz(a) __builtin_ctzll(a)\n\n#define clz(a) __builtin_clzll(a)\n\n#define loop(n) for(int i=0;i>n; vector a(n); for(int i=0;i>a[i];\n\n#define ink(a,n,k) int n,k; cin>>n>>k; vector a(n); for(int i=0;i>a[i];\n\n#define out(a) for(auto x9: a) cout<>_; for(int tt=1;tt<=_;tt++)\n\n#define en \"\\n\"\n\n#define sz(a) (int)a.size()\n\n#define sortf(a) sort(a.begin(),a.end())\n\n#define sortr(a) sort(a.rbegin(),a.rend())\n\n#define all(a) a.begin(),a.end()\n\n#define gsum(a) accumulate(a.begin(),a.end(),0LL)\n\n#define gmax(a) *max_element(a.begin(),a.end())\n\n#define gmin(a) *min_element(a.begin(),a.end())\n\n#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)\n\nconst int mod = 1000000007;\n\n\/\/const int mod = 998244353;\n\nconst int inf = 2100000000;\n\nconst lld pi = 3.1415926535897932;\n\nconst long long INF = 1e18+5;\n\n\/\/typedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds;\n\n\/\/ ans val flag temp fin fish eye kill stat tic tac time cnt cost\n\nvoid yesno(bool xxx)\n\n{\n\n if(xxx)\n\n cout<<\"YES\\n\";\n\n else\n\n cout<<\"NO\\n\";\n\n}\n\nvoid NGE(vi &arr,vi &ans)\n\n{\n\n int n=sz(arr);\n\n stack s;\n\n \n\n \n\n s.push(arr[0]);\n\n \n\n \/\/ iterate for rest of the elements\n\n for (int i = 1; i < n; i++) {\n\n \n\n if (s.empty()) {\n\n s.push(arr[i]);\n\n continue;\n\n }\n\n \n\n \n\n while (s.empty() == false && arr[s.top()] > arr[i]) {\n\n ans[s.top()]=i;\n\n s.pop();\n\n }\n\n \n\n \n\n s.push(i);\n\n }\n\n \n\n \n\n while (s.empty() == false) {\n\n ans[s.top()]=0;\n\n s.pop();\n\n }\n\n}\n\nint32_t main() \n\n{\n\n \n\n fastio;\n\n \/\/code goes here\n\n int n;\n\n cin>>n;\n\n vi a(n+2,0);\n\n fo(i,1,n+1)\n\n cin>>a[i];\n\n \n\n vi fans(n+2,0),bans(n+2,0);\n\n \n\n NGE(a,fans);\n\n vi b=a;\n\n reverse(all(b));\n\n NGE(b,bans);\n\n reverse(all(bans));\n\n \n\n vi fdp(n+2,0),bdp(n+2,0);\n\n \/\/ out(fans)\n\n for(int i=n;i>=1;i--)\n\n {\n\n fdp[i]=(fans[i]-i)*a[i]+fdp[fans[i]];\n\n bans[i]=n-bans[i]+1;\n\n }\n\n \/\/out(bans)\n\n for(int i=1;i<=n;i++)\n\n {\n\n bdp[i]=(i-bans[i])*a[i]+bdp[bans[i]];\n\n }\n\n \n\n int note=1;\n\n int ans=0;\n\n for(int i=1;i<=n;i++)\n\n {\n\n int val = bdp[i]+fdp[i+1];\n\n if(val > ans)\n\n {\n\n if(a[i]>a[i+1])\n\n note=i;\n\n else\n\n note=i+1;\n\n ans=val;\n\n }\n\n }\n\n \n\n vi fin(n+2,0);\n\n fin[note]=a[note];\n\n int r=note;\n\n while(r<=n)\n\n {\n\n int p=r;\n\n int to=fans[p];\n\n while(p=1)\n\n {\n\n int p=l;\n\n int to=bans[p];\n\n while(p>to)\n\n {\n\n fin[p]=a[l];\n\n p--;\n\n }\n\n l=to;\n\n }\n\n \n\n for(int i=1;i<=n;i++)\n\n cout<\n\nconst int N = 2e6 + 101;\n\nint n, m;\n\nint dep[N], f[N][25], du[N], belong[N], vis[N];\n\nstd::vector e[N], t[N];\n\nstd::queue q;\n\nvoid dfs(int u, int fa) {\n\tdep[u] = dep[fa] + 1;\n\tf[u][0] = fa;\n\tfor (int i = 0; i <= 22; ++i) f[u][i + 1] = f[f[u][i]][i];\n\tfor (auto v : e[u]) {\n\t\tif (v == fa) continue;\n\t\tdfs(v, u);\n\t}\n}\n\nint lca(int x, int y) {\n\tif (dep[x] < dep[y]) std::swap(x, y);\n\tfor (int i = 22; i >= 0; --i) {\n\t\tif (dep[f[x][i]] >= dep[y]) x = f[x][i];\n\t\tif (x == y) return x;\n\t}\n\tfor (int i = 22; i >= 0; --i) {\n\t\tif (f[x][i] != f[y][i]) {\n\t\t\tx = f[x][i];\n\t\t\ty = f[y][i];\n\t\t}\n\t}\n\treturn f[x][0];\n}\n\nint find(int x) {\n\tif (belong[x] == x) return x;\n\telse return belong[x] = find(belong[x]);\n}\n\nsigned main() {\n\t\n\tstd::ios::sync_with_stdio(false);\n\tstd::cin.tie(nullptr);\n\t\n\tstd::cin >> n;\n\tfor (int i = 1; i <= n; ++i) belong[i] = i;\n\tfor (int i = 1; i < n; ++i) {\n\t\tint u, v;\n\t\tstd::cin >> u >> v;\n\t\te[u].push_back(v), e[v].push_back(u);\n\t}\n\tfor (int i = 1; i < n; ++i) {\n\t\tint u, v;\n\t\tstd::cin >> u >> v;\n\t\tt[u].push_back(v), t[v].push_back(u);\n\t\t++du[u], ++du[v];\n\t}\n\tdfs(1, 0);\n\tfor (int i = 1; i <= n; ++i) {\n\t\tif (du[i] == 1) q.push(i);\n\t}\n\t\/\/for (int i = 1; i <= n; ++i) std::cout << dep[i] << '\\n';\n\tstd::cout << n - 1 << '\\n';\n\twhile (q.size() >= 2) {\n\t\tint u = q.front(), v;\n\t\tq.pop();\n\t\tvis[u] = 1;\n\t\tfor (auto to : t[u]) {\n\t\t\tif (vis[to] == 1) continue;\n\t\t\tv = to;\n\t\t\t--du[v];\n\t\t\tif (du[v] == 1) q.push(v);\n\t\t\tbreak;\t\n\t\t}\n\t\tint k = lca(u, v);\n\t\tint a = find(u), b;\n\t\t\/\/std::cout << \"a: \" << a << \" u: \" << u << \" v: \" << v << \" k: \" << k << '\\n';\n\t\tif (dep[a] > dep[k]) {\n\t\t\tb = f[a][0];\n\t\t\tstd::cout << a << \" \" << b << \" \" << u << \" \" << v << '\\n';\n\t\t\tbelong[a] = find(b);\n\t\t}\n\t\telse {\n\t\t\tb = v;\n\t\t\tfor (int i = 22; i >= 0; --i) {\n\t\t\t\t\/\/std::cout << \"b: \" << b << '\\n';\n\t\t\t\tif (dep[f[b][i]] > dep[k] && find(f[b][i]) != a) b = f[b][i];\n\t\t\t}\n\t\t\tstd::cout << b << \" \" << f[b][0] << \" \" << u << \" \" << v << '\\n';\n\t\t\tbelong[b] = a;\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\t \t \t\t\t\t\t \t \t\t\t\t \t \t\t\t \t \t\t\t","language":"cpp"} {"contest_id":"1299","problem_id":"D","statement":"D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1\u2264n,m\u22641051\u2264n,m\u2264105)\u00a0\u2014 the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1\u2264ai,bi\u2264n,ai\u2260bi,0\u2264wi<321\u2264ai,bi\u2264n,ai\u2260bi,0\u2264wi<32)\u00a0\u2014 the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8\n1 2 0\n2 3 1\n2 4 3\n2 6 2\n3 4 8\n3 5 4\n5 4 5\n5 6 6\nOutputCopy2\nInputCopy7 9\n1 2 0\n1 3 1\n2 3 9\n2 4 3\n2 5 4\n4 5 7\n3 6 6\n3 7 7\n6 7 8\nOutputCopy1\nInputCopy4 4\n1 2 27\n1 3 1\n1 4 1\n3 4 0\nOutputCopy6NoteThe pictures below represent the graphs from examples. In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11. In the second example, if we don't remove the edge 1\u221221\u22122, then there is a cycle 1\u22122\u22124\u22125\u22122\u221211\u22122\u22124\u22125\u22122\u22121 with cost 00; also if we don't remove the edge 1\u221231\u22123, then there is a cycle 1\u22123\u22122\u22124\u22125\u22122\u22123\u221211\u22123\u22122\u22124\u22125\u22122\u22123\u22121 of cost 00. The only valid subset consists of both edges. In the third example, all subsets are valid except for those two in which both edges 1\u221231\u22123 and 1\u221241\u22124 are kept.","tags":["bitmasks","combinatorics","dfs and similar","dp","graphs","graphs","math","trees"],"code":"#include \n\nusing namespace std;\n\n\n\nconst int D = 5;\n\nconst int S = 374;\n\n\n\nint transition[S][1<>k)&1;\n\n }\n\n bool operator == (const linear_space& other) {\n\n return x == other.x;\n\n }\n\n bool operator < (const linear_space& other) {\n\n return x < other.x;\n\n }\n\n linear_space operator + (int k) {\n\n uint32_t res = x;\n\n for (int i = 0; i < (1<>i)&1) res |= 1<<(k^i);\n\n }\n\n return linear_space(res);\n\n }\n\n linear_space operator + (const linear_space& other) {\n\n uint32_t res = 0;\n\n for (int i = 0; i < (1<>i)&1 && (other.x>>j)&1) res |= 1<<(i^j);\n\n }\n\n }\n\n return linear_space(res);\n\n }\n\n friend ostream& operator << (ostream& os, const linear_space& l) {\n\n return os << bitset<32>(l.x);\n\n }\n\n};\n\n\n\nvector spaces(1);\n\n\n\nint get_index(linear_space x) {\n\n return lower_bound(spaces.begin(), spaces.end(), x)-spaces.begin();\n\n}\n\n\n\nvoid precompute() {\n\n for (int i = 0; i < (int)spaces.size(); i++) {\n\n for (int j = 0; j < (1<= MOD) x -= MOD;\n\n}\n\n\n\nconst int N = 1e5+5;\n\nvector> G[N];\n\nint wt[N], tree_space[N], dep[N];\n\nbool inner[N], vis[N];\n\n\n\nvector> special_edges;\n\n\n\nvoid dfs(int v) {\n\n for (auto& [u, w]: G[v]) {\n\n if (inner[u] && inner[v]) {\n\n if (u < v) special_edges.emplace_back(u, v, w);\n\n continue;\n\n }\n\n if (dep[u] < dep[v] && (dep[u] > 0 || u == 1)) continue;\n\n if (dep[u] > dep[v]+1) {\n\n if (tree_space[v] != -1) {\n\n tree_space[v] = transition[tree_space[v]][wt[u]^wt[v]^w];\n\n }\n\n continue;\n\n }\n\n dep[u] = dep[v]+1;\n\n wt[u] = wt[v]^w;\n\n dfs(u);\n\n if (v != 1 && tree_space[v] != -1) {\n\n if (tree_space[u] == -1) tree_space[v] = -1;\n\n else tree_space[v] = combination[tree_space[v]][tree_space[u]];\n\n }\n\n }\n\n}\n\n\n\nvoid increment(array& a, array& b, int c) {\n\n for (int i = 0; i < S; i++) {\n\n int j = combination[i][c];\n\n if (j != -1) add(b[j], a[i]);\n\n }\n\n}\n\n\n\nint main () {\n\n ios_base::sync_with_stdio(0); cin.tie(0);\n\n precompute();\n\n\n\n int n, m;\n\n cin >> n >> m;\n\n for (int i = 0; i < m; i++) {\n\n int u, v, w;\n\n cin >> u >> v >> w;\n\n G[u].emplace_back(v, w);\n\n G[v].emplace_back(u, w);\n\n }\n\n for (auto& [v, _]: G[1]) inner[v] = 1;\n\n dfs(1);\n\n\n\n fill(vis, vis+N, 0);\n\n array dp({});\n\n dp[0] = 1;\n\n for (auto& [u, v, w]: special_edges) {\n\n vis[u] = vis[v] = 1;\n\n array _dp = dp;\n\n if (tree_space[u] != -1 && tree_space[v] != -1) {\n\n int k = combination[tree_space[u]][tree_space[v]];\n\n if (k != -1) {\n\n increment(dp, _dp, k);\n\n increment(dp, _dp, k);\n\n int l = transition[k][wt[u]^wt[v]^w];\n\n if (l != -1) increment(dp, _dp, l);\n\n }\n\n }\n\n swap(dp, _dp);\n\n }\n\n\n\n for (auto& [v, _]: G[1]) {\n\n if (vis[v]) continue;\n\n if (tree_space[v] != -1) {\n\n array _dp = dp;\n\n increment(dp, _dp, tree_space[v]);\n\n swap(dp, _dp);\n\n }\n\n }\n\n\n\n int ans = 0;\n\n for (int x: dp) add(ans, x);\n\n cout << ans << '\\n';\n\n}\n\n","language":"cpp"} {"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":"#include\n\nusing namespace std;\n\n#define taskname \"\"\n\nstruct line{\n\nint l,r;\n\nbool operator < (const line &p)const{\n\nreturn l>n>>m>>k;\n\n vectorpos;\n\n mapdm;\n\n pos.push_back(m);\n\n dm[m]=1;\n\n for (int i=1;i<=n;i++){\n\n cin>>a[i].l>>a[i].r;\n\n if (dm[a[i].l]==0){\n\n pos.push_back(a[i].l);\n\n dm[a[i].l]=1;\n\n }\n\n if (dm[a[i].r+1]==0){\n\n dm[a[i].r+1]=1;\n\n pos.push_back(a[i].r+1);\n\n }\n\n }\n\n if (dm[m+1]==0)pos.push_back(m+1);\n\n sort(pos.begin(),pos.end());\n\n sort(a+1,a+1+n);\n\n int p=0;\n\n int mask=0;\n\n vectorlast;\n\n int ans=0;\n\n for (int i=0;i<(int)pos.size()-1;i++){\n\n for (int j=0;jnewline;\n\n for (int j=p+1;j<=n;j++){\n\n if (a[j].l==pos[i]){\n\n p=j;\n\n newline.push_back(j);\n\n }\n\n else break;\n\n }\n\n \/\/cout<=pos[i+1])newmask+=(1<=pos[i+1])newmask+=(1<0)sum=dp2[i-1][huhu];\n\n if (__builtin_popcount(j)%2==1){\n\n sum+=(pos[i+1]-pos[i]);\n\n }\n\n dp[i][j]=sum;\n\n ans=max(ans,sum);\n\n \/\/cout<\n\n\/\/#include \n\n\/\/#include \n\n\/\/#include \n\n\n\n\/\/#pragma GCC optimize(\"Ofast\")\n\n\/\/#pragma GCC optimization(\"unroll-loops, no-stack-protector\")\n\n\/\/#pragma GCC target(\"avx,avx2,fma\")\n\n\n\n\/\/using namespace std;\n\n\/\/using namespace __gnu_pbds;\n\n\/\/using namespace __gnu_cxx;\n\n\n\n#define fi first\n\n#define se second\n\n#define TASK \"test\"\n\n#define pb push_back\n\n#define EL cout << endl\n\n#define Ti20_ntson int main()\n\n#define in(x) cout << x << endl\n\n#define all(x) (x).begin(),(x).end()\n\n#define getbit(x, i) (((x) >> (i)) & 1)\n\n#define cntbit(x) __builtin_popcount(x)\n\n#define FOR(i,l,r) for (int i = l; i <= r; i++)\n\n#define FORD(i,l,r) for (int i = l; i >= r; i--)\n\n#define Debug(a,n) for (int i = 1; i <= n; i++) cout << a[i] << \" \"; cout << endl\n\n\n\nusing namespace std;\n\n\n\ntypedef long long ll;\n\ntypedef vector vi;\n\ntypedef pair vii;\n\ntypedef unsigned long long ull;\n\ntypedef vector> vvi;\n\nint fastMax(int x, int y) { return (((y-x)>>(32-1))&(x^y))^y; }\n\n\n\nconst int N = 2e4 + 5;\n\nconst int oo = INT_MAX;\n\nconst int mod = 1e9 + 7;\n\nconst int d4x[4] = {-1, 0, 1, 0} , d4y[4] = {0, 1, 0, -1};\n\nconst int d8x[8] = {-1, -1, 0, 1, 1, 1, 0, -1}, d8y[8] = {0, 1, 1, 1, 0, -1, -1, -1};\n\n\n\nint n, a[55][N], m, k;\n\nll dp[55][N];\n\n\n\ninline void Read_Input() {\n\n cin >> n >> m >> k;\n\n FOR(i, 1, n)\n\n FOR(j, 1, m) {\n\n cin >> a[i][j];\n\n a[i][j] = a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1] + a[i][j];\n\n }\n\n}\n\n\n\nint Get(int x, int y, int xx, int yy) {\n\n return a[xx][yy] - a[x - 1][yy] - a[xx][y - 1] + a[x - 1][y - 1];\n\n}\n\n\n\nstruct Segment_Tree {\n\n ll st[4 * N + 5], lz[4 * N + 5];\n\n\n\n void build(int id, int l, int r, int cur) {\n\n lz[id] = 0;\n\n if (l == r) {\n\n st[id] = dp[cur][l];\n\n return;\n\n }\n\n int mid = (l + r) >> 1;\n\n build(id * 2, l, mid, cur);\n\n build(id * 2 + 1, mid + 1, r, cur);\n\n st[id] = max(st[id * 2], st[id * 2 + 1]);\n\n }\n\n\n\n void Down(int id) {\n\n if (lz[id] == 0)\n\n return;\n\n lz[id * 2] += lz[id];\n\n lz[id * 2 + 1] += lz[id];\n\n st[id * 2] += lz[id];\n\n st[id * 2 + 1] += lz[id];\n\n lz[id] = 0;\n\n }\n\n\n\n void update(int id, int l, int r, int u, int v, int val) {\n\n if (l > v || r < u)\n\n return;\n\n if (l >= u && r <= v) {\n\n st[id] += val;\n\n lz[id] += val;\n\n return;\n\n }\n\n int mid = (l + r) >> 1;\n\n Down(id);\n\n update(id * 2, l, mid, u, v, val);\n\n update(id * 2 + 1, mid + 1, r, u, v, val);\n\n st[id] = max(st[id * 2], st[id * 2 + 1]);\n\n }\n\n\n\n ll Get(int id, int l, int r, int u, int v) {\n\n if (l > v || r < u)\n\n return 0;\n\n if (l >= u && r <= v)\n\n return st[id];\n\n Down(id);\n\n int mid = (l + r) >> 1;\n\n return max(Get(id * 2, l, mid, u, v), Get(id * 2 + 1, mid + 1, r, u, v));\n\n }\n\n\n\n}it;\n\n\n\ninline void Solve() {\n\n const int mx = m - k + 1;\n\n ll Ans = 0;\n\n FOR(i, 1, mx)\n\n dp[1][i] = Get(1, i, 1, i + k - 1);\n\n if (n > 1)\n\n FOR(i, 1, mx)\n\n dp[1][i] += Get(2, i, 2, i + k - 1);\n\n FOR(i, 2, n) {\n\n it.build(1, 1, mx, i - 1);\n\n int val = Get(i, 1, i, k);\n\n FOR(j, 1, k) {\n\n it.update(1, 1, mx, j, j, -val),\n\n val -= Get(i, j, i, j);\n\n }\n\n FOR(j, 1, mx) {\n\n dp[i][j] = it.st[1] + Get(i, j, i, j + k - 1);\n\n if (i != n)\n\n dp[i][j] += Get(i + 1, j, i + 1, j + k - 1);\n\n if (j != mx) {\n\n\/\/ cout << \"CHECK \" << j << endl;\n\n int l = max(1, j - k + 1);\n\n\/\/ cout << \"UPDATE \" << l << \" \" << j << \" \" << Get(i, j, i, j) << endl;\n\n it.update(1, 1, mx, l, j, Get(i, j, i, j));\n\n int cur = j + k;\n\n cur = Get(i, cur, i, cur);\n\n int r = min(mx, j + k);\n\n it.update(1, 1, mx, j + 1, r, -cur);\n\n\/\/ cout << \"UPDATE \" << j + 1 << \" \" << r << \" \" << -cur << endl;\n\n\/\/ FOR(k, 1, mx)\n\n\/\/ cout << it.Get(1, 1, mx, k, k) << \" \"; cout << endl;\n\n }\n\n }\n\n\/\/ FOR(j, 1, mx)\n\n\/\/ cout << dp[i][j] << \" \\n\"[j == mx];\n\n }\n\n cout << *max_element(dp[n] + 1, dp[n] + mx + 1);\n\n}\n\n\n\nTi20_ntson {\n\n\/\/ freopen(TASK\".INP\",\"r\",stdin);\n\n\/\/ freopen(TASK\".OUT\",\"w\",stdout);\n\n ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n\n int T = 1;\n\n\/\/ cin >> T;\n\n while (T -- ) {\n\n Read_Input();\n\n Solve();\n\n }\n\n}\n\n\n\n","language":"cpp"} {"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":"#include \n#include \nusing namespace std;\nint t, x;\n\nvoid Solve() {\n for (int i=1; i<=t; i++) {\n cin >> x;\n cout << 1 << ' ' << x - 1 << '\\n';\n }\n}\n\nint main()\n{\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n cin >> t;\n Solve();\n return 0;\n}\n\n\t\t \t \t \t\t\t\t \t \t \t\t \t \t","language":"cpp"} {"contest_id":"1320","problem_id":"B","statement":"B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http:\/\/tk.codeforces.com\/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2\u2264n\u2264m\u22642\u22c51052\u2264n\u2264m\u22642\u22c5105) \u2014 the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1\u2264u,v\u2264n1\u2264u,v\u2264n, u\u2260vu\u2260v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2\u2264k\u2264n2\u2264k\u2264n) \u2014 the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1\u2264pi\u2264n1\u2264pi\u2264n, all these integers are pairwise distinct) \u2014 the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i\u2208[1,k\u22121]i\u2208[1,k\u22121] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9\n1 5\n5 4\n1 2\n2 3\n3 4\n4 1\n2 6\n6 4\n4 2\n4\n1 2 3 4\nOutputCopy1 2\nInputCopy7 7\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 1\n7\n1 2 3 4 5 6 7\nOutputCopy0 0\nInputCopy8 13\n8 7\n8 6\n7 5\n7 4\n6 5\n6 4\n5 3\n5 2\n4 3\n4 2\n3 1\n2 1\n1 8\n5\n8 7 5 2 1\nOutputCopy0 3\n","tags":["dfs and similar","graphs","shortest paths"],"code":"#include \n\nusing namespace std;\n\n#define FOR(i, x, y) for (int i = x; i < y; i++)\n\nconst int mx = 2e5 + 5;\n\nint n, m, k, A[mx], dst[mx], cnt[mx]; vector adj[mx];\n\nint main(){\ncin >> n >> m;\nFOR(i, 1, m + 1){\nint u, v; cin >> u >> v;\nadj[v].push_back(u);\n}\ncin >> k;\nFOR(i, 1, k + 1) cin >> A[i];\n\nqueue q; memset(dst, 0x3f, sizeof(dst));\nq.push(A[k]); dst[A[k]] = 0;\n\nwhile (!q.empty()){\nint cur = q.front(); q.pop();\nfor (int nxt : adj[cur]){\nif (dst[cur] + 1 < dst[nxt]){\ndst[nxt] = dst[cur] + 1;\ncnt[nxt] = 0;\nq.push(nxt);\n}\nif (dst[cur] + 1 == dst[nxt]) cnt[nxt]++;\n}\n}\nint bstMn = 0, bstMx = 0;\nFOR(i, 1, k){\nif (dst[A[i]] - 1 != dst[A[i + 1]]) bstMn++, bstMx++;\nelse if (cnt[A[i]] > 1) bstMx++;\n}\ncout<