index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
500
8
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his programming skills by solving a task, he'll work as a cybersecurity specialist. Otherwise, he'll be delivering some doubtful products for the next two years. You're given n positive integers a_1, a_2, ..., a_n. Using each of them exactly at once, you're to make such sequence b_1, b_2, ..., b_n that sequence c_1, c_2, ..., c_n is lexicographically maximal, where c_i=GCD(b_1,...,b_i) - the greatest common divisor of the first i elements of b. Alexander is really afraid of the conditions of this simple task, so he asks you to solve it. A sequence a is lexicographically smaller than a sequence b if and only if one of the following holds: * a is a prefix of b, but a β‰  b; * in the first position where a and b differ, the sequence a has a smaller element than the corresponding element in b. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^3). Description of the test cases follows. The first line of each test case contains a single integer n (1 ≀ n ≀ 10^3) β€” the length of the sequence a. The second line of each test case contains n integers a_1,...,a_n (1 ≀ a_i ≀ 10^3) β€” the sequence a. It is guaranteed that the sum of n over all test cases does not exceed 10^3. Output For each test case output the answer in a single line β€” the desired sequence b. If there are multiple answers, print any. Example Input 7 2 2 5 4 1 8 2 3 3 3 8 9 5 64 25 75 100 50 1 42 6 96 128 88 80 52 7 5 2 4 8 16 17 Output 5 2 8 2 1 3 9 3 8 100 50 25 75 64 42 128 96 80 88 52 7 17 2 4 8 16 Note In the first test case of the example, there are only two possible permutations b β€” [2, 5] and [5, 2]: for the first one c=[2, 1], for the second one c=[5, 1]. In the third test case of the example, number 9 should be the first in b, and GCD(9, 3)=3, GCD(9, 8)=1, so the second number of b should be 3. In the seventh test case of the example, first four numbers pairwise have a common divisor (a power of two), but none of them can be the first in the optimal permutation b.
def gcd(x, y): while(y): x, y = y, x % y return x for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) m=x=0 while(l): m,x=max((gcd(m,i),i)for i in l) print(x) l.remove(x)
{ "input": [ "7\n2\n2 5\n4\n1 8 2 3\n3\n3 8 9\n5\n64 25 75 100 50\n1\n42\n6\n96 128 88 80 52 7\n5\n2 4 8 16 17\n" ], "output": [ "5 2\n8 2 1 3\n9 3 8\n100 50 25 75 64\n42\n128 96 80 88 52 7\n17 2 4 8 16\n" ] }
501
12
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard. Igor generated sequence p using the following algorithm: 1. initially, p = [x]; 2. for each 1 ≀ i ≀ n he did the following operation |d_i| times: * if d_i β‰₯ 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p; * if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p. For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5]. Igor decided to calculate the length of the longest increasing subsequence of p and the number of them. A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements. A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element. For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}]. Input The first line contains a single integer n (1 ≀ n ≀ 50) β€” the length of the sequence d. The second line contains a single integer x (-10^9 ≀ x ≀ 10^9) β€” the integer on the blackboard. The third line contains n integers d_1, d_2, …, d_n (-10^9 ≀ d_i ≀ 10^9). Output Print two integers: * the first integer should be equal to the length of the longest increasing subsequence of p; * the second should be equal to the number of them modulo 998244353. You should print only the second number modulo 998244353. Examples Input 3 3 1 -1 2 Output 3 3 Input 3 100 5 -3 6 Output 9 7 Input 3 1 999999999 0 1000000000 Output 2000000000 1 Input 5 34 1337 -146 42 -69 228 Output 1393 3876 Note The first test case was explained in the statement. In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108]. In the third test case p = [1, 2, …, 2000000000].
import sys, io, os if os.environ['USERNAME']=='kissz': inp=open('in55.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def debug(*args): pass def mexp(size,power): A=[] for i in range(size): A.append([int(j<=(i//2)*2) for j in range(size)]) powers={1: A} p=1 while p*2<=power: powers[p*2]=mmmult(powers[p],powers[p]) p*=2 A=powers[p] power-=p while power>0: p=p//2 if p<=power: A=mmmult(A,powers[p]) power-=p return A def mvmult(A,V): res=[] for i in range(len(A)): res.append(sum(a*v for a,v in zip(A[i],V)) % 998244353 ) return res def mmmult(A,B): res=[] for i in range(len(A)): res.append([sum(a*B[j][k] for j,a in enumerate(A[i])) for k in range(len(B[0]))]) return res def get_rep(corners): corners[0]-=1 corners[-1]+=1 bps=sorted(list(set(corners))) m=len(bps) X=[1] active=[1] for i in range(1,m): x,y=bps[i-1],bps[i] d=y-x A=mexp(len(active),d) X=mvmult(A,X) #debug(active,X) #debug(A) if i<m-1: for j,c in enumerate(corners): if c==y: if j%2: # top: j and j+1 in active idx=active.index(j) X[idx+2]+=X[idx] active.pop(idx) active.pop(idx) X.pop(idx) X.pop(idx) else: # bottom active+=[j,j+1] active.sort() idx=active.index(j) X=X[:idx]+[0,X[idx-1]]+X[idx:] else: return X[0] n=int(inp()) inp() d,*D=map(int,inp().split()) if d==0 and all(dd==0 for dd in D): print(1,1) else: while d==0: d,*D=D up=(d>=0) corners=[0,d] for d in D: x=corners[-1]+d if up==(d>=0): corners[-1]=x if up!=(d>=0): up=(d>=0) corners.append(x) debug(corners) cands=[(-1,0,0)] low=(0,0) maxdiff=(0,0,0) for i,corner in enumerate(corners): if corner<low[0]: low=(corner,i) if corner-low[0]>=cands[0][0]: if corner-low[0]==cands[0][0] and low[1]>cands[0][1]: cands+=[(corner-low[0],low[1],i)] else: cands=[(corner-low[0],low[1],i)] L=cands[0][0]+1 if L>1: X=0 debug(cands) for _, starti, endi in cands: #debug(corners[starti:endi+1]) X+=get_rep(corners[starti:endi+1]) else: X=1-corners[-1] print(L,X % 998244353)
{ "input": [ "3\n100\n5 -3 6\n", "3\n3\n1 -1 2\n", "5\n34\n1337 -146 42 -69 228\n", "3\n1\n999999999 0 1000000000\n" ], "output": [ "\n9 7\n", "\n3 3\n", "\n1393 3876\n", "\n2000000000 1\n" ] }
502
9
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him. Input The input data contain four lines. Each of these lines contains four integers x1, y1, x2, y2 ( - 109 ≀ x1, y1, x2, y2 ≀ 109) β€” coordinates of segment's beginning and end positions. The given segments can degenerate into points. Output Output the word Β«YESΒ», if the given four segments form the required rectangle, otherwise output Β«NOΒ». Examples Input 1 1 6 1 1 0 6 0 6 0 6 1 1 1 1 0 Output YES Input 0 0 0 3 2 0 0 0 2 2 2 0 0 2 2 2 Output NO
def main(): dict = {0: 0, 1: 0} final = "YES" for i in range(4): x1, y1, x2, y2 = input().split() if(x1 == x2 and y1 != y2): dict[0] += 1 elif(y1 == y2 and x1 != x2): dict[1] += 1 for j in [(x1, y1), (x2, y2)]: dict[j] = dict.get(j, 0) + 1 for i in dict.values(): if(i != 2): final = "NO" print(final) if __name__ == '__main__': main()
{ "input": [ "0 0 0 3\n2 0 0 0\n2 2 2 0\n0 2 2 2\n", "1 1 6 1\n1 0 6 0\n6 0 6 1\n1 1 1 0\n" ], "output": [ "NO\n", "YES\n" ] }
503
8
As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i). Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth? Input The first line contains two integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ n) β€” the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≀ ai ≀ n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth. Output Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime. Examples Input 1 1 +1 Output Truth Input 3 2 -1 -2 -3 Output Not defined Not defined Not defined Input 4 1 +2 -3 +4 -1 Output Lie Not defined Lie Not defined Note The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth. In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not. In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.
# SHRi GANESHA author: Kunal Verma # import os import sys from bisect import bisect_right from collections import Counter, defaultdict, deque from heapq import * from io import BytesIO, IOBase from math import gcd, inf, sqrt, ceil def lcm(a, b): return (a * b) // gcd(a, b) ''' mod = 10 ** 9 + 7 fac = [1] for i in range(1, 2 * 10 ** 5 + 1): fac.append((fac[-1] * i) % mod) fac_in = [pow(fac[-1], mod - 2, mod)] for i in range(2 * 10 ** 5, 0, -1): fac_in.append((fac_in[-1] * i) % mod) fac_in.reverse() def comb(a, b): if a < b: return 0 return (fac[a] * fac_in[b] * fac_in[a - b]) % mod ''' #MAXN = 10000004 # spf = [0 for i in range(MAXN)] # adj = [[] for i in range(MAXN)] def sieve(): global spf, adj, MAXN spf[1] = 1 for i in range(2, MAXN): spf[i] = i for i in range(2, MAXN): if i * i > MAXN: break if (spf[i] == i): for j in range(i * i, MAXN, i): if (spf[j] == j): spf[j] = i def getdistinctFactorization(n): global adj, spf, MAXN for i in range(1, n + 1): index = 1 x = i if (x != 1): adj[i].append(spf[x]) x = x // spf[x] while (x != 1): if (adj[i][index - 1] != spf[x]): adj[i].append(spf[x]) index += 1 x = x // spf[x] def printDivisors(n): i = 2 z = [1, n] while i <= sqrt(n): if (n % i == 0): if (n / i == i): z.append(i) else: z.append(i) z.append(n // i) i = i + 1 return z def create(n, x, f): pq = len(bin(n)[2:]) if f == 0: tt = min else: tt = max dp = [[inf] * n for _ in range(pq)] dp[0] = x for i in range(1, pq): for j in range(n - (1 << i) + 1): dp[i][j] = tt(dp[i - 1][j], dp[i - 1][j + (1 << (i - 1))]) return dp def enquiry(l, r, dp, f): if l > r: return inf if not f else -inf if f == 1: tt = max else: tt = min pq1 = len(bin(r - l + 1)[2:]) - 1 return tt(dp[pq1][l], dp[pq1][r - (1 << pq1) + 1]) def SieveOfEratosthenes(n): prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n + 1, p): prime[i] = False p += 1 x = [] for i in range(2, n + 1): if prime[i]: x.append(i) return x def main(): n,m=map(int,input().split()) z=[[0,0]for i in range(n+1) ] xx=[] for i in range(n): p=int(input()) if p>0: z[p][1]+=1 else: z[abs(p)][0]+=1 xx.append(p) s=0 for i in range(1,n+1): s+=z[i][1] an=[] # print(z) for i in range(1,n+1): # print(n - z[i][0] - s + z[i][1],s) if n-z[i][0]-s+z[i][1]==m: an.append(i) z=Counter(an) m=[0]*n # print(an) for j in range(n): if xx[j]>0: if z[xx[j]]==len(an): m[j]=1 elif z[xx[j]]==0: m[j]=0 else: m[j]=0.7 else: if z[abs(xx[j])]==len(an): m[j]=0 elif z[abs(xx[j])]>0: m[j]=0.7 else: m[j]=1 #print(an) for i in range(n): if m[i]==1: m[i]="Truth" elif m[i]==0: m[i]= "Lie" else: m[i]="Not defined" print(*m,sep='\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()
{ "input": [ "4 1\n+2\n-3\n+4\n-1\n", "1 1\n+1\n", "3 2\n-1\n-2\n-3\n" ], "output": [ "Lie\nNot defined\nLie\nNot defined\n", "Truth\n", "Not defined\nNot defined\nNot defined\n" ] }
504
12
The Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series. There are n single men and n single women among the main characters. An opinion poll showed that viewers like several couples, and a marriage of any of them will make the audience happy. The Smart Beaver formalized this fact as k triples of numbers (h, w, r), where h is the index of the man, w is the index of the woman, and r is the measure of the audience's delight in case of the marriage of this couple. The same poll showed that the marriage of any other couple will leave the audience indifferent, so the screenwriters decided not to include any such marriages in the plot. The script allows you to arrange several marriages between the heroes or not to arrange marriages at all. A subset of some of the k marriages is considered acceptable if each man and each woman is involved in at most one marriage of the subset (the series won't allow any divorces). The value of the acceptable set of marriages is the total delight the spectators will get from the marriages included in this set. Obviously, there is a finite number of acceptable sets, and they all describe some variants of the script. The screenwriters do not want to choose a set with maximum value β€” it would make the plot too predictable. So the Smart Beaver offers the following option: sort all the acceptable sets in increasing order of value and choose the t-th set from the sorted list. Thus, t = 1 corresponds to a plot without marriages, t = 2 β€” to a single marriage resulting in minimal delight for the audience, and so on. Help the Beaver to implement the algorithm for selecting the desired set. Input The first input line contains integers n, k and t (1 ≀ k ≀ min(100, n2), 1 ≀ t ≀ 2Β·105), separated by single spaces. Next k lines contain triples of integers (h, w, r) (1 ≀ h, w ≀ n; 1 ≀ r ≀ 1000), separated by single spaces, which describe the possible marriages. It is guaranteed that the input data is correct: t doesn't exceed the total number of acceptable sets, and each pair (h, w) is present in at most one triple. The input limitations for getting 30 points are: * 1 ≀ n ≀ 5 The input limitations for getting 100 points are: * 1 ≀ n ≀ 20 Output Print a single number β€” the value of the t-th acceptable variant. Examples Input 2 4 3 1 1 1 1 2 2 2 1 3 2 2 7 Output 2 Input 2 4 7 1 1 1 1 2 2 2 1 3 2 2 7 Output 8 Note The figure shows 7 acceptable sets of marriages that exist in the first sample. <image>
I=lambda:list(map(int,input().split())) n,k,T=I() t=[I()for _ in '0'*k] def b(h,w,r,a): if h>n:a+=[r] else: b(h+1,w,r,a) for f,s,v in t: if f==h and s in w:b(h+1,w-set([s]),r+v,a) return a print(sorted(b(1,set(range(1,n+1)), 0,[]))[T-1])
{ "input": [ "2 4 3\n1 1 1\n1 2 2\n2 1 3\n2 2 7\n", "2 4 7\n1 1 1\n1 2 2\n2 1 3\n2 2 7\n" ], "output": [ "2\n", "8\n" ] }
505
9
Qwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high. At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into k bacteria. After that some abnormal effects create b more bacteria in the test tube. Thus, if at the beginning of some second the test tube had x bacteria, then at the end of the second it will have kx + b bacteria. The experiment showed that after n seconds there were exactly z bacteria and the experiment ended at this point. For the second experiment Qwerty is going to sterilize the test tube and put there t bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least z bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment. Help Qwerty and find the minimum number of seconds needed to get a tube with at least z bacteria in the second experiment. Input The first line contains four space-separated integers k, b, n and t (1 ≀ k, b, n, t ≀ 106) β€” the parameters of bacterial growth, the time Qwerty needed to grow z bacteria in the first experiment and the initial number of bacteria in the second experiment, correspondingly. Output Print a single number β€” the minimum number of seconds Qwerty needs to grow at least z bacteria in the tube. Examples Input 3 1 3 5 Output 2 Input 1 4 4 7 Output 3 Input 2 2 4 100 Output 0
#------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') 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") ALPHA='abcdefghijklmnopqrstuvwxyz' M=10**9+7 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() def canMake(iter): pass k,b,n,t=value() z=1 reduced=0 # for i in range(n): # z=z*k+b # print(z) # print() # z=t # for i in range(n): # z=z*k+b # print(z) while(z<=t): reduced+=1 z=z*k+b print(max(0,n-reduced+1))
{ "input": [ "2 2 4 100\n", "3 1 3 5\n", "1 4 4 7\n" ], "output": [ "0\n", "2\n", "3\n" ] }
506
10
A boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances. Help Vasya's teacher, find two numbers β€” the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad. Input The first line contains two space-separated integers n, x (1 ≀ n ≀ 105; 0 ≀ x ≀ 2Β·105) β€” the number of Olympiad participants and the minimum number of points Vasya earned. The second line contains n space-separated integers: a1, a2, ..., an (0 ≀ ai ≀ 105) β€” the participants' points in the first tour. The third line contains n space-separated integers: b1, b2, ..., bn (0 ≀ bi ≀ 105) β€” the participants' points in the second tour. The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad β€” there are two integers i, j (1 ≀ i, j ≀ n) such, that ai + bj β‰₯ x. Output Print two space-separated integers β€” the best and the worst place Vasya could have got on the Olympiad. Examples Input 5 2 1 1 1 1 1 1 1 1 1 1 Output 1 5 Input 6 7 4 3 5 6 4 4 8 6 0 4 3 4 Output 1 5 Note In the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place. In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that β€” {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}. In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour. In the worst case scenario Vasya can get the fifth place if the table looks like that β€” {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly.
import os import sys from io import BytesIO, IOBase 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") #n=int(input()) #arr = list(map(int, input().split())) n,x= map(int, input().split()) arr = sorted(list(map(int, input().split()))) ls = list(map(int, input().split())) ls=sorted(ls,reverse=True) #print(arr) #print(ls) ans=0 j=0 for i in range(n): while j<n and arr[j]+ls[i]<x: j+=1 if j<n and arr[j]+ls[i]>=x: ans+=1 j+=1 print(1, ans)
{ "input": [ "6 7\n4 3 5 6 4 4\n8 6 0 4 3 4\n", "5 2\n1 1 1 1 1\n1 1 1 1 1\n" ], "output": [ "1 5\n", "1 5\n" ] }
507
8
Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: * he chooses two elements of the array ai, aj (i β‰  j); * he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus. Input The first line contains integer n (1 ≀ n ≀ 105) β€” the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≀ 104) β€” the original array. Output Print a single integer β€” the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation. Examples Input 2 2 1 Output 1 Input 3 1 4 1 Output 3
def solve(l): n = len(l) if(not sum(l)%n): print(n) else: print(n-1) N = int(input()) l = list(map(int, input().split())) ans = solve(l)
{ "input": [ "3\n1 4 1\n", "2\n2 1\n" ], "output": [ "3\n", "1\n" ] }
508
9
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order. We'll say that the secret is safe if the following conditions are hold: * for any two indexes i, j (1 ≀ i < j ≀ k) the intersection of sets Ui and Uj is an empty set; * the union of sets U1, U2, ..., Uk is set (1, 2, ..., n); * in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| β‰₯ 3 should hold). Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≀ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't. Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition. Input The input consists of a single line which contains two integers n and k (2 ≀ k ≀ n ≀ 106) β€” the number of words in the secret and the number of the Keepers. The numbers are separated by a single space. Output If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret. If there are multiple solutions, print any of them. Examples Input 11 3 Output 3 1 2 1 1 2 3 2 2 3 1 Input 5 2 Output -1
import sys def solve(): n, k = map(int, input().split()) if n // k < 3 or n < 6: print(-1) return res = list() for i in range(1, k + 1): res.append(i) res.append(i) for i in range(1, k + 1): res.append(i) while len(res) < n: res.append(1); print(" ".join(map(str, res))) solve()
{ "input": [ "11 3\n", "5 2\n" ], "output": [ "1 1 2 2 3 3 1 2 3 1 1\n", "-1" ] }
509
9
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y). What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect? Input Single line of the input contains three integers x, y and m ( - 1018 ≀ x, y, m ≀ 1018). Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier. Output Print the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one. Examples Input 1 2 5 Output 2 Input -1 4 15 Output 4 Input 0 -1 5 Output -1 Note In the first sample the following sequence of operations is suitable: (1, 2) <image> (3, 2) <image> (5, 2). In the second sample: (-1, 4) <image> (3, 4) <image> (7, 4) <image> (11, 4) <image> (15, 4). Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations.
#_________________ Mukul Mohan Varshney _______________# #Template import sys import os import math import copy from math import gcd from bisect import bisect from io import BytesIO, IOBase from math import sqrt,floor,factorial,gcd,log,ceil from collections import deque,Counter,defaultdict from itertools import permutations, combinations #define function def Int(): return int(sys.stdin.readline()) def Mint(): return map(int,sys.stdin.readline().split()) def Lstr(): return list(sys.stdin.readline().strip()) def Str(): return sys.stdin.readline().strip() def Mstr(): return map(str,sys.stdin.readline().strip().split()) def List(): return list(map(int,sys.stdin.readline().split())) def Hash(): return dict() def Mod(): return 1000000007 def Ncr(n,r,p): return ((fact[n])*((ifact[r]*ifact[n-r])%p))%p def Most_frequent(list): return max(set(list), key = list.count) def Mat2x2(n): return [List() for _ in range(n)] def btod(n): return int(n,2) def dtob(n): return bin(n).replace("0b","") # Driver Code def solution(): #for _ in range(Int()): x,y,m=Mint() ans=0 if(x>=m or y>=m): print(0) elif(x<=0 and y<=0): print(-1) else: if(x>0 and y<0): ans=(x-y-1)//x y+=ans*x elif(y>0 and x<0): ans=(y-x-1)//y x+=ans*y while(x<m and y<m): t=x+y if(x<y): x=t else: y=t ans+=1 print(ans) #Call the solve function if __name__ == "__main__": solution()
{ "input": [ "-1 4 15\n", "1 2 5\n", "0 -1 5\n" ], "output": [ "4\n", " 2\n", "-1\n" ] }
510
10
Fox Ciel wants to write a task for a programming contest. The task is: "You are given a simple undirected graph with n vertexes. Each its edge has unit length. You should calculate the number of shortest paths between vertex 1 and vertex 2." Same with some writers, she wants to make an example with some certain output: for example, her birthday or the number of her boyfriend. Can you help her to make a test case with answer equal exactly to k? Input The first line contains a single integer k (1 ≀ k ≀ 109). Output You should output a graph G with n vertexes (2 ≀ n ≀ 1000). There must be exactly k shortest paths between vertex 1 and vertex 2 of the graph. The first line must contain an integer n. Then adjacency matrix G with n rows and n columns must follow. Each element of the matrix must be 'N' or 'Y'. If Gij is 'Y', then graph G has a edge connecting vertex i and vertex j. Consider the graph vertexes are numbered from 1 to n. The graph must be undirected and simple: Gii = 'N' and Gij = Gji must hold. And there must be at least one path between vertex 1 and vertex 2. It's guaranteed that the answer exists. If there multiple correct answers, you can output any of them. Examples Input 2 Output 4 NNYY NNYY YYNN YYNN Input 9 Output 8 NNYYYNNN NNNNNYYY YNNNNYYY YNNNNYYY YNNNNYYY NYYYYNNN NYYYYNNN NYYYYNNN Input 1 Output 2 NY YN Note In first example, there are 2 shortest paths: 1-3-2 and 1-4-2. In second example, there are 9 shortest paths: 1-3-6-2, 1-3-7-2, 1-3-8-2, 1-4-6-2, 1-4-7-2, 1-4-8-2, 1-5-6-2, 1-5-7-2, 1-5-8-2.
n, m, cnt = int(input()), 148, 0 ans = [['N'] * m for i in range(m)] def edge(i, j): ans[i][j] = ans[j][i] = 'Y' def node(adj): global cnt i = cnt cnt += 1 for j in adj: edge(i, j) return i start = node([]) end = node([]) choice = node([end] if n&1 else []) for i in range(1, 30): end = node([node([end]), node([end])]) choice = node([node([choice])] + ([end] if (n>>i)&1 else [])) edge(start, choice) print(m) for line in ans: print(''.join(line))
{ "input": [ "2", "1", "9" ], "output": [ "4\nNNYY\nNNYY\nYYNN\nYYNN\n", "2\nNY\nYN\n", "11\nNNYYNNNNYNN\nNNNNNNYYNNY\nYNNNYYNNNNN\nYNNNYYNNNNN\nNNYYNNYYNNN\nNNYYNNYYNNN\nNYNNYYNNNNN\nNYNNYYNNNNN\nYNNNNNNNNYN\nNNNNNNNNYNY\nNYNNNNNNNYN\n" ] }
511
8
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks. Fortunately, Picks remembers something about his set S: * its elements were distinct integers from 1 to limit; * the value of <image> was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102) = 102, lowbit(100012) = 12, lowbit(100002) = 100002 (binary representation). Can you help Picks and find any set S, that satisfies all the above conditions? Input The first line contains two integers: sum, limit (1 ≀ sum, limit ≀ 105). Output In the first line print an integer n (1 ≀ n ≀ 105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them. If it's impossible to find a suitable set, print -1. Examples Input 5 5 Output 2 4 5 Input 4 3 Output 3 2 3 1 Input 5 1 Output -1 Note In sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5. In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4.
def lowbit(x): return x & (- x) s, l = map(int , input().split()) lst = [] while s > 0 and l > 0: if s - l >= 0: s -= lowbit(l) lst.append(l) l -= 1 if s != 0: print(-1) else: print(len(lst)) print(*lst)
{ "input": [ "4 3\n", "5 1\n", "5 5\n" ], "output": [ "3\n3 2 1 ", "-1", "2\n5 4 " ] }
512
10
On a history lesson the teacher asked Vasya to name the dates when n famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [li, ri] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose such n dates of famous events that will fulfill both conditions. It is guaranteed that it is possible. Input The first line contains one integer n (1 ≀ n ≀ 100) β€” the number of known events. Then follow n lines containing two integers li and ri each (1 ≀ li ≀ ri ≀ 107) β€” the earliest acceptable date and the latest acceptable date of the i-th event. Output Print n numbers β€” the dates on which the events took place. If there are several solutions, print any of them. It is guaranteed that a solution exists. Examples Input 3 1 2 2 3 3 4 Output 1 2 3 Input 2 1 3 1 3 Output 1 2
# http://codeforces.com/contest/45/problem/D from sys import stdin inFile = stdin tokens = [] tokens_next = 0 def next_str(): global tokens, tokens_next while tokens_next >= len(tokens): tokens = inFile.readline().split() tokens_next = 0 tokens_next += 1 return tokens[tokens_next - 1] def nextInt(): return int(next_str()) n = nextInt() intervals = [(nextInt(), nextInt(), i) for i in range(n)] intervals.sort(key=lambda x: (x[1], x[0])) # for i in intervals: # print(i[0], i[1]) seen = set() for i in range(n): cur = intervals[i][0] while cur in seen: cur += 1 seen.add(cur) intervals[i] = (intervals[i][0], intervals[i][1], intervals[i][2], cur) intervals.sort(key=lambda x: x[2]) for i in range(n): print(intervals[i][3], end=' ') print()
{ "input": [ "3\n1 2\n2 3\n3 4\n", "2\n1 3\n1 3\n" ], "output": [ "1 2 3 ", "1 2 " ] }
513
8
You are given a n Γ— m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle). Input The first line contains two positive integer numbers n and m (1 ≀ n, m ≀ 1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed. Output Output a single number β€” total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). Examples Input 2 2 ** *. Output 1 Input 3 4 *..* .**. *.** Output 9
import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m = map(int, input().split()) a = ([[0] * (m + 2)] + [[0] + list(1 if c == '*' else 0 for c in input().rstrip()) + [0] for _ in range(n)] + [[0] * (m + 2)]) lr = [[0] * (m + 2) for _ in range(n + 2)] ud = [[0] * (m + 2) for _ in range(n + 2)] for i in range(1, n + 1): for j in range(1, m + 2): lr[i][j] = lr[i][j - 1] + a[i][j] for j in range(1, m + 1): for i in range(1, n + 2): ud[i][j] = ud[i - 1][j] + a[i][j] ans = 0 for i in range(1, n + 1): for j in range(1, m + 1): if a[i][j]: l, r, u, d = lr[i][j - 1], lr[i][-1] - lr[i][j], ud[i - 1][j], ud[-1][j] - ud[i][j] ans += u * r + r * d + d * l + l * u print(ans)
{ "input": [ "3 4\n*..*\n.**.\n*.**\n", "2 2\n**\n*.\n" ], "output": [ "9", "1" ] }
514
9
Petya loves computer games. Finally a game that he's been waiting for so long came out! The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values ​​of <image> for all i from 1 to n. The expression ⌊ xβŒ‹ denotes the result of rounding the number x down to the nearest integer. At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused. Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units. Input The first line of the input contains two positive integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 107) β€” the number of skills of the character and the number of units of improvements at Petya's disposal. The second line of the input contains a sequence of n integers ai (0 ≀ ai ≀ 100), where ai characterizes the level of the i-th skill of the character. Output The first line of the output should contain a single non-negative integer β€” the maximum total rating of the character that Petya can get using k or less improvement units. Examples Input 2 4 7 9 Output 2 Input 3 8 17 15 19 Output 5 Input 2 2 99 100 Output 20 Note In the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to lfloor frac{100}{10} rfloor + lfloor frac{100}{10} rfloor = 10 + 10 = 20. In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is <image>. In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to <image>.
import math def func(x): return 10*math.ceil(x/10)-x n,k = map(int,input().split()) skills = list(map(int,input().split())) skills_sort = sorted(skills,key=func) rating = tens = 0 for i in skills_sort: p = math.ceil(i/10) tens += (100-p*10)//10 t = p*10-i if k>=t: rating += p k -= t else: rating += i//10 rating += min(tens,k//10) print(rating)
{ "input": [ "2 2\n99 100\n", "2 4\n7 9\n", "3 8\n17 15 19\n" ], "output": [ "20\n", "2\n", "5\n" ] }
515
8
As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that <image> for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.) It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7. Input The input consists of two space-separated integers p and k (3 ≀ p ≀ 1 000 000, 0 ≀ k ≀ p - 1) on a single line. It is guaranteed that p is an odd prime number. Output Print a single integer, the number of distinct functions f modulo 109 + 7. Examples Input 3 2 Output 3 Input 5 4 Output 25 Note In the first sample, p = 3 and k = 2. The following functions work: 1. f(0) = 0, f(1) = 1, f(2) = 2. 2. f(0) = 0, f(1) = 2, f(2) = 1. 3. f(0) = f(1) = f(2) = 0.
def main(): p, k = map(int, input().split()) s = 1 m = pow(10,9)+7 if k == 0: s = pow(p,p-1,m) elif k == 1: s = pow(p,p,m) else: o = 1 n = k while n != 1: n = k*n %p o += 1 c = (p-1)//o s = pow(p,c,m) print(s%m) main()
{ "input": [ "3 2\n", "5 4\n" ], "output": [ "3", "25" ] }
516
7
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that si = b. Of course, you are the person he asks for a help. Input The first line of the input contain three integers a, b and c ( - 109 ≀ a, b, c ≀ 109) β€” the first element of the sequence, Vasya's favorite number and the difference between any two neighbouring elements of the sequence, respectively. Output If b appears in the sequence s print "YES" (without quotes), otherwise print "NO" (without quotes). Examples Input 1 7 3 Output YES Input 10 10 0 Output YES Input 1 -4 5 Output NO Input 0 60 50 Output NO Note In the first sample, the sequence starts from integers 1, 4, 7, so 7 is its element. In the second sample, the favorite integer of Vasya is equal to the first element of the sequence. In the third sample all elements of the sequence are greater than Vasya's favorite integer. In the fourth sample, the sequence starts from 0, 50, 100, and all the following elements are greater than Vasya's favorite integer.
def f(l): a,b,c = l if c==0: return a==b return (b-a)%c==0 and (b-a)//c>=0 l = list(map(int,input().split())) print('YES' if f(l) else 'NO')
{ "input": [ "1 -4 5\n", "1 7 3\n", "0 60 50\n", "10 10 0\n" ], "output": [ "NO\n", "YES\n", "NO\n", "YES\n" ] }
517
8
You are given a description of a depot. It is a rectangular checkered field of n Γ— m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*"). You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column y. You are to determine if it is possible to wipe out all walls in the depot by placing and triggering exactly one bomb. The bomb can be laid both in an empty cell or in a cell occupied by a wall. Input The first line contains two positive integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the depot field. The next n lines contain m symbols "." and "*" each β€” the description of the field. j-th symbol in i-th of them stands for cell (i, j). If the symbol is equal to ".", then the corresponding cell is empty, otherwise it equals "*" and the corresponding cell is occupied by a wall. Output If it is impossible to wipe out all walls by placing and triggering exactly one bomb, then print "NO" in the first line (without quotes). Otherwise print "YES" (without quotes) in the first line and two integers in the second line β€” the coordinates of the cell at which the bomb should be laid. If there are multiple answers, print any of them. Examples Input 3 4 .*.. .... .*.. Output YES 1 2 Input 3 3 ..* .*. *.. Output NO Input 6 5 ..*.. ..*.. ***** ..*.. ..*.. ..*.. Output YES 3 3
import sys;input = sys.stdin.readline;print = sys.stdout.write def main(): n, m = map(int, input().split()) arr, have, dpx, dpy, cnt = [0]*n, set(), [0]*n, [0]*m, 0 for i in range(n): arr[i] = input().rstrip() for j in range(m): if arr[i][j] == "*": dpx[i], dpy[j], cnt = dpx[i] + 1, dpy[j] + 1, cnt + 1 for i in range(n): for j in range(m): if dpx[i] + dpy[j] - (arr[i][j] == "*") == cnt: print("YES\n{0} {1}".format(i + 1, j + 1)), exit(0) print("NO") main()
{ "input": [ "3 3\n..*\n.*.\n*..\n", "6 5\n..*..\n..*..\n*****\n..*..\n..*..\n..*..\n", "3 4\n.*..\n....\n.*..\n" ], "output": [ "NO\n", "YES\n3 3\n", "YES\n1 2\n" ] }
518
10
Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them. Vasya lays out nm cards as a rectangle n Γ— m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved. Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 Γ— 3, inside each of which all the cards either have the same suit, or pairwise different ranks. Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible. Input The first line contains integers n and m (3 ≀ n, m ≀ 17, n Γ— m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different. Output If the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: * "There are no jokers.", if there are no jokers in the input data. * "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. * "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly. On the third line print the coordinates of the upper left corner of the first square 3 Γ— 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 Γ— 3 in the format "Put the second square to (r, c).". If there are several solutions to that problem, print any of them. If there are no solutions, print of the single line "No solution." without the quotes. See the samples to understand the output format better. Examples Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H 5S TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output No solution. Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H J1 TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. Replace J1 with 2H. Put the first square to (1, 1). Put the second square to (2, 4). Input 4 6 2S 3S 4S 7S 8S AS 5H 6H 7H QC TC AC 8H 9H TH 7C 8C 9C 2D 2C 3C 4C 5C 6C Output Solution exists. There are no jokers. Put the first square to (1, 1). Put the second square to (2, 4). Note The pretests cover all the possible output formats.
ranks = '23456789TJQKA' suits = 'CDHS' n, m = [int(i) for i in input().split()] b = [input().split() for _ in range(n)] p = [r + s for r in ranks for s in suits] j1, j2 = False, False for r in b: for c in r: if c == 'J1': j1 = True elif c == 'J2': j2 = True else: p.remove(c) def valid(n, m): r = set() s = set() for ni in range(n, n + 3): for mi in range(m, m + 3): c = b[ni][mi] if c == 'J1': c = j1v if c == 'J2': c = j2v r.add(c[0]) s.add(c[1]) return len(r) == 9 or len(s) == 1 def solve(): global j1v, j2v, n0, m0, n1, m1 for j1v in p: for j2v in p: if j1v == j2v: continue for n0 in range(n-2): for m0 in range(m-2): if not valid(n0, m0): continue for n1 in range(n-2): for m1 in range(m-2): if (n0 + 2 < n1 or n1 + 2 < n0 or m0 + 2 < m1 or m1 + 2 < m0): if valid(n1, m1): return True return False if solve(): print('Solution exists.') if j1 and j2: print('Replace J1 with {} and J2 with {}.'.format(j1v, j2v)) elif j1: print('Replace J1 with {}.'.format(j1v)) elif j2: print('Replace J2 with {}.'.format(j2v)) else: print('There are no jokers.') print('Put the first square to ({}, {}).'.format(n0+1, m0+1)) print('Put the second square to ({}, {}).'.format(n1+1, m1+1)) else: print('No solution.')
{ "input": [ "4 6\n2S 3S 4S 7S 8S AS\n5H 6H 7H 5S TC AC\n8H 9H TH 7C 8C 9C\n2D 2C 3C 4C 5C 6C\n", "4 6\n2S 3S 4S 7S 8S AS\n5H 6H 7H QC TC AC\n8H 9H TH 7C 8C 9C\n2D 2C 3C 4C 5C 6C\n", "4 6\n2S 3S 4S 7S 8S AS\n5H 6H 7H J1 TC AC\n8H 9H TH 7C 8C 9C\n2D 2C 3C 4C 5C 6C\n" ], "output": [ "No solution.\n", "Solution exists.\nThere are no jokers.\nPut the first square to (1, 1).\nPut the second square to (2, 4).\n", "Solution exists.\nReplace J1 with 2H.\nPut the first square to (1, 1).\nPut the second square to (2, 4).\n" ] }
519
7
As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. <image> Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows. The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time. Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t β‰₯ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible. Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i). Input The first line of input contains integer n (1 ≀ n ≀ 100) β€” the number of people in Arpa's land. The second line contains n integers, i-th of them is crushi (1 ≀ crushi ≀ n) β€” the number of i-th person's crush. Output If there is no t satisfying the condition, print -1. Otherwise print such smallest t. Examples Input 4 2 3 1 4 Output 3 Input 4 4 4 4 4 Output -1 Input 4 2 1 4 3 Output 1 Note In the first sample suppose t = 3. If the first person starts some round: The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1. The process is similar for the second and the third person. If the fourth person starts some round: The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4. In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.
def gcd(a, b): return a if b == 0 else gcd(b, a % b) def lcm(a, b): return a * b // gcd(a, b) n = int(input()) c = [int(v)-1 for v in input().split(' ')] t = 1 for i in range(n): k = i for j in range(1, n+2): k = c[k] if k == i: break if j > n: print(-1) exit() t = lcm(t, j if j % 2 != 0 else j // 2) print(t) # Made By Mostafa_Khaled
{ "input": [ "4\n2 1 4 3\n", "4\n4 4 4 4\n", "4\n2 3 1 4\n" ], "output": [ "1\n", "-1\n", "3\n" ] }
520
11
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo m, or not. Arithmetical progression modulo m of length n with first element x and difference d is sequence of integers x, x + d, x + 2d, ..., x + (n - 1)Β·d, each taken modulo m. Input The first line contains two integers m and n (2 ≀ m ≀ 109 + 7, 1 ≀ n ≀ 105, m is prime) β€” Timofey's favorite prime module and the length of the sequence. The second line contains n distinct integers a1, a2, ..., an (0 ≀ ai < m) β€” the elements of the sequence. Output Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo m. Otherwise, print two integers β€” the first element of the obtained progression x (0 ≀ x < m) and its difference d (0 ≀ d < m). If there are multiple answers, print any of them. Examples Input 17 5 0 2 4 13 15 Output 13 2 Input 17 5 0 2 4 13 14 Output -1 Input 5 3 1 2 3 Output 3 4
from functools import reduce def gcd_extended(bigger, less): if less == 0: return(bigger, 1, 0) mod = bigger % less div = bigger // less gcd, c_less, c_mod = gcd_extended(less, mod) #gcd == c_less * less + c_mod * mod #mod == bigger - div * less #gcd = (c_less - c_mod * div) * less # + c_mod * bigger c_bigger = c_mod c_less = c_less - c_mod * div return(gcd, c_bigger, c_less) def mlp_inverse(x, p): one, c_p, c_x = gcd_extended(p, x) #one == c_x * x + c_p * p return (c_x + p) % p def tests(x, d, p, row): _row = set(row) n = len(row) if d == 0: return False for i in range(n): elem = x + i * d elem = (elem % p + p) % p if elem not in _row: return False return True p, n = (int(x) for x in input().split()) row = [int(x) for x in input().split()] if p == n: print(1, 1) exit() if n == 1: print(row[0], 0) exit() #precounting constants c1 = reduce(lambda x, y: (x + y) % p, row, 0) c2 = reduce(lambda x, y: (x + y * y) % p, row, 0) sum_i = reduce(lambda x, y: (x + y) % p, range(0, n), 0) sum_i_sq = reduce(lambda x, y: (x + y * y) % p, range(0, n), 0) inv_sum_i = mlp_inverse(sum_i, p) inv_sum_i_sq = mlp_inverse(sum_i_sq, p) #algorythm for x in row: # d = (c1 - n * x) * inv_sum_i d = (d % p + p) % p equasion = n * x * x + 2 * d * x * sum_i + d * d * sum_i_sq equasion = (equasion % p + p) % p # print(x, d) # print(c2, equasion) if (equasion == c2 and tests(x, d, p, row) ): print(x, d) exit() print(-1)
{ "input": [ "17 5\n0 2 4 13 15\n", "5 3\n1 2 3\n", "17 5\n0 2 4 13 14\n" ], "output": [ " 13 2\n", " 1 1\n", "-1\n" ] }
521
8
<image> It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in. There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously. For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed. Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened. Input Two integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26). In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest. Output Output Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise. You can output each letter in arbitrary case (upper or lower). Examples Input 5 1 AABBB Output NO Input 5 1 ABABB Output YES Note In the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened. In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door.
def main(): n, m = map(int, input().split()) s, l = input(), [] for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': i = s.find(c) if i != -1: l += (((i, -1), (s.rfind(c), 1))) for _, i in sorted(l): m += i if m < 0: print('YES') return print('NO') if __name__ == '__main__': main()
{ "input": [ "5 1\nAABBB\n", "5 1\nABABB\n" ], "output": [ "NO\n", "YES\n" ] }
522
9
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well. In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned. Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023. Input The first line contains an integer n (1 ≀ n ≀ 5Β·105) β€” the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≀ xi ≀ 1023. Output Output an integer k (0 ≀ k ≀ 5) β€” the length of your program. Next k lines must contain commands in the same format as in the input. Examples Input 3 | 3 ^ 2 | 1 Output 2 | 3 ^ 2 Input 3 &amp; 1 &amp; 3 &amp; 5 Output 1 &amp; 1 Input 3 ^ 1 ^ 2 ^ 3 Output 0 Note You can read about bitwise operations in <https://en.wikipedia.org/wiki/Bitwise_operation>. Second sample: Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.
def fun (n1,o,n2): if o=="|": return n1|n2 elif o=="&": return n1&n2 else: return n1^n2 def fun2(n): l=[0 for i in range(10)] for i in range(9,-1,-1): if 1<<i <=n: l[i]=1 n-=1<<i return l n=int(input()) a=0 b=1023 for i in range(n): o,n2=input().split() n2=int(n2) a=fun(a,o,n2) b=fun(b,o,n2) l1=fun2(a) l2=fun2(b) a=0 b=0 for i in range(10): if l1[i]==1 and l2[i]==1: a+=1<<i elif l1[i]==0 and l2[i]==0: a+=1<<i b+=1<<i elif l1[i]==1 and l2[i]==0: b+=1<<i print(2) print("|",a) print("^",b)
{ "input": [ "3\n&amp; 1\n&amp; 3\n&amp; 5\n", "3\n^ 1\n^ 2\n^ 3\n", "3\n| 3\n^ 2\n| 1\n" ], "output": [ "3\n& 0\n| 0\n^ 0\n", "3\n& 1023\n| 0\n^ 0\n", "3\n& 1021\n| 1\n^ 0\n" ] }
523
7
In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor. The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), …, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible. You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?" Input The first line contains five integers n, m, c_l, c_e, v (2 ≀ n, m ≀ 10^8, 0 ≀ c_l, c_e ≀ 10^5, 1 ≀ c_l + c_e ≀ m - 1, 1 ≀ v ≀ n - 1) β€” the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains c_l integers l_1, …, l_{c_l} in increasing order (1 ≀ l_i ≀ m), denoting the positions of the stairs. If c_l = 0, the second line is empty. The third line contains c_e integers e_1, …, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct. The fourth line contains a single integer q (1 ≀ q ≀ 10^5) β€” the number of queries. The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 ≀ x_1, x_2 ≀ n, 1 ≀ y_1, y_2 ≀ m) β€” the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. y_1 and y_2 are not among l_i and e_i. Output Print q integers, one per line β€” the answers for the queries. Example Input 5 6 1 1 3 2 5 3 1 1 5 6 1 3 5 4 3 3 5 3 Output 7 5 4 Note In the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit. In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.
from bisect import bisect_left input = __import__('sys').stdin.readline MIS = lambda: map(int,input().split()) def walk(x1, y1, x2, y2, L, v): if y1 == y2: return abs(x2-x1) dy = abs(y1-y2) vertical = dy // v if dy%v: vertical+= 1 i = bisect_left(L, x1) xs1 = L[i-1] if 0<=i-1<len(L) else float('inf') xs2 = L[i] if 0<=i<len(L) else float('inf') xs3 = L[i+1] if 0<=i+1<len(L) else float('inf') d = min(abs(x1-xs1)+abs(xs1-x2), abs(x1-xs2)+abs(xs2-x2), abs(x1-xs3)+abs(xs3-x2)) return d + vertical n, m, cs, ce, v = MIS() sta = list(MIS()) ele = list(MIS()) for TEST in range(int(input())): y1, x1, y2, x2 = MIS() if x1 > x2: x1, x2 = x2, x1 y1, y2 = y2, y1 print(min(walk(x1, y1, x2, y2, sta, 1), walk(x1, y1, x2, y2, ele, v)))
{ "input": [ "5 6 1 1 3\n2\n5\n3\n1 1 5 6\n1 3 5 4\n3 3 5 3\n" ], "output": [ "7\n5\n4\n" ] }
524
8
You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard. Initially, you have an empty string. Until you type the whole string, you may perform the following operation: * add a character to the end of the string. Besides, at most once you may perform one additional operation: copy the string and append it to itself. For example, if you have to type string abcabca, you can type it in 7 operations if you type all the characters one by one. However, you can type it in 5 operations if you type the string abc first and then copy it and type the last character. If you have to type string aaaaaaaaa, the best option is to type 4 characters one by one, then copy the string, and then type the remaining character. Print the minimum number of operations you need to type the given string. Input The first line of the input containing only one integer number n (1 ≀ n ≀ 100) β€” the length of the string you have to type. The second line containing the string s consisting of n lowercase Latin letters. Output Print one integer number β€” the minimum number of operations you need to type the given string. Examples Input 7 abcabca Output 5 Input 8 abcdefgh Output 8 Note The first test described in the problem statement. In the second test you can only type all the characters one by one.
def main(): n = int(input()) line = input() ans = 0 for i in range(50): if line[:i + 1] == line[i + 1:2 * (i + 1)]: ans = i print(n - ans) main()
{ "input": [ "8\nabcdefgh\n", "7\nabcabca\n" ], "output": [ "8\n", "5\n" ] }
525
7
A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. <image> You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts. Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them. Note that the final necklace should remain as one circular part of the same length as the initial necklace. Input The only line of input contains a string s (3 ≀ |s| ≀ 100), representing the necklace, where a dash '-' represents a link and the lowercase English letter 'o' represents a pearl. Output Print "YES" if the links and pearls can be rejoined such that the number of links between adjacent pearls is equal. Otherwise print "NO". You can print each letter in any case (upper or lower). Examples Input <span class="tex-font-style-tt">-o-o--</span> Output YES Input <span class="tex-font-style-tt">-o---</span> Output YES Input <span class="tex-font-style-tt">-o---o-</span> Output NO Input ooo Output YES
def go(): s = input() p = s.count('o') l = s.count('-') if p == 0: return 'YES' if l % p == 0: return 'YES' return 'NO' print(go())
{ "input": [ "<span class=\"tex-font-style-tt\">-o---o-</span>\n", "<span class=\"tex-font-style-tt\">-o-o--</span>", "ooo\n", "<span class=\"tex-font-style-tt\">-o---</span>\n" ], "output": [ "NO\n", "NO\n", "YES\n", "NO\n" ] }
526
7
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place. But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams. Yakko thrown a die and got Y points, Wakko β€” W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania. It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win. Input The only line of the input file contains two natural numbers Y and W β€” the results of Yakko's and Wakko's die rolls. Output Output the required probability in the form of irreducible fraction in format Β«A/BΒ», where A β€” the numerator, and B β€” the denominator. If the required probability equals to zero, output Β«0/1Β». If the required probability equals to 1, output Β«1/1Β». Examples Input 4 2 Output 1/2 Note Dot will go to Transylvania, if she is lucky to roll 4, 5 or 6 points.
from fractions import Fraction def main(): a = Fraction(7 - max(map(int, input().split())), 6) print(a if a != 1 else '1/1') main()
{ "input": [ "4 2\n" ], "output": [ "1/2\n" ] }
527
9
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are. Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows: Suppose we want to analyze the segment of n consecutive days. We have measured the temperatures during these n days; the temperature during i-th day equals a_i. We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day x to day y, we calculate it as \frac{βˆ‘ _{i = x}^{y} a_i}{y - x + 1} (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than k consecutive days. For example, if analyzing the measures [3, 4, 1, 2] and k = 3, we are interested in segments [3, 4, 1], [4, 1, 2] and [3, 4, 1, 2] (we want to find the maximum value of average temperature over these segments). You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task? Input The first line contains two integers n and k (1 ≀ k ≀ n ≀ 5000) β€” the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 5000) β€” the temperature measures during given n days. Output Print one real number β€” the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than k consecutive days. Your answer will be considered correct if the following condition holds: |res - res_0| < 10^{-6}, where res is your answer, and res_0 is the answer given by the jury's solution. Example Input 4 3 3 4 1 2 Output 2.666666666666667
def mp():return map(int,input().split()) def it():return int(input()) n,k=mp() l=list(mp()) ans=0 for i in range(n): avg,count=0,0 for j in range(i,n): count+=l[j] if j-i+1>=k: avg=count/(j-i+1) ans=max(avg,ans) print(ans)
{ "input": [ "4 3\n3 4 1 2\n" ], "output": [ "2.666666666666667" ] }
528
10
Medicine faculty of Berland State University has just finished their admission campaign. As usual, about 80\% of applicants are girls and majority of them are going to live in the university dormitory for the next 4 (hopefully) years. The dormitory consists of n rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number i costs c_i burles. Rooms are numbered from 1 to n. Mouse doesn't sit in place all the time, it constantly runs. If it is in room i in second t then it will run to room a_i in second t + 1 without visiting any other rooms inbetween (i = a_i means that mouse won't leave room i). It's second 0 in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap. That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from 1 to n at second 0. What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from? Input The first line contains as single integers n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of rooms in the dormitory. The second line contains n integers c_1, c_2, ..., c_n (1 ≀ c_i ≀ 10^4) β€” c_i is the cost of setting the trap in room number i. The third line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ n) β€” a_i is the room the mouse will run to the next second after being in room i. Output Print a single integer β€” the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from. Examples Input 5 1 2 3 2 10 1 3 4 3 3 Output 3 Input 4 1 10 2 10 2 4 2 2 Output 10 Input 7 1 1 1 1 1 1 1 2 2 2 3 6 7 6 Output 2 Note In the first example it is enough to set mouse trap in rooms 1 and 4. If mouse starts in room 1 then it gets caught immideately. If mouse starts in any other room then it eventually comes to room 4. In the second example it is enough to set mouse trap in room 2. If mouse starts in room 2 then it gets caught immideately. If mouse starts in any other room then it runs to room 2 in second 1. Here are the paths of the mouse from different starts from the third example: * 1 β†’ 2 β†’ 2 β†’ ...; * 2 β†’ 2 β†’ ...; * 3 β†’ 2 β†’ 2 β†’ ...; * 4 β†’ 3 β†’ 2 β†’ 2 β†’ ...; * 5 β†’ 6 β†’ 7 β†’ 6 β†’ ...; * 6 β†’ 7 β†’ 6 β†’ ...; * 7 β†’ 6 β†’ 7 β†’ ...; So it's enough to set traps in rooms 2 and 6.
def main(): n=int(input()) c=[int(i) for i in input().split()] a=[int(i) for i in input().split()] vis=[0]*(n+1) sum=0 for i in range(1,n+1): x=i while(vis[x]==0): vis[x]=i x=a[x-1] if vis[x]!=i: continue p=x cos=c[x-1] while(p!=a[x-1]): x=a[x-1] cos=min(c[x-1],cos) sum=sum+cos return sum print(main())
{ "input": [ "4\n1 10 2 10\n2 4 2 2\n", "5\n1 2 3 2 10\n1 3 4 3 3\n", "7\n1 1 1 1 1 1 1\n2 2 2 3 6 7 6\n" ], "output": [ "10", "3", "2" ] }
529
9
Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race. Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race. Input The first line contains two integer numbers N (1 ≀ N ≀ 200000) representing number of F1 astronauts, and current position of astronaut D (1 ≀ D ≀ N) you want to calculate best ranking for (no other competitor will have the same number of points before the race). The second line contains N integer numbers S_k (0 ≀ S_k ≀ 10^8, k=1...N), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order. The third line contains N integer numbers P_k (0 ≀ P_k ≀ 10^8, k=1...N), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points. Output Output contains one integer number β€” the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking. Example Input 4 3 50 30 20 10 15 10 7 3 Output 2 Note If the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position.
import sys def get_ints(): return map(int, sys.stdin.readline().strip().split()) n,d=get_ints() s=list(map(int,input().split())) p=list(map(int,input().split())) m=s.pop(d-1) a=p.pop(0)+m p.reverse() j=0 ans=-1 for i in range(n-1): if s[i]+p[j]>a: z=p.pop(-1) s[i]+=z else: s[i]+=p[j] j+=1 s.append(a) s.sort();s.reverse() #if ans==-1: ans=n print(s.index(a)+1)
{ "input": [ "4 3\n50 30 20 10\n15 10 7 3\n" ], "output": [ "2" ] }
530
8
Berkomnadzor β€” Federal Service for Supervision of Communications, Information Technology and Mass Media β€” is a Berland federal executive body that protects ordinary residents of Berland from the threats of modern internet. Berkomnadzor maintains a list of prohibited IPv4 subnets (blacklist) and a list of allowed IPv4 subnets (whitelist). All Internet Service Providers (ISPs) in Berland must configure the network equipment to block access to all IPv4 addresses matching the blacklist. Also ISPs must provide access (that is, do not block) to all IPv4 addresses matching the whitelist. If an IPv4 address does not match either of those lists, it's up to the ISP to decide whether to block it or not. An IPv4 address matches the blacklist (whitelist) if and only if it matches some subnet from the blacklist (whitelist). An IPv4 address can belong to a whitelist and to a blacklist at the same time, this situation leads to a contradiction (see no solution case in the output description). An IPv4 address is a 32-bit unsigned integer written in the form a.b.c.d, where each of the values a,b,c,d is called an octet and is an integer from 0 to 255 written in decimal notation. For example, IPv4 address 192.168.0.1 can be converted to a 32-bit number using the following expression 192 β‹… 2^{24} + 168 β‹… 2^{16} + 0 β‹… 2^8 + 1 β‹… 2^0. First octet a encodes the most significant (leftmost) 8 bits, the octets b and c β€” the following blocks of 8 bits (in this order), and the octet d encodes the least significant (rightmost) 8 bits. The IPv4 network in Berland is slightly different from the rest of the world. There are no reserved or internal addresses in Berland and use all 2^{32} possible values. An IPv4 subnet is represented either as a.b.c.d or as a.b.c.d/x (where 0 ≀ x ≀ 32). A subnet a.b.c.d contains a single address a.b.c.d. A subnet a.b.c.d/x contains all IPv4 addresses with x leftmost (most significant) bits equal to x leftmost bits of the address a.b.c.d. It is required that 32 - x rightmost (least significant) bits of subnet a.b.c.d/x are zeroes. Naturally it happens that all addresses matching subnet a.b.c.d/x form a continuous range. The range starts with address a.b.c.d (its rightmost 32 - x bits are zeroes). The range ends with address which x leftmost bits equal to x leftmost bits of address a.b.c.d, and its 32 - x rightmost bits are all ones. Subnet contains exactly 2^{32-x} addresses. Subnet a.b.c.d/32 contains exactly one address and can also be represented by just a.b.c.d. For example subnet 192.168.0.0/24 contains range of 256 addresses. 192.168.0.0 is the first address of the range, and 192.168.0.255 is the last one. Berkomnadzor's engineers have devised a plan to improve performance of Berland's global network. Instead of maintaining both whitelist and blacklist they want to build only a single optimised blacklist containing minimal number of subnets. The idea is to block all IPv4 addresses matching the optimised blacklist and allow all the rest addresses. Of course, IPv4 addresses from the old blacklist must remain blocked and all IPv4 addresses from the old whitelist must still be allowed. Those IPv4 addresses which matched neither the old blacklist nor the old whitelist may be either blocked or allowed regardless of their accessibility before. Please write a program which takes blacklist and whitelist as input and produces optimised blacklist. The optimised blacklist must contain the minimal possible number of subnets and satisfy all IPv4 addresses accessibility requirements mentioned above. IPv4 subnets in the source lists may intersect arbitrarily. Please output a single number -1 if some IPv4 address matches both source whitelist and blacklist. Input The first line of the input contains single integer n (1 ≀ n ≀ 2β‹…10^5) β€” total number of IPv4 subnets in the input. The following n lines contain IPv4 subnets. Each line starts with either '-' or '+' sign, which indicates if the subnet belongs to the blacklist or to the whitelist correspondingly. It is followed, without any spaces, by the IPv4 subnet in a.b.c.d or a.b.c.d/x format (0 ≀ x ≀ 32). The blacklist always contains at least one subnet. All of the IPv4 subnets given in the input are valid. Integer numbers do not start with extra leading zeroes. The provided IPv4 subnets can intersect arbitrarily. Output Output -1, if there is an IPv4 address that matches both the whitelist and the blacklist. Otherwise output t β€” the length of the optimised blacklist, followed by t subnets, with each subnet on a new line. Subnets may be printed in arbitrary order. All addresses matching the source blacklist must match the optimised blacklist. All addresses matching the source whitelist must not match the optimised blacklist. You can print a subnet a.b.c.d/32 in any of two ways: as a.b.c.d/32 or as a.b.c.d. If there is more than one solution, output any. Examples Input 1 -149.154.167.99 Output 1 0.0.0.0/0 Input 4 -149.154.167.99 +149.154.167.100/30 +149.154.167.128/25 -149.154.167.120/29 Output 2 149.154.167.99 149.154.167.120/29 Input 5 -127.0.0.4/31 +127.0.0.8 +127.0.0.0/30 -195.82.146.208/29 -127.0.0.6/31 Output 2 195.0.0.0/8 127.0.0.4/30 Input 2 +127.0.0.1/32 -127.0.0.1 Output -1
#!/usr/bin/env python3 # Copied solution import collections import sys import traceback class Input(object): def __init__(self): self.fh = sys.stdin def next_line(self): while True: line = sys.stdin.readline() if line == '\n': continue return line def next_line_ints(self): line = self.next_line() return [int(x) for x in line.split()] def next_line_strs(self): line = self.next_line() return line.split() class Node(object): def __init__(self, color, subtree_color): self.left = self.right = None self.color = color self.subtree_color = subtree_color def list_to_number(list): """Return (color, bits, number).""" color = 1 if list[0] == '-' else 2 values = list[1:].split('/') bits = 32 if len(values) == 2: bits = int(values[1]) nums = values[0].split('.') number = 0 for num in nums: number = number * 256 + int(num) return (color, bits, number) def add_list_to_tree(tree, list): color, bits, number = list_to_number(list) shift = 31 for _ in range(bits): tree.subtree_color |= color value = (number >> shift) & 1 if value == 0: if not tree.left: tree.left = Node(0, 0) tree = tree.left else: if not tree.right: tree.right = Node(0, 0) tree = tree.right shift -= 1 tree.subtree_color |= color tree.color |= color def check_tree(tree): if not tree: return True if tree.color == 3 or (tree.color and (tree.subtree_color & ~tree.color)): return False return check_tree(tree.left) and check_tree(tree.right) def number_to_list(number, bits): number <<= (32 - bits) values = [] for _ in range(4): #print('number = {}'.format(number)) values.append(str(number % 256)) number //= 256 values = values[::-1] return '.'.join(values) + '/' + str(bits) def get_optimized(tree, optimized, number, bits): if not tree or (tree.subtree_color & 1) == 0: return if tree.subtree_color == 1: list = number_to_list(number, bits) #print('number_to_list({}, {}) = {}'.format(number, bits, list)) optimized.append(list) return get_optimized(tree.left, optimized, number * 2, bits + 1) get_optimized(tree.right, optimized, number * 2 + 1, bits + 1) def get_optimized_lists(lists): tree = Node(0, 0) for list in lists: add_list_to_tree(tree, list) if not check_tree(tree): return None optimized = [] get_optimized(tree, optimized, 0, 0) return optimized def main(): input = Input() while True: try: nums = input.next_line_ints() if not nums: break n, = nums if n == -1: break lists = [] for _ in range(n): lists.append(input.next_line_strs()[0]) except: print('read input failed') try: optimized = get_optimized_lists(lists) if optimized is None: print("-1") else: print("{}".format(len(optimized))) for l in optimized: print("{}".format(l)) except: traceback.print_exc(file=sys.stdout) print('get_min_dist failed') main()
{ "input": [ "5\n-127.0.0.4/31\n+127.0.0.8\n+127.0.0.0/30\n-195.82.146.208/29\n-127.0.0.6/31\n", "4\n-149.154.167.99\n+149.154.167.100/30\n+149.154.167.128/25\n-149.154.167.120/29\n", "2\n+127.0.0.1/32\n-127.0.0.1\n", "1\n-149.154.167.99\n" ], "output": [ "2\n127.0.0.4/30\n128.0.0.0/1\n", "2\n149.154.167.96/30\n149.154.167.112/28\n", "-1", "1\n0.0.0.0/0\n" ] }
531
12
Bob is a duck. He wants to get to Alice's nest, so that those two can duck! <image> Duck is the ultimate animal! (Image courtesy of See Bang) The journey can be represented as a straight line, consisting of n segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last segment. Each segment has a length in meters, and also terrain type: grass, water or lava. Bob has three movement types: swimming, walking and flying. He can switch between them or change his direction at any point in time (even when he is located at a non-integer coordinate), and doing so doesn't require any extra time. Bob can swim only on the water, walk only on the grass and fly over any terrain. Flying one meter takes 1 second, swimming one meter takes 3 seconds, and finally walking one meter takes 5 seconds. Bob has a finite amount of energy, called stamina. Swimming and walking is relaxing for him, so he gains 1 stamina for every meter he walks or swims. On the other hand, flying is quite tiring, and he spends 1 stamina for every meter flown. Staying in place does not influence his stamina at all. Of course, his stamina can never become negative. Initially, his stamina is zero. What is the shortest possible time in which he can reach Alice's nest? Input The first line contains a single integer n (1 ≀ n ≀ 10^5) β€” the number of segments of terrain. The second line contains n integers l_1, l_2, ..., l_n (1 ≀ l_i ≀ 10^{12}). The l_i represents the length of the i-th terrain segment in meters. The third line contains a string s consisting of n characters "G", "W", "L", representing Grass, Water and Lava, respectively. It is guaranteed that the first segment is not Lava. Output Output a single integer t β€” the minimum time Bob needs to reach Alice. Examples Input 1 10 G Output 30 Input 2 10 10 WL Output 40 Input 2 1 2 WL Output 8 Input 3 10 10 10 GLW Output 80 Note In the first sample, Bob first walks 5 meters in 25 seconds. Then he flies the remaining 5 meters in 5 seconds. In the second sample, Bob first swims 10 meters in 30 seconds. Then he flies over the patch of lava for 10 seconds. In the third sample, the water pond is much smaller. Bob first swims over the water pond, taking him 3 seconds. However, he cannot fly over the lava just yet, as he only has one stamina while he needs two. So he swims back for half a meter, and then half a meter forward, taking him 3 seconds in total. Now he has 2 stamina, so he can spend 2 seconds flying over the lava. In the fourth sample, he walks for 50 seconds, flies for 10 seconds, swims for 15 seconds, and finally flies for 5 seconds.
def read(type = 1): if type: file = open("input.dat", "r") n = int(file.readline()) a = list(map(int, file.readline().split())) b = file.readline() file.close() else: n = int(input().strip()) a = list(map(int, input().strip().split())) b = input().strip() return n, a, b def solve(): sol = 0 e = 0 big = 0 g = 0 for i in range(n): if b[i] == "W": big = 1 sol += 3 * a[i] e += a[i] if b[i] == "G": sol += 5 * a[i] e += a[i] g += 2*a[i] if b[i] == "L": sol += a[i] e -= a[i] if e < 0: if big: sol -= 3 * e else: sol -= 5 * e e = 0 g = min(e,g) if e: sol -= 2*g sol -= (e-g) return int(sol) n, a, b = read(0) sol = solve() print(sol)
{ "input": [ "2\n1 2\nWL\n", "3\n10 10 10\nGLW\n", "2\n10 10\nWL\n", "1\n10\nG\n" ], "output": [ "8", "80", "40", "30" ] }
532
10
You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have n tiles in your hand. Each tile has an integer between 1 and m written on it. To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tiles are either all the same or consecutive. For example, 7, 7, 7 is a valid triple, and so is 12, 13, 14, but 2,2,3 or 2,4,6 are not. You can only use the tiles in your hand to form triples. Each tile can be used in at most one triple. To determine how close you are to the win, you want to know the maximum number of triples you can form from the tiles in your hand. Input The first line contains two integers integer n and m (1 ≀ n, m ≀ 10^6) β€” the number of tiles in your hand and the number of tiles types. The second line contains integers a_1, a_2, …, a_n (1 ≀ a_i ≀ m), where a_i denotes the number written on the i-th tile. Output Print one integer: the maximum number of triples you can form. Examples Input 10 6 2 3 3 3 4 4 4 5 5 6 Output 3 Input 12 6 1 5 3 3 3 4 3 5 3 2 3 3 Output 3 Input 13 5 1 1 5 1 2 3 3 2 4 2 3 4 5 Output 4 Note In the first example, we have tiles 2, 3, 3, 3, 4, 4, 4, 5, 5, 6. We can form three triples in the following way: 2, 3, 4; 3, 4, 5; 4, 5, 6. Since there are only 10 tiles, there is no way we could form 4 triples, so the answer is 3. In the second example, we have tiles 1, 2, 3 (7 times), 4, 5 (2 times). We can form 3 triples as follows: 1, 2, 3; 3, 3, 3; 3, 4, 5. One can show that forming 4 triples is not possible.
import sys class Reader: def __init__(self): self.in_strs = list(reversed(sys.stdin.read().split())) def read_int(self): out = self.in_strs.pop() return int(out) def main(): r = Reader() cc = r.read_int() n = r.read_int() a = [0 for i in range(n)] for i in range(cc): a[r.read_int() - 1] += 1 dp = [[0 for j in range(3)] for i in range(3)] for c in a: new_dp = [[0 for j in range(3)] for i in range(3)] for x in range(3): for y in range(3): for z in range(3): if x + y + z <= c: new_dp[y][z] = max([new_dp[y][z], dp[x][y] + z + (c - x - y - z) // 3]) new_dp, dp = dp, new_dp print(dp[0][0]) if __name__ == "__main__": main()
{ "input": [ "10 6\n2 3 3 3 4 4 4 5 5 6\n", "13 5\n1 1 5 1 2 3 3 2 4 2 3 4 5\n", "12 6\n1 5 3 3 3 4 3 5 3 2 3 3\n" ], "output": [ "3\n", "4\n", "3\n" ] }
533
7
Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i β‰₯ i). Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page i such that Ivan already has read it, but hasn't read page a_i). After that, he closes the book and continues to read it on the following day from the next page. How many days will it take to read the whole book? Input The first line contains single integer n (1 ≀ n ≀ 10^4) β€” the number of pages in the book. The second line contains n integers a_1, a_2, ..., a_n (i ≀ a_i ≀ n), where a_i is the number of page which contains the explanation of the mystery on page i. Output Print one integer β€” the number of days it will take to read the whole book. Example Input 9 1 3 3 6 7 6 8 8 9 Output 4 Note Explanation of the example test: During the first day Ivan will read only the first page. During the second day Ivan will read pages number 2 and 3. During the third day β€” pages 4-8. During the fourth (and the last) day Ivan will read remaining page number 9.
input() l=list(map(int,input().split())) d=0 def read(): global d for i in range(len(l)): if max(l[0:i+1])==i+1: d+=1 read() print(d)
{ "input": [ "9\n1 3 3 6 7 6 8 8 9\n" ], "output": [ "4\n" ] }
534
10
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle. After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task. In this task you are given a cell field n β‹… m, consisting of n rows and m columns, where point's coordinates (x, y) mean it is situated in the x-th row and y-th column, considering numeration from one (1 ≀ x ≀ n, 1 ≀ y ≀ m). Initially, you stand in the cell (1, 1). Every move you can jump from cell (x, y), which you stand in, by any non-zero vector (dx, dy), thus you will stand in the (x+dx, y+dy) cell. Obviously, you can't leave the field, but also there is one more important condition β€” you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited). Tolik's uncle is a very respectful person. Help him to solve this task! Input The first and only line contains two positive integers n, m (1 ≀ n β‹… m ≀ 10^{6}) β€” the number of rows and columns of the field respectively. Output Print "-1" (without quotes) if it is impossible to visit every cell exactly once. Else print n β‹… m pairs of integers, i-th from them should contain two integers x_i, y_i (1 ≀ x_i ≀ n, 1 ≀ y_i ≀ m) β€” cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have (1, 1) coordinates, according to the statement. Examples Input 2 3 Output 1 1 1 3 1 2 2 2 2 3 2 1 Input 1 1 Output 1 1 Note The vectors from the first example in the order of making jumps are (0, 2), (0, -1), (1, 0), (0, 1), (0, -2).
from sys import stdout as so n, m = [int(x) for x in input().split()] def printa(x1, x2): so.write(str(x1) + " " + str(x2) + "\n") mn = 1 mx = n while mn < mx: for i in range(1, m+1): printa(mn, i) printa(mx, m-i+1) mn += 1 mx -= 1 if mn == mx: for i in range(1, m//2+1): printa(mn, i) printa(mn, m-i+1) if m%2 == 1: printa(mn, m//2+1)
{ "input": [ "1 1\n", "2 3\n" ], "output": [ "1 1\n", "1 1\n2 3\n1 2\n2 2\n1 3\n2 1\n" ] }
535
10
There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have. Sometimes the government makes payouts to the poor: all citizens who have strictly less money than x are paid accordingly so that after the payout they have exactly x money. In this case the citizens don't send a receipt. You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^{5}) β€” the numer of citizens. The next line contains n integers a_1, a_2, ..., a_n (0 ≀ a_{i} ≀ 10^{9}) β€” the initial balances of citizens. The next line contains a single integer q (1 ≀ q ≀ 2 β‹… 10^{5}) β€” the number of events. Each of the next q lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x (1 ≀ p ≀ n, 0 ≀ x ≀ 10^{9}), or 2 x (0 ≀ x ≀ 10^{9}). In the first case we have a receipt that the balance of the p-th person becomes equal to x. In the second case we have a payoff with parameter x. Output Print n integers β€” the balances of all citizens after all events. Examples Input 4 1 2 3 4 3 2 3 1 2 2 2 1 Output 3 2 3 4 Input 5 3 50 2 1 10 3 1 2 0 2 8 1 3 20 Output 8 8 20 8 10 Note In the first example the balances change as follows: 1 2 3 4 β†’ 3 3 3 4 β†’ 3 2 3 4 β†’ 3 2 3 4 In the second example the balances change as follows: 3 50 2 1 10 β†’ 3 0 2 1 10 β†’ 8 8 8 8 10 β†’ 8 8 20 8 10
""" Code of Ayush Tiwari Codeforces: servermonk Codechef: ayush572000 """ import sys input = sys.stdin.buffer.readline def solution(): n=int(input()) l=list(map(int,input().split())) m=-1 a=[-1]*n q=[] for _ in range(int(input())): t=list(map(int,input().split())) q.append(t) for t in q[::-1]: if t[0]==1 and a[t[1]-1]==-1: a[t[1]-1]=max(t[2],m) if t[0]==2: m=max(t[1],m) for i in range(n): if a[i]==-1: a[i]=max(l[i],m) print(*a) solution()
{ "input": [ "5\n3 50 2 1 10\n3\n1 2 0\n2 8\n1 3 20\n", "4\n1 2 3 4\n3\n2 3\n1 2 2\n2 1\n" ], "output": [ "8 8 20 8 10\n", "3 2 3 4\n" ] }
536
9
There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bottom left corner of the white sheet has coordinates (x_1, y_1), and the top right β€” (x_2, y_2). After that two black sheets of paper are placed on the table. Sides of both black sheets are also parallel to the sides of the table. Coordinates of the bottom left corner of the first black sheet are (x_3, y_3), and the top right β€” (x_4, y_4). Coordinates of the bottom left corner of the second black sheet are (x_5, y_5), and the top right β€” (x_6, y_6). <image> Example of three rectangles. Determine if some part of the white sheet can be seen from the above after the two black sheets are placed. The part of the white sheet can be seen if there is at least one point lying not strictly inside the white sheet and strictly outside of both black sheets. Input The first line of the input contains four integers x_1, y_1, x_2, y_2 (0 ≀ x_1 < x_2 ≀ 10^{6}, 0 ≀ y_1 < y_2 ≀ 10^{6}) β€” coordinates of the bottom left and the top right corners of the white sheet. The second line of the input contains four integers x_3, y_3, x_4, y_4 (0 ≀ x_3 < x_4 ≀ 10^{6}, 0 ≀ y_3 < y_4 ≀ 10^{6}) β€” coordinates of the bottom left and the top right corners of the first black sheet. The third line of the input contains four integers x_5, y_5, x_6, y_6 (0 ≀ x_5 < x_6 ≀ 10^{6}, 0 ≀ y_5 < y_6 ≀ 10^{6}) β€” coordinates of the bottom left and the top right corners of the second black sheet. The sides of each sheet of paper are parallel (perpendicular) to the coordinate axes. Output If some part of the white sheet can be seen from the above after the two black sheets are placed, print "YES" (without quotes). Otherwise print "NO". Examples Input 2 2 4 4 1 1 3 5 3 1 5 5 Output NO Input 3 3 7 5 0 0 4 6 0 0 7 4 Output YES Input 5 2 10 5 3 1 7 6 8 1 11 7 Output YES Input 0 0 1000000 1000000 0 0 499999 1000000 500000 0 1000000 1000000 Output YES Note In the first example the white sheet is fully covered by black sheets. In the second example the part of the white sheet can be seen after two black sheets are placed. For example, the point (6.5, 4.5) lies not strictly inside the white sheet and lies strictly outside of both black sheets.
def R():x,y,*u=map(int,input().split());return[-x,-y]+u x=lambda a,b:[*map(min,a,b)] s=lambda x,y,u,v:max(0,x+u)*max(0,y+v) a,b,c=R(),R(),R() d=x(a,b) print('YNEOS'[s(*a)==s(*d)+s(*x(a,c))-s(*x(d,c))::2])
{ "input": [ "0 0 1000000 1000000\n0 0 499999 1000000\n500000 0 1000000 1000000\n", "3 3 7 5\n0 0 4 6\n0 0 7 4\n", "5 2 10 5\n3 1 7 6\n8 1 11 7\n", "2 2 4 4\n1 1 3 5\n3 1 5 5\n" ], "output": [ "YES\n", "YES\n", "YES\n", "NO\n" ] }
537
12
Let's call two numbers similar if their binary representations contain the same number of digits equal to 1. For example: * 2 and 4 are similar (binary representations are 10 and 100); * 1337 and 4213 are similar (binary representations are 10100111001 and 1000001110101); * 3 and 2 are not similar (binary representations are 11 and 10); * 42 and 13 are similar (binary representations are 101010 and 1101). You are given an array of n integers a_1, a_2, ..., a_n. You may choose a non-negative integer x, and then get another array of n integers b_1, b_2, ..., b_n, where b_i = a_i βŠ• x (βŠ• denotes bitwise XOR). Is it possible to obtain an array b where all numbers are similar to each other? Input The first line contains one integer n (2 ≀ n ≀ 100). The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2^{30} - 1). Output If it is impossible to choose x so that all elements in the resulting array are similar to each other, print one integer -1. Otherwise, print any non-negative integer not exceeding 2^{30} - 1 that can be used as x so that all elements in the resulting array are similar. Examples Input 2 7 2 Output 1 Input 4 3 17 6 0 Output 5 Input 3 1 2 3 Output -1 Input 3 43 12 12 Output 1073709057
H = 15 n = int(input()) a = list(map(int, input().split())) def pc(v): v = v - ((v >> 1) & 0x55555555) v = (v & 0x33333333) + ((v >> 2) & 0x33333333) return (((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) & 0xFFFFFFFF) >> 24 mask = (1 << H) - 1 rec = {} for x in range(1 << H): r = [pc((ai & mask) ^ x) for ai in a] d = tuple(r[-1] - ri for ri in r[:-1]) rec.setdefault(d, x) ans = None mask = ((1 << H) - 1) << H for x in range(1 << H): x <<= H r = [pc((ai & mask) ^ x) for ai in a] y = rec.get(tuple(ri - r[-1] for ri in r[:-1]), None) if y is not None: ans = x | y break print(-1 if ans is None else ans)
{ "input": [ "4\n3 17 6 0\n", "3\n1 2 3\n", "2\n7 2\n", "3\n43 12 12\n" ], "output": [ "5\n", "-1", "1\n", "1\n" ] }
538
7
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms. Let us tell you how it works. * If a sentence ends with "po" the language is Filipino. * If a sentence ends with "desu" or "masu" the language is Japanese. * If a sentence ends with "mnida" the language is Korean. Given this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean. Oh, did I say three suffixes? I meant four. Input The first line of input contains a single integer t (1 ≀ t ≀ 30) denoting the number of test cases. The next lines contain descriptions of the test cases. Each test case consists of a single line containing a single string denoting the sentence. Spaces are represented as underscores (the symbol "_") for ease of reading. The sentence has at least 1 and at most 1000 characters, and consists only of lowercase English letters and underscores. The sentence has no leading or trailing underscores and no two consecutive underscores. It is guaranteed that the sentence ends with one of the four suffixes mentioned above. Output For each test case, print a single line containing either "FILIPINO", "JAPANESE", or "KOREAN" (all in uppercase, without quotes), depending on the detected language. Example Input 8 kamusta_po genki_desu ohayou_gozaimasu annyeong_hashimnida hajime_no_ippo bensamu_no_sentou_houhou_ga_okama_kenpo ang_halaman_doon_ay_sarisari_singkamasu si_roy_mustang_ay_namamasu Output FILIPINO JAPANESE JAPANESE KOREAN FILIPINO FILIPINO JAPANESE JAPANESE Note The first sentence ends with "po", so it is written in Filipino. The second and third sentences end with "desu" and "masu", so they are written in Japanese. The fourth sentence ends with "mnida", so it is written in Korean.
def main(): n = int(input()) for _ in range(n): print({"o": "FILIPINO", "u": "JAPANESE", "a": "KOREAN"}[input()[-1]]) main()
{ "input": [ "8\nkamusta_po\ngenki_desu\nohayou_gozaimasu\nannyeong_hashimnida\nhajime_no_ippo\nbensamu_no_sentou_houhou_ga_okama_kenpo\nang_halaman_doon_ay_sarisari_singkamasu\nsi_roy_mustang_ay_namamasu\n" ], "output": [ "FILIPINO\nJAPANESE\nJAPANESE\nKOREAN\nFILIPINO\nFILIPINO\nJAPANESE\nJAPANESE\n" ] }
539
7
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i. For every i (1 ≀ i ≀ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly n swap operations, each of them either c_i ↔ a_i or c_i ↔ b_i (i iterates over all integers between 1 and n, inclusive). For example, if a is "code", b is "true", and c is "help", you can make c equal to "crue" taking the 1-st and the 4-th letters from a and the others from b. In this way a becomes "hodp" and b becomes "tele". Is it possible that after these swaps the string a becomes exactly the same as the string b? Input The input consists of multiple test cases. The first line contains a single integer t (1 ≀ 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 a. The second line of each test case contains a string of lowercase English letters b. The third line of each test case contains a string of lowercase English letters c. It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100. Output Print t lines with answers for all test cases. For each test case: If it is possible to make string a equal to string b print "YES" (without quotes), otherwise print "NO" (without quotes). You can print either lowercase or uppercase letters in the answers. Example Input 4 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim Output NO YES YES NO Note In the first test case, it is impossible to do the swaps so that string a becomes exactly the same as string b. In the second test case, you should swap c_i with a_i for all possible i. After the swaps a becomes "bca", b becomes "bca" and c becomes "abc". Here the strings a and b are equal. In the third test case, you should swap c_1 with a_1, c_2 with b_2, c_3 with b_3 and c_4 with a_4. Then string a becomes "baba", string b becomes "baba" and string c becomes "abab". Here the strings a and b are equal. In the fourth test case, it is impossible to do the swaps so that string a becomes exactly the same as string b.
def solve(): a=input() b=input() c=input() n=len(a) for x in range(n): if a[x]!=c[x] and b[x]!=c[x]: return "NO" return "YES" t=int(input()) for i in range(t): print(solve())
{ "input": [ "4\naaa\nbbb\nccc\nabc\nbca\nbca\naabb\nbbaa\nbaba\nimi\nmii\niim\n" ], "output": [ "NO\nYES\nYES\nNO\n" ] }
540
7
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If there are several such pairs (a, b), you can output any of them. Input The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of testcases. Each testcase consists of one line containing a single integer, x (2 ≀ x ≀ 10^9). Output For each testcase, output a pair of positive integers a and b (1 ≀ a, b ≀ 10^9) such that GCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a, b), you can output any of them. Example Input 2 2 14 Output 1 1 6 4 Note In the first testcase of the sample, GCD(1,1)+LCM(1,1)=1+1=2. In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14.
def main(): for i in range(int(input())): print(1, int(input())-1) main()
{ "input": [ "2\n2\n14\n" ], "output": [ "1 1\n1 13\n" ] }
541
12
We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≀ n ≀ 200) β€” the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≀ k_i ≀ n) β€” the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (βˆ‘ n ≀ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≀ p_i ≀ n, all p_i should be distinct) β€” any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
import copy t = int(input()) def fn(ivs, v, n): result = list() while len(result) < n - 1: w = None for iv in ivs: if v in iv: iv.remove(v) if len(iv) == 1: if w is None: w = iv.pop() else: return if w is None: return result.append(v) v = w result.append(v) return result def check(res, sivs, n): if res is None: return False for i in range(1, n): good = False for j in range(i): if tuple(sorted(res[j:i + 1])) in sivs: good = True if not good: return False return True for _ in range(t): n = int(input()) ivs = list() for _ in range(n - 1): ivs.append(set(map(int, input().split(' ')[1:]))) sivs = set() for iv in ivs: sivs.add(tuple(iv)) for v in range(1, n + 1): res = fn(copy.deepcopy(ivs), v, n) if check(res, sivs, n): print(' '.join(map(str, res))) break
{ "input": [ "5\n6\n3 2 5 6\n2 4 6\n3 1 3 4\n2 1 3\n4 1 2 4 6\n5\n2 2 3\n2 1 2\n2 1 4\n2 4 5\n7\n3 1 2 6\n4 1 3 5 6\n2 1 2\n3 4 5 7\n6 1 2 3 4 5 6\n3 1 3 6\n2\n2 1 2\n5\n2 2 5\n3 2 3 5\n4 2 3 4 5\n5 1 2 3 4 5\n" ], "output": [ "3 1 4 6 2 5 \n3 2 1 4 5 \n2 1 6 3 5 4 7 \n1 2 \n2 5 3 4 1 \n" ] }
542
11
Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan. There are n cities in the republic, some of them are connected by m directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary directed graph. Egor will arrive to the city 1, travel to the city n by roads along some path, give a concert and fly away. As any famous artist, Egor has lots of haters and too annoying fans, so he can travel only by safe roads. There are two types of the roads in Dagestan, black and white: black roads are safe at night only, and white roads β€” in the morning. Before the trip Egor's manager's going to make a schedule: for each city he'll specify it's color, black or white, and then if during the trip they visit some city, the only time they can leave it is determined by the city's color: night, if it's black, and morning, if it's white. After creating the schedule Egor chooses an available path from 1 to n, and for security reasons it has to be the shortest possible. Egor's manager likes Dagestan very much and wants to stay here as long as possible, so he asks you to make such schedule that there would be no path from 1 to n or the shortest path's length would be greatest possible. A path is one city or a sequence of roads such that for every road (excluding the first one) the city this road goes from is equal to the city previous road goes into. Egor can move only along paths consisting of safe roads only. The path length is equal to the number of roads in it. The shortest path in a graph is a path with smallest length. Input The first line contains two integers n, m (1 ≀ n ≀ 500000, 0 ≀ m ≀ 500000) β€” the number of cities and the number of roads. The i-th of next m lines contains three integers β€” u_i, v_i and t_i (1 ≀ u_i, v_i ≀ n, t_i ∈ \{0, 1\}) β€” numbers of cities connected by road and its type, respectively (0 β€” night road, 1 β€” morning road). Output In the first line output the length of the desired path (or -1, if it's possible to choose such schedule that there's no path from 1 to n). In the second line output the desired schedule β€” a string of n digits, where i-th digit is 0, if the i-th city is a night one, and 1 if it's a morning one. If there are multiple answers, print any. Examples Input 3 4 1 2 0 1 3 1 2 3 0 2 3 1 Output 2 011 Input 4 8 1 1 0 1 3 0 1 3 1 3 2 0 2 1 0 3 4 1 2 4 0 2 4 1 Output 3 1101 Input 5 10 1 2 0 1 3 1 1 4 0 2 3 0 2 3 1 2 5 0 3 4 0 3 4 1 4 2 1 4 5 0 Output -1 11111 Note For the first sample, if we paint city 1 white, the shortest path is 1 β†’ 3. Otherwise, it's 1 β†’ 2 β†’ 3 regardless of other cities' colors. For the second sample, we should paint city 3 black, and there are both black and white roads going from 2 to 4. Note that there can be a road connecting a city with itself.
import sys from math import ceil, gcd from collections import deque input = sys.stdin.buffer.readline # def print(val): # sys.stdout.write(str(val) + '\n') n, m = [int(i) for i in input().split()] adj = [[] for i in range(n+1)] mark = [0] * (n+1) d = [-1] * (n+1) c = [-1] * (n+1) for i in range(m): u, v, b = [int(i) for i in input().split()] adj[v].append((u,b)) q = deque() q.append(n) d[n] = 0 mark[n] = 1 while q: f = q.popleft() for i in adj[f]: if mark[i[0]] == 0: if c[i[0]] == -1: if i[1] == 1: c[i[0]] = 0 else: c[i[0]] = 1 elif c[i[0]] == i[1]: d[i[0]] = d[f]+1 q.append(i[0]) mark[i[0]] = 1 sys.stdout.write(str(d[1])) sys.stdout.write('\n') for i in range(1, n+1): if c[i] == -1: sys.stdout.write(str(1)) else: sys.stdout.write(str(c[i])) sys.stdout.write('\n')
{ "input": [ "3 4\n1 2 0\n1 3 1\n2 3 0\n2 3 1\n", "5 10\n1 2 0\n1 3 1\n1 4 0\n2 3 0\n2 3 1\n2 5 0\n3 4 0\n3 4 1\n4 2 1\n4 5 0\n", "4 8\n1 1 0\n1 3 0\n1 3 1\n3 2 0\n2 1 0\n3 4 1\n2 4 0\n2 4 1\n" ], "output": [ "2\n010\n", "-1\n01010", "3\n1100" ] }
543
9
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated. For example, Zookeeper can use two such operations: AABABBA β†’ AABBA β†’ AAA. Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string? Input Each test contains multiple test cases. The first line contains a single integer t (1 ≀ t ≀ 20000) β€” the number of test cases. The description of the test cases follows. Each of the next t lines contains a single test case each, consisting of a non-empty string s: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of s are either 'A' or 'B'. It is guaranteed that the sum of |s| (length of s) among all test cases does not exceed 2 β‹… 10^5. Output For each test case, print a single integer: the length of the shortest string that Zookeeper can make. Example Input 3 AAA BABA AABBBABBBB Output 3 2 0 Note For the first test case, you can't make any moves, so the answer is 3. For the second test case, one optimal sequence of moves is BABA β†’ BA. So, the answer is 2. For the third test case, one optimal sequence of moves is AABBBABBBB β†’ AABBBABB β†’ AABBBB β†’ ABBB β†’ AB β†’ (empty string). So, the answer is 0.
def ab(): s = input() c=0 for i in s: if (i=='B' and c!=0): c-=1 else: c+=1 print(c) t = int(input()) for i in range(t): ab()
{ "input": [ "3\nAAA\nBABA\nAABBBABBBB\n" ], "output": [ "3\n2\n0\n" ] }
544
9
Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters. He wants to convert string a into string b by performing some (possibly zero) operations on a. In one move, he can either * choose an index i (1 ≀ i≀ n-1) and swap a_i and a_{i+1}, or * choose an index i (1 ≀ i ≀ n-k+1) and if a_i, a_{i+1}, …, a_{i+k-1} are all equal to some character c (c β‰  'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it. Input The first line contains a single integer t (1 ≀ t ≀ 10^5) β€” the number of test cases. The description of each test case is as follows. The first line of each test case contains two integers n (2 ≀ n ≀ 10^6) and k (1 ≀ k ≀ n). The second line of each test case contains the string a of length n consisting of lowercase English letters. The third line of each test case contains the string b of length n consisting of lowercase English letters. It is guaranteed that the sum of values n among all test cases does not exceed 10^6. Output For each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No". You may print the letters of the answer in any case (upper or lower). Example Input 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes Note In the first test case it can be shown that it is impossible to convert a into b. In the second test case, "abba" \xrightarrow{inc} "acca" \xrightarrow{inc} … \xrightarrow{inc} "azza". Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type. In the fourth test case, "aaabba" \xrightarrow{swap} "aaabab" \xrightarrow{swap} "aaaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddaabb" \xrightarrow{inc} … \xrightarrow{inc} "ddddbb" \xrightarrow{inc} … \xrightarrow{inc} "ddddcc".
def fun(A,B,n,k): temp = [0]*26 t = ord("a") for i in range(n): temp[ord(A[i])-t] -= 1 temp[ord(B[i])-t] += 1 cu = 0 for i in range(26): if temp[i] == 0: continue else: if abs(temp[i])%k != 0: print("NO") return if temp[i]>0: if cu<temp[i]: print("NO") return else: cu -= temp[i] else: cu += abs(temp[i]) print("YES") for _ in range(int(input())): n,k = map(int,input().split()) a = input() b = input() fun(a,b,n,k)
{ "input": [ "4\n3 3\nabc\nbcd\n4 2\nabba\nazza\n2 1\nzz\naa\n6 2\naaabba\nddddcc\n" ], "output": [ "\nNo\nYes\nNo\nYes\n" ] }
545
9
At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls. Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not all girls are ready to dance in pairs. Formally, you know k possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair. For example, if a=3, b=4, k=4 and the couples (1, 2), (1, 3), (2, 2), (3, 4) are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): * (1, 3) and (2, 2); * (3, 4) and (1, 3); But the following combinations are not possible: * (1, 3) and (1, 2) β€” the first boy enters two pairs; * (1, 2) and (2, 2) β€” the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs. Input The first line contains one integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. Then t test cases follow. The first line of each test case contains three integers a, b and k (1 ≀ a, b, k ≀ 2 β‹… 10^5) β€” the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains k integers a_1, a_2, … a_k. (1 ≀ a_i ≀ a), where a_i is the number of the boy in the pair with the number i. The third line of each test case contains k integers b_1, b_2, … b_k. (1 ≀ b_i ≀ b), where b_i is the number of the girl in the pair with the number i. It is guaranteed that the sums of a, b, and k over all test cases do not exceed 2 β‹… 10^5. It is guaranteed that each pair is specified at most once in one test case. Output For each test case, on a separate line print one integer β€” the number of ways to choose two pairs that match the condition above. Example Input 3 3 4 4 1 1 2 3 2 3 2 4 1 1 1 1 1 2 2 4 1 1 2 2 1 2 1 2 Output 4 0 2 Note In the first test case, the following combinations of pairs fit: * (1, 2) and (3, 4); * (1, 3) and (2, 2); * (1, 3) and (3, 4); * (2, 2) and (3, 4). There is only one pair in the second test case. In the third test case, the following combinations of pairs fit: * (1, 1) and (2, 2); * (1, 2) and (2, 1).
def lkp(l): r = {} for e in l: if e in r: r[e] += 1 else: r[e] = 1 return r for _ in range(int(input())): a,b,k = map(int,input().split()) la = list(map(int, input().split())) lb = list(map(int, input().split())) la_look = lkp(la) lb_look = lkp(lb) ans = 0 for ea,eb in zip(la,lb): ans += k-la_look[ea]-lb_look[eb]+1 print(ans//2)
{ "input": [ "3\n3 4 4\n1 1 2 3\n2 3 2 4\n1 1 1\n1\n1\n2 2 4\n1 1 2 2\n1 2 1 2\n" ], "output": [ "\n4\n0\n2\n" ] }
546
7
It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≀ n ≀ 200 000) β€” the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2.5 β‹… 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≀ x, y, z, w ≀ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
def path(arr): d={} for i in range(len(arr)): for j in range(i): if d.get(arr[i]+arr[j],None)!=None: ii,jj=d[arr[i]+arr[j]] if len(set([ii,jj,i,j]))==4: print("YES") print(ii+1,jj+1,i+1,j+1) return "" d[arr[i]+arr[j]]=(i,j) return "NO" a=input() lst=list(map(int,input().strip().split())) print(path(lst))
{ "input": [ "5\n1 3 1 9 20\n", "6\n2 1 5 2 7 4\n" ], "output": [ "\nNO", "\nYES\n2 3 1 6 " ] }
547
9
There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m. The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate. Whenever a robot reaches a wall, it turns around instantly and continues his ride in the opposite direction with the same speed. Whenever several robots meet at the same integer coordinate, they collide and explode into dust. Once a robot has exploded, it doesn't collide with any other robot. Note that if several robots meet at a non-integer coordinate, nothing happens. For each robot find out if it ever explodes and print the time of explosion if it happens and -1 otherwise. Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. Then the descriptions of t testcases follow. The first line of each testcase contains two integers n and m (1 ≀ n ≀ 3 β‹… 10^5; 2 ≀ m ≀ 10^8) β€” the number of robots and the coordinate of the right wall. The second line of each testcase contains n integers x_1, x_2, ..., x_n (0 < x_i < m) β€” the starting coordinates of the robots. The third line of each testcase contains n space-separated characters 'L' or 'R' β€” the starting directions of the robots ('L' stands for left and 'R' stands for right). All coordinates x_i in the testcase are distinct. The sum of n over all testcases doesn't exceed 3 β‹… 10^5. Output For each testcase print n integers β€” for the i-th robot output the time it explodes at if it does and -1 otherwise. Example Input 5 7 12 1 2 3 4 9 10 11 R R L L R R R 2 10 1 6 R R 2 10 1 3 L L 1 10 5 R 7 8 6 1 7 2 3 5 4 R L R L L L L Output 1 1 1 1 2 -1 2 -1 -1 2 2 -1 -1 2 7 3 2 7 3 Note Here is the picture for the seconds 0, 1, 2 and 3 of the first testcase: <image> Notice that robots 2 and 3 don't collide because they meet at the same point 2.5, which is not integer. After second 3 robot 6 just drive infinitely because there's no robot to collide with.
def solve(robots, m, ans): robots.sort();stack = [] for x, dire, i in robots: if dire=='L': if not stack:stack.append((i, -x)) else:i2, x2 = stack[-1];ans[i] = ans[i2] = (x-x2)//2;stack.pop() else:stack.append((i,x)) while len(stack) >= 2:i1, x1 = stack[-1];stack.pop();x1 = m + (m-x1);i2, x2 = stack[-1];stack.pop();ans[i1] = ans[i2] = (x1-x2)//2 for _ in range(int(input())): n, m = map(int,input().split());info = list(zip(map(int,input().split()),input().split()));robots = [[],[]] for i in range(n):x, dire = info[i];robots[x&1].append((x, dire, i)) ans = [-1 for i in range(n)];solve(robots[0], m, ans);solve(robots[1], m, ans);print(*ans)
{ "input": [ "5\n7 12\n1 2 3 4 9 10 11\nR R L L R R R\n2 10\n1 6\nR R\n2 10\n1 3\nL L\n1 10\n5\nR\n7 8\n6 1 7 2 3 5 4\nR L R L L L L\n" ], "output": [ "\n1 1 1 1 2 -1 2 \n-1 -1 \n2 2 \n-1 \n-1 2 7 3 2 7 3 \n" ] }
548
7
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: * the final tournament features n teams (n is always even) * the first n / 2 teams (according to the standings) come through to the knockout stage * the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage. Input The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once. Output Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity. Examples Input 4 A B C D A-B 1:1 A-C 2:2 A-D 1:0 B-C 1:0 B-D 0:3 C-D 0:3 Output A D Input 2 a A a-A 2:1 Output a
#!/usr/bin/env python3 from collections import defaultdict def score(x, y): if x > y: return 3 if x == y: return 1 return 0 n = int(input()) players = [input() for _ in range(n)] mp = defaultdict(lambda:[0, 0, 0]) for _ in range(n*(n-1)//2): part1, part2 = input().split() p1, p2 = part1.split('-') g1, g2 = [int(x) for x in part2.split(':')] mp[p1][0] += score(g1, g2) mp[p1][1] += g1 - g2 mp[p1][2] += g1 mp[p2][0] += score(g2, g1) mp[p2][1] += g2 - g1 mp[p2][2] += g2 print("\n".join(sorted(map( lambda v:v[-1], list(reversed(sorted( v + [k] for k, v in mp.items() )))[:n//2]))))
{ "input": [ "4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3\n", "2\na\nA\na-A 2:1\n" ], "output": [ "A\nD\n", "a\n" ] }
549
7
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment. For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place. Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima. Input The first line contains integer n (1 ≀ n ≀ 100) β€” the number of Dima's friends. Dima himself isn't considered to be his own friend. The second line contains n positive integers, not exceeding 5, representing, how many fingers the Dima's friends will show. The numbers in the lines are separated by a single space. Output In a single line print the answer to the problem. Examples Input 1 1 Output 3 Input 1 2 Output 2 Input 2 3 5 Output 3 Note In the first sample Dima can show 1, 3 or 5 fingers. If Dima shows 3 fingers, then the counting-out will go like that: Dima, his friend, Dima, his friend. In the second sample Dima can show 2 or 4 fingers.
def main(): n = int(input().strip()) + 1 x = sum(map(int, input().strip().split())) % n return sum((x + i) % n != 1 for i in range(1, 6)) print(main())
{ "input": [ "1\n2\n", "2\n3 5\n", "1\n1\n" ], "output": [ "2\n", "3\n", "3\n" ] }
550
7
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member of NFC. One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (a, b) such that member a from MDC dances with member b from NFC. The complexity of a pairs' assignment is the number of pairs of dancing pairs (a, b) and (c, d) such that a < c and b > d. You are given a binary number of length n named x. We know that member i from MDC dances with member <image> from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (109 + 7). Expression <image> denotes applying Β«XORΒ» to numbers x and y. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as Β«^Β», in Pascal β€” Β«xorΒ». Input The first line of input contains a binary number x of lenght n, (1 ≀ n ≀ 100). This number may contain leading zeros. Output Print the complexity of the given dance assignent modulo 1000000007 (109 + 7). Examples Input 11 Output 6 Input 01 Output 2 Input 1 Output 1
t = input() n, d = len(t), 1000000007 def f(k): return 0 if k == n else 2 * f(k + 1) + (pow(2, 2 * (n - k - 1), d) if t[k] == '1' else 0) print(f(0) % d)
{ "input": [ "1\n", "01\n", "11\n" ], "output": [ "1\n", "2\n", "6\n" ] }
551
7
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value. However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements: 1. one resistor; 2. an element and one resistor plugged in sequence; 3. an element and one resistor plugged in parallel. <image> With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals <image>. In this case Re equals the resistance of the element being connected. Mike needs to assemble an element with a resistance equal to the fraction <image>. Determine the smallest possible number of resistors he needs to make such an element. Input The single input line contains two space-separated integers a and b (1 ≀ a, b ≀ 1018). It is guaranteed that the fraction <image> is irreducible. It is guaranteed that a solution always exists. Output Print a single number β€” the answer to the problem. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier. Examples Input 1 1 Output 1 Input 3 2 Output 3 Input 199 200 Output 200 Note In the first sample, one resistor is enough. In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance <image>. We cannot make this element using two resistors.
def gcd(a,b): return 0 if b == 0 else a//b + gcd(b, a%b) print(gcd(*(int(x) for x in input().split())))
{ "input": [ "3 2\n", "1 1\n", "199 200\n" ], "output": [ "3\n", "1\n", "200\n" ] }
552
9
Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words, <image> , where aj is the taste of the j-th chosen fruit and bj is its calories. Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem β€” now the happiness of a young couple is in your hands! Inna loves Dima very much so she wants to make the salad from at least one fruit. Input The first line of the input contains two integers n, k (1 ≀ n ≀ 100, 1 ≀ k ≀ 10). The second line of the input contains n integers a1, a2, ..., an (1 ≀ ai ≀ 100) β€” the fruits' tastes. The third line of the input contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 100) β€” the fruits' calories. Fruit number i has taste ai and calories bi. Output If there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer β€” the maximum possible sum of the taste values of the chosen fruits. Examples Input 3 2 10 8 1 2 7 1 Output 18 Input 5 3 4 4 4 4 4 2 2 2 2 2 Output -1 Note In the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition <image> fulfills, that's exactly what Inna wants. In the second test sample we cannot choose the fruits so as to follow Inna's principle.
class Dict(dict): def __missing__(self, key): return float('-inf') n, k = map(int, input().split()) a = [0] + list(map(int, input().split())) b = [0] + list(map(int, input().split())) dp = [Dict() for _ in range(n+1)] dp[0][n*100] = 0 for i in range(1, n+1): s = a[i] - b[i]*k for j in range(n*200, -1, -1): dp[i][j] = max(dp[i-1][j], dp[i-1][j-s] + a[i]) print(dp[n][n*100] or -1)
{ "input": [ "5 3\n4 4 4 4 4\n2 2 2 2 2\n", "3 2\n10 8 1\n2 7 1\n" ], "output": [ "-1\n", "18\n" ] }
553
8
Two chess pieces, a rook and a knight, stand on a standard chessboard 8 Γ— 8 in size. The positions in which they are situated are known. It is guaranteed that none of them beats the other one. Your task is to find the number of ways to place another knight on the board so that none of the three pieces on the board beat another one. A new piece can only be placed on an empty square. Input The first input line contains the description of the rook's position on the board. This description is a line which is 2 in length. Its first symbol is a lower-case Latin letter from a to h, and its second symbol is a number from 1 to 8. The second line contains the description of the knight's position in a similar way. It is guaranteed that their positions do not coincide. Output Print a single number which is the required number of ways. Examples Input a1 b2 Output 44 Input a8 d4 Output 38
r = input() k = input() cont = 0 def kn(k, i, j): a, b = [ord(x)-96 for x in [k[0], i]] return( k == (i+str(j)) or (abs(a-b) == 1 and abs(int(k[1]) - j) == 2) or (abs(a-b) == 2 and abs(int(k[1]) - j) == 1) ) for i in "abcdefgh": if i == r[0]: continue for j in range(1,9): if str(j) == r[1]: continue if not kn(k, i, j) and not kn(r, i, j): cont += 1 print(cont)
{ "input": [ "a1\nb2\n", "a8\nd4\n" ], "output": [ "44\n", "38\n" ] }
554
7
Not so long ago as a result of combat operations the main Berland place of interest β€” the magic clock β€” was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin corresponds to the clock center. The clock was painted two colors as is shown in the picture: <image> The picture shows only the central part of the clock. This coloring naturally extends to infinity. The balls can be taken to be points on the plane. Your task is to find the color of the area, damaged by the given ball. All the points located on the border of one of the areas have to be considered painted black. Input The first and single line contains two integers x and y β€” the coordinates of the hole made in the clock by the ball. Each of the numbers x and y has an absolute value that does not exceed 1000. Output Find the required color. All the points between which and the origin of coordinates the distance is integral-value are painted black. Examples Input -2 1 Output white Input 2 1 Output black Input 4 3 Output black
def findcolor(x,p): i=0 while i*i<x*x+p*p: i+=1 l=0 if (i*i==x*x+p*p) or (x*p>=0)!=(i%2==0): l=1 print("black")if l else print("white") x,p=map(int,input().split()) findcolor(x,p)
{ "input": [ "-2 1\n", "4 3\n", "2 1\n" ], "output": [ "white\n", "black\n", "black\n" ] }
555
7
Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the pair (a, c) is coprime. You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (a, b, c), for which the statement is false, and the numbers meet the condition l ≀ a < b < c ≀ r. More specifically, you need to find three numbers (a, b, c), such that l ≀ a < b < c ≀ r, pairs (a, b) and (b, c) are coprime, and pair (a, c) is not coprime. Input The single line contains two positive space-separated integers l, r (1 ≀ l ≀ r ≀ 1018; r - l ≀ 50). Output Print three positive space-separated integers a, b, c β€” three distinct numbers (a, b, c) that form the counterexample. If there are several solutions, you are allowed to print any of them. The numbers must be printed in ascending order. If the counterexample does not exist, print the single number -1. Examples Input 2 4 Output 2 3 4 Input 10 11 Output -1 Input 900000000000000009 900000000000000029 Output 900000000000000009 900000000000000010 900000000000000021 Note In the first sample pair (2, 4) is not coprime and pairs (2, 3) and (3, 4) are. In the second sample you cannot form a group of three distinct integers, so the answer is -1. In the third sample it is easy to see that numbers 900000000000000009 and 900000000000000021 are divisible by three.
def f(ll): l,r =ll if r-l<2 or (r-l==2 and l%2>0): return [-1] return [l,l+1,l+2] if l%2==0 else [l+1,l+2,l+3] l = list(map(int,input().split())) print(*f(l))
{ "input": [ "900000000000000009 900000000000000029\n", "2 4\n", "10 11\n" ], "output": [ "900000000000000010 900000000000000011 900000000000000012\n", "2 3 4\n", "-1\n" ] }
556
7
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea. Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments. Amr asked for your help to distribute his free days between instruments so that he can achieve his goal. Input The first line contains two numbers n, k (1 ≀ n ≀ 100, 0 ≀ k ≀ 10 000), the number of instruments and number of days respectively. The second line contains n integers ai (1 ≀ ai ≀ 100), representing number of days required to learn the i-th instrument. Output In the first line output one integer m representing the maximum number of instruments Amr can learn. In the second line output m space-separated integers: the indices of instruments to be learnt. You may output indices in any order. if there are multiple optimal solutions output any. It is not necessary to use all days for studying. Examples Input 4 10 4 3 1 2 Output 4 1 2 3 4 Input 5 6 4 3 1 1 2 Output 3 1 3 4 Input 1 3 4 Output 0 Note In the first test Amr can learn all 4 instruments. In the second test other possible solutions are: {2, 3, 5} or {3, 4, 5}. In the third test Amr doesn't have enough time to learn the only presented instrument.
def sortl(inp): return inp[0] n,k=map(int,input().split(" ")) mas = [[x,i] for i,x in enumerate(map(int,input().split(" ")))] mas.sort(key=sortl) res=0 for i in range(n): k-=mas[i][0] if k>=0: res+=1 else: break print(res) for i in range(res): print(mas[i][1]+1,end=" ")
{ "input": [ "5 6\n4 3 1 1 2\n", "1 3\n4\n", "4 10\n4 3 1 2\n" ], "output": [ "3\n3 4 5 ", "0\n", "4\n3 4 2 1 " ] }
557
8
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on. Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active. Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake. Input The first line contains integer n (1 ≀ n ≀ 1000) β€” the number of gears. The second line contains n digits a1, a2, ..., an (0 ≀ ai ≀ n - 1) β€” the sequence of active teeth: the active tooth of the i-th gear contains number ai. Output In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise. Examples Input 3 1 0 0 Output Yes Input 5 4 2 1 4 3 Output Yes Input 4 0 2 3 1 Output No Note In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
def main(): n = int(input()) l = list(map(int, input().split())) a = l[0] for i, x in enumerate(l): l[i] = ((x + a if i & 1 else x - a) - i) % n print(("Yes", "No")[any(l)]) if __name__ == '__main__': main()
{ "input": [ "4\n0 2 3 1\n", "5\n4 2 1 4 3\n", "3\n1 0 0\n" ], "output": [ "No\n", "Yes\n", "Yes\n" ] }
558
9
Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks. The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers. Input The first line of the input contains two space-separated integers n and m (0 ≀ n, m ≀ 1 000 000, n + m > 0) β€” the number of students using two-block pieces and the number of students using three-block pieces, respectively. Output Print a single integer, denoting the minimum possible height of the tallest tower. Examples Input 1 3 Output 9 Input 3 2 Output 8 Input 5 0 Output 10 Note In the first case, the student using two-block pieces can make a tower of height 4, and the students using three-block pieces can make towers of height 3, 6, and 9 blocks. The tallest tower has a height of 9 blocks. In the second case, the students can make towers of heights 2, 4, and 8 with two-block pieces and towers of heights 3 and 6 with three-block pieces, for a maximum height of 8 blocks.
def right(m, n, a): b = True n2 = a // 2 - a // 6 n3 = a // 3 - a // 6 n6 = a // 6 if n2+n6<n or n3+n6<m or n2+n3+n6<n+m: b = False return b n, m = map(int, input().split()) ans = n+m while not right(m, n, ans): ans += 1 print(ans)
{ "input": [ "3 2\n", "5 0\n", "1 3\n" ], "output": [ "8\n", "10\n", "9\n" ] }
559
7
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula <image>. The success of the operation relies on the number of pairs (i, j) (1 ≀ i < j ≀ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs. Input The first line of the input contains the single integer n (1 ≀ n ≀ 200 000) β€” the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≀ 109). Some positions may coincide. Output Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel. Examples Input 3 1 1 7 5 1 5 Output 2 Input 6 0 0 0 1 0 2 -1 1 0 1 1 1 Output 11 Note In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and <image> for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
def f(t): return sum(v*(v-1)/2 for v in t.values()) a,b,c={},{},{} for _ in range(int(input())): x,y=map(int,input().split()) a[x]=a.get(x,0)+1 b[y]=b.get(y,0)+1 c[(x,y)]=c.get((x,y),0)+1 print(int(f(a)+f(b)-f(c)))
{ "input": [ "3\n1 1\n7 5\n1 5\n", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1\n" ], "output": [ "2", "11" ] }
560
9
Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins. Across all the sets Misha scored a points in total, and Vanya scored b points. Given this information, determine the maximum number of sets they could have played, or that the situation is impossible. Note that the game consisted of several complete sets. Input The first line contains three space-separated integers k, a and b (1 ≀ k ≀ 109, 0 ≀ a, b ≀ 109, a + b > 0). Output If the situation is impossible, print a single number -1. Otherwise, print the maximum possible number of sets. Examples Input 11 11 5 Output 1 Input 11 2 3 Output -1 Note Note that the rules of the game in this problem differ from the real table tennis game, for example, the rule of "balance" (the winning player has to be at least two points ahead to win a set) has no power within the present problem.
string = input() n, a, b = map(int, string.split()) def check(p, q): return p % n != 0 and q < n if check(a, b) or check(b, a): print(-1) else: print(a // n + b // n)
{ "input": [ "11 2 3\n", "11 11 5\n" ], "output": [ "-1", "1" ] }
561
8
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels! There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock. Due to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll. Fortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00. You can only rotate the hands forward, that is, as is shown in the picture: <image> As since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction. Note that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still. Input The only line of input contains current time according to the digital clock, formatted as HH:MM (00 ≀ HH ≀ 23, 00 ≀ MM ≀ 59). The mantel clock initially shows 12:00. Pretests contain times of the beginning of some morning TV programs of the Channel One Russia. Output Print two numbers x and y β€” the angles of turning the hour and minute hands, respectively (0 ≀ x, y < 360). The absolute or relative error in the answer should not exceed 10 - 9. Examples Input 12:00 Output 0 0 Input 04:30 Output 135 180 Input 08:17 Output 248.5 102 Note A note to the second example: the hour hand will be positioned exactly in the middle, between 4 and 5.
def main(): x,y = map(int,input().split(":")) x = x%12 + 1*(y/60) print(x*30,(y*360)/60) main()
{ "input": [ "04:30\n", "08:17\n", "12:00\n" ], "output": [ "135 180\n", "248.5 102\n", "0 0\n" ] }
562
7
Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence. When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every a minutes, but a train goes to Masha's direction every b minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample). We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously. Help Vasya count to which girlfriend he will go more often. Input The first line contains two integers a and b (a β‰  b, 1 ≀ a, b ≀ 106). Output Print "Dasha" if Vasya will go to Dasha more frequently, "Masha" if he will go to Masha more frequently, or "Equal" if he will go to both girlfriends with the same frequency. Examples Input 3 7 Output Dasha Input 5 3 Output Masha Input 2 3 Output Equal Note Let's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0, 6], he will go to both girls equally often. If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute. If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute. If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute. If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction. In sum Masha and Dasha get equal time β€” three minutes for each one, thus, Vasya will go to both girlfriends equally often.
a,b=[int(x) for x in input().split()] def hcf(a,b): if a==0: return b return hcf(b%a,a) lcm=(a*b)/hcf(a,b) d=lcm/a m=lcm/b if d-m>1: print('Dasha') elif m-d>1: print('Masha') else: print('Equal')
{ "input": [ "2 3\n", "3 7\n", "5 3\n" ], "output": [ "Equal\n", "Dasha\n", "Masha\n" ] }
563
9
Mishka has got n empty boxes. For every i (1 ≀ i ≀ n), i-th box is a cube with side length ai. Mishka can put a box i into another box j if the following conditions are met: * i-th box is not put into another box; * j-th box doesn't contain any other boxes; * box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box. Help Mishka to determine the minimum possible number of visible boxes! Input The first line contains one integer n (1 ≀ n ≀ 5000) β€” the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the side length of i-th box. Output Print the minimum possible number of visible boxes. Examples Input 3 1 2 3 Output 1 Input 4 4 2 4 3 Output 2 Note In the first example it is possible to put box 1 into box 2, and 2 into 3. In the second example Mishka can put box 2 into box 3, and box 4 into box 1.
def f(A): x = 0 for i in A: if A.count(i)>x: x = A.count(i) return x n = input() A = input().split(' ') print(f(A))
{ "input": [ "3\n1 2 3\n", "4\n4 2 4 3\n" ], "output": [ "1\n", "2\n" ] }
564
11
Consider a system of n water taps all pouring water into the same container. The i-th water tap can be set to deliver any amount of water from 0 to ai ml per second (this amount may be a real number). The water delivered by i-th tap has temperature ti. If for every <image> you set i-th tap to deliver exactly xi ml of water per second, then the resulting temperature of water will be <image> (if <image>, then to avoid division by zero we state that the resulting water temperature is 0). You have to set all the water taps in such a way that the resulting temperature is exactly T. What is the maximum amount of water you may get per second if its temperature has to be T? Input The first line contains two integers n and T (1 ≀ n ≀ 200000, 1 ≀ T ≀ 106) β€” the number of water taps and the desired temperature of water, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) where ai is the maximum amount of water i-th tap can deliver per second. The third line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 106) β€” the temperature of water each tap delivers. Output Print the maximum possible amount of water with temperature exactly T you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0). Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Examples Input 2 100 3 10 50 150 Output 6.000000000000000 Input 3 9 5 5 30 6 6 10 Output 40.000000000000000 Input 2 12 1 3 10 15 Output 1.666666666666667
import sys readline = sys.stdin.readline readlines = sys.stdin.readlines ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) prn = lambda x: print(*x, sep='\n') def solve(): n, T = nm() a = nl() t = nl() if min(t) > T or max(t) < T: print(0) return g = [(t[i] - T, i) for i in range(n)] h = sum((t[i] - T)*a[i] for i in range(n)) ans = sum(a) if h < 0: g.sort() for x, i in g: if h < x * a[i]: ans -= a[i] h -= x * a[i] else: if h and x != 0: ans -= h / x break elif h > 0: g.sort(reverse=True) for x, i in g: if h > x * a[i]: ans -= a[i] h -= x * a[i] else: if h and x != 0: ans -= h / x break print(ans) return solve() # T = ni() # for _ in range(T): # solve()
{ "input": [ "2 12\n1 3\n10 15\n", "2 100\n3 10\n50 150\n", "3 9\n5 5 30\n6 6 10\n" ], "output": [ "1.6666666667\n", "6.0000000000\n", "40\n" ] }
565
10
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive). Input The first line of input contains a single integer n (1 ≀ n ≀ 5000), the size of the array. The second line contains n integers a_1,a_2,...,a_n (-10^8 ≀ a_i ≀ 10^8), the values of the array. Output Output n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k. Examples Input 2 5 5 Output 3 0 Input 5 5 -4 2 1 8 Output 5 5 3 2 0 Input 1 0 Output 1
from math import sqrt primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463] def sqfree(x): if x == 0: return x y = 1 for p in primes: pp=p*p while x % pp == 0: x //= pp if x % p == 0: x //= p y *= p if abs(x) < p: break if int(sqrt(abs(x)))**2 == abs(x): return (y if x > 0 else -y) else: return x * y n = int(input().strip()) ais = list(map(int, input().strip().split())) bis = list(map(sqfree, ais)) prev = [-1 for i in range(n)] last = {} for i, b in enumerate(bis): if b in last: prev[i] = last[b] last[b] = i res = [0 for i in range(n)] for l in range(n): cnt = 0 for r in range(l, n): if bis[r] != 0 and prev[r] < l: cnt += 1 res[max(cnt - 1, 0)] += 1 print (' '.join(map(str, res)))
{ "input": [ "2\n5 5\n", "1\n0\n", "5\n5 -4 2 1 8\n" ], "output": [ "3 0 ", "1 ", "5 5 3 2 0 " ] }
566
10
In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong β€” the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure β€” and then terrible Game Cubes fall down on the city, bringing death to those modules, who cannot win the game... For sure, as guard Bob appeared in Mainframe many modules stopped fearing Game Cubes. Because Bob (as he is alive yet) has never been defeated by User, and he always meddles with Game Cubes, because he is programmed to this. However, unpleasant situations can happen, when a Game Cube falls down on Lost Angles. Because there lives a nasty virus β€” Hexadecimal, who is... mmm... very strange. And she likes to play very much. So, willy-nilly, Bob has to play with her first, and then with User. This time Hexadecimal invented the following entertainment: Bob has to leap over binary search trees with n nodes. We should remind you that a binary search tree is a binary tree, each node has a distinct key, for each node the following is true: the left sub-tree of a node contains only nodes with keys less than the node's key, the right sub-tree of a node contains only nodes with keys greater than the node's key. All the keys are different positive integer numbers from 1 to n. Each node of such a tree can have up to two children, or have no children at all (in the case when a node is a leaf). In Hexadecimal's game all the trees are different, but the height of each is not lower than h. In this problem Β«heightΒ» stands for the maximum amount of nodes on the way from the root to the remotest leaf, the root node and the leaf itself included. When Bob leaps over a tree, it disappears. Bob gets the access to a Cube, when there are no trees left. He knows how many trees he will have to leap over in the worst case. And you? Input The input data contains two space-separated positive integer numbers n and h (n ≀ 35, h ≀ n). Output Output one number β€” the answer to the problem. It is guaranteed that it does not exceed 9Β·1018. Examples Input 3 2 Output 5 Input 3 3 Output 4
dic={} def dfs(a,res): if a<=1 and res<=a: return 1 elif a*100+res in dic: return dic[a*100+res] else: cnt=0 for i in range(a): if i<res-1 and a-i-1<res-1: continue else: cnt=cnt+dfs(i,0)*dfs(a-i-1,res-1)+dfs(i,res-1)*dfs(a-i-1,0)-dfs(i,res-1)*dfs(a-i-1,res-1) dic[a*100+res]=cnt return cnt inp=input().split() print(dfs(int(inp[0]),int(inp[1])))
{ "input": [ "3 2\n", "3 3\n" ], "output": [ "5\n", "4\n" ] }
567
7
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant "n"; after this letter, there can be any letter (not only a vowel) or there can be no letter at all. For example, the words "harakiri", "yupie", "man", and "nbo" are Berlanese while the words "horse", "king", "my", and "nz" are not. Help Vitya find out if a word s is Berlanese. Input The first line of the input contains the string s consisting of |s| (1≀ |s|≀ 100) lowercase Latin letters. Output Print "YES" (without quotes) if there is a vowel after every consonant except "n", otherwise print "NO". You can print each letter in any case (upper or lower). Examples Input sumimasen Output YES Input ninja Output YES Input codeforces Output NO Note In the first and second samples, a vowel goes after each consonant except "n", so the word is Berlanese. In the third sample, the consonant "c" goes after the consonant "r", and the consonant "s" stands on the end, so the word is not Berlanese.
def check(a): n = len(a) for i in range(n): if a[i] not in 'aeioun': if i+1>=n or a[i+1] not in 'aeiou': return "NO" return "YES" a = input() print(check(a))
{ "input": [ "codeforces\n", "ninja\n", "sumimasen\n" ], "output": [ "NO\n", "YES\n", "YES\n" ] }
568
12
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3). You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n. The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation. Calculate the expected total number of inversions in the resulting valid permutation. It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q β‰  0. Report the value of P β‹… Q^{-1} \pmod {998244353}. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the sequence. The second line contains n integers p_1, p_2, ..., p_n (-1 ≀ p_i ≀ n, p_i β‰  0) β€” the initial sequence. It is guaranteed that all elements not equal to -1 are pairwise distinct. Output Print a single integer β€” the expected total number of inversions in the resulting valid permutation. It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q β‰  0. Report the value of P β‹… Q^{-1} \pmod {998244353}. Examples Input 3 3 -1 -1 Output 499122179 Input 2 1 2 Output 0 Input 2 -1 -1 Output 499122177 Note In the first example two resulting valid permutations are possible: * [3, 1, 2] β€” 2 inversions; * [3, 2, 1] β€” 3 inversions. The expected value is (2 β‹… 1 + 3 β‹… 1)/(2) = 2.5. In the second example no -1 are present, thus the only valid permutation is possible β€” the given one. It has 0 inversions. In the third example there are two resulting valid permutations β€” one with 0 inversions and one with 1 inversion.
K = 998244353 def mu(a, n): if n == 0: return 1 q = mu(a, n // 2) if n % 2 == 0: return q * q % K return q * q % K * a % K MAXN = 200005 dd = [0 for i in range(MAXN)] p = [0 for i in range(MAXN)] s = [0 for i in range(MAXN)] a = [0 for i in range(MAXN)] fen = [0 for i in range(MAXN)] def add(u, v): i = u while (i <= 200000): fen[i] += v i += i & -i def get(u): res = 0 i = u while (i > 0): res += fen[i] i -= i & -i return res n = int(input()) data = input().split() cnt = 0 for i in range(1, n + 1): p[i] = int(data[i - 1]) if (p[i] > 0): dd[p[i]] = 1 else: cnt += 1 for i in range(1, n + 1): if (dd[i] == 0): s[i] = s[i - 1] + 1 else: s[i] = s[i - 1] cnt1 = 0 P = 0 den = mu(cnt, K - 2) for i in range(1, n + 1): if (p[i] == -1): cnt1 += 1 else: u = cnt - cnt1 P = (P + u * s[p[i]] % K * den % K) % K P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K m = 0 for i in range(1, n + 1): if p[i] > 0: m += 1 a[m] = p[i] P1 = 0 for i in range(m, 0, -1): P1 = (P1 + get(a[i])) % K add(a[i], 1) P = (P + P1) % K print(P)
{ "input": [ "2\n1 2\n", "2\n-1 -1\n", "3\n3 -1 -1\n" ], "output": [ " 0", " 499122177", " 499122179" ] }
569
9
Two integer sequences existed initially β€” one of them was strictly increasing, and the other one β€” strictly decreasing. Strictly increasing sequence is a sequence of integers [x_1 < x_2 < ... < x_k]. And strictly decreasing sequence is a sequence of integers [y_1 > y_2 > ... > y_l]. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. They were merged into one sequence a. After that sequence a got shuffled. For example, some of the possible resulting sequences a for an increasing sequence [1, 3, 4] and a decreasing sequence [10, 4, 2] are sequences [1, 2, 3, 4, 4, 10] or [4, 2, 1, 10, 4, 3]. This shuffled sequence a is given in the input. Your task is to find any two suitable initial sequences. One of them should be strictly increasing and the other one β€” strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. If there is a contradiction in the input and it is impossible to split the given sequence a to increasing and decreasing sequences, print "NO". Input The first line of the input contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2 β‹… 10^5), where a_i is the i-th element of a. Output If there is a contradiction in the input and it is impossible to split the given sequence a to increasing and decreasing sequences, print "NO" in the first line. Otherwise print "YES" in the first line and any two suitable sequences. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing. In the second line print n_i β€” the number of elements in the strictly increasing sequence. n_i can be zero, in this case the increasing sequence is empty. In the third line print n_i integers inc_1, inc_2, ..., inc_{n_i} in the increasing order of its values (inc_1 < inc_2 < ... < inc_{n_i}) β€” the strictly increasing sequence itself. You can keep this line empty if n_i = 0 (or just print the empty line). In the fourth line print n_d β€” the number of elements in the strictly decreasing sequence. n_d can be zero, in this case the decreasing sequence is empty. In the fifth line print n_d integers dec_1, dec_2, ..., dec_{n_d} in the decreasing order of its values (dec_1 > dec_2 > ... > dec_{n_d}) β€” the strictly decreasing sequence itself. You can keep this line empty if n_d = 0 (or just print the empty line). n_i + n_d should be equal to n and the union of printed sequences should be a permutation of the given sequence (in case of "YES" answer). Examples Input 7 7 2 7 3 3 1 4 Output YES 2 3 7 5 7 4 3 2 1 Input 5 4 3 1 5 3 Output YES 1 3 4 5 4 3 1 Input 5 1 1 2 1 2 Output NO Input 5 0 1 2 3 4 Output YES 0 5 4 3 2 1 0
def solve(): n = int(input()) arr=list(map(int,input().split())) s1 = set(); s2 = set() for i in arr: if not i in s1: s1.add(i) elif not i in s2: s2.add(i) else: print("NO") return print("YES") print(len(s1)) print(*sorted(s1)) print(len(s2)) print(*sorted(s2, reverse = True)) if __name__ == "__main__": solve()
{ "input": [ "5\n4 3 1 5 3\n", "5\n0 1 2 3 4\n", "7\n7 2 7 3 3 1 4\n", "5\n1 1 2 1 2\n" ], "output": [ "YES\n4\n1 3 4 5\n1\n3\n", "YES\n5\n0 1 2 3 4\n0\n\n", "YES\n5\n1 2 3 4 7\n2\n7 3\n", "NO\n" ] }
570
8
Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly 1 problem, during the second day β€” exactly 2 problems, during the third day β€” exactly 3 problems, and so on. During the k-th day he should solve k problems. Polycarp has a list of n contests, the i-th contest consists of a_i problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly k problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least k problems that Polycarp didn't solve yet during the k-th day, then Polycarp stops his training. How many days Polycarp can train if he chooses the contests optimally? Input The first line of the input contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of contests. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” the number of problems in the i-th contest. Output Print one integer β€” the maximum number of days Polycarp can train if he chooses the contests optimally. Examples Input 4 3 1 4 1 Output 3 Input 3 1 1 1 Output 1 Input 5 1 1 1 2 2 Output 2
def arr_inp(): return [int(x) for x in input().split()] n, a = int(input()), arr_inp() a.sort() days = 0 for i in a: if i >= days + 1: days += 1 print(days)
{ "input": [ "4\n3 1 4 1\n", "5\n1 1 1 2 2\n", "3\n1 1 1\n" ], "output": [ "3\n", "2\n", "1\n" ] }
571
9
The Cybermen and the Daleks have long been the Doctor's main enemies. Everyone knows that both these species enjoy destroying everything they encounter. However, a little-known fact about them is that they both also love taking Turing tests! Heidi designed a series of increasingly difficult tasks for them to spend their time on, which would allow the Doctor enough time to save innocent lives! The funny part is that these tasks would be very easy for a human to solve. The first task is as follows. There are some points on the plane. All but one of them are on the boundary of an axis-aligned square (its sides are parallel to the axes). Identify that point. Input The first line contains an integer n (2 ≀ n ≀ 10). Each of the following 4n + 1 lines contains two integers x_i, y_i (0 ≀ x_i, y_i ≀ 50), describing the coordinates of the next point. It is guaranteed that there are at least n points on each side of the square and all 4n + 1 points are distinct. Output Print two integers β€” the coordinates of the point that is not on the boundary of the square. Examples Input 2 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 Output 1 1 Input 2 0 0 0 1 0 2 0 3 1 0 1 2 2 0 2 1 2 2 Output 0 3 Note In both examples, the square has four sides x=0, x=2, y=0, y=2.
n = int(input()) l = [ list(map(int,input().split())) for _ in range(4*n+1) ] x, y = map(list, zip(*l)) hx, lx, hy, ly = max(x), min(x), max(y), min(y) def find(w, i): for j in l: if j[ w ] == i: return j if x.count(hx) == 1: print( *find( 0, hx ) ) elif x.count(lx) == 1: print( *find( 0, lx ) ) elif y.count(hy) == 1: print( *find( 1, hy ) ) elif y.count(ly) == 1: print( *find( 1, ly ) ) else: for i in l: if i[ 0 ] not in[ hx, lx ] and i[ 1 ] not in [ hy, ly ]: print( *i ) break
{ "input": [ "2\n0 0\n0 1\n0 2\n0 3\n1 0\n1 2\n2 0\n2 1\n2 2\n", "2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2\n" ], "output": [ "0 3\n", "1 1\n" ] }
572
10
The subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. You are given an integer n. You have to find a sequence s consisting of digits \{1, 3, 7\} such that it has exactly n subsequences equal to 1337. For example, sequence 337133377 has 6 subsequences equal to 1337: 1. 337\underline{1}3\underline{3}\underline{3}7\underline{7} (you can remove the second and fifth characters); 2. 337\underline{1}\underline{3}3\underline{3}7\underline{7} (you can remove the third and fifth characters); 3. 337\underline{1}\underline{3}\underline{3}37\underline{7} (you can remove the fourth and fifth characters); 4. 337\underline{1}3\underline{3}\underline{3}\underline{7}7 (you can remove the second and sixth characters); 5. 337\underline{1}\underline{3}3\underline{3}\underline{7}7 (you can remove the third and sixth characters); 6. 337\underline{1}\underline{3}\underline{3}3\underline{7}7 (you can remove the fourth and sixth characters). Note that the length of the sequence s must not exceed 10^5. You have to answer t independent queries. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of queries. Next t lines contains a description of queries: the i-th line contains one integer n_i (1 ≀ n_i ≀ 10^9). Output For the i-th query print one string s_i (1 ≀ |s_i| ≀ 10^5) consisting of digits \{1, 3, 7\}. String s_i must have exactly n_i subsequences 1337. If there are multiple such strings, print any of them. Example Input 2 6 1 Output 113337 1337
def string_1337(n, L = [], first = True): j=int((2*n)**0.5) if j*(j+1)//2<=n: j+=1 m = j*(j-1)//2 print('1','33','7'*(n-m),'3'*(j-2),'7',sep='') n = int(input()) for _ in range(n): string_1337(int(input()),[])
{ "input": [ "2\n6\n1\n" ], "output": [ "133337\n1337\n" ] }
573
10
You are given a tree consisting of n vertices. A tree is an undirected connected acyclic graph. <image> Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color. You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples (x, y, z) such that x β‰  y, y β‰  z, x β‰  z, x is connected by an edge with y, and y is connected by an edge with z. The colours of x, y and z should be pairwise distinct. Let's call a painting which meets this condition good. You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it. Input The first line contains one integer n (3 ≀ n ≀ 100 000) β€” the number of vertices. The second line contains a sequence of integers c_{1, 1}, c_{1, 2}, ..., c_{1, n} (1 ≀ c_{1, i} ≀ 10^{9}), where c_{1, i} is the cost of painting the i-th vertex into the first color. The third line contains a sequence of integers c_{2, 1}, c_{2, 2}, ..., c_{2, n} (1 ≀ c_{2, i} ≀ 10^{9}), where c_{2, i} is the cost of painting the i-th vertex into the second color. The fourth line contains a sequence of integers c_{3, 1}, c_{3, 2}, ..., c_{3, n} (1 ≀ c_{3, i} ≀ 10^{9}), where c_{3, i} is the cost of painting the i-th vertex into the third color. Then (n - 1) lines follow, each containing two integers u_j and v_j (1 ≀ u_j, v_j ≀ n, u_j β‰  v_j) β€” the numbers of vertices connected by the j-th undirected edge. It is guaranteed that these edges denote a tree. Output If there is no good painting, print -1. Otherwise, print the minimum cost of a good painting in the first line. In the second line print n integers b_1, b_2, ..., b_n (1 ≀ b_i ≀ 3), where the i-th integer should denote the color of the i-th vertex. If there are multiple good paintings with minimum cost, print any of them. Examples Input 3 3 2 3 4 3 2 3 1 3 1 2 2 3 Output 6 1 3 2 Input 5 3 4 2 1 2 4 2 1 5 4 5 3 2 1 1 1 2 3 2 4 3 5 3 Output -1 Input 5 3 4 2 1 2 4 2 1 5 4 5 3 2 1 1 1 2 3 2 4 3 5 4 Output 9 1 3 2 1 3 Note All vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color 1, the second vertex β€” into color 3, and the third vertex β€” into color 2. The cost of this painting is 3 + 2 + 1 = 6.
#!/usr/bin/env python3 import sys from itertools import permutations from math import inf #lines = stdin.readlines() def rint(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline().rstrip('\n') def oint(): return int(input()) n = oint() c = [] for i in range(3): c.append(list(rint())) adj = [set() for i in range(n)] for i in range(n-1): u, v = rint() u -= 1 v -= 1 adj[u].add(v) adj[v].add(u) for i in range(n): if len(adj[i]) >= 3: print(-1) exit() if len(adj[i]) == 1: start = i minv = inf i = [0]*3 ord = [] prev = -1 cur = start for j in range(n): ord.append(cur) for next in adj[cur]: if next != prev: break prev = cur cur = next for i[0], i[1], i[2] in permutations([0,1,2]): v = 0 for j in range(n): v += c[i[j%3]][ord[j]] if v < minv: imin = i.copy() minv = v ans = [0]*n for j in range(n): ans[ord[j]] = imin[j%3] + 1 print(minv) print(*ans)
{ "input": [ "5\n3 4 2 1 2\n4 2 1 5 4\n5 3 2 1 1\n1 2\n3 2\n4 3\n5 3\n", "5\n3 4 2 1 2\n4 2 1 5 4\n5 3 2 1 1\n1 2\n3 2\n4 3\n5 4\n", "3\n3 2 3\n4 3 2\n3 1 3\n1 2\n2 3\n" ], "output": [ "-1\n", "9\n1 3 2 1 3 \n", "6\n1 3 2 \n" ] }
574
8
An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, …, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 ≀ i ≀ n - 1. Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequence using all of these a + b + c + d numbers. However, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans? Input The only input line contains four non-negative integers a, b, c and d (0 < a+b+c+d ≀ 10^5). Output If it is impossible to construct a beautiful sequence satisfying the above constraints, print "NO" (without quotes) in one line. Otherwise, print "YES" (without quotes) in the first line. Then in the second line print a + b + c + d integers, separated by spaces β€” a beautiful sequence. There should be a numbers equal to 0, b numbers equal to 1, c numbers equal to 2 and d numbers equal to 3. If there are multiple answers, you can print any of them. Examples Input 2 2 2 1 Output YES 0 1 0 1 2 3 2 Input 1 2 3 4 Output NO Input 2 2 2 3 Output NO Note In the first test, it is easy to see, that the sequence is beautiful because the difference between any two consecutive numbers is equal to 1. Also, there are exactly two numbers, equal to 0, 1, 2 and exactly one number, equal to 3. It can be proved, that it is impossible to construct beautiful sequences in the second and third tests.
def printit(s): print("YES") print(*s) exit() def solve(j,i): tt = sum(j) jj = [] for nn in j: jj.append(nn) s = [] while(1): if(i==4 or jj[i]==0): break s.append(i) jj[i]-=1 if(i>0 and jj[i-1]>0): i-=1 else: i+=1 if(len(s)==tt): printit(s) l = list(map(int,input().split())) for i in range(0,4): solve(l,i) print("NO")
{ "input": [ "1 2 3 4\n", "2 2 2 3\n", "2 2 2 1\n" ], "output": [ "NO\n", "NO\n", "YES\n0 1 0 1 2 3 2 \n" ] }
575
10
Today, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, ..., a_n and challenged him to choose an integer X such that the value \underset{1 ≀ i ≀ n}{max} (a_i βŠ• X) is minimum possible, where βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of \underset{1 ≀ i ≀ n}{max} (a_i βŠ• X). Input The first line contains integer n (1≀ n ≀ 10^5). The second line contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 2^{30}-1). Output Print one integer β€” the minimum possible value of \underset{1 ≀ i ≀ n}{max} (a_i βŠ• X). Examples Input 3 1 2 3 Output 2 Input 2 1 5 Output 4 Note In the first sample, we can choose X = 3. In the second sample, we can choose X = 5.
def q(s,b): if(not s)or b<0:return 0 n,f=[],[] for i in s: if i&(1<<b):n+=i, else:f+=i, if not n:return q(f,b-1) if not f:return q(n,b-1) return min(q(n,b-1),q(f,b-1))+2**b input() print(q([*map(int,input().split())],32))
{ "input": [ "2\n1 5\n", "3\n1 2 3\n" ], "output": [ "4", "2" ] }
576
7
Dreamoon likes coloring cells very much. There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n. You are given an integer m and m integers l_1, l_2, …, l_m (1 ≀ l_i ≀ n) Dreamoon will perform m operations. In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation. Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints. Input The first line contains two integers n,m (1 ≀ m ≀ n ≀ 100 000). The second line contains m integers l_1, l_2, …, l_m (1 ≀ l_i ≀ n). Output If it's impossible to perform m operations to satisfy all constraints, print "'-1" (without quotes). Otherwise, print m integers p_1, p_2, …, p_m (1 ≀ p_i ≀ n - l_i + 1), after these m operations, all colors should appear at least once and all cells should be colored. If there are several possible solutions, you can print any. Examples Input 5 3 3 2 2 Output 2 4 1 Input 10 1 1 Output -1
def res(): print(-1) exit() n,m = map(int,input().split()) l = list(map(int,input().split())) idx = [] if sum(l)<n:res() else: for i in range(m): if i+l[i]>n:res() for i in range(m-1,-1,-1): if n>min(i,m-1-i): curr = min(n-i,l[i]) idx.append(n-curr+1) n-=curr else: idx.append(n) n-=1 print(*idx[::-1])
{ "input": [ "10 1\n1\n", "5 3\n3 2 2\n" ], "output": [ "-1", "1 2 4 " ] }
577
7
For the multiset of positive integers s=\\{s_1,s_2,...,s_k\}, define the Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of s as follow: * \gcd(s) is the maximum positive integer x, such that all integers in s are divisible on x. * lcm(s) is the minimum positive integer x, that divisible on all integers from s. For example, \gcd(\{8,12\})=4,\gcd(\{12,18,6\})=6 and lcm(\{4,6\})=12. Note that for any positive integer x, \gcd(\\{x\})=lcm(\\{x\})=x. Orac has a sequence a with length n. He come up with the multiset t=\{lcm(\\{a_i,a_j\})\ |\ i<j\}, and asked you to find the value of \gcd(t) for him. In other words, you need to calculate the GCD of LCMs of all pairs of elements in the given sequence. Input The first line contains one integer n\ (2≀ n≀ 100 000). The second line contains n integers, a_1, a_2, …, a_n (1 ≀ a_i ≀ 200 000). Output Print one integer: \gcd(\{lcm(\\{a_i,a_j\})\ |\ i<j\}). Examples Input 2 1 1 Output 1 Input 4 10 24 40 80 Output 40 Input 10 540 648 810 648 720 540 594 864 972 648 Output 54 Note For the first example, t=\{lcm(\{1,1\})\}=\{1\}, so \gcd(t)=1. For the second example, t=\{120,40,80,120,240,80\}, and it's not hard to see that \gcd(t)=40.
from math import gcd def lcm(a,b): return a*b//gcd(a,b) input() a=list(map(int,input().split())) t=gcd(a[0],a[1]) q=lcm(a[0],a[1]) for i in range(2,len(a)): q=gcd(q,lcm(a[i],t)) t=gcd(t,a[i]) print(q)
{ "input": [ "2\n1 1\n", "10\n540 648 810 648 720 540 594 864 972 648\n", "4\n10 24 40 80\n" ], "output": [ "1\n", "54\n", "40\n" ] }
578
11
Lee bought some food for dinner time, but Lee's friends eat dinner in a deadly way. Lee is so scared, he doesn't want to die, at least not before seeing Online IOI 2020... There are n different types of food and m Lee's best friends. Lee has w_i plates of the i-th type of food and each friend has two different favorite types of food: the i-th friend's favorite types of food are x_i and y_i (x_i β‰  y_i). Lee will start calling his friends one by one. Whoever is called will go to the kitchen and will try to eat one plate of each of his favorite food types. Each of the friends will go to the kitchen exactly once. The only problem is the following: if a friend will eat at least one plate of food (in total) then he will be harmless. But if there is nothing left for him to eat (neither x_i nor y_i), he will eat Lee instead Γ—\\_Γ—. Lee can choose the order of friends to call, so he'd like to determine if he can survive dinner or not. Also, he'd like to know the order itself. Input The first line contains two integers n and m (2 ≀ n ≀ 10^5; 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of different food types and the number of Lee's friends. The second line contains n integers w_1, w_2, …, w_n (0 ≀ w_i ≀ 10^6) β€” the number of plates of each food type. The i-th line of the next m lines contains two integers x_i and y_i (1 ≀ x_i, y_i ≀ n; x_i β‰  y_i) β€” the favorite types of food of the i-th friend. Output If Lee can survive the dinner then print ALIVE (case insensitive), otherwise print DEAD (case insensitive). Also, if he can survive the dinner, print the order Lee should call friends. If there are multiple valid orders, print any of them. Examples Input 3 3 1 2 1 1 2 2 3 1 3 Output ALIVE 3 2 1 Input 3 2 1 1 0 1 2 1 3 Output ALIVE 2 1 Input 4 4 1 2 0 1 1 3 1 2 2 3 2 4 Output ALIVE 1 3 2 4 Input 5 5 1 1 1 2 1 3 4 1 2 2 3 4 5 4 5 Output ALIVE 5 4 1 3 2 Input 4 10 2 4 1 4 3 2 4 2 4 1 3 1 4 1 1 3 3 2 2 1 3 1 2 4 Output DEAD Note In the first example, any of the following orders of friends are correct : [1, 3, 2], [3, 1, 2], [2, 3, 1], [3, 2, 1]. In the second example, Lee should call the second friend first (the friend will eat a plate of food 1) and then call the first friend (the friend will eat a plate of food 2). If he calls the first friend sooner than the second one, then the first friend will eat one plate of food 1 and food 2 and there will be no food left for the second friend to eat.
import sys from collections import deque def input(): return sys.stdin.readline().rstrip() def input_split(): return [int(i) for i in input().split()] n,m = input_split() w = input_split() num = [0 for i in range(n)] p = [[] for i in range(n)] done = [False for i in range(n)] done_people = [False for i in range(m)] people = [] for i in range(m): x,y = map(int, input().split()) x-=1; y-=1 num[x]+= 1; num[y]+= 1 p[x].append(i) p[y].append(i) people.append((x,y)) q = deque() for i in range(n): if num[i] <= w[i]: q.append(i) done[i] = True ans = [] while (len(q) > 0): u = q.popleft() for elem in p[u]: if people[elem][0] == u: food = people[elem][1] else: food = people[elem][0] if done_people[elem] == False: ans.append(elem) done_people[elem] = True if done[food] == False: num[food] -= 1 if (num[food] <= w[food]): q.append(food) done[food] = True for i in done: if i == False: print("DEAD") break else: print("ALIVE") ans.reverse() ans = [i+1 for i in ans] print(*ans, sep = " ")
{ "input": [ "3 2\n1 1 0\n1 2\n1 3\n", "4 4\n1 2 0 1\n1 3\n1 2\n2 3\n2 4\n", "5 5\n1 1 1 2 1\n3 4\n1 2\n2 3\n4 5\n4 5\n", "4 10\n2 4 1 4\n3 2\n4 2\n4 1\n3 1\n4 1\n1 3\n3 2\n2 1\n3 1\n2 4\n", "3 3\n1 2 1\n1 2\n2 3\n1 3\n" ], "output": [ "ALIVE\n2 1 \n", "ALIVE\n1 3 2 4\n", "ALIVE\n5 4 1 3 2\n", "DEAD\n", "ALIVE\n3 2 1\n" ] }
579
10
A binary matrix is called good if every even length square sub-matrix has an odd number of ones. Given a binary matrix a consisting of n rows and m columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all. All the terms above have their usual meanings β€” refer to the Notes section for their formal definitions. Input The first line of input contains two integers n and m (1 ≀ n ≀ m ≀ 10^6 and nβ‹… m ≀ 10^6) β€” the number of rows and columns in a, respectively. The following n lines each contain m characters, each of which is one of 0 and 1. If the j-th character on the i-th line is 1, then a_{i,j} = 1. Similarly, if the j-th character on the i-th line is 0, then a_{i,j} = 0. Output Output the minimum number of cells you need to change to make a good, or output -1 if it's not possible at all. Examples Input 3 3 101 001 110 Output 2 Input 7 15 000100001010010 100111010110001 101101111100100 010000111111010 111010010100001 000011001111101 111111011010011 Output -1 Note In the first case, changing a_{1,1} to 0 and a_{2,2} to 1 is enough. You can verify that there is no way to make the matrix in the second case good. Some definitions β€” * A binary matrix is one in which every element is either 1 or 0. * A sub-matrix is described by 4 parameters β€” r_1, r_2, c_1, and c_2; here, 1 ≀ r_1 ≀ r_2 ≀ n and 1 ≀ c_1 ≀ c_2 ≀ m. * This sub-matrix contains all elements a_{i,j} that satisfy both r_1 ≀ i ≀ r_2 and c_1 ≀ j ≀ c_2. * A sub-matrix is, further, called an even length square if r_2-r_1 = c_2-c_1 and r_2-r_1+1 is divisible by 2.
from collections import * from sys import exit, stdin, stderr def rl(): return [int(w) for w in stdin.readline().split()] n, m = rl() if n > 3: print(-1) exit(0) if n < 2: print(0) exit(0) a = [[int(c) for c in stdin.readline().rstrip()] for _ in range(n)] if n == 2: a.append(a[0]) r = n * m for target in range(4): total = 0 for a0, a1, a2 in zip(*a): if a0 ^ a1 != target & 1 or a1 ^ a2 != target >> 1: total += 1 target ^= 3 if total < r: r = total print(r)
{ "input": [ "3 3\n101\n001\n110\n", "7 15\n000100001010010\n100111010110001\n101101111100100\n010000111111010\n111010010100001\n000011001111101\n111111011010011\n" ], "output": [ "2\n", "-1\n" ] }
580
7
You are given an array a consisting of n integers numbered from 1 to n. Let's define the k-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length k (recall that a subsegment of a of length k is a contiguous part of a containing exactly k elements). If there is no integer occuring in all subsegments of length k for some value of k, then the k-amazing number is -1. For each k from 1 to n calculate the k-amazing number of the array a. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 3 β‹… 10^5) β€” the number of elements in the array. The second line contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ n) β€” the elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 3 β‹… 10^5. Output For each test case print n integers, where the i-th integer is equal to the i-amazing number of the array. Example Input 3 5 1 2 3 4 5 5 4 4 4 4 2 6 1 3 1 5 3 1 Output -1 -1 3 2 1 -1 4 4 4 2 -1 -1 1 1 1 1
maxn=3e5+5 def solve(arr,n): f=[0]*(n+1) last=[0]*(n+1) ans=[-1]*(n+1) for i in range(1,n+1): x=arr[i] f[x]=max(f[x],i-last[x]) last[x]=i # print(last) for x in range(1,n+1): f[x]=max(f[x],n-last[x]+1) i=f[x] while i<=n and ans[i]==-1: ans[i]=x i+=1 print(*ans[1:]) for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) arr=[0]+arr solve(arr,n)
{ "input": [ "3\n5\n1 2 3 4 5\n5\n4 4 4 4 2\n6\n1 3 1 5 3 1\n" ], "output": [ "-1 -1 3 2 1\n-1 4 4 4 2\n-1 -1 1 1 1 1\n" ] }
581
7
Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string s = s_1 s_2 ... s_n of length n consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move. In a move, a player must choose an index i (1 ≀ i ≀ n) that has not been chosen before, and change s_i to any other lowercase English letter c that c β‰  s_i. When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be. A string a is lexicographically smaller than a string b if and only if one of the following holds: * a is a prefix of b, but a β‰  b; * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. Input Each test contains multiple test cases. The first line contains t (1 ≀ t ≀ 1000) β€” the number of test cases. Description of the test cases follows. The only line of each test case contains a single string s (1 ≀ |s| ≀ 50) consisting of lowercase English letters. Output For each test case, print the final string in a single line. Example Input 3 a bbbb az Output b azaz by Note In the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'. In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'. In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.
def doit(): s=input() for i in range(len(s)): if ((i&1)==0): print('b' if s[i]=='a' else 'a', end='') else: print('y' if s[i]=='z' else 'z', end='') print('') T=int(input()) for _ in range(T): doit()
{ "input": [ "3\na\nbbbb\naz\n" ], "output": [ "\nb\nazaz\nby\n" ] }
582
7
Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag). You are given an n Γ— m grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count). Your job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells. Input The first line contains t (1 ≀ t ≀ 100), the number of test cases. In each test case, the first line will contain n (1 ≀ n ≀ 50) and m (1 ≀ m ≀ 50), the height and width of the grid respectively. The next n lines will contain the grid. Each character of the grid is either 'R', 'W', or '.'. Output For each test case, output "YES" if there is a valid grid or "NO" if there is not. If there is, output the grid on the next n lines. If there are multiple answers, print any. In the output, the "YES"s and "NO"s are case-insensitive, meaning that outputs such as "yEs" and "nO" are valid. However, the grid is case-sensitive. Example Input 3 4 6 .R.... ...... ...... .W.... 4 4 .R.W .... .... .... 5 1 R W R W R Output YES WRWRWR RWRWRW WRWRWR RWRWRW NO YES R W R W R Note The answer for the first example case is given in the example output, and it can be proven that no grid exists that satisfies the requirements of the second example case. In the third example all cells are initially coloured, and the colouring is valid.
t=int(input()) def solve(): n,m=map(int,input().split()) d=-1; x=True for i in range(n): s=input() for j in range(m): cnt=i+j if s[j]!='.': if d==-1: d=cnt+(s[j]!='R') elif s[j]=='R': if (cnt-d)%2!=0: x=False else: if (cnt-d)%2!=1: x=False if x: print("Yes") s="" for i in range(n): for j in range(m): cnt=i+j if (d-cnt)%2==0: s+='R' else: s+='W' s+='\n' print(s,end='') else: print("No") for i in range(t): solve()
{ "input": [ "3\n4 6\n.R....\n......\n......\n.W....\n4 4\n.R.W\n....\n....\n....\n5 1\nR\nW\nR\nW\nR\n" ], "output": [ "\nYES\nWRWRWR\nRWRWRW\nWRWRWR\nRWRWRW\nNO\nYES\nR\nW\nR\nW\nR\n" ] }
583
9
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm: * On the first step the string consists of a single character "a". * On the k-th step Polycarpus concatenates two copies of the string obtained on the (k - 1)-th step, while inserting the k-th character of the alphabet between them. Polycarpus uses the alphabet that consists of lowercase Latin letters and digits (a total of 36 characters). The alphabet characters are numbered like this: the 1-st character is "a", the 2-nd β€” "b", ..., the 26-th β€” "z", the 27-th β€” "0", the 28-th β€” "1", ..., the 36-th β€” "9". Let's have a closer look at the algorithm. On the second step Polycarpus will concatenate two strings "a" and insert the character "b" between them, resulting in "aba" string. The third step will transform it into "abacaba", and the fourth one - into "abacabadabacaba". Thus, the string constructed on the k-th step will consist of 2k - 1 characters. Polycarpus wrote down the string he got after 30 steps of the given algorithm and chose two non-empty substrings of it. Your task is to find the length of the longest common substring of the two substrings selected by Polycarpus. A substring s[i... j] (1 ≀ i ≀ j ≀ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac". The string is its own substring. The longest common substring of two strings s and t is the longest string that is a substring of both s and t. For example, the longest common substring of "contest" and "systemtesting" is string "test". There can be several common substrings of maximum length. Input The input consists of a single line containing four integers l1, r1, l2, r2 (1 ≀ li ≀ ri ≀ 109, i = 1, 2). The numbers are separated by single spaces. li and ri give the indices of the first and the last characters of the i-th chosen substring, correspondingly (i = 1, 2). The characters of string abracadabra are numbered starting from 1. Output Print a single number β€” the length of the longest common substring of the given strings. If there are no common substrings, print 0. Examples Input 3 6 1 4 Output 2 Input 1 1 4 4 Output 0 Note In the first sample the first substring is "acab", the second one is "abac". These two substrings have two longest common substrings "ac" and "ab", but we are only interested in their length β€” 2. In the second sample the first substring is "a", the second one is "c". These two substrings don't have any common characters, so the length of their longest common substring is 0.
aaa =0 def f(l1,r1,l2,r2,top): global aaa if (l1>r1 or l2> r2): return 0 if (top-1<=aaa) or (r1-l1+1<=aaa) or (r2-l2+1<=aaa): return 0 if top==2: return 1 if (l1>top): l1 -=top r1 -= top if (l2>top): l2-=top r2-=top #print(l1,r1,l2,r2,top) if (l1==l2 and r1==r2): return r1-l1+1 if (l1==0 and r1==top-1): return r2-l2+1 if (l2==0 and r2==top-1): return r1-l1+1 if ( (l1<= l2 and l2<= r1) or (l2<= l1 and l1<= r2)): ans = min(r1,r2) -max(l1,l2) +1 else: ans = 0 #print(ans) top = top//2 ans = max(ans, f(l1,min(r1,top-1),l2,min(r2,top-1), top)) ans = max(ans, f(l1,min(r1,top-1),max(top+1,l2),r2, top)) ans = max(ans, f(max(l1,top+1),r1, l2,min(r2,top-1), top)) ans = max(ans, f(max(l1,top+1),r1, max(l2,top+1),r2, top)) aaa = max(aaa,ans) return ans a = input().split() print(f(int(a[0]),int(a[1]),int(a[2]),int(a[3]),2**36))
{ "input": [ "3 6 1 4\n", "1 1 4 4\n" ], "output": [ "2\n", "0\n" ] }
584
11
Let's imagine that you're playing the following simple computer game. The screen displays n lined-up cubes. Each cube is painted one of m colors. You are allowed to delete not more than k cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) and the system counts the score. The number of points you score equals to the length of the maximum sequence of cubes of the same color that follow consecutively. Write a program that determines the maximum possible number of points you can score. Remember, you may delete no more than k any cubes. It is allowed not to delete cubes at all. Input The first line contains three integers n, m and k (1 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 105, 0 ≀ k < n). The second line contains n integers from 1 to m β€” the numbers of cube colors. The numbers of colors are separated by single spaces. Output Print the maximum possible number of points you can score. Examples Input 10 3 2 1 2 1 1 3 2 1 1 2 2 Output 4 Input 10 2 2 1 2 1 2 1 1 2 1 1 2 Output 5 Input 3 1 2 1 1 1 Output 3 Note In the first sample you should delete the fifth and the sixth cubes. In the second sample you should delete the fourth and the seventh cubes. In the third sample you shouldn't delete any cubes.
from sys import stdout from sys import stdin def get(): return stdin.readline().strip() def getf(): return [int(i) for i in get().split()] def put(a, end = "\n"): stdout.write(str(a) + end) def putf(a, sep = " ", end = "\n"): stdout.write(sep.join([str(i) for i in a]) + end) from collections import defaultdict as dd def bruh(): n, m, k = getf() a = getf() col = [[] for i in range(m + 1)] for i in range(n): col[a[i]] += [i] pref_c = [[0] * len(col[i]) for i in range(m + 1)] for i in range(1, m + 1): for j in range(1, len(col[i])): pref_c[i][j] = pref_c[i][j - 1] + col[i][j] - col[i][j - 1] - 1 ans = 1 for i in range(1, m + 1): r = 1 for j in range(len(col[i])): while(r < len(col[i]) and pref_c[i][r] - pref_c[i][j] <= k): r += 1 ans = max(ans, r - j) put(ans) bruh()
{ "input": [ "3 1 2\n1 1 1\n", "10 2 2\n1 2 1 2 1 1 2 1 1 2\n", "10 3 2\n1 2 1 1 3 2 1 1 2 2\n" ], "output": [ "3", "5", "4" ] }
585
7
The Little Elephant very much loves sums on intervals. This time he has a pair of integers l and r (l ≀ r). The Little Elephant has to find the number of such integers x (l ≀ x ≀ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not. Help him and count the number of described numbers x for a given pair l and r. Input The single line contains a pair of integers l and r (1 ≀ l ≀ r ≀ 1018) β€” the boundaries of the interval. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. Output On a single line print a single integer β€” the answer to the problem. Examples Input 2 47 Output 12 Input 47 1024 Output 98 Note In the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44.
def f(x): s = str(x); return x//10 + min(x,9) - (s[0] > s[-1]) n,m = map(int,input().split()) print(f(m)-f(n-1))
{ "input": [ "47 1024\n", "2 47\n" ], "output": [ "98\n", "12\n" ] }
586
11
Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not. The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home. Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters β€” illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it. Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most n days. Help the king. Input The first line contains two space-separated integers n, m <image> β€” the number of cities and roads in Berland, correspondingly. Next m lines contain the descriptions of roads in Berland: the i-th line contains three space-separated integers ai, bi, ci (1 ≀ ai, bi ≀ n; ai β‰  bi; 0 ≀ ci ≀ 1). The first two integers (ai, bi) are indexes of the cities that are connected by the i-th road, the third integer (ci) equals 1, if the road was initially asphalted, and 0 otherwise. Consider the cities in Berland indexed from 1 to n, and the roads indexed from 1 to m. It is guaranteed that between two Berlandian cities there is not more than one road. Output In the first line print a single integer x (0 ≀ x ≀ n) β€” the number of days needed to asphalt all roads. In the second line print x space-separated integers β€” the indexes of the cities to send the workers to. Print the cities in the order, in which Valera send the workers to asphalt roads. If there are multiple solutions, print any of them. If there's no way to asphalt all roads, print "Impossible" (without the quotes). Examples Input 4 4 1 2 1 2 4 0 4 3 1 3 2 0 Output 4 3 2 1 3 Input 3 3 1 2 0 2 3 0 3 1 0 Output Impossible
s=list(map(int,input().split())) n=s[0] m=s[1] roads=[] for i in range(0,n+1): roads.append([]) for i in range(0,m): s=list(map(int,input().split())) roads[s[0]].append([s[1],s[2]]) roads[s[1]].append([s[0],s[2]]) col=[-1]*(n+1) ##def dfs(v,c): ## success=True ## col[v]=c ## for e in roads[v]: ## if col[e[0]]==-1: ## if e[1]: ## success=success and dfs(e[0],c) ## else: ## success=success and dfs(e[0],1-c) ## else: ## if abs(col[e[0]]-c)!=1-e[1]: ## return False ## return success bfs=True for start in range(1,n+1): if col.count(-1)==1: break if col[start]==-1: Q=[start] col[start]=1 while len(Q)>0 and bfs: curr=Q.pop(0) for e in roads[curr]: if col[e[0]]==-1: Q.append(e[0]) if e[1]: col[e[0]]=col[curr] else: col[e[0]]=1-col[curr] elif abs(col[e[0]]-col[curr])!=(1-e[1]): #CONTRADICTION bfs=False Q=[] break if bfs: L=[j for j in range(1,n+1) if col[j]==1] print(len(L)) ans='' for i in range(0,len(L)): ans+=str(L[i])+' ' ans=ans[:len(ans)-1] print(ans) else: print("Impossible")
{ "input": [ "3 3\n1 2 0\n2 3 0\n3 1 0\n", "4 4\n1 2 1\n2 4 0\n4 3 1\n3 2 0\n" ], "output": [ "Impossible\n", "2\n1 2\n" ] }
587
9
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d. Note that the order of the points inside the group of three chosen points doesn't matter. Input The first line contains two integers: n and d (1 ≀ n ≀ 105; 1 ≀ d ≀ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 β€” the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase. Output Print a single integer β€” the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 4 3 1 2 3 4 Output 4 Input 4 2 -3 -2 -1 0 Output 2 Input 5 19 1 10 20 30 50 Output 1 Note In the first sample any group of three points meets our conditions. In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}. In the third sample only one group does: {1, 10, 20}.
def main(): n, d = map(int, input().split()) x = list(map(int, input().split())) ans = j = 0 for i in range(2, n): while x[i] - x[j] > d: j += 1 span = i - j ans += span * (span - 1) // 2 print(ans) if __name__ == "__main__": main()
{ "input": [ "4 3\n1 2 3 4\n", "4 2\n-3 -2 -1 0\n", "5 19\n1 10 20 30 50\n" ], "output": [ "4\n", "2\n", "1\n" ] }
588
7
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. Input The first line contains an integer number n (1 ≀ n ≀ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. Output Print the name of the winner. Examples Input 3 mike 3 andrew 5 mike 2 Output andrew Input 3 andrew 3 andrew 2 mike 5 Output andrew
a = [] b = {} def solve(): n = int(input()) for i in range(n): x, y = input().split() y = int(y) b[x] = b.get(x, 0) + y a.append([x, b[x]]) m = max(b.values()) for i, j in a: if j >= m and b[i] == m: print(i) break #if __name__ == "__main__": solve()
{ "input": [ "3\nandrew 3\nandrew 2\nmike 5\n", "3\nmike 3\nandrew 5\nmike 2\n" ], "output": [ "andrew\n", "andrew\n" ] }
589
7
You are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle). Your task is to determine if the rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square. Input The first line contains a single integer n (1 ≀ n ≀ 5). Next n lines contain four integers each, describing a single rectangle: x1, y1, x2, y2 (0 ≀ x1 < x2 ≀ 31400, 0 ≀ y1 < y2 ≀ 31400) β€” x1 and x2 are x-coordinates of the left and right edges of the rectangle, and y1 and y2 are y-coordinates of the bottom and top edges of the rectangle. No two rectangles overlap (that is, there are no points that belong to the interior of more than one rectangle). Output In a single line print "YES", if the given rectangles form a square, or "NO" otherwise. Examples Input 5 0 0 2 3 0 3 3 5 2 0 5 2 3 2 5 5 2 2 3 3 Output YES Input 4 0 0 2 3 0 3 3 5 2 0 5 2 3 2 5 5 Output NO
import sys fin = sys.stdin # fout = sys.stdout n = int(fin.readline()) p = [] for i in range(n): a, b, c, d = map(int, fin.readline().split()) p += [((a, b), (c, d))] def width(rect): return rect[1][0] - rect[0][0] def height(rect): return rect[1][1] - rect[0][1] def square(rect): return width(rect) * height(rect) def squareOfRects(rects): return sum(square(r) for r in rects) def left(rects): return min(r[0][0] for r in rects) def right(rects): return max(r[1][0] for r in rects) def bottom(rects): return min(r[0][1] for r in rects) def top(rects): return max(r[1][1] for r in rects) def isSquare(rects): w, h = right(rects) - left(rects), top(rects) - bottom(rects) return w == h and squareOfRects(rects) == w * h print("YES" if isSquare(p) else "NO")
{ "input": [ "5\n0 0 2 3\n0 3 3 5\n2 0 5 2\n3 2 5 5\n2 2 3 3\n", "4\n0 0 2 3\n0 3 3 5\n2 0 5 2\n3 2 5 5\n" ], "output": [ "YES\n", "NO\n" ] }
590
9
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) ΠΈ 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "Π’SCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again. Polycarpus has nb pieces of bread, ns pieces of sausage and nc pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are pb rubles for a piece of bread, ps for a piece of sausage and pc for a piece of cheese. Polycarpus has r rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient. Input The first line of the input contains a non-empty string that describes the recipe of "Le Hamburger de Polycarpus". The length of the string doesn't exceed 100, the string contains only letters 'B' (uppercase English B), 'S' (uppercase English S) and 'C' (uppercase English C). The second line contains three integers nb, ns, nc (1 ≀ nb, ns, nc ≀ 100) β€” the number of the pieces of bread, sausage and cheese on Polycarpus' kitchen. The third line contains three integers pb, ps, pc (1 ≀ pb, ps, pc ≀ 100) β€” the price of one piece of bread, sausage and cheese in the shop. Finally, the fourth line contains integer r (1 ≀ r ≀ 1012) β€” the number of rubles Polycarpus has. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Output Print the maximum number of hamburgers Polycarpus can make. If he can't make any hamburger, print 0. Examples Input BBBSSC 6 4 1 1 2 3 4 Output 2 Input BBC 1 10 1 1 10 1 21 Output 7 Input BSC 1 1 1 1 1 3 1000000000000 Output 200000000001
def f(x): cb = max(0, (tb*x - nb)*pb) cs = max(0, (ts*x - ns)*ps) cc = max(0, (tc*x - nc)*pc) return cc+cs+cb <= rs s = list(input()) tb, ts, tc = s.count('B'), s.count('S'), s.count('C') nb, ns, nc = map(int, input().split()) pb, ps, pc = map(int, input().split()) rs = int(input()) l, r = 0, 10**14 while l < r: m = (l+r) // 2 if f(m): l = m+1 else: r = m print(l-1)
{ "input": [ "BBC\n1 10 1\n1 10 1\n21\n", "BSC\n1 1 1\n1 1 3\n1000000000000\n", "BBBSSC\n6 4 1\n1 2 3\n4\n" ], "output": [ "7\n", "200000000001\n", "2\n" ] }
591
7
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show. The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions: * Is it true that y is strictly larger than number x? * Is it true that y is strictly smaller than number x? * Is it true that y is larger than or equal to number x? * Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no". Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible". Input The first line of the input contains a single integer n (1 ≀ n ≀ 10000) β€” the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is: * ">" (for the first type queries), * "<" (for the second type queries), * ">=" (for the third type queries), * "<=" (for the fourth type queries). All values of x are integer and meet the inequation - 109 ≀ x ≀ 109. The answer is an English letter "Y" (for "yes") or "N" (for "no"). Consequtive elements in lines are separated by a single space. Output Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation - 2Β·109 ≀ y ≀ 2Β·109. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes). Examples Input 4 &gt;= 1 Y &lt; 3 N &lt;= -3 N &gt; 55 N Output 17 Input 2 &gt; 100 Y &lt; -100 Y Output Impossible
def main(): lo, hi = -2000000000, 2000000001 for _ in range(int(input())): s, x, yn = input().split() if yn == "N": s = {"<": ">=", ">": "<=", "<=": ">", ">=": "<"}[s] x = int(x) + 1 if s in ("<=", ">") else int(x) if s[0] == "<": if hi > x: hi = x else: if lo < x: lo = x print((lo + hi) // 2 if lo < hi else "Impossible") if __name__ == '__main__': main()
{ "input": [ "4\n&gt;= 1 Y\n&lt; 3 N\n&lt;= -3 N\n&gt; 55 N\n", "2\n&gt; 100 Y\n&lt; -100 Y\n" ], "output": [ "-2000000000\n", "-2000000000\n" ] }
592
10
Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right. Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: * Each piece should contain at least l numbers. * The difference between the maximal and the minimal number on the piece should be at most s. Please help Alexandra to find the minimal number of pieces meeting the condition above. Input The first line contains three space-separated integers n, s, l (1 ≀ n ≀ 105, 0 ≀ s ≀ 109, 1 ≀ l ≀ 105). The second line contains n integers ai separated by spaces ( - 109 ≀ ai ≀ 109). Output Output the minimal number of strip pieces. If there are no ways to split the strip, output -1. Examples Input 7 2 2 1 3 1 2 4 1 2 Output 3 Input 7 2 2 1 100 1 100 1 100 1 Output -1 Note For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2]. For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.
def split(a,n,s,l): pieces = [] i = 1 tmpmin = a[0] tmpmax = a[0] tmppc = [a[0]] while i<n: if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s: tmppc.append(a[i]) if a[i]<tmpmin: tmpmin=a[i] elif a[i]>tmpmax: tmpmax = a[i] else: pieces.append(tmppc) tmppc = [a[i]] tmpmin = a[i] tmpmax = a[i] i += 1 pieces.append(tmppc) fail = False for j in range(len(pieces)): if len(pieces[j])<l: if j>0: prevpc = pieces[j-1] minj = min(pieces[j]) maxj = max(pieces[j]) while len(pieces[j])<l: tmp = prevpc.pop() if abs(tmp-minj)<=s and abs(tmp-maxj)<=s: pieces[j].insert(0,tmp) if tmp<minj: minj=tmp elif tmp>maxj: maxj=tmp else: return -1 if len(prevpc)<l: return -1 else: return -1 return len(pieces) n,s,l = [int(s) for s in input().split()] a = [int(s) for s in input().split()] res = split(a,n,s,l) if res<0: a.reverse() res = split(a,n,s,l) print(res)
{ "input": [ "7 2 2\n1 3 1 2 4 1 2\n", "7 2 2\n1 100 1 100 1 100 1\n" ], "output": [ "3", "-1" ] }
593
9
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old. They will have dinner around some round tables. You want to distribute foxes such that: 1. Each fox is sitting at some table. 2. Each table has at least 3 foxes sitting around it. 3. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≀ i ≀ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent. If it is possible to distribute the foxes in the desired manner, find out a way to do that. Input The first line contains single integer n (3 ≀ n ≀ 200): the number of foxes in this party. The second line contains n integers ai (2 ≀ ai ≀ 104). Output If it is impossible to do this, output "Impossible". Otherwise, in the first line output an integer m (<image>): the number of tables. Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers β€” indices of fox sitting around that table in clockwise order. If there are several possible arrangements, output any of them. Examples Input 4 3 4 8 9 Output 1 4 1 2 4 3 Input 5 2 2 2 2 2 Output Impossible Input 12 2 3 4 5 6 7 8 9 10 11 12 13 Output 1 12 1 2 3 6 5 12 9 8 7 10 11 4 Input 24 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Output 3 6 1 2 3 6 5 4 10 7 8 9 12 15 14 13 16 11 10 8 17 18 23 22 19 20 21 24 Note In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes. In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number.
#E def main(): sieve = [False, True] * 10001 for i in range(3, 140, 2): if sieve[i]: j, k = i * 2, i * i le = (20001 - k) // j + 1 sieve[k::j] = [False] * le n = int(input()) aa = list(map(int, input().split())) pp = [-1] * n def dget(v): if dsu[v]!=v: dsu[v] = dget(dsu[v]) return dsu[v] def dfs(v): if free[v]: free[v], a, pv = False, aa[v], pp[v] for i, p in enumerate(pp): if sieve[a + aa[i]] and pv != i and (p == -1 or dfs(p)): pp[i] = v return True return False for i in range(n): free = [True] * n if not dfs(i): print('Impossible') return dsu = list(range(n)) for i, p in enumerate(pp): i, p = dget(i), dget(p) dsu[p] = i print(sum(dget(i)==i for i in range(n))) for i in range(n): if dget(i) == i: row = [sum(dget(j) == i for j in range(n)), i + 1] j = pp[i] while j != i: row.append(j + 1) j = pp[j] print(*row) main()
{ "input": [ "5\n2 2 2 2 2\n", "4\n3 4 8 9\n", "12\n2 3 4 5 6 7 8 9 10 11 12 13\n", "24\n2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25\n" ], "output": [ "Impossible\n", "1\n4 1 2 4 3\n", "1\n12 1 2 3 6 5 12 9 8 7 10 11 4\n", "3\n8 1 2 3 24 5 6 23 4\n10 7 8 9 12 15 14 13 16 11 10\n6 17 18 21 20 19 22\n" ] }
594
11
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h Γ— w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process. Input The first line of the input contains three integers: h, w, n β€” the sides of the board and the number of black cells (1 ≀ h, w ≀ 105, 1 ≀ n ≀ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≀ ri ≀ h, 1 ≀ ci ≀ w) β€” the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct. Output Print a single line β€” the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7. Examples Input 3 4 2 2 2 2 3 Output 2 Input 100 100 3 15 16 16 15 99 88 Output 545732279
#!/usr/bin/env python # 560E_chess.py - Codeforces.com 560E Chess program # # Copyright (C) 2015 Sergey """ Input The first line of the input contains three integers: h,w,n the sides of the board and the number of black cells Next n lines contain the description of black cells. The ith of these lines contains numbers ri,?ci the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct. Output Print a single line the remainder of the number of ways to move Gerald's pawn from the upper lef to the lower right corner modulo 10^9+7. """ # Standard modules import unittest import sys # Additional modules ############################################################################### # Chess Class ############################################################################### class Chess: """ Chess representation """ N = 200001 MOD = 10**9+7 def __init__(self, args): """ Default constructor """ self.h, self.w, self.imax, self.numa, self.numb = args # Sort black cells self.pt = sorted(zip(self.numa, self.numb)) self.pt.append((self.h, self.w)) # Populate factorial self.fact = [1] prev = 1 for i in range(1, self.N): f = (prev * i) % self.MOD self.fact.append(f) prev = f # Populate Inv factorial self.inv = [0] * self.N self.inv[self.N-1] = self.modInvfact(self.N-1) for i in range(self.N-2, -1, -1): self.inv[i] = (self.inv[i+1] * (i+1)) % self.MOD # Populate number of ways self.ways = [] for i in range(len(self.pt)): (h, w) = self.pt[i] self.ways.append(self.modC(h + w - 2, h - 1)) for j in range(i): (hj, wj) = self.pt[j] if (hj <= h and wj <= w): mult = self.modC(h - hj + w - wj, h - hj) self.ways[i] = self.modSub( self.ways[i], self.ways[j] * mult, self.MOD) def modC(self, n, k): return ( self.fact[n] * ((self.inv[k] * self.inv[n-k]) % self.MOD)) % self.MOD def modInvfact(self, n): return self.modExp(self.fact[n], self.MOD-2, self.MOD) def modExp(self, n, e, p): res = 1 while e > 0: if (e % 2 == 1): res = (res * n) % p e >>= 1 n = (n * n) % p return res def modSub(self, a, b, p): return ((a - b) % p + p) % p def calculate(self): """ Main calcualtion function of the class """ result = self.ways[-1] return str(result) ############################################################################### # Helping classes ############################################################################### ############################################################################### # Chess Class testing wrapper code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return sys.stdin.readline() # Getting string inputs. Place all uinput() calls here h, w, imax = list(map(int, uinput().split())) numnums = list(map(int, " ".join(uinput() for i in range(imax)).split())) # Splitting numnums into n arrays numa = [] numb = [] for i in range(0, 2*imax, 2): numa.append(numnums[i]) numb.append(numnums[i+1]) # Decoding inputs into a list return [h, w, imax, numa, numb] def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Chess(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_Chess_class__basic_functions(self): """ Chess class basic functions testing """ # Constructor test d = Chess([3, 4, 2, [2, 2], [2, 3]]) self.assertEqual(d.imax, 2) self.assertEqual(d.pt[0], (2, 2)) # modExp self.assertEqual(d.modExp(3, 3, 6), 3) # Factorials self.assertEqual(d.fact[3], 6) self.assertEqual(d.inv[3], d.modInvfact(3)) # Binominal self.assertEqual(d.modC(4, 2), 6) # Ways self.assertEqual(d.ways[0], 2) def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ # Sample test 1 test = "3 4 2\n2 2\n2 3" self.assertEqual(calculate(test), "2") self.assertEqual(get_inputs(test)[0], 3) self.assertEqual(list(get_inputs(test)[3]), [2, 2]) self.assertEqual(list(get_inputs(test)[4]), [2, 3]) # Sample test 2 test = "100 100 3\n15 16\n16 15\n99 88" self.assertEqual(calculate(test), "545732279") # Sample test 3 test = "1\n12" # self.assertEqual(calculate(test), "0") # My test 4 test = "1\n12" # self.assertEqual(calculate(test), "0") def test_time_limit_test(self): """ Quiz time limit test """ import random # Time limit test imax = 2000 h = 100000 w = 99000 num = str(imax) test = str(h) + " " + str(w) + " " + num + "\n" numnums = [str(i) + " " + str(i+1) for i in range(imax)] test += "\n".join(numnums) + "\n" import timeit start = timeit.default_timer() args = get_inputs(test) init = timeit.default_timer() d = Chess(args) calc = timeit.default_timer() d.calculate() stop = timeit.default_timer() print( "\nTime Test: " + "{0:.3f}s (inp {1:.3f}s init {2:.3f}s calc {3:.3f}s)". format(stop-start, init-start, calc-init, stop-calc)) if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string sys.stdout.write(calculate())
{ "input": [ "100 100 3\n15 16\n16 15\n99 88\n", "3 4 2\n2 2\n2 3\n" ], "output": [ "545732279\n", "2\n" ] }
595
7
Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. <image> Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two. Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps. Input The first line of input contains integer n (1 ≀ n ≀ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≀ wi ≀ 106 for each 1 ≀ i ≀ n), the powers of two forming the weights values. Output Print the minimum number of steps in a single line. Examples Input 5 1 1 2 3 3 Output 2 Input 4 0 1 2 3 Output 4 Note In the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two. In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.
def inc(a,w): n=len(a) i=w while(i<n and a[i]==1): a[i]=0 i+=1 if(i<n): a[i]=1 else: a.append(1) n=int(input()) x=input().split(' ') w=[int(y) for y in x] a=[0]*1000024 for t in w: inc(a,t) print(sum(a))
{ "input": [ "5\n1 1 2 3 3\n", "4\n0 1 2 3\n" ], "output": [ "2\n", "4\n" ] }
596
9
In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server. In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma - mb, where a is the most loaded server and b is the least loaded one. In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another. Write a program to find the minimum number of seconds needed to balance the load of servers. Input The first line contains positive number n (1 ≀ n ≀ 105) β€” the number of the servers. The second line contains the sequence of non-negative integers m1, m2, ..., mn (0 ≀ mi ≀ 2Β·104), where mi is the number of tasks assigned to the i-th server. Output Print the minimum number of seconds required to balance the load. Examples Input 2 1 6 Output 2 Input 7 10 11 10 11 10 11 11 Output 0 Input 5 1 2 3 4 5 Output 3 Note In the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2. In the second example the load is already balanced. A possible sequence of task movements for the third example is: 1. move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5); 2. then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4); 3. then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds.
def inpList(): return list(map(int,input().split())) def inp(): return int(input()) n=inp() a=inpList() x=sum(a) p=x//n t=x%n a.sort() suma=0 for i in range(n-t): suma+=abs(p-a[i]) for i in range(n-t,n): suma+=abs(a[i]-p-1) print(suma//2)
{ "input": [ "2\n1 6\n", "7\n10 11 10 11 10 11 11\n", "5\n1 2 3 4 5\n" ], "output": [ "2\n", "0\n", "3\n" ] }
597
8
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time. Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well. You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times. Input The only line of the input contains a pair of integers n (1000 ≀ n ≀ 10 000) and t (0 ≀ t ≀ 2 000 000 000) β€” the number of transistors in the initial time and the number of seconds passed since the initial time. Output Output one number β€” the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10 - 6. Examples Input 1000 1000000 Output 1011.060722383550382782399454922040
def f(l): n,t = l #1e3-1e4; 2e9; return n*(1.000000011**t) l = list(map(int,input().split())) print(f(l))
{ "input": [ "1000 1000000\n" ], "output": [ "1011.060722405749039" ] }
598
12
Input The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid"). Output Output a single integer. Examples Input A221033 Output 21 Input A223635 Output 22 Input A232726 Output 23
def f(n): if n == 'A': return 1 if n == '1': return 10 return int(n) print(sum(map(f, input())))
{ "input": [ "A232726\n", "A223635\n", "A221033\n" ], "output": [ "23\n", "22\n", "21\n" ] }
599
7
A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer. Limak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards. He is allowed to at most once discard two or three cards with the same number. Of course, he won't discard cards if it's impossible to choose two or three cards with the same number. Given five numbers written on cards, cay you find the minimum sum of numbers on remaining cards? Input The only line of the input contains five integers t1, t2, t3, t4 and t5 (1 ≀ ti ≀ 100) β€” numbers written on cards. Output Print the minimum possible sum of numbers written on remaining cards. Examples Input 7 3 7 3 20 Output 26 Input 7 9 3 1 8 Output 28 Input 10 10 10 10 10 Output 20 Note In the first sample, Limak has cards with numbers 7, 3, 7, 3 and 20. Limak can do one of the following. * Do nothing and the sum would be 7 + 3 + 7 + 3 + 20 = 40. * Remove two cards with a number 7. The remaining sum would be 3 + 3 + 20 = 26. * Remove two cards with a number 3. The remaining sum would be 7 + 7 + 20 = 34. You are asked to minimize the sum so the answer is 26. In the second sample, it's impossible to find two or three cards with the same number. Hence, Limak does nothing and the sum is 7 + 9 + 1 + 3 + 8 = 28. In the third sample, all cards have the same number. It's optimal to discard any three cards. The sum of two remaining numbers is 10 + 10 = 20.
import sys from collections import Counter def main(): s = list(map(int, sys.stdin.read().strip().split())) return sum(s) - max((i*min(j, 3) for i,j in Counter(s).items() if j > 1), default=0) print(main())
{ "input": [ "7 9 3 1 8\n", "7 3 7 3 20\n", "10 10 10 10 10\n" ], "output": [ "28\n", "26\n", "20\n" ] }