contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) a.sort() median = n print(a[median]-a[median-1])
py
1295
C
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≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) 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⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
from __future__ import division, print_function import os,sys from io import BytesIO, IOBase from random import randint, randrange if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip from math import ceil, floor, factorial, log10 # from math import log,sqrt,cos,tan,sin,radians from bisect import bisect_left, bisect_right from collections import deque, Counter, defaultdict # from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right # from decimal import * # from heapq import nsmallest, nlargest, heapify, heappop, heappush, heapreplace # from collections import OrderedDict # from itertools import permutations M=1000000007 # M=998244353 INF = float("inf") PI = 3.141592653589793 R = randrange(2, 1 << 32) # R = 0 # Enable this for debugging of dict keys in myDict # ========================= Main ========================== def main(): TestCases = 1 TestCases = int(input()) for _ in range(TestCases): s, t = input(), input() s1, t1 = set(s), set(t) possible = True for ch in list(t1): if ch not in s1: possible = False break if not possible: print(-1) continue ind = [[] for i in range(26)] for i in range(len(s)): pos = abd[s[i]] ind[pos].append(i) ans = 1 i = 0 for ch in t: pos = abd[ch] v = bisect_left(ind[pos], i) if v == len(ind[pos]): ans += 1 i = 0 v = bisect_left(ind[pos], i) # print(ch, v, i, ind[pos]) i = ind[pos][v] + 1 print(ans) # ======================== Functions declaration Starts ======================== abc='abcdefghijklmnopqrstuvwxyz' abd={'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25} def copy2d(lst): return [x[:] for x in lst] #Copy 2D list... Avoid Using Deepcopy def no_of_digits(num): return 0 if num <= 0 else int(log10(num)) + 1 def powm(num, power, mod=M): return pow(num, power, mod) def isPowerOfTwo(x): return (x and (not(x & (x - 1)))) def LSB(num): """Returns Least Significant Bit of a number (Rightmost bit) in O(1)""" return num & -num def MSB(num): """Returns Most Significant Bit of a number (Leftmost bit) in O(logN)""" if num <= 0: return 0 ans = 1; num >>= 1 while num: num >>= 1; ans <<= 1 return ans LB = bisect_left # Lower bound UB = bisect_right # Upper bound def BS(a, x): # Binary Search i = bisect_left(a, x) if i != len(a) and a[i] == x: return i else: return -1 def gcd(x, y): while y: x, y = y, x % y return x def lcm(x, y): return (x*y)//gcd(x,y) # import threading # def dmain(): # sys.setrecursionlimit(1000000) # threading.stack_size(1024000) # thread = threading.Thread(target=main) # thread.start() # =============================== Custom Classes =============================== class Wrapper(int): def __init__(self, x): int.__init__(x) def __hash__(self): return super(Wrapper, self).__hash__() ^ R Int = lambda x:Wrapper(int(x)) class myDict(): def __init__(self,func=int): # self.RANDOM = randint(0,1<<32) self.RANDOM = R self.default=func self.dict={} def __getitem__(self,key): myKey=self.RANDOM^key if myKey not in self.dict: self.dict[myKey]=self.default() return self.dict[myKey] def __setitem__(self,key,item): myKey=self.RANDOM^key self.dict[myKey]=item def __contains__(self,key): myKey=self.RANDOM^key return myKey in self.dict def __delitem__(self,key): myKey=self.RANDOM^key del self.dict[myKey] def keys(self): return [self.RANDOM^i for i in self.dict] # =============================== Region Fastio =============================== if not os.path.isdir('C:/users/acer'): BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # =============================== Endregion =============================== if __name__ == "__main__": #read() main() #dmain()
py
1321
A
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 — 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 — 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≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). 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≤bi≤10≤bi≤1). 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 −1−1.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 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn 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" — 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.
[ "greedy" ]
I=input I() r=p=0 for x,y in zip(I(),I()):r+=x>y;p+=x<y print(r and p//r+1or-1)
py
13
C
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 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1
[ "dp", "sortings" ]
import heapq input() ans = 0 a = [] inf = 10**9 for x in map(int, input().split()): x = inf-x heapq.heappush(a, x) ans += a[0] - x heapq.heappop(a) heapq.heappush(a, x) print(-ans)
py
1324
B
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−i−1ai=an−i−1 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≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), 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 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn 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.
[ "brute force", "strings" ]
t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) f = False for j in range(n): for k in range(j, n): if a[j] == a[k] and (k - j) >= 2: print('YES') f = True break if f == True: break if f == False: print("NO")
py
1305
C
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,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n, m = map(int, input().split()) a = list(map(int, input().split())) cnt = [0] * m for i in a: cnt[i % m] += 1 if max(cnt) >= 2: ans = 0 print(ans) exit() ans = 1 for i in range(n): ai = a[i] for j in range(i + 1, n): ans = ans * abs(ai - a[j]) % m print(ans)
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline n = int(input()) l = pow(10, 6) + 5 c = [0] * l u = [] for _ in range(n): s = list(map(int, input().split()))[1:] f = 0 for i in range(len(s) - 1): if s[i] < s[i + 1]: f = 1 break if not f: c[s[0]] += 1 u.append(s[-1]) for i in range(1, l): c[i] += c[i - 1] ng = 0 for i in u: ng += c[i] ans = n * n - ng print(ans)
py
1305
C
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,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
import math from sys import stdin input = stdin.readline #// - remember to add .strip() when input is a string n, m = map(int,input().split()) arr = list(map(int,input().split())) if n > m: print(0) else: prod = 1 for i in range(0,n): for j in range(i+1,n): prod = (prod *abs(arr[j]-arr[i])) % m print(prod % m) # print answer modulo m
py
1295
D
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≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3 4 9 5 10 42 9999999967 OutputCopy6 1 9999999966 NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.
[ "math", "number theory" ]
import math import sys input = sys.stdin.readline def prime_factorize(n): ans = [] for i in range(2, int(n ** (1 / 2)) + 1): while True: if n % i: break ans.append(i) n //= i if n == 1: break if not n == 1: ans.append(n) return ans def euler_func(n): p = set(prime_factorize(n)) x = n for i in p: x *= (i - 1) x //= i return x t = int(input()) ans = [] for _ in range(t): a, m = map(int, input().split()) g = math.gcd(a, m) m //= g a //= g ans0 = euler_func(m) ans.append(ans0) sys.stdout.write("\n".join(map(str, ans)))
py
1324
B
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−i−1ai=an−i−1 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≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), 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 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn 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.
[ "brute force", "strings" ]
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ans="NO" for i in range(n-2): if a[i] in a[i+2:]: ans="YES"; break print(ans)
py
1316
C
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+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, 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,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. 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≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — 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,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — 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 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn 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.
[ "constructive algorithms", "math", "ternary search" ]
n,m,p=map(int,input().split()) f=list(map(int,input().split())) g=list(map(int,input().split())) an=0 an2=0 for i in range(n): if f[i]%p!=0: an=i break for i in range(m): if g[i]%p!=0: an2=i break print(an+an2)
py
1320
B
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≤n≤m≤2⋅1052≤n≤m≤2⋅105) — 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≤u,v≤n1≤u,v≤n, u≠vu≠v) 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≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — 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∈[1,k−1]i∈[1,k−1] 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 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
# Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase from collections import deque def main(): n,m=map(int,input().split()) graph=[[] for _ in range(n+1)] for _ in range(m): u,v=map(int,input().split()) graph[v].append(u) k=int(input()) path=list(map(int,input().split())) start=path[0] end=path[-1] dist=[-1]*(n+1) dist[end]=0 directCount=[0]*(n+1) queue=deque([end]) vis=[0]*(n+1) vis[end]=1 while queue: z=queue.popleft() for item in graph[z]: if vis[item]==0: vis[item]=1 dist[item]=dist[z]+1 queue.append(item) directCount[item]=1 elif dist[item]==dist[z]+1: directCount[item]+=1 # print(dist) mm,mx=0,0 prev=dist[start] for i in range(1,k-1): z=path[i] if dist[z]==prev-1: if directCount[path[i-1]]>1: mx+=1 else: mm+=1 prev=dist[z] print(mm,mx+mm) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main()
py
1288
D
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≤i,j≤n1≤i,j≤n, 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∈[1,m]k∈[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≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — 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≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — 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 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 OutputCopy1 5
[ "binary search", "bitmasks", "dp" ]
from sys import stdin N,M = map(int,stdin.readline().split()) ARRS = [list(map(int,stdin.readline().split())) for i in range(N)] def test(x): bitmasks = dict() for i,row in enumerate(ARRS): key = tuple(1 if num >= x else 0 for num in row) if key not in bitmasks: bitmasks[key] = i+1 bitmasks = list(bitmasks.items()) for i in range(len(bitmasks)): for j in range(i,len(bitmasks)): mask1,i1 = bitmasks[i] mask2,i2 = bitmasks[j] if all(b1 or b2 for b1,b2 in zip(mask1,mask2)): return True,i1,i2 return False,None,None l,r = 0,10**9 ans = None while l <= r: m = (l+r)//2 works,i,j = test(m) if works: l = m+1 ans = i,j else: r = m-1 print(*ans)
py
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
import sys from array import array input = lambda: sys.stdin.buffer.readline().decode().strip() n = int(input()) if n & 1: exit(print('no')) ys, xs = array('i'), array('i') for _ in range(n): x, y = map(int, input().split()) ys.append(y) xs.append(x) curx, cury = 1e9 + 1, 1e9 + 1 for i in range(n // 2): l, r = i, i + n // 2 mx = abs(xs[l] - xs[r]) + 2 * min(xs[l], xs[r]) my = abs(ys[l] - ys[r]) + 2 * min(ys[l], ys[r]) if (curx == cury == 1e9 + 1) or curx == mx and cury == my: curx, cury = mx, my else: exit(print('no')) print('yes')
py
1321
C
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≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 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≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe 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.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
n = int(input()) s = input() ans=0 for i in range(122,97,-1): if len(s)==1: break j = 0 while j<len(s): if len(s)==1: break if ord(s[j])==i: if j==0 or j==len(s)-1: if j==0 and ord(s[j+1])==i-1: ans+=1 s = s[1:] elif j==len(s)-1 and ord(s[j-1])==i-1: ans+=1 s = s[:len(s)-1] j+=1 else: j+=1 elif j>0 and j<len(s)-1: if ord(s[j-1])==i-1 or ord(s[j+1])==i-1: ans+=1 s = s[:j] + s[j+1:] j-=1 else: j+=1 else: j+=1 else: j+=1 print(ans)
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
import sys input = sys.stdin.readline for _ in range(int(input())): n, x = map(int, input().split()) w = list(map(int, input().split())) a = max(w) if a >= x: for i in w: if i == x: print(1) break else: print(2) else: print((x+a-1)//a)
py
1296
C
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−1,y)(x−1,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−1)(x,y−1). 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≤t≤10001≤t≤1000) — 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≤n≤2⋅1051≤n≤2⋅105) — 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' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).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≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR OutputCopy1 2 1 4 3 4 -1
[ "data structures", "implementation" ]
import sys, io, os import math import bisect from sys import stdin,stdout from math import gcd,floor,sqrt,log from collections import defaultdict as dd from bisect import bisect_left as bl,bisect_right as br #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline inp =lambda: int(input()) strng =lambda: input().strip() jn =lambda x,l: x.join(map(str,l)) strl =lambda: list(input().strip()) mul =lambda: map(int,input().strip().split()) mulf =lambda: map(float,input().strip().split()) seq =lambda: list(map(int,input().strip().split())) ceil =lambda x: int(x) if(x==int(x)) else int(x)+1 ceildiv=lambda x,d: x//d if(x%d==0) else x//d+1 flush =lambda: stdout.flush() stdstr =lambda: stdin.readline() stdint =lambda: int(stdin.readline()) stdpr =lambda x: stdout.write(str(x) + "\n") printls = lambda l: print(*l, sep=" ") mod=1000000007 """ Paste solution below """ def solution(s): def coordToString(coord): return str(coord[0]) + "," + str(coord[1]) locations = {} shortest = [-1, -1] shortest_l = float('inf') curr_coord = [0, 0] locations[coordToString(curr_coord)] = -1 for i in range(len(s)): ch = s[i] if ch == 'L': curr_coord[0] -= 1 elif ch == 'R': curr_coord[0] += 1 elif ch == 'U': curr_coord[1] += 1 else: curr_coord[1] -= 1 coord_string = coordToString(curr_coord) if coord_string in locations: if i - locations[coord_string] < shortest_l: shortest_l = i - locations[coord_string] shortest = [locations[coord_string]+2, i+1] locations[coord_string] = i return shortest if shortest[0] != -1 else [-1] t = inp() for i in range(t): n = inp() s = strng() ans = solution(s) print(*ans)
py
1301
A
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≤i≤n1≤i≤n) 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↔aici↔ai or ci↔bici↔bi (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≤t≤1001≤t≤100)  — 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 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim OutputCopyNO YES YES NO NoteIn 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.
[ "implementation", "strings" ]
for _ in range(int(input())): a = input() b = input() c = input() s = 'YES' for i in range(len(a)): if not(c[i] == a[i] or c[i] == b[i]): s = 'NO' break print(s)
py
1141
E
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,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). 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≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), 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 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
from itertools import accumulate from math import ceil H, n = map(int, input().split()) nums = list(map(int, input().split())) prefixsum = list(accumulate(nums)) # find the min elmnt the_min = -min(prefixsum) # calculate the iteration turns = 0 if H > the_min and prefixsum[-1] < 0: turns = ceil(-(H - the_min)/prefixsum[-1]) # print(turns) H -= -prefixsum[-1] * turns ans = turns * n # print(H) for num in nums: ans += 1 H += num if H <= 0: break if H <= 0: print(ans) else: print(-1)
py
1312
E
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,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≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5 4 3 2 2 3 OutputCopy2 InputCopy7 3 3 4 4 4 3 3 OutputCopy2 InputCopy3 1 3 5 OutputCopy3 InputCopy1 1000 OutputCopy1 NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.
[ "dp", "greedy" ]
import sys from array import array input = lambda: sys.stdin.buffer.readline().decode().strip() inp = lambda dtype: [dtype(x) for x in input().split()] debug = lambda *x: print(*x, file=sys.stderr) ceil1 = lambda a, b: (a + b - 1) // b Mint, Mlong, out = 2 ** 31 - 1, 2 ** 63 - 1, [] def shrink(l, r): stk = array('i') for i in range(l, r + 1): cur = a[i] while stk and stk[-1] == cur: stk.pop() cur += 1 stk.append(cur) return len(stk) == 1 for _ in range(1): n, a = int(input()), array('i', inp(int)) dp = array('i', list(range(1, n + 1)) + [0]) for i in range(n): for j in range(i, -1, -1): if shrink(j, i): dp[i] = min(dp[i], dp[j - 1] + 1) out.append(dp[n - 1]) print('\n'.join(map(str, out)))
py
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,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≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).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 −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
#import io, os #input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t=int(input()) for _ in range(t): n=int(input()) b=list(map(int,input().split())) a=[] for i in range(1,2*n+1): a.append(i) perm=[] visited={} for i in b: visited.update({i:1}) flag=False for i in b: perm.append(i) for j in a: if not j in visited: if j>i: perm.append(j) visited.update({j:1}) break else: flag=True if flag:print(-1) else:print(*perm)
py
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
from sys import stdin input = stdin.readline inp = lambda : list(map(int,input().split())) def answer(): ans = [] j = n - 1 for i in range(n): if(a[i] == '('): while(j > i and a[j] == '('): j -= 1 if(j == i):break ans.append(i + 1) ans.append(j + 1) j -= 1 if(i == j):break if(len(ans) == 0): print(0) return ans.sort() print(1) print(len(ans)) print(*ans) for T in range(1): a = input().strip() n = len(a) answer()
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
def solve(): n, x = read_ints() aseq = read_ints() if x in aseq: return 1 amax = max(aseq) if amax > x: return 2 ans = 0--x // amax return ans def main(): t = int(input()) output = [] for _ in range(t): ans = solve() output.append(ans) print_lines(output) def read_ints(): return [int(c) for c in input().split()] def print_lines(lst): print('\n'.join(map(str, lst))) if __name__ == "__main__": from os import environ as env if 'COMPUTERNAME' in env and 'L2A6HRI' in env['COMPUTERNAME']: import sys sys.stdout = open('out.txt', 'w') sys.stdin = open('in.txt', 'r') main()
py
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3 5 7 10 19 10 18 OutputCopyYES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO NotePictures corresponding to the first and the second test cases of the example:
[ "brute force", "constructive algorithms", "trees" ]
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..) import sys def main(n, d): P = [0] + list(range(n - 1)) C = [set() for _ in range(n)] for v in range(n - 1): C[v].add(v + 1) D = list(range(n)) Vd = [set() for _ in range(n)] for v in range(n): Vd[v].add(v) L = [n - 1] # B = [0] * n s = (n - 1) * n // 2 if d > s: return None while s > d: if not L: return None v = L.pop() if D[v] < 2: continue # if B[v]: continue for p in Vd[D[v] - 2]: if len(C[p]) == 2: continue s -= 1 bp = P[v] C[bp].remove(v) if len(C[bp]) == 0: L.append(bp) P[v] = p C[p].add(v) Vd[D[v]].remove(v) D[v] -= 1 Vd[D[v]].add(v) L.append(v) break # else: # B[v] = 1 return (P[i] + 1 for i in range(1, n)) if __name__ == '__main__': input = sys.stdin.readline T = int(input()) for _ in range(T): n, d = map(int, input().split()) ans = main(n, d) if ans is None: print('NO') else: print('YES') print(*ans)
py
1304
D
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⁡n) 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−1n−1, 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≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), 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−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.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 3 << 7 >><>>< 5 >>>< OutputCopy1 2 3 1 2 3 5 4 3 7 2 1 6 4 3 1 7 5 2 6 4 3 2 1 5 5 4 2 1 3 NoteIn 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.
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
import sys input=sys.stdin.readline t=int(input()) for _ in range(t): n,s=input().rstrip().split() n=int(n) last=0 num=n ans1=[0]*n for i in range(n): if i==n-1 or s[i]==">": for j in range(last,i+1)[::-1]: ans1[j]=num num-=1 last=i+1 print(*ans1) num=1 last=0 ans2=[0]*n for i in range(n): if i==n-1 or s[i]=="<": for j in range(last,i+1)[::-1]: ans2[j]=num num+=1 last=i+1 print(*ans2)
py
1284
D
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≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). 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)≤min(y,v)max(x,u)≤min(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≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn 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.
[ "binary search", "data structures", "hashing", "sortings" ]
import sys input = lambda: sys.stdin.readline().rstrip() ke = 133333333 pp = 1000000000001003 def rand(): global ke ke = ke ** 2 % pp return ((ke >> 10) % (1<<15)) + (1<<15) N = int(input()) W = [rand() for _ in range(N)] A = [] B = [] for i in range(N): a, b, c, d = map(int, input().split()) A.append((a+1, b+2, i)) B.append((c+1, d+2, i)) def chk(L): # NN = 18 BIT = [0] * (200200) BITC = [0] * (200200) SS = [0] CC = [0] def addrange(r0, x=1): r = r0 SS[0] += x CC[0] += 1 while r <= 200200: BIT[r] -= x BITC[r] -= 1 r += r & (-r) def getvalue(r): a = 0 c = 0 while r != 0: a += BIT[r] c += BITC[r] r -= r&(-r) return (SS[0] + a, CC[0] + c) S = [] for a, b, i in L: S.append(a) S.append(b) S = sorted(list(set(S))) D = {s:i for i, s in enumerate(S)} L = [(D[a], D[b], i) for a, b, i in L] s = 0 L = sorted(L) m = -1 for a, b, i in L: v, c = getvalue(a) s += v + c * W[i] addrange(b, W[i]) return s print("YES" if chk(A) == chk(B) else "NO")
py
1304
C
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 — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — 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≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), 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≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), 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 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn 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.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
#import sys #input = sys.stdin.readline q = int(input()) for _ in range(q): ans = "YES" n,m = map(int,input().split()) mh = ml = m tx = 0 for _ in range(n): t,l,h = map(int, input().split()) if tx < t: mh += t - tx ml -= t - tx tx = t mh = min(mh, h) ml = max(ml, l) if mh < ml: ans = "NO" print(ans)
py
1294
B
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≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.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 sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 OutputCopyYES RUUURRRRUU NO YES RRRRUUU NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
[ "implementation", "sortings" ]
from sys import stdin input=lambda :stdin.readline()[:-1] def solve(): n=int(input()) xy=[] for i in range(n): x,y=map(int,input().split()) xy.append((x,y)) xy.sort() nowx,nowy=0,0 ans=[] for x,y in xy: if nowx>x or nowy>y: print('NO') return while nowx<x: ans.append('R') nowx+=1 while nowy<y: ans.append('U') nowy+=1 print('YES') print(*ans,sep='') for _ in range(int(input())): solve()
py
1300
A
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,…,ana1,a2,…,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≤i≤n1≤i≤n) 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+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — 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 3 2 -1 -1 4 -1 0 0 1 2 -1 2 3 0 -2 1 OutputCopy1 2 0 2 NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], 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 [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. 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,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.
[ "implementation", "math" ]
import math def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) nonz = 0 c = 0 for i in a: if i == 0: c+=1 nonz += 1 else: nonz += i if nonz == 0: c += 1 print(c) main()
py
1294
F
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≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — 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≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8 1 2 2 3 3 4 4 5 4 6 3 7 3 8 OutputCopy5 1 8 6 NoteThe 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.
[ "dfs and similar", "dp", "greedy", "trees" ]
from bisect import bisect_right from collections import defaultdict import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") sys.setrecursionlimit(3*10**5) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(u,p): curr=u m=0 for j in adj[u]: if(j!=p): q=yield dfs(j,u) if((size[j]+1)>m): m=size[j]+1 curr=q size[u]=m val[u]=curr yield curr @bootstrap def dfs1(u,p): global curr global c size[u]=0 q=u for j in adj[u]: if(j!=p): r=yield dfs1(j,u) if(val[j]!=b): if(size[j]+1>size[u]): size[u]=size[j]+1 q=r if(curr<=size[u]): curr=size[u] c=q yield q n=int(input()) adj=[[] for i in range(n+1)] for _ in range(n-1): u,v=map(int,input().split()) adj[u].append(v) adj[v].append(u) size=[0 for i in range(n+1)] val=[i for i in range(n+1)] a=dfs(1,0) size=[0 for i in range(n+1)] b=dfs(a,0) dm=size[a] curr=0 c=-1 dfs1(a,0) if(dm==n-1 or c==-1): for i in range(1,4): if(i!=a and i!=b): c=i break print(dm+curr) print(a,b,c)
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
from bisect import bisect_right def is_seq(s, t): return (s != t[::-1]) n = int(input()) count = 0 mx, mn = [], [] for _ in range(n): _, *item = map(int, input().split()) if item == sorted(item, reverse=1): mx.append(item[-1]) mn.append(item[0]) mn.sort() for i in mx: count += bisect_right(mn, i) print(n*n - count)
py
1323
B
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×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (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≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,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≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2 1 0 1 1 1 1 OutputCopy4 InputCopy3 5 4 1 1 1 1 1 1 1 1 OutputCopy14 NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
[ "binary search", "greedy", "implementation" ]
import sys input = sys.stdin.readline def f(x, w, nw): if x > nw: return 0 s1 = w[:x].count('1') c = 0 if s1 == x: c += 1 for i in range(nw-x): if w[i] == '1': s1 -= 1 if w[i+x] == '1': s1 += 1 if s1 == x: c += 1 return c def fs(x, y): if x == y: return f(x, a, n) * f(x, b, m) else: return f(x, a, n) * f(y, b, m) + f(x, b, m) * f(y, a, n) n, m, k = map(int, input().split()) a = input()[:-1].replace(' ','') b = input()[:-1].replace(' ','') s = {(1, k)} for i in range(2, int(k**0.5)+1): if k % i == 0: s.add((i, k//i)) ew = 0 for i, j in s: ew += fs(i, j) print(ew)
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
n = int(input()) ans = 0 mx = [0] * (10 ** 6 + 5) mn = [] koltrue = 0 for _ in range(n): l = list(map(int, input().split())) mnn = l[1] mxx = l[1] t = False for i in range(2, l[0] + 1): if l[i-1] < l[i]: t = True mnn = min(mnn, l[i]) mxx = max(mxx, l[i]) if t: koltrue += 1 mn.append('t') else: mn.append(mnn) mx[mxx] += 1 #print(koltrue) sufs = [0] * (10 ** 6 + 5) for i in range(len(sufs) - 2, -1, -1): sufs[i] = mx[i] + sufs[i+1] #print(sufs[:10]) #print(mn) for i in range(len(mn)): if mn[i] == 't': ans += n else: ans += koltrue #print('#', mn[i], i) ans += sufs[mn[i] + 1] #print(ans) print(ans) # Thu Nov 24 2022 20:38:24 GMT+0300 (Moscow Standard Time) # Sat Nov 26 2022 14:10:03 GMT+0300 (Moscow Standard Time) # Sat Nov 26 2022 14:10:19 GMT+0300 (Moscow Standard Time)
py
1305
E
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,…,ana1,a2,…,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≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter # from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var): sys.stdout.write(' '.join(map(str, var)) + '\n') def out(var): sys.stdout.write(str(var) + '\n') from decimal import Decimal # from fractions import Fraction # sys.setrecursionlimit(100000) mod = int(1e9) + 7 INF=10**8 n,m=mdata() if n==1 and m==0: out(1) exit() l=[] k=math.floor(((1+4*m)**0.5-1)/2) if k>n: out(-1) exit() l=list(range(1,2*k+3)) m-=k*(k+1) while m: l.append(l[-1]+l[max(0,l[-1]-2*m)]) m-=min(m,l[-1]//2) if len(l)>n: out(-1) exit() i=0 t=l[-1] while len(l)<n: l.append(INF+i*(t+1)) i+=1 outl(l)
py
1304
D
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⁡n) 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−1n−1, 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≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), 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−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.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 3 << 7 >><>>< 5 >>>< OutputCopy1 2 3 1 2 3 5 4 3 7 2 1 6 4 3 1 7 5 2 6 4 3 2 1 5 5 4 2 1 3 NoteIn 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.
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
from sys import stdin input = stdin.readline inp = lambda : list(map(int,input().split())) def assign1(ans , take , what): if(what == '<'): ans.extend(take) else: if(len(ans)): this = ans.pop() ans.extend(take[::-1]) ans.append(this) else: ans.extend(take[::-1]) def assign2(ans , take , what): if(what == '<'): if(len(ans)): this = ans.pop() ans.extend(take[::-1]) ans.append(this) else: ans.extend(take[::-1]) else: ans.extend(take) def answer(): take = [n] minans = [] for i in range(n - 2): take.append(n - i - 1) if(a[i] != a[i + 1]): assign2(minans , take , a[i]) take = [] take.append(1) assign2(minans , take , a[-1]) print(*minans) take =[1] maxans = [] for i in range(n - 2): take.append(i + 2) if(a[i] != a[i + 1]): assign1(maxans , take , a[i]) take = [] take.append(n) assign1(maxans , take , a[-1]) print(*maxans) for T in range(int(input())): s = input().split() n = int(s[0]) a = s[1] answer()
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
for _ in range(int(input())): n, x = map(int, input().split()) a = list(map(int, input().split())) if x in a: print(1) else: m = max(a) print(max(2, (x + m - 1) // m))
py
1321
A
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 — 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 — 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≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). 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≤bi≤10≤bi≤1). 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 −1−1.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 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn 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" — 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.
[ "greedy" ]
import sys input = sys.stdin.readline n = int(input()) r = list(map(int, input().split())) b = list(map(int, input().split())) f = 0 s = 0 for i in range(n): if r[i] == 1 and b[i] == 1: pass else: if r[i] == 1: f += 1 if b[i] == 1: s += 1 if f == 0: print(-1) else: if f > s: print(1) elif f == s: print(2) else: print(s // f + 1)
py
1316
D
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×nn×n 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  — UU, DD, LL, RR or XX  — 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−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,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 (−1−1,−1−1), 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≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) 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 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor 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 :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
from sys import stdin, stdout import __pypy__ def main(): n = int(stdin.readline()) matrix = [[]] ans = [[]] s = [] cnt = 0 for i in range(n): matrix.append([]) matrix[-1].append((-9,-9)) ans.append([]) ans[-1].append("Z") temp = list(map(int, stdin.readline().split())) for j in range(n): x,y = temp[j*2], temp[j*2+1] matrix[-1].append((x,y)) if i+1 == x and j+1 == y: s.append((x,y)) ans[-1].append("X") else: ans[-1].append("Z") while s: x,y = s.pop() cnt += 1 if 0 < x-1 <= n and ans[x-1][y] == 'Z' and matrix[x-1][y] == matrix[x][y]: s.append((x-1,y)) ans[x-1][y] = 'D' if 0 < x+1 <= n and ans[x+1][y] == 'Z' and matrix[x+1][y] == matrix[x][y]: s.append((x+1,y)) ans[x+1][y] = 'U' if 0 < y-1 <= n and ans[x][y-1] == 'Z' and matrix[x][y-1] == matrix[x][y]: s.append((x,y-1)) ans[x][y-1] = 'R' if 0 < y+1 <= n and ans[x][y+1] == 'Z' and matrix[x][y+1] == matrix[x][y]: s.append((x,y+1)) ans[x][y+1] = 'L' for i in range(1,n+1): for j in range(1,n+1): if matrix[i][j] == (-1,-1) and ans[i][j] =='Z': x,y = i,j if 0 < x-1 <= n and matrix[x-1][y] == (-1, -1): cnt+=1 ans[x][y] = 'U' elif 0 < x+1 <= n and matrix[x+1][y] == (-1, -1): cnt+=1 ans[x][y] = 'D' elif 0 < y-1 <= n and matrix[x][y-1] == (-1, -1): cnt+=1 ans[x][y] = 'L' elif 0 < y+1 <= n and matrix[x][y+1] == (-1, -1): cnt+=1 ans[x][y] = 'R' else: stdout.write("INVALID") return if n*n != cnt: stdout.write("INVALID") return stdout.write("VALID\n") res = __pypy__.builders.StringBuilder() for i in range(1,n+1): for j in range(1,n+1): res.append("%s"%(ans[i][j])) res.append("\n") stdout.write(res.build()) main()
py
1322
C
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≤t≤5000001≤t≤500000) — 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 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). 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≤ui,vi≤n1≤ui,vi≤n), 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 — the required greatest common divisor.ExampleInputCopy3 2 4 1 1 1 1 1 2 2 1 2 2 3 4 1 1 1 1 1 1 2 2 2 2 3 4 7 36 31 96 29 1 2 1 3 1 4 2 2 2 4 3 1 4 3 OutputCopy2 1 12 NoteThe 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.
[ "graphs", "hashing", "math", "number theory" ]
import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import Counter from math import gcd t=int(input()) for tests in range(t): n,m=map(int,input().split()) C=list(map(int,input().split())) X=[[] for i in range(n+1)] for k in range(m): x,y=map(int,input().split()) X[y].append(x) #print(X) A=Counter() for i in range(n): A[hash(tuple(sorted(X[i+1])))]+=C[i] #print(A) ANS=0 for g in A: if g==hash(tuple()): continue ANS=gcd(ANS,A[g]) print(ANS) _=input()
py
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
def main(): brackets = input() length = len (brackets) left = 0 right = length - 1 ans = [] while (left < right): while (left < right and brackets[left] == ')'): left += 1 while (left < right and brackets[right] == '('): right -= 1 if (left < right): ans.append(left + 1) ans.append(right + 1) left += 1 right -= 1 ans.sort() if (len(ans) > 0): print(1) print(len(ans)) print(*ans) else: print(0) main()
py
1286
B
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 — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase class SortedList: def __init__(self,iterable=None,_load=200): """Initialize sorted list instance.""" if iterable is None: iterable = [] values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i+_load] for i in range(0,_len,_load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i|i+1<len(_fen_tree): _fen_tree[i|i+1] += _fen_tree[i] self._rebuild = False def _fen_update(self,index,value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index<len(_fen_tree): _fen_tree[index] += value index |= index+1 def _fen_query(self,end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end-1] end &= end-1 return x def _fen_findkth(self,k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k<_list_lens[0]: return 0,k if k>=self._len-_list_lens[-1]: return len(_list_lens)-1,k+_list_lens[-1]-self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx+(1<<d) if right_idx<len(_fen_tree) and k>=_fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx+1,k def _delete(self,pos,idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos,-1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self,value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0,0 _lists = self._lists _mins = self._mins lo,pos = -1,len(_lists)-1 while lo+1<pos: mi = (lo+pos)>>1 if value<=_mins[mi]: pos = mi else: lo = mi if pos and value<=_lists[pos-1][-1]: pos -= 1 _list = _lists[pos] lo,idx = -1,len(_list) while lo+1<idx: mi = (lo+idx)>>1 if value<=_list[mi]: idx = mi else: lo = mi return pos,idx def _loc_right(self,value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0,0 _lists = self._lists _mins = self._mins pos,hi = 0,len(_lists) while pos+1<hi: mi = (pos+hi)>>1 if value<_mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo,idx = -1,len(_list) while lo+1<idx: mi = (lo+idx)>>1 if value<_list[mi]: idx = mi else: lo = mi return pos,idx def add(self,value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos,idx = self._loc_right(value) self._fen_update(pos,1) _list = _lists[pos] _list.insert(idx,value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load+_load<len(_list): _lists.insert(pos+1,_list[_load:]) _list_lens.insert(pos+1,len(_list)-_load) _mins.insert(pos+1,_list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self,value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos,idx = self._loc_right(value) if idx and _lists[pos][idx-1]==value: self._delete(pos,idx-1) def remove(self,value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len==self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self,index=-1): """Remove and return value at `index` in sorted list.""" pos,idx = self._fen_findkth(self._len+index if index<0 else index) value = self._lists[pos][idx] self._delete(pos,idx) return value def bisect_left(self,value): """Return the first index to insert `value` in the sorted list.""" pos,idx = self._loc_left(value) return self._fen_query(pos)+idx def bisect_right(self,value): """Return the last index to insert `value` in the sorted list.""" pos,idx = self._loc_right(value) return self._fen_query(pos)+idx def count(self,value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value)-self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self,index): """Lookup value at `index` in sorted list.""" pos,idx = self._fen_findkth(self._len+index if index<0 else index) return self._lists[pos][idx] def __delitem__(self,index): """Remove value at `index` from sorted list.""" pos,idx = self._fen_findkth(self._len+index if index<0 else index) self._delete(pos,idx) def __contains__(self,value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos,idx = self._loc_left(value) return idx<len(_lists[pos]) and _lists[pos][idx]==value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) def dfs(root,path,ans,n): st = [root] nums = SortedList(range(1,n+1)) val = [-1]*n if ans[st[-1]] >= len(nums): print('NO') return val[st[-1]-1] = nums[ans[st[-1]]] nums.discard(nums[ans[st[-1]]]) while len(st): if not len(path[st[-1]]): if len(nums) and nums[0] <= val[st[-1]-1]: print('NO') return st.pop() continue st.append(path[st[-1]].pop()) if ans[st[-1]] >= len(nums): print('NO') return val[st[-1]-1] = nums[ans[st[-1]]] nums.discard(nums[ans[st[-1]]]) print('YES') print(*val) def main(): n = int(input()) path = [[] for _ in range(n+1)] ans = [0]*(n+1) for i in range(1,n+1): p,c = map(int,input().split()) if p: path[p].append(i) else: root = i ans[i] = c dfs(root,path,ans,n) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main()
py
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,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,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
n = int(input()) diff = list(map(int,input().split())) nums = [1] for i in diff: nums.append(nums[-1]+i) mini = min(nums) extra = 0 if mini<=0: extra = (-1)*mini + 1 for i in range(len(nums)): nums[i]+=extra result = [i for i in range(1,n+1)] if sorted(nums)==result: print(*nums) else: print(-1)
py
1316
B
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≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] 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≠ba≠b; 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≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — 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′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) 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 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn 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.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
#I = lambda: [int(i) for i in input().split()] #import io, os, sys #input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # n = int(input()) # l1 = list(map(int,input().split())) # n,x = map(int,input().split()) # s = input() #mod = 1000000007 # print("Case #"+str(_+1)+":",) from collections import Counter,defaultdict import sys import math #import bisect for _ in range(int(input())): n = int(input()) l = list(input()) x = min(l) a = [] for i in range(1,n): if l[i]==x: a.append(i) ans = l ans1 = 1 for i in a: k = i+1 if (n-k+1)&1: t = l[:i] t.reverse() temp = l[i:]+t else: temp = l[i:]+l[:i] if temp<ans: ans = temp ans1 = k print(''.join(i for i in ans)) print(ans1)
py
1290
B
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≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,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≤l≤r≤|s|1≤l≤r≤|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≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|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 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn 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.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
s = input() h = [] for i in range(len(s)): h.append([-1] * 26) i = len(s) - 2 h[-1][ord(s[-1]) - 97] = len(s) - 1 while i >= 0: for j in range(26): h[i][j] = h[i+1][j] h[i][ord(s[i]) - 97] = i i -= 1 # print(h) q = int(input()) for i in range(q): x, y = map(int, input().split()) x -= 1 y -= 1 if y - x == 0: print("Yes") elif s[x] != s[y]: print("Yes") else: c = 0 for j in range(26): if -1 < h[x][j] <= y: c += 1 if c > 2: print("Yes") else: print("No")
py
1301
A
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≤i≤n1≤i≤n) 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↔aici↔ai or ci↔bici↔bi (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≤t≤1001≤t≤100)  — 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 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim OutputCopyNO YES YES NO NoteIn 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.
[ "implementation", "strings" ]
t=int(input()) r=[] for i in range(t): a=input() b=input() c=input() k=0 for j in range(len(a)): if a[j]==b[j]: if c[j]!=a[j]: k=1 break else: if c[j]!=a[j] and c[j]!=b[j]: k=1 break if k==0: r.append("YES") else: r.append("NO") for i in range(len(r)): print(r[i])
py
1313
C1
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≤1000n≤1000The 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≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "brute force", "data structures", "dp", "greedy" ]
from cmath import inf from sys import stdin, stdout n = int(stdin.readline().strip()) arr = list(map(int, stdin.readline().split())) mono_stack = [] non_dec_sum = [0] * n prefix_sum = 0 for i, num in enumerate(reversed(arr)): count = 1 while mono_stack and num <= mono_stack[-1][0]: val, cc = mono_stack.pop() prefix_sum -= val * cc count += cc prefix_sum += (num * count) mono_stack.append((num, count)) non_dec_sum[~i] = prefix_sum mono_stack.clear() prefix_sum = 0 best_peak = -1 best_sum = -inf for i, num in enumerate(arr): count = 1 while mono_stack and num <= mono_stack[-1][0]: val, cc = mono_stack.pop() prefix_sum -= val * cc count += cc prefix_sum += (num * count) mono_stack.append((num, count)) if prefix_sum + non_dec_sum[i] - num > best_sum: best_peak = i best_sum = prefix_sum + non_dec_sum[i] - num # print(best_peak) ans = [0] * n ans[best_peak] = arr[best_peak] prev = arr[best_peak] for i in range(best_peak + 1, n): ans[i] = min(arr[i], prev) prev = ans[i] prev = arr[best_peak] for i in range(best_peak - 1, -1, -1): ans[i] = min(arr[i], prev) prev = ans[i] print(*ans)
py
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 OutputCopy2 1 5
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
from sys import stdin input = stdin.buffer.readline t = int(input()) while t: t -= 1 n = int(input()) seg = [] for i in range(n): l, r = map(int, input().split()) seg.append((l, 0, i)) seg.append((r, 1, i)) seg.sort() ans = 0 seq = [] active = set() increase = [0] * -~n for pos, p, i in seg: if p == 0: if len(seq) > 1 and seq[-2:] == [2, 1]: increase[next(iter(active))] += 1 active.add(i) else: active.remove(i) if len(active) == 0: ans += 1 seq.append(len(active)) if max(seq) == 1: print(ans - 1) else: print(ans + max(increase))
py
1324
A
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×12×1 (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×12×1 (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−1ai−1. 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≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4 3 1 1 3 4 1 1 2 1 2 11 11 1 100 OutputCopyYES NO YES YES NoteThe 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.
[ "implementation", "number theory" ]
import os os.system("cls") # clear screen # Debug mode (color output green) if os.getcwd().endswith("codeforces_py"): from colorama import Fore, Style import builtins def print(*args, **kwargs): builtins.print(Fore.GREEN, end="") builtins.print(*args, **kwargs) builtins.print(Style.RESET_ALL, end="") t = int(input()) for T in range(t): n = int(input()) arr = list(map(int, input().split())) parity = arr[0] % 2 answer = "YES" for x in arr: if x % 2 != parity: answer = "NO" break print(answer)
py
1324
F
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−1n−1 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−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,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 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 OutputCopy2 2 2 2 2 1 1 0 2 InputCopy4 0 0 1 0 1 2 1 3 1 4 OutputCopy0 -1 1 -1 NoteThe 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.
[ "dfs and similar", "dp", "graphs", "trees" ]
def I(): return input().strip() def II(): return int(input().strip()) def LI(): return [*map(int, input().strip().split())] import sys, os, copy, string, math, time, functools, fractions input = sys.stdin.readline from io import BytesIO, IOBase from heapq import heappush, heappop, heapify from bisect import bisect_left, bisect_right from collections import deque, defaultdict, Counter, OrderedDict from itertools import permutations, chain, combinations, groupby from operator import itemgetter from types import GeneratorType # for recursion from typing import Iterable, TypeVar, Union # for sorted set # template starts BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc # template ends def main(): n = II() a = LI() graph = defaultdict(list) for i in range(n - 1): u, v = LI() u, v = u - 1, v - 1 graph[u].append(v) graph[v].append(u) dp = [0] * n vis = [False] * n @bootstrap def dfs(src): vis[src] = True curr = 0 for vrt in graph[src]: if not vis[vrt]: temp = yield dfs(vrt) curr += max(temp, 0) curr += (1 if a[src] else -1) dp[src] = curr yield curr dfs(0) ans = [0] * n vis = [False] * n ans[0] = dp[0] vis[0] = True @bootstrap def dfs(src): for vrt in graph[src]: if not vis[vrt]: vis[vrt] = True ans[vrt] = dp[vrt] + max(0, ans[src] - max(dp[vrt], 0)) yield dfs(vrt) yield True dfs(0) print(*ans) for _ in range(1): main()
py
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,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≤t≤10001≤t≤1000)  — 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≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — 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,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — 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 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn 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.
[ "brute force", "data structures", "implementation" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline t = int(input()) ans = [] inf = pow(10, 9) + 1 for _ in range(t): n, m, k = map(int, input().split()) a = list(map(int, input().split())) k = min(k, m - 1) l = m - k c = n - m ans0 = 0 for i in range(k + 1): mi = inf for j in range(i, i + l): mi = min(mi, max(a[j], a[j + c])) ans0 = max(ans0, mi) ans.append(ans0) sys.stdout.write("\n".join(map(str, ans)))
py
1304
A
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<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
n=int(input()) L=list() for i in range(n): x,y,a,b=[int(x) for x in input().split()] L.append((x,y,a,b)) for (x,y,a,b) in L: if (y-x)%(a+b)==0: print((y-x)//(a+b)) else: print(-1)
py
1293
A
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≤t≤10001≤t≤1000) — 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≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — 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,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — 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 — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn 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.
[ "binary search", "brute force", "implementation" ]
import sys input = lambda: sys.stdin.buffer.readline().decode().strip() from math import inf, gcd, lcm, log, log2, floor, ceil, sqrt from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify from functools import lru_cache from itertools import permutations, accumulate, groupby from bisect import insort, bisect_left, bisect_right import random import threading #template taken from https://codeforces.com/contest/1703/submission/164030692 - Author mkawa2 class DefaultDict: def __init__(self, default=None): self.default = default self.x = random.randrange(1, 1 << 31) self.dd = defaultdict(default) def __repr__(self): return "{"+", ".join(f"{k ^ self.x}: {v}" for k, v in self.dd.items())+"}" def __eq__(self, other): for k in set(self) | set(other): if self[k] != other[k]: return False return True def __or__(self, other): res = DefaultDict(self.default) for k, v in self.dd: res[k] = v for k, v in other.dd: res[k] = v return res def __len__(self): return len(self.dd) def __getitem__(self, item): return self.dd[item ^ self.x] def __setitem__(self, key, value): self.dd[key ^ self.x] = value def __delitem__(self, key): del self.dd[key ^ self.x] def __contains__(self, item): return item ^ self.x in self.dd def items(self): for k, v in self.dd.items(): yield (k ^ self.x, v) def keys(self): for k in self.dd: yield k ^ self.x def values(self): for v in self.dd.values(): yield v def __iter__(self): for k in self.dd: yield k ^ self.x class CounterInt(DefaultDict): def __init__(self, aa=[]): super().__init__(int) for a in aa: self.dd[a ^ self.x] += 1 def __add__(self, other): res = CounterInt() for k in set(self) | set(other): v = self[k]+other[k] if v > 0: res[k] = v return res def __sub__(self, other): res = CounterInt() for k in set(self) | set(other): v = self[k]-other[k] if v > 0: res[k] = v return res def __and__(self, other): res = CounterInt() for k in self: v = min(self[k], other[k]) if v > 0: res[k] = v return res def __or__(self, other): res = CounterInt() for k in set(self) | set(other): v = max(self[k], other[k]) if v > 0: res[k] = v return res class Set: def __init__(self, aa=[]): self.x = random.randrange(1, 1 << 31) self.st = set() for a in aa: self.st.add(a ^ self.x) def __repr__(self): return "{"+", ".join(str(k ^ self.x) for k in self.st)+"}" def __len__(self): return len(self.st) def add(self, item): self.st.add(item ^ self.x) def discard(self, item): self.st.discard(item ^ self.x) def __contains__(self, item): return item ^ self.x in self.st def __iter__(self): for k in self.st: yield k ^ self.x def pop(self): return self.st.pop() ^ self.x def __or__(self, other): res = Set(self) for a in other: res.add(a) return res def __and__(self, other): res = Set() for a in self: if a in other: res.add(a) for a in other: if a in self: res.add(a) return res class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) #https://leetcode.com/problems/create-sorted-array-through-instructions/discuss/1245397/C%2B%2BJavaPython-Binary-Indexed-Tree-Feel-free-to-reuse class BIT: def __init__(self, size): self.bit = [0] * (size + 1) def getSum(self, idx): # Get sum in range [0..idx], 1-based indexing s = 0 while idx > 0: s += self.bit[idx] idx -= idx & (-idx) return s def getSumRange(self, left, right): # left, right inclusive, 1-based indexing return self.getSum(right) - self.getSum(left - 1) def addValue(self, idx, val): # 1-based indexing while idx < len(self.bit): self.bit[idx] += val idx += idx & (-idx) class TrieNode: def __init__(self): self.children = defaultdict(TrieNode) self.word = None def addWord(self, word): cur = self for c in word: cur = cur.children[c] cur.word = "*" # UnionFind class class UnionFind: def __init__(self, size): self.root = [i for i in range(size)] # Use a rank array to record the height of each vertex, i.e., the "rank" of each vertex. # The initial "rank" of each vertex is 1, because each of them is # a standalone vertex with no connection to other vertices. self.rank = [1] * size self.connected = size # The find function here is the same as that in the disjoint set with path compression. def find(self, x): if x == self.root[x]: return x self.root[x] = self.find(self.root[x]) return self.root[x] # The union function with union by rank def union(self, x, y): rootX = self.find(x) rootY = self.find(y) if rootX != rootY: if self.rank[rootX] > self.rank[rootY]: self.root[rootY] = rootX elif self.rank[rootX] < self.rank[rootY]: self.root[rootX] = rootY else: self.root[rootY] = rootX self.rank[rootX] += 1 self.connected -= 1 def connected(self, x, y): return self.find(x) == self.find(y) def largestPrime(n): primes = set() if n == 1: return {1} while n % 2 == 0: primes.add(2) n //= 2 for i in range(3, int(sqrt(n)) + 1, 2): while n % i == 0: primes.add(i) n //= i if n > 2: primes.add(n) return primes def sumtoN(n): return ((n)*(n+1)) // 2 def powerOf2(n): return n > 0 and n & (n-1) == 0 # d4 = [(0, 1), (-1, 0), (0, -1), (1, 0)] # d8 = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)] #mod = 1000000007 def read_int(): return(int(input())) def read_ints(): return(map(int,input().split())) def read_list(): return(list(map(int,input().split()))) def read_matrix(m,n): ans = [] for _ in range(m): ans.append(read_list()) return ans def solve(n,mx,cur,arr): s = Set(arr) ans = float("inf") up = cur down = cur while up in s: up += 1 while down in s: down -= 1 if down != 0: ans = min(ans, cur-down) if up != mx+1: ans = min(ans, up-cur) return ans t = read_int() for _ in range(t): mx, cur, n = read_ints() #arr = input() arr = read_list() print(solve(n, mx, cur, arr)) #if solve(n,arr): # print("YES") #else: # print("NO") #threading.stack_size(10 ** 8) #t = threading.Thread(target=main) #t.start() #t.join()
py
1324
B
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−i−1ai=an−i−1 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≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), 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 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn 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.
[ "brute force", "strings" ]
t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) flag = 'NO' k = 0 while k < n: if a.count(a[k]) == 1: k += 1 elif a.count(a[k]) == 2: if a[k] == a[k+1]: k += 2 else: flag = 'YES' break else: flag = 'YES' break print(flag)
py
1290
B
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≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,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≤l≤r≤|s|1≤l≤r≤|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≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|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 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn 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.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
# import sys,os,io # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline PI = 3.141592653589793238460 INF = float('inf') MOD = 1000000007 # MOD = 998244353 def bin32(num): return '{0:032b}'.format(num) def add(x,y): return (x+y)%MOD def sub(x,y): return (x-y+MOD)%MOD def mul(x,y): return (x*y)%MOD def gcd(x,y): if y == 0: return x return gcd(y,x%y) def lcm(x,y): return (x*y)//gcd(x,y) def power(x,y): res = 1 x%=MOD while y!=0: if y&1 : res = mul(res,x) y>>=1 x = mul(x,x) return res def mod_inv(n): return power(n,MOD-2) def prob(p,q): return mul(p,power(q,MOD-2)) def ii(): return int(input()) def li(): return [int(i) for i in input().split()] def ls(): return [i for i in input().split()] s = input() n = len(s) f = [] tmp = [0 for i in range(26)] tmp[ord(s[0]) - 97] +=1 f.append(tmp) for i in range(1 , n): tmp = f[-1][:] tmp[ord(s[i]) - 97] +=1 f.append(tmp) q = ii() for _ in range(q): l,r = li() l-=1 r-=1 if r == l: print("Yes") continue if s[l]!= s[r]: print("Yes") continue cnt = 0 for i in range(26): if l!= 0: x = f[r][i] - f[l-1][i] if x > 0: cnt+=1 else: x = f[r][i] if x > 0: cnt+=1 if cnt > 2: print("Yes") continue print("No")
py
1300
A
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,…,ana1,a2,…,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≤i≤n1≤i≤n) 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+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — 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 3 2 -1 -1 4 -1 0 0 1 2 -1 2 3 0 -2 1 OutputCopy1 2 0 2 NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], 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 [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. 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,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.
[ "implementation", "math" ]
a = int(input()) for i in range(a): q = int(input()) *s, = map(int, input().split(' ')) d = 0 for j in range(q): if s[j] == 0: d += 1 s[j] = 1 if sum(s) == 0: d += 1 print(d)
py
1307
A
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≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, 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≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — 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 4 5 1 0 3 2 2 2 100 1 1 8 0 OutputCopy3 101 0 NoteIn 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.
[ "greedy", "implementation" ]
t=int(input()) for i in range(t): n,d=[int(j) for j in input().split()] a=[int(j) for j in input().split()] i=1 while d>0 and i<n: if a[i]>0: a[0]+=1 a[i]-=1 d-=i else : i+=1 if d>=0: print(a[0]) else : print(a[0]-1)
py
1313
B
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 — 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≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — 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 — 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 — third place.
[ "constructive algorithms", "greedy", "implementation", "math" ]
t=int(input()) for k in range(t): n,x,yellow=map(int,input().split()) print(max(1,min(n,x+yellow-n+1)),min(x+yellow-1,n))
py
1305
A
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≤t≤1001≤t≤100)  — 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≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,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 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn 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.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
a=int(input()) for i in range(a): n=int(input()) a1=list(map(int, input().split())) a2=list(map(int, input().split())) a1.sort() a2.sort() print(*a1) print(*a2)
py
1307
C
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≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn 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.
[ "brute force", "dp", "math", "strings" ]
import sys input = sys.stdin.readline from itertools import combinations s = input()[:-1] d = [] x = 0 for i in range(97, 123): d.append(chr(i)) for a, b in combinations(d, 2): c0, c1 = 0, 0 x0, x1 = 0, 0 for i in s: if i == a: c0 += 1 x0 += c1 elif i == b: c1 += 1 x1 += c0 x = max(x, c0*(c0-1)//2, c1*(c1-1)//2, x0, x1, c0, c1) print(x)
py
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
t=int(input()) for i in range(t): n=int(input()) l=list(map(int,input().split())) l.sort() print(l[n]-l[n-1])
py
1325
F
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 ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. 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≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) 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 ⌈n−−√⌉⌈n⌉ 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 1 3 3 4 4 2 2 6 5 6 5 1 OutputCopy1 1 6 4InputCopy6 8 1 3 3 4 4 2 2 6 5 6 5 1 1 4 2 5 OutputCopy2 4 1 5 2 4InputCopy5 4 1 2 1 3 2 4 2 5 OutputCopy1 3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
from collections import deque from sys import stdin import sys from math import ceil sys.setrecursionlimit(3*10**5) n,m = map(int,stdin.readline().split()) rn = ceil(n**0.5) lis = [ [] for i in range(n) ] for i in range(m): u,v = map(int,stdin.readline().split()) u -= 1 v -= 1 lis[u].append(v) lis[v].append(u) stk = [0] slis = [0] * n d = [float("inf")] * n p = [i for i in range(n)] d[0] = 0 while stk: v = stk[-1] if slis[v] < len(lis[v]): nex = lis[v][slis[v]] slis[v] += 1 if d[nex] == float("inf"): d[nex] = d[v] + 1 p[nex] = v stk.append(nex) elif d[v] - d[nex] + 1 >= rn: back = [v+1] now = v while now != nex: now = p[now] back.append(now+1) #print (back) print (2) print (len(back)) print (*back) sys.exit() else: del stk[-1] dlis = [ [] for i in range(rn-1) ] for i in range(n): dlis[d[i] % (rn-1)].append(i+1) maxind = 0 for i in range(rn-1): if len(dlis[i]) > len(dlis[maxind]): maxind = i print (1) print (*dlis[maxind][:rn])
py
1324
B
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−i−1ai=an−i−1 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≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), 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 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn 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.
[ "brute force", "strings" ]
for i in range(int(input())): n = int(input()) s = list(map(int, input().split())) ok = False for i in range(n): for j in range(i + 2, n): if s[i] == s[j]: ok = True print('YES' if ok else 'NO')
py
1288
B
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≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+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≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1 0 1337 NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
[ "math" ]
for _ in range(int(input())) : a,b = map(int,input().split()) i = 0 x = 9 while x <= b : x*=10; x += 9; i += 1 print(a*i)
py
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,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,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
n = int(input()) a = list(map(int, input().split())) d = 0 m = 0 was = {0} for i in a: d += i was.add(d) m = min(d, m) q = -m+1 if was == {i for i in range(m, n-q+1)}: for i in a: print(q, end=' ') q += i print(q) else: print(-1)
py
1141
A
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≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840 OutputCopy7 InputCopy42 42 OutputCopy0 InputCopy48 72 OutputCopy-1 NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. 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.
[ "implementation", "math" ]
n, m = map(int, input().split()) is_a = True if n == m: print(0) elif n * 2 == m or n * 3 == m: print(1) elif (n * 2 > m and n * 3 > m) or (m % 2 != 0 and m % 3 != 0): print(-1) else: cnt = 0 delenie = m // n while delenie != 1: if delenie % 2 != 0 and delenie % 3 != 0: is_a = False break if delenie % 3 == 0: delenie //= 3 cnt += 1 else: delenie //= 2 cnt += 1 if is_a and m % n == 0: print(cnt) else: print(-1)
py
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3 3 1 2 7 1 4 OutputCopy4 InputCopy4 2 4 1 3 5 9 8 3 OutputCopy3 InputCopy6 3 5 1 6 2 4 9 1 9 9 1 9 OutputCopy2
[ "data structures", "divide and conquer" ]
def main(): import sys input = sys.stdin.buffer.readline N = int(input()) P = list(map(int, input().split())) A = list(map(float, input().split())) class LazySegTree: # Range add query def __init__(self, A, initialize=True, segfunc=min, ident=2000000000): self.N = len(A) self.LV = (self.N - 1).bit_length() self.N0 = 1 << self.LV self.segfunc = segfunc self.ident = ident if initialize: self.data = [self.ident] * self.N0 + A + [self.ident] * (self.N0 - self.N) for i in range(self.N0 - 1, 0, -1): self.data[i] = segfunc(self.data[i * 2], self.data[i * 2 + 1]) else: self.data = [self.ident] * (self.N0 * 2) self.lazy = [0] * (self.N0 * 2) def _ascend(self, i): for _ in range(i.bit_length() - 1): i >>= 1 self.data[i] = self.segfunc(self.data[i * 2], self.data[i * 2 + 1]) + self.lazy[i] def _descend(self, idx): lv = idx.bit_length() for j in range(lv - 1, 0, -1): i = idx >> j x = self.lazy[i] if not x: continue self.lazy[i] = 0 self.lazy[i * 2] += x self.lazy[i * 2 + 1] += x self.data[i * 2] += x self.data[i * 2 + 1] += x # open interval [l, r) def add(self, l, r, x): l += self.N0 - 1 r += self.N0 - 1 l_ori = l r_ori = r while l < r: if l & 1: self.data[l] += x self.lazy[l] += x l += 1 if r & 1: r -= 1 self.data[r] += x self.lazy[r] += x l >>= 1 r >>= 1 self._ascend(l_ori // (l_ori & -l_ori)) self._ascend(r_ori // (r_ori & -r_ori) - 1) # open interval [l, r) def query(self, l, r): l += self.N0 - 1 r += self.N0 - 1 self._descend(l // (l & -l)) self._descend(r // (r & -r) - 1) ret = self.ident while l < r: if l & 1: ret = self.segfunc(ret, self.data[l]) l += 1 if r & 1: ret = self.segfunc(self.data[r - 1], ret) r -= 1 l >>= 1 r >>= 1 return ret p2i = {} for i, p in enumerate(P): p2i[p] = i S = 0 init = [0.] * N for i in range(1, N): S += A[i-1] init[i-1] = S segtree = LazySegTree(init, ident=float('inf')) ans = A[0] cnt = 0 for p in range(1, N+1): i = p2i[p] a = A[i] cnt += a segtree.add(i+1, N, -a * 2) ans = min(ans, segtree.query(1, N) + cnt) print(int(ans)) if __name__ == '__main__': main()
py
1288
B
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≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+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≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1 0 1337 NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
[ "math" ]
t = int(input()) for i in range(t): a,b = [i for i in input().split()] toadd = 0 cmpr = '9'*len(b) if int(b) == int(cmpr): toadd = 1 print(int(a)*(len(b)-1+toadd)) # count = 0 # for i in range(1,10001): # for j in range(1,1000): # if i+j+i*j == int(str(i)+str(j)): # s = str(j) # if s.count('9') != len(s): # print(i,j) # count+=1 # print(count,)
py
1322
B
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 — 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)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y 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≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2 1 2 OutputCopy3InputCopy3 1 2 3 OutputCopy2NoteIn 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⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, 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⊕00112=0110201012⊕00112=01102.
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
import sys input = sys.stdin.buffer.readline def radix(a): digits = len(str(max(a))) for i in range (digits): b = [[] for _ in range (10)] e = pow(10, i) for j in a: num = (j//e)%10 b[num].append(j) a *= 0 for l in b: a += l N = int(input()) a = list(map(int, input().split())) res = 0 radix(a) for k in range(max(a).bit_length(), -1, -1): z = 1 << k c = 0 j = jj = jjj = N - 1 for i in range(N): while j >= 0 and a[i] + a[j] >= z: j -= 1 while jj >= 0 and a[i] + a[jj] >= z << 1: jj -= 1 while jjj >= 0 and a[i] + a[jjj] >= z * 3: jjj -= 1 c += N - 1 - max(i, j) + max(i, jj) - max(i, jjj) res += z * (c & 1) for i in range(N): a[i] = min(a[i] ^ z, a[i]) a.sort() #print(res, a, c) print(res)
py
1285
B
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≤l≤r≤n)(1≤l≤r≤n) 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,…,rl,l+1,…,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,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,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≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), 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 4 1 2 3 4 3 7 4 -1 3 5 -5 5 OutputCopyYES NO NO NoteIn 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.
[ "dp", "greedy", "implementation" ]
from itertools import accumulate def smart(a): if a[0] <= 0 or a[-1] <= 0: return False acc = list(accumulate(a)) if 0 in acc: return False y = sum(a) minsofar = 0 for i, cursum in enumerate(acc): if cursum - minsofar >= y and (minsofar != 0 or i != len(a) - 1): return False minsofar = min(minsofar, cursum) return True for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) print("YES" if smart(a) else "NO")
py
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
#Lockout 1 Round #4 #Problem C import sys input = lambda: sys.stdin.readline()[:-1] get_int = lambda: int(input()) get_int_iter = lambda: map(int, input().split()) get_int_list = lambda: list(get_int_iter()) flush = lambda: sys.stdout.flush() #DEBUG DEBUG = False def debug(*args): if DEBUG: print(*args) def solve_case(n,x,nums): val = max(nums) if x < val: if x in nums: return 1 return 2 if x % val == 0: return x // val return x // val + 1 for _ in range(get_int()): n,x = get_int_iter() nums = get_int_list() print(solve_case(n,x,nums))
py
1304
C
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 — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — 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≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), 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≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), 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 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn 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.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
for _ in range(int(input())): n,m=map(int,input().split()) lo,hi=m,m t0=0 ans="YES" for __ in range(n): t,l,h=map(int,input().split()) lo-=t-t0;hi+=t-t0 t0=t lo,hi=max(lo,l),min(hi,h) if lo>hi:ans="NO" print(ans)
py
1141
F1
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],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(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≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>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≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "greedy" ]
# Legends Always Come Up with Solution # Author: Manvir Singh import os import sys from io import BytesIO, IOBase from collections import defaultdict def main(): n=int(input()) a=list(map(int,input().split())) b=defaultdict(list) for i in range(n): su=0 for j in range(i,n): su+=a[j] b[su].append([i,j]) for i in b: b[i].sort() ma,ans=0,set() for i in b: z,c=b[i],set() for j in range(len(z)-1): if z[j+1][0]<=z[j][1]: if z[j][1]<=z[j+1][1]: z[j+1]=z[j] z[j]=[] for j in range(len(z)): if z[j]: c.add(tuple(z[j])) if ma<len(c): ma=len(c) ans=c print(ma) for i in ans: print(i[0]+1,i[1]+1) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main()
py
1295
A
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≤t≤1001≤t≤100) — 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≤n≤1052≤n≤105) — 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 3 4 OutputCopy7 11
[ "greedy" ]
for i in range(int(input())): n=int(input()) f=n%2 k=n//2 print("7"*f + "1"*(k-f))
py
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,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≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).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 −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
import sys from math import sqrt, gcd, factorial, ceil, floor, pi, inf from collections import deque, Counter, OrderedDict from heapq import heapify, heappush, heappop #sys.setrecursionlimit(10**6) #======================================================# input = lambda: sys.stdin.readline() I = lambda: int(input().strip()) S = lambda: input().strip() M = lambda: map(int,input().strip().split()) L = lambda: list(map(int,input().strip().split())) #======================================================# #======================================================# def primelist(): L = [False for i in range(10**9)] primes = [False for i in range(10**9)] for i in range(2,10**9): if not L[i]: primes[i]=True for j in range(i,10**9,i): L[j]=True return primes def isPrime(n): p = primelist() return p[n] #======================================================# def bst(arr,x): low,high = 0,len(arr)-1 ans = -1 while low<=high: mid = (low+high)//2 if arr[mid]==x: return mid elif arr[mid]<x: ans = mid low = mid+1 else: high = mid-1 return ans #======================================================# for _ in range(I()): n = I() b = L() d = {i+1:False for i in range(2*n)} a = [0 for i in range(2*n)] f = True for i in range(n): a[2*i]=b[i] if b[i]>2*n: f = False break d[b[i]]=True if not f: print(-1) continue f = True for i in range(1,2*n,2): j=a[i-1]+1 if j==(2*n+1): f = False break while d[j]: j+=1 if j==(2*n+1): f = False break if not f: break a[i]=j d[j]=True if f: print(*a) else: print(-1)
py
1303
C
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 — 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≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) 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 — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
import sys import threading from math import inf from bisect import * from collections import defaultdict, deque def li(): return list(map(int, input().split())) def nn(): return int(input().split()) def w(): return input() def solve(): word = input() if len(word) == 1: print("YES") print("".join([chr(x) for x in range(ord('a'), ord('z') + 1)])) return graph = defaultdict(set) for i in range(len(word)-1): cur = word[i] next = word[i+1] graph[cur].add(next) graph[next].add(cur) if len(graph[cur])>2: return print("NO") leaf = [char for char in graph if len(graph[char])<=1] if len(leaf)<2: return print("NO") ans = [] queue = deque([leaf[0]]) while queue: top = queue.popleft() ans.append(top) for nbr in graph[top]: graph[nbr].remove(top) queue.append(nbr) for char in ([chr(i) for i in range(ord('a'), ord('z')+1)]): if char not in ans: ans.append(char) print("YES") print(''.join(ans)) return def main(): t = int(input()) for i in range(t): solve() main() # sys.setrecursionlimit(1<<30) # threading.stack_size(1<<27) # main_thread=threading.Thread(target=main) # main_thread.start() # main_thread.join()
py
1290
C
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,…,AkA1,…,Ak of {1,2,…,n}{1,2,…,n}, such that the intersection of any three subsets is empty. In other words, for all 1≤i1<i2<i3≤k1≤i1<i2<i3≤k, Ai1∩Ai2∩Ai3=∅Ai1∩Ai2∩Ai3=∅.In one operation, you can choose one of these kk subsets and switch the state of all lamps in it. It is guaranteed that, with the given subsets, it's possible to make all lamps be simultaneously on using this type of operation.Let mimi be the minimum number of operations you have to do in order to make the ii first lamps be simultaneously on. Note that there is no condition upon the state of other lamps (between i+1i+1 and nn), they can be either off or on.You have to compute mimi for all 1≤i≤n1≤i≤n.InputThe first line contains two integers nn and kk (1≤n,k≤3⋅1051≤n,k≤3⋅105).The second line contains a binary string of length nn, representing the initial state of each lamp (the lamp ii is off if si=0si=0, on if si=1si=1).The description of each one of the kk subsets follows, in the following format:The first line of the description contains a single integer cc (1≤c≤n1≤c≤n)  — the number of elements in the subset.The second line of the description contains cc distinct integers x1,…,xcx1,…,xc (1≤xi≤n1≤xi≤n)  — the elements of the subset.It is guaranteed that: The intersection of any three subsets is empty; It's possible to make all lamps be simultaneously on using some operations. OutputYou must output nn lines. The ii-th line should contain a single integer mimi  — the minimum number of operations required to make the lamps 11 to ii be simultaneously on.ExamplesInputCopy7 3 0011100 3 1 4 6 3 3 4 7 2 2 3 OutputCopy1 2 3 3 3 3 3 InputCopy8 6 00110011 3 1 3 8 5 1 2 5 6 7 2 6 8 2 3 5 2 4 7 1 2 OutputCopy1 1 1 1 1 1 4 4 InputCopy5 3 00011 3 1 2 3 1 4 3 3 4 5 OutputCopy1 1 1 1 1 InputCopy19 5 1001001001100000110 2 2 3 2 5 6 2 8 9 5 12 13 14 15 16 1 19 OutputCopy0 1 1 1 2 2 2 3 3 3 3 4 4 4 4 4 4 4 5 NoteIn the first example: For i=1i=1; we can just apply one operation on A1A1, the final states will be 10101101010110; For i=2i=2, we can apply operations on A1A1 and A3A3, the final states will be 11001101100110; For i≥3i≥3, we can apply operations on A1A1, A2A2 and A3A3, the final states will be 11111111111111. In the second example: For i≤6i≤6, we can just apply one operation on A2A2, the final states will be 1111110111111101; For i≥7i≥7, we can apply operations on A1,A3,A4,A6A1,A3,A4,A6, the final states will be 1111111111111111.
[ "dfs and similar", "dsu", "graphs" ]
import sys, os, io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def get_root(s): v = [] while not s == root[s]: v.append(s) s = root[s] for i in v: root[i] = s return s def unite(s, t): rs, rt = get_root(s), get_root(t) if not rs ^ rt: return if rank[s] == rank[t]: rank[rs] += 1 if rank[s] >= rank[t]: root[rt] = rs size[rs] += size[rt] else: root[rs] = rt size[rt] += size[rs] cnt[get_root(s)] = min(cnt[rs] + cnt[rt], inf) return def same(s, t): return True if get_root(s) == get_root(t) else False def get_size(s): return size[get_root(s)] n, k = map(int, input().split()) s = list(input().rstrip()) c1 = [0] * (n + 1) c2 = [0] * (n + 1) for i in range(1, k + 1): c = int(input()) x = list(map(int, input().split())) for j in x: if not c1[j]: c1[j] = i else: c2[j] = i root = [i for i in range(2 * k + 1)] rank = [1 for _ in range(2 * k + 1)] size = [1 for _ in range(2 * k + 1)] cnt = [0] * (2 * k + 1) for i in range(1, k + 1): cnt[i] = 1 ans = [] ans0 = 0 inf = pow(10, 9) + 1 for u, v, w in zip(c1[1:], c2[1:], s): if u: ans0 -= min(cnt[get_root(u)], cnt[get_root(u + k)]) if v and not same(u, v) and not same(u, v + k): ans0 -= min(cnt[get_root(v)], cnt[get_root(v + k)]) if w & 1 and u: if not v: cnt[get_root(u)] = inf else: unite(u, v) unite(u + k, v + k) elif not w & 1 and u: if not v: cnt[get_root(u + k)] = inf else: unite(u, v + k) unite(u + k, v) if u: ans0 += min(cnt[get_root(u)], cnt[get_root(u + k)]) ans.append(ans0) for i in range(n - 2, -1, -1): ans[i] = min(ans[i], ans[i + 1]) sys.stdout.write("\n".join(map(str, ans)))
py
1284
C
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≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. 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≤l≤r≤n1≤l≤r≤n, 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≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853 OutputCopy1 InputCopy2 993244853 OutputCopy6 InputCopy3 993244853 OutputCopy32 InputCopy2019 993244853 OutputCopy923958830 InputCopy2020 437122297 OutputCopy265955509 NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
[ "combinatorics", "math" ]
# Thank God that I'm not you. from itertools import permutations, combinations; import heapq; from collections import Counter, deque; import math; import sys; from functools import lru_cache; n, mod = map(int, input().split()) factorials = [1] currMul = 1; for i in range(1, n + 1): currMul *= i; currMul %= mod; factorials.append(currMul); ans = 0; sub = 0; currN = n; for i in range(1, n + 1): ans += ((currN) * factorials[n - i] * factorials[i] * (currN)); currN -= 1; ans %= mod; print(ans)
py
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
s = input() l = [] for j in range(len(s)): l.append(s[j]) # bracketOpen = [] # bracketClose = [] ans = [] # if len(s)%2==0 or len(s)%2==1: # for j in range(len(s)): # if l[j]=="(": # bracketOpen.append(j+1) # # for j in range(len(s)//2,len(s)): # elif l[j]==")": # bracketClose.append(j+1) # if len(bracketClose)>len(bracketOpen): # ans = [] # for j in range(len(bracketOpen)): # ans.append(bracketOpen[j]) # for j in range(len(bracketOpen)): # ans.append(bracketClose[j]) # else: # ans = [] # for j in range(len(bracketClose)): # ans.append(bracketOpen[j]) # for j in range(len(bracketClose)): # ans.append(bracketClose[j]) # if len(ans)==0: # print(0) # else: # print(1) # print(len(ans)) # print(*ans) f = 0 r = len(s) - 1 while f < r: if l[f]=="(" and l[r]==")": ans.append(f+1) ans.append(r+1) f+=1 r-=1 elif l[f]=="(" and l[r]!=")": r-=1 elif l[f]!="(" and l[r]==")": f+=1 else: f+=1 r-=1 if len(ans)==0: print(0) else: print(1) print(len(ans)) ans.sort() print(*ans)
py
1141
B
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 — it is a sequence a1,a2,…,ana1,a2,…,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≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), 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 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn 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.
[ "implementation" ]
n = int(input()) a = [int(x) for x in input().split()][:n] count, max = 0, 0 check1, check2 = False, False start, end = 0, 0 for i in range(n): if a[i] == 1: count += 1 if not check1: start += 1 else: count = 0 check1 = True if count > max: max = count for i in reversed(range(n)): if a[i] == 1 and not check2: end += 1 else: break if start + end > max: max = start + end print(max) ## hahaha! indentation changed
py
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
def get(f): return f(input().strip()) def gets(f): return [*map(f, input().split())] for _ in range(get(int)): n = get(int) a = sorted(gets(int)) print(a[n] - a[n - 1])
py
1311
A
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−ya−y. 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≤t≤1041≤t≤104) — the number of test cases.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — 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 2 3 10 10 2 4 7 4 9 3 OutputCopy1 0 2 2 1 NoteIn 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.
[ "greedy", "implementation", "math" ]
n = int(input()) for i in range(n): p,q = [int(i) for i in input().split()] if p==q: print(0) elif p<q: diff = q-p if diff%2==0: print(2) else: print(1) elif p>q: diff = p-q if diff%2==0: print(1) else: print(2)
py
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
import sys from array import array from collections import deque input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: [dtype(x) for x in input().split()] inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)] debug = lambda *x: print(*x, file=sys.stderr) ceil1 = lambda a, b: (a + b - 1) // b out, tests = [], 1 class graph: def __init__(self, n): self.n = n self.gdict = [array('i') for _ in range(n + 1)] def add_edge(self, node1, node2): self.gdict[node1].append(node2) self.gdict[node2].append(node1) def bfs_util(self, root): visit, self.dist = array('b', [0] * (self.n + 1)), [0] * (self.n + 1) queue, visit[root] = deque([root]), True while queue: s = queue.popleft() for i1 in self.gdict[s]: if visit[i1] == False: queue.append(i1) visit[i1], self.dist[i1] = True, self.dist[s] + 1 return self.dist for _ in range(tests): n, m, k = inp(int) sp = array('i', inp(int)) g, ans = graph(n), 0 for i in range(m): u, v = inp(int) g.add_edge(u, v) dist1 = g.bfs_util(1) distn = g.bfs_util(n) sor = array('i', sorted(range(k), key=lambda x: dist1[sp[x]] - distn[sp[x]])) suf = array('i', [0]) for i in sor[::-1]: suf.append(max(suf[-1], distn[sp[i]])) suf.reverse() for ix in range(k - 1): i = sor[ix] ans = min(max(ans, suf[ix + 1] + dist1[sp[i]] + 1), dist1[n]) out.append(ans) print('\n'.join(map(str, out)))
py
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,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,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
n = int(input()) l = list(map(int,input().split())) ans = [0] for i in range (n-1): ans.append(ans[-1]+l[i]) a = min(ans) for i in range(n): ans[i] = ans[i] - a + 1 a = [False for i in range (n)] for i in range(n): if ans[i] <= n: a[ans[i]-1] = True bb = True for i in range(n): bb = bb and a[i] if bb: for i in ans: print(i, end = " ") else: print(-1)
py
1291
A
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−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 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≤t≤10001≤t≤1000)  — 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≤n≤30001≤n≤3000)  — 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 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn 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 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
for _ in range(int(input())): t=int(input()) p=input() l=list(p) a='' for i in p: if int(i)%2!=0: a+=i if len(a)<2: print("-1") else: print(a[:2])
py
1325
D
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4 OutputCopy2 3 1InputCopy1 3 OutputCopy3 1 1 1InputCopy8 5 OutputCopy-1InputCopy0 0 OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
a,b=map(int, input().split()) if a>b or (b-a)%2==1: print(-1) elif a==b: if a==0: print(0) else: print(1) print(a) else: x=(b-a)//2 if (a+x)^x==a: print(2) print(x+a,x) else: print(3) print(a,x,x)
py
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 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≤B≤CA≤B≤C 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≤t≤1001≤t≤100) — 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≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C 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 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
from heapq import heappop, heappush, heapify from math import ceil, factorial, gcd, log, floor from sys import stdin, stdout from collections import defaultdict, deque, Counter from bisect import bisect_left, bisect_right, insort_right inf = int(1e19) input = stdin.readline mod = 998244353 #D V ARAVIND for _ in range (int(input())): a, b, c = map(int, input().split()) ans = inf val = [1, 1, 1] for x in range (1, (2*a)+1): y = x while y <= (2*b): zm = (c//y)*y z = zm + y sol = min(c-zm, z-c) + abs(y-b) + abs(x-a) if sol < ans: ans = sol val[0] = x val[1] = y if c-zm <= z-c : val[2] = zm else: val[2] = z y += x print(ans) print(*val)
py
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
from math import inf n, h, l, r = map(int, input().split()) nums = list(map(int, input().split())) f = [-inf]*h f[0] = 0 for i, x in enumerate(nums): g = [-inf]*h for s in range(h): g[s] = max(f[(s-x)%h], f[(s-x+1)%h])+(l<=s<=r) f = g print(max(f))
py
1316
B
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≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] 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≠ba≠b; 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≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — 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′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) 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 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn 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.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
def find(S,N,k): ans = S[k-1:] if len(ans)%2==0: ans+=S[:k-1] else: ans+=S[:k-1][::-1] return ans for _ in range(int(input())): N = int(input()) S = input() ans = [[S,1]] for k in range(2,N+1): ans.append([find(S,N,k),k]) ans.sort() print(ans[0][0]) print(ans[0][1])
py
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 OutputCopy2 1 5
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
import sys # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ t = int(input()) for _ in range(t): n = int(input()) edges = [] for i in range(n): li, ri = map(int, input().split()) edges.append((li, 0, i)) edges.append((ri, 1, i)) edges.sort() ctr = [0] * n opened = set() segmCtr = 0 for k, (e, isEnd, i) in enumerate(edges): if isEnd: opened.remove(i) if not opened and edges[k-1][2] == i: ctr[i] -= 1 elif len(opened) == 1 and edges[k+1][1] == 0: for j in opened: ctr[j] += 1 else: if not opened: segmCtr += 1 opened.add(i) print(segmCtr + max(ctr)) # inf.close()
py
1325
F
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 ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. 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≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) 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 ⌈n−−√⌉⌈n⌉ 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 1 3 3 4 4 2 2 6 5 6 5 1 OutputCopy1 1 6 4InputCopy6 8 1 3 3 4 4 2 2 6 5 6 5 1 1 4 2 5 OutputCopy2 4 1 5 2 4InputCopy5 4 1 2 1 3 2 4 2 5 OutputCopy1 3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
input = __import__('sys').stdin.readline n, m = map(int, input().split()) adj = [[] for _ in range(n)] for _ in range(m): u, v = map(lambda x: int(x)-1, input().split()) adj[u].append(v) adj[v].append(u) k = int(n**0.5) while k*k < n: k += 1 DFS_IN = 0 DFS_OUT = 1 # cc ans = [] taken = [False]*n depth = [-1]*n parent = [-1]*n stack = [(0, -1, DFS_IN)] while len(stack) > 0: u, par, state = stack.pop() if state == DFS_IN: if depth[u] != -1: continue stack.append((u, par, DFS_OUT)) if par != -1: parent[u] = par depth[u] = depth[par] + 1 for v in adj[u][::-1]: if depth[v] == -1: stack.append((v, u, DFS_IN)) elif depth[v] + 1 < depth[u]: if depth[u] - depth[v] + 1 >= k: ans = [u] while ans[-1] != v: ans.append(parent[ans[-1]]) print(2) print(len(ans)) print(' '.join(str(x+1) for x in ans)) exit(0) if state == DFS_OUT: if not taken[u]: taken[u] = True ans.append(u) for v in adj[u]: taken[v] = True print(1) print(' '.join(str(x+1) for x in ans[:k]))
py
1310
A
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 — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn 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.
[ "data structures", "greedy", "sortings" ]
import os,sys from io import BytesIO, IOBase from heapq import * def main(): n = int(input()) lst = [(a,b)for a,b in zip(map(int,input().split()),map(int,input().split()))] lst.sort(key=lambda xx:xx[0]) heap = [] i,ans,su = 0,0,0 while i != n: j,st = i,lst[max(0,i-1)][0] ans += su*(lst[i][0]-st) for x in range(lst[i][0]-st): if not len(heap): break r = heappop(heap) su += r ans += r*(lst[i][0]-x-st) while i != n and lst[i][0] == lst[j][0]: su += lst[i][1] heappush(heap,-lst[i][1]) i += 1 cou = 0 while len(heap): ans -= cou*heappop(heap) cou += 1 print(ans) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main()
py
1301
D
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−2n−2m)(4nm−2n−2m) 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−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); 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≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), 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≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) 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 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe 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):
[ "constructive algorithms", "graphs", "implementation" ]
import sys import math from collections import defaultdict,Counter # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') # m=pow(10,9)+7 n,m,k=map(int,input().split()) if k>(4*m*n-2*n-2*m): print("NO") else: k1=k print("YES") s='' c=0 if m>=n: flag=0 d=min(k,m-1) if d!=0: s+=str(d)+' R'+'\n' k-=d c+=1 while k: # print(k) if c==2*n+n-1: c+=1 s+=str(k)+' U\n' break if flag%3==0: d=min(k,m-1) s+=str(d)+' L'+'\n' k-=d flag+=1 elif flag%3==1: s+='1 D\n' flag+=1 k-=1 else: d=min(k,(m-1)*3) if d==3*(m-1): s+=str(m-1)+' RUD'+'\n' else: if k>=3: s+=str(k//3)+' RUD'+'\n' else: c-=1 if d%3==1: s+='1 R\n' c+=1 elif d%3==2: s+='1 RU\n' c+=1 k-=d flag+=1 c+=1 else: flag=0 d=min(k,n-1) if d!=0: s+=str(d)+' D'+'\n' k-=d c+=1 while k: if c==2*m+m-1: c+=1 s+=str(k)+' L\n' break if flag%3==0: d=min(k,n-1) s+=str(d)+' U'+'\n' k-=d flag+=1 elif flag%3==1: s+='1 R\n' flag+=1 k-=1 else: d=min(k,(n-1)*3) if d==3*(n-1): s+=str(n-1)+' DLR'+'\n' else: if k>=3: s+=str(k//3)+' DLR'+'\n' else: c-=1 if d%3==1: s+='1 D\n' c+=1 elif d%3==2: s+='1 DL\n' c+=1 k-=d flag+=1 c+=1 print(c) print(s[:-1])
py
1288
C
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≤biai≤bi 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≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn 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].
[ "combinatorics", "dp" ]
def f0(n, m): mod = int(1e9 + 7) c = 2 * m + 1 dp = [[0] * c for _ in range(n + 1)] dp[0][0] = 1 for i in range(n): # TODO 空间压缩 / 斜率优化 for j in range(c): for k in range(j, c): dp[i + 1][k] = (dp[i + 1][k] + dp[i][j]) % mod return dp[-1][-1] def f1(n, m): def power(base, exp): val = 1 while exp: if exp & 1: val = val * base % mod base = base * base % mod exp >>= 1 return val mod = int(1e9 + 7) a = b = c = 1 x = n + m * 2 - 1 y = 2 * m z = x - y for i in range(1, x + 1): a = a * i % mod if i == y: b = a if i == z: c = a ans = a ans = ans * power(b, mod - 2) % mod ans = ans * power(c, mod - 2) % mod return ans n, m = map(int, input().split()) print(f1(n, m))
py
1287
B
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 — color, number, shape, and shading — 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≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — 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 — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
#Don't stalk me, don't stop me, from making submissions at high speed. If you don't trust me, import sys #then trust me, don't waste your time not trusting me. I don't plagiarise, don't fantasize, import os #just let my hard work synthesize my rating. Don't be sad, just try again, everyone fails from io import BytesIO, IOBase BUFSIZE = 8192 #every now and then. Just keep coding, just keep working and you'll keep progressing at speed- # -forcing. class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") #code by _Frust(CF)/Frust(AtCoder) sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def hasher(str1, prime=257, mod=1000000007): po=1 p1=prime h=0 for i in range(len(str1)): h=(h + (po * (ord(str1[i]) - ord("a") + 1))%mod)%mod po=(po * p1)%mod return h # n=int(input()) n, k=map(int, input().split()) l1=[] d1={} for i in range(n): s1=input() l1.append(s1) hc1=hasher(s1, 257) hc2=hasher(s1, 263) d1[(hc1, hc2)]=d1.get((hc1, hc2), 0)+1 ans=0 for i in range(n): for j in range(i+1, n): h1, p1, po1=0, 257, 1 h2, p2, po2=0, 263, 1 mod=1000000007 for l in range(k): req="" if l1[i][l]==l1[j][l]: req=l1[i][l] else: for letter in "SET": if l1[i][l]!=letter and l1[j][l]!=letter: req=letter break h1=(h1 + (po1 * (ord(req) - ord("a") + 1))%mod)%mod po1=(po1*p1)%mod h2=(h2 + (po2 * (ord(req) - ord("a") + 1))%mod)%mod po2=(po2*p2)%mod ans+=d1.get((h1, h2), 0) print(ans//3)
py
13
B
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 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — 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 «YES» (without quotes), if the segments form the letter A and «NO» 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
[ "geometry", "implementation" ]
import random from math import sqrt as s def dist(x1, y1, x2, y2): return s((x2 - x1) ** 2 + (y2 - y1) ** 2) def is_dot_on_line(c1, c2, dot): A = c1[1] - c2[1] B = c2[0] - c1[0] C = c1[0] * c2[1] - c2[0] * c1[1] maxx, minx = max(c1[0], c2[0]), min(c1[0], c2[0]) maxy, miny = max(c1[1], c2[1]), min(c1[1], c2[1]) res = A * dot[0] + B * dot[1] + C if res == 0 and minx <= dot[0] <= maxx and miny <= dot[1] <= maxy: return True return False def cosangle(x1, y1, x2, y2): return x1 * x2 + y1 * y2 def same(k11, k12, k21, k22, k31, k32): if k11 == k21 or k11 == k22 or k12 == k21 or k12 == k22: return 0, 1, 2 if k11 == k31 or k11 == k32 or k12 == k31 or k12 == k32: return 0, 2, 1 if k21 == k31 or k21 == k32 or k22 == k31 or k22 == k32: return 1, 2, 0 return False def is_a(c1, c2, c3, debug=-1): al = [c1, c2, c3] lines = same(*c1, *c2, *c3) if not lines: return False c1, c2, c3 = al[lines[0]], al[lines[1]], al[lines[2]] if c1[0] == c2[1]: c2[0], c2[1] = c2[1], c2[0] if c1[1] == c2[0]: c1[0], c1[1] = c1[1], c1[0] if not (is_dot_on_line(c1[0], c1[1], c3[0]) and is_dot_on_line(c2[0], c2[1], c3[1])): if not (is_dot_on_line(c1[0], c1[1], c3[1]) and is_dot_on_line(c2[0], c2[1], c3[0])): return False c3[0], c3[1] = c3[1], c3[0] cosa = cosangle(c1[0][0] - c1[1][0], c1[0][1] - c1[1][1], c2[0][0] - c2[1][0], c2[0][1] - c2[1][1]) if cosa < 0: return False l1 = dist(*c1[0], *c3[0]), dist(*c1[1], *c3[0]) l2 = dist(*c2[0], *c3[1]), dist(*c2[1], *c3[1]) if min(l1) / max(l1) < 1/4 or min(l2) / max(l2) < 1/4: return False return True n = int(input()) for i in range(n): c1 = list(map(int, input().split())) c2 = list(map(int, input().split())) c3 = list(map(int, input().split())) if is_a([c1[:2], c1[2:]], [c2[:2], c2[2:]], [c3[:2], c3[2:]], debug=i): print("YES") else: print("NO")
py
1290
B
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≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,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≤l≤r≤|s|1≤l≤r≤|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≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|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 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn 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.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
def diff(a,b): ans = [] for i in range(len(a)): ans.append(a[i]-b[i]) return ans a = input() n = len(a) q = int(input()) count = [[0 for i in range(26)] for j in range(n)] count[0][ord(a[0])-97] += 1 for i in range(1,n): for j in range(26): count[i][j] = count[i-1][j] count[i][ord(a[i])-97] += 1 # for i in count: # print (*i) for i in range(q): l,r = map(int,input().split()) if l==r: print ("Yes") else: if a[l-1]!=a[r-1]: print ("Yes") else: d = diff(count[r-1],count[l-1]) if d.count(0)<=23: print("Yes") else: print ("No")
py
1324
A
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×12×1 (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×12×1 (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−1ai−1. 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≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4 3 1 1 3 4 1 1 2 1 2 11 11 1 100 OutputCopyYES NO YES YES NoteThe 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.
[ "implementation", "number theory" ]
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) flag=False for i in range(n): for j in range(n): if abs(a[i]-a[j])%2!=0:print("NO");flag=True;break; if flag:break if not flag: print("YES")
py
1321
C
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≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 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≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe 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.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
n = int(input()) ak = input() co = 0 n1 = n while True: max1 = 'a' maxi = -1 for i in range(n): if i + 1 < n and ak[i] == chr(ord(ak[i + 1]) + 1) and max1 <= ak[i]: maxi = i max1 = ak[i] if i - 1 >= 0 and ak[i] == chr(ord(ak[i - 1]) + 1) and max1 <= ak[i]: maxi = i max1 = ak[i] if maxi == -1: break ak = ak[:maxi] + ak[maxi + 1:] n = n - 1 print(n1-n)
py
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — 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≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — 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≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — 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≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 OutputCopy1
[ "brute force", "data structures", "sortings" ]
class LazySegmentTree: # add operations, max queries def __init__(self, data, func=max): """initialize the lazy segment tree with data""" self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self._lazy = [0] * (2 * _size) self.data = [-int(2e9 - 5)] * (2 * _size) # TO CHANGE FOR MIN self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = self._func(self.data[i + i], self.data[i + i + 1]) def __len__(self): return self._len def _push(self, idx): """push query on idx to its children""" # Let the children know of the queries q, self._lazy[idx] = self._lazy[idx], 0 self._lazy[2 * idx] += q self._lazy[2 * idx + 1] += q self.data[2 * idx] += q self.data[2 * idx + 1] += q def _update(self, idx): """updates the node idx to know of all queries applied to it via its ancestors""" for i in reversed(range(1, idx.bit_length())): self._push(idx >> i) def _build(self, idx): """make the changes to idx be known to its ancestors""" idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx] idx >>= 1 def add(self, start, stop, value): """lazily add value to [start, stop]""" stop += 1 start = start_copy = start + self._size stop = stop_copy = stop + self._size while start < stop: if start & 1: self._lazy[start] += value self.data[start] += value start += 1 if stop & 1: stop -= 1 self._lazy[stop] += value self.data[stop] += value start >>= 1 stop >>= 1 # Tell all nodes above of the updated area of the updates self._build(start_copy) self._build(stop_copy - 1) def query(self, start, stop): """func of data[start, stop]""" stop += 1 start += self._size stop += self._size # Apply all the lazily stored queries self._update(start) self._update(stop - 1) res = -int(2e9) # TO CHANGE FOR MIN while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "LazySegmentTree({0})".format(self.data) def main(): n, m, p = readIntArr() aca = [] # weapons for _ in range(n): a, ca = readIntArr() aca.append((a, ca)) bcb = [] # armor for _ in range(m): b, cb = readIntArr() bcb.append((b, cb)) yxz = [] # monsters for _ in range(p): x, y, z = readIntArr() yxz.append((y, x, z)) aca.sort(key = lambda x : x[0]) # sort by a asc segArr = [-ca for a, ca in aca] lst = LazySegmentTree(segArr) bcb.sort(key = lambda x : x[0]) # sort by b asc yxz.sort(key = lambda x : x[0]) # sort by y asc ans = -2e9 - 5 i = 0 for b, cb in bcb: # identify killable monsters with y < b, and update the seg tree while i < p and yxz[i][0] < b: y, x, z = yxz[i] # binary search for j where aca[j][0] > x lo = -1; hi = n - 1 while lo < hi: mid = (lo + hi + 1) // 2 if aca[mid][0] <= x: lo = mid else: hi = mid - 1 j = lo + 1 if j < n: lst.add(j, n - 1, z) i += 1 ans = max(ans, -cb + lst.query(0, n - 1)) print(ans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(a, b, c): print('? {} {} {}'.format(a, b, c)) sys.stdout.flush() return int(input()) def answerInteractive(ansArr): print('! {}'.format(' '.join([str(x) for x in ansArr]))) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil import math # from math import floor,ceil # for Python2 for _abc in range(1): main()
py
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
seq = int(input()) cresc = ncresc = h = 0 maxi = [] mini = [] for _ in range(seq): s = [int(p) for p in input().split()[1:]] c = False for i in range(1, len(s)): if s[i] > s[i-1]: cresc += 1 c = True break if not c: maxi.append(max(s)) mini.append(min(s)) ncresc += 1 cresc = cresc * cresc + (cresc * ncresc * 2) mini.sort() maxi.sort() for g in maxi: while h < ncresc and mini[h] < g: h += 1 cresc += h print(cresc)
py