text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` n = int(input()) m = list(map(int, input().split())) t = int(input()) m.sort() if n == 1 or len(m) == 1: print(1) elif m[-1]-m[0] <= t: print(n) else: mx = 1 for i in range(n-1): ma = 1 fr = m[i] for j in range(i+1, n): if m[j]-fr <= t: ma += 1 else: break mx = max(ma, mx) print(mx) ```
12,800
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` n = int(input()) t = list(map(int, input().split())) tem = int(input()) t.sort() rmax = 1 for cont in range(0,n-1): r = 1 for cont2 in range(cont+1,n): if t[cont2] -t[cont] <= tem: r += 1 else: break if r > rmax: rmax = r print(rmax) ``` Yes
12,801
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` class CodeforcesTask386BSolution: def __init__(self): self.result = '' self.n = 0 self.times = [] self.t = 0 def read_input(self): self.n = int(input()) self.times = [int(x) for x in input().split(" ")] self.t = int(input()) def process_task(self): result = 0 self.times.sort() for start in set(self.times): in_range = 0 for time in self.times: if start <= time <= start + self.t: in_range += 1 result = max(result, in_range) self.result = str(result) def get_result(self): return self.result if __name__ == "__main__": Solution = CodeforcesTask386BSolution() Solution.read_input() Solution.process_task() print(Solution.get_result()) ``` Yes
12,802
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` 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") ########################################################## from collections import Counter # c=sorted((i,int(val))for i,val in enumerate(input().split())) import heapq # c=sorted((i,int(val))for i,val in enumerate(input().split())) # n = int(input()) # ls = list(map(int, input().split())) # n, k = map(int, input().split()) # n =int(input()) # e=list(map(int, input().split())) from collections import Counter #print("\n".join(ls)) #print(os.path.commonprefix(ls[0:2])) #for i in range(int(input())): n=int(input()) arr=list(map(int, input().split())) t=int(input()) arr.sort() r=0 l=0 ans=0 while r<n: while arr[r]-arr[l]>t: l+=1 ans=max(ans,r-l+1) r+=1 print(ans) #for i in range(n): ``` Yes
12,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` __author__ = 'asmn' n = int(input()) a = sorted(map(int, input().split())) dt = int(input()) ans, l, r = 0, 0, 0 while r < len(a): while r < len(a) and a[r] - a[l] <= dt: r += 1 ans = max(ans, r - l) l += 1 print(ans) ``` Yes
12,804
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) t=int(input()) a.sort() a=set(a) b=list(a) d=1 if(len(b)==1): print(1) else: for i in range(1,len(b)-1): if(b[i]-b[i-1]>t): d=1+d if(b[len(b)-1]-b[len(b)-2]>t): print(d+1) else: print(d) ``` No
12,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` def check(n, li, t): num = 0 li.sort() for i in range(len(li)): diff = 0 if(i < len(li)-1): diff = li[i] - li[i+1] else: diff = li[i] - li[0] if(abs(diff) <= t ): num += 1 return num n = int(input()) li = list(map(int, input().split())) t = int(input()) print(check(n, li, t)) ``` No
12,806
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` n=int(input()) l=list(map(int,input().split())) t=int(input()) l.sort() mx=0 for j in range(0,n-1): i=j count=1 while i<n-1: if l[i+1]-l[i]<=t: i+=1 count+=1 else: break if count>mx: mx=count print(mx) ``` No
12,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Submitted Solution: ``` import math n = int(input()) a = list(map(int,input().strip().split()))[:n] t=int(input()) a.sort() c=0 for i in range(0,n-1,1): if(math.fabs(a[i]-a[i+1])<=t): c+=1 else: continue print(c) ``` No
12,808
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` a, b = map(int, input().split()) s = [i*i for i in range(1, a)] t = [i*i for i in range(1, b)] def r(x): return int(x**0.5) for i in s: if a*a-i in s: for j in t: if b*b-j in t: if i!=j and i*j-(a*a-i)*(b*b-j) == 0: print('YES') print(r(i),r(a*a-i)) print(r(j),-r(b*b-j)) print(0,0) exit() print('NO') ```
12,809
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` a,b=list(map(int,input().split())) f=0 x1,y1,x2,y2=0,0,0,0 for x in range(1,a+1): for y in range(1,a+1): if (x**2+y**2==a**2) and (x!=0 and y!=0): m=-x/y if float(int(b/(1+m**2)**(0.5)))==b/(1+m**2)**(0.5) and float(int((b*m)/(1+m**2)**(0.5)))==(b*m)/(1+m**2)**(0.5): x1=x y1=y x2=int(b/(1+m**2)**(0.5)) y2=int((b*m)/(1+m**2)**(0.5)) if x1==x2 or y1==y2: x2=-x2 y2=-y2 f=1 break if f: break if f: print('YES') print(0,0) print(x1,y1) print(x2,y2) else: print('NO') ```
12,810
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` a,b=map(int,input().split()) def get(a): return list([i,j] for i in range(1,a) for j in range(1,a) if i*i+j*j==a*a) A=get(a) B=get(b) for [a,b] in A: for [c,d] in B: if a*c==b*d and b!=d: print("YES\n0 0") print(-a,b) print(c,d) exit(0) print("NO") ```
12,811
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` sqrt = {i * i: i for i in range(1, 1000)} a, b = map(int, input().split()) for y in range(1, a): x2 = a * a - y * y if x2 in sqrt: x = sqrt[x2] if b * y % a == 0 and b * x % a == 0 and b * x // a != y: print('YES') print(-x, y) print(0, 0) print(b * y // a, b * x // a) exit() print('NO') ```
12,812
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` import math squares = set() for i in range(1, 1001): squares.add(i ** 2) def check(n): global squares for i in range(1, 1001): if (n - i ** 2) in squares: return True return False a, b = map(int, input().split()) g = math.gcd(a ** 2, b ** 2) if check(g): f = False for i in range(1, 1001): if (g - i ** 2) in squares: x = i y = int((g - i ** 2) ** 0.5) t = int((a ** 2 // g) ** 0.5) s = int((b ** 2 // g) ** 0.5) if (abs(t*x) != abs(s * y)): print("YES") print(-t * y, t * x) print(0, 0) print(s * x, s * y) f = True break if not f: print("NO") else: print("NO") ```
12,813
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` x,y = map(int,input().split()) if x>=y: a=x b=y else: a=y b=x lmb = a/b f=1 for i in range(1,b): p = lmb*pow((b**2-i**2),1/2) q = lmb*i if p-int(p)<=0.00001 and q-int(q)<=0.00001: print("YES") print("0 0") print(str(int(p/lmb))+" "+str(i)) print(str(-1*int(q))+" "+str(int(p))) f=0 break if f: print("NO") ```
12,814
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def count1(s): c=0 for i in s: if(i=='1'): c+=1 return(c) def binary(n): return(bin(n).replace("0b","")) def decimal(s): return(int(s,2)) def pow2(n): p=0 while(n>1): n//=2 p+=1 return(p) def isPrime(n): if(n==1): return(False) else: root=int(n**0.5) root+=1 for i in range(2,root): if(n%i==0): return(False) return(True) a,b=map(int,input().split()) a,b=min(a,b),max(a,b) f=False ans=[[0,0]] f=False l1=[] l2=[] for i in range(1,a): t=(a*a-i*i)**0.5 if(int(t)==t): l1.append([int(t),i]) for i in range(1,b): t=(b*b-i*i)**0.5 if(int(t)==t): l2.append([int(t),-i]) f=True for i in range(0,len(l1)): if(f): for j in range(0,len(l2)): x1=l1[i][0] x2=l2[j][0] y1=l1[i][1] y2=l2[j][1] if(x1!=x2 and ((y2-y1)**2+(x2-x1)**2)==(a**2+b**2)): f=False print("YES") print(0,0) print(x1,y1) print(x2,y2) break if(f): print("NO") ```
12,815
Provide tags and a correct Python 3 solution for this coding contest problem. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Tags: brute force, geometry, implementation, math Correct Solution: ``` from math import * a,b=map(int,input().split()) def gen(n): for x in range(1,n): y = round(sqrt(n*n-x*x)) if x*x+y*y == n*n: yield (x,y) for u in gen(a): for v in gen(b): if u[0]*v[0]-u[1]*v[1]==0 and u[0]!=v[0]: print("YES\n0 0") print(u[0],u[1]) print(v[0],-v[1]) exit() print("NO") ```
12,816
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` #!/usr/bin/python3 -SOO from math import sqrt a,b = map(int,input().strip().split()) for i in range(1,a): x = a*a - i*i if x<=0 or int(sqrt(x) + 0.5)**2 != x: continue u = b*i/a v = b*sqrt(x)/a if abs(u-int(u)) < 0.0005 and abs(v-int(v)) < 0.0005 and int(v)!=i: print('YES') print('0 0') print('%d %d'%(-int(u),int(v))) print('%d %d'%(int(sqrt(x)),i)) break else: print('NO') ``` Yes
12,817
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` a,b=map(int,input().split()) def get(a): return list([i,j] for i in range(1,a) for j in range(1,a) if i*i+j*j==a*a) A=get(a) B=get(b) for [a,b] in A: for [c,d] in B: if a*c==b*d and b!=d: print("YES\n0 0\n%d %d\n%d %d" %(-a,b,c,d)) exit(0) print("NO") ``` Yes
12,818
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` a, b = map(int, input().split()) import math EPS = 1e-9 for x1 in range(1, a): y1 = math.sqrt(a**2 - x1**2) if y1.is_integer(): y1 = round(y1) g = math.gcd(x1, y1) xv, yv = -1* (y1//g), x1//g r = b / (math.sqrt(xv**2 + yv**2)) if r.is_integer() and round(yv*r) != y1: print("YES") print(0, 0) print(round(x1), round(y1)) print(round(xv*r), round(yv*r)) break else: print("NO") ``` Yes
12,819
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` from math import hypot a, b = map(int, input().split()) c = max(a, b) for x in range(1, c + 1): for y in range(1, c + 1): if abs(hypot(x, y) - a) <= 1e-12: nx = y ny = -x l = hypot(nx, ny) nx = round(nx / l * b) ny = round(ny / l * b) if x != nx and abs(hypot(nx, ny) - b) <= 1e-12: print("YES") print(x, y) print(nx, ny) print(0, 0) exit() print("NO") ``` Yes
12,820
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` a, b = map(int, input().split()) cand_a = [] cand_b = [] for i in range(1, 1000): j = 1 while j * j + i * i <= 1000000: if i * i + j * j == a * a: cand_a.append((i, j)) if i * i + j * j == b * b: cand_b.append((-i, j)) j += 1 def dist(a, b): return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 for point_a in cand_a: for point_b in cand_b: print(point_a, point_b) if dist(point_a, point_b) == a * a + b * b: print("YES") print("0 0") print("%d %d" % (point_a[0], point_a[1])) print("%d %d" % (point_b[0], point_b[1])) exit(0) print("NO") ``` No
12,821
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` import math def square(a): lis=[] for k in range(a+1): if math.sqrt(a**2-k **2)==int(math.sqrt(a**2-k **2)): lis.append((k,math.sqrt(a**2-k **2))) return lis def check(a): boo=1 if len(square(a))==2 and int(math.sqrt(a))==math.sqrt(a): boo=0 return boo a,b=input().split() a=int(a) b=int(b) if check(a)*check(b)==0: print('NO') else: v=0 lisA=[] lisB=[] for A in square(a): for B in square(b): if A[0]*B[0]-A[1]*B[1]==0: v=1 lisA.append(A) lisB.append(B) if v==1: print('YES') print(0,0) print(-int(lisA[1][0]),int(lisA[1][1])) print(int(lisB[1][0]),int(lisB[1][1])) else: print('NO') ``` No
12,822
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` a,b=map(int,input().split()) x1,y1=0,0 for i in range(1,1001): for j in range(i+1,1001): if a**2==i**2+j**2 and x1==0: x1,y1=i,j x2,y2=-10**18,-10**18 for i in range(-1000,1001): if i==0: continue for j in range(-1000,1001): if j==0: continue if b**2==i**2+j**2 and i*x1+j*y1==0 and x2==-10**18 and (not x1==i or y1==j): x2,y2=i,j if x1>0 and x2!=-10**18: print("YES") print(0,0) print(x1,y1) print(x2,y2) else: print("NO") ``` No
12,823
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices. Input The first line contains two integers a, b (1 ≀ a, b ≀ 1000), separated by a single space. Output In the first line print either "YES" or "NO" (without the quotes) depending on whether the required location exists. If it does, print in the next three lines three pairs of integers β€” the coordinates of the triangle vertices, one pair per line. The coordinates must be integers, not exceeding 109 in their absolute value. Examples Input 1 1 Output NO Input 5 5 Output YES 2 1 5 5 -2 4 Input 5 10 Output YES -10 4 -2 -2 1 2 Submitted Solution: ``` from math import sqrt def dist(A, B): x = A[0] - B[0] y = A[1] - B[1] return sqrt(x**2 + y**2) def is_int(gip, kat): if not sqrt(gip**2 - kat**2)%1: return True else: return False A = 0, 0 B = 0, 0 C = 0, 0 a, b = list(map(int, input().split())) #a, b = 5, 5 #print(a, b) result = 'NO' for x in range(A[0]+1, A[0]+a): if is_int(a, x): B = x, int(sqrt(a**2 - x**2)) cos = B[1]/a #print(cos) newx = cos*b #print(newx%1) if not newx%1: C = -int(newx), int(sqrt(b**2 - newx**2)) result = 'YES' #print(A, B, C) #print(x) print(result) if result == 'YES': print(A[0], A[1]) print(B[0], B[1]) print(C[0], C[1]) ``` No
12,824
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium. The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i, j). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light. Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i, j) belongs to a side of sub-rectangle with (x1, y1) and (x2, y2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition: ((i = x1 or i = x2) and (y1 ≀ j ≀ y2)) or ((j = y1 or j = y2) and (x1 ≀ i ≀ x2)). Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them? Input The first line contains three space-separated integers n, m and q (1 ≀ n, m, q ≀ 1000) β€” the height and width of the digital board, and the number of operations. Then follow n lines, each line containing m space-separated integers. The j-th integer of the i-th line is ai, j β€” the initial state of pixel (i, j). * If ai, j = 0, pixel (i, j) is initially dark. * If ai, j = 1, pixel (i, j) is initially light. Then follow q lines, each line containing three space-separated integers op, x, and y (1 ≀ op ≀ 2; 1 ≀ x ≀ n; 1 ≀ y ≀ m), describing an operation. * If op = 1, the pixel at (x, y) changes its state (from light to dark or from dark to light). * If op = 2, Nanami queries the biggest light block with pixel (x, y) on its side. Output For each query, print a single line containing one integer β€” the answer to Nanami's query. Examples Input 3 4 5 0 1 1 0 1 0 0 1 0 1 1 0 2 2 2 2 1 2 1 2 2 1 2 3 2 2 2 Output 0 2 6 Input 3 3 4 1 1 1 1 1 1 1 1 1 2 2 2 1 2 2 2 1 1 2 2 1 Output 6 3 3 Note Consider the first sample. The first query specifies pixel (2, 2), which is dark itself, so there are no valid light blocks, thus the answer is 0. The second query specifies pixel (1, 2). The biggest light block is the block with (1, 2) as its upper-left vertex and (1, 3) as its lower-right vertex. The last query specifies pixel (2, 2), which became light in the third operation. The biggest light block is the block with (1, 2) as its upper-left vertex and (3, 3) as its lower-right vertex. Submitted Solution: ``` n, m, q = [int(c) for c in input().split()] field = [] for i in range(n): field.append([int(c) for c in input().split()]) def max_dim(x, y, dx, dy): ix = x iy = y count = 0 while (0 <= ix < m) and (0 <= iy < n) and (field[iy][ix] == 1): ix += dx iy += dy count += 1 return count def find_square(arr, value): f = 0 while arr[f] < value: f += 1 l = len(arr) - 1 while arr[l] < value: l -= 1 return (l - f + 1) * value def count_one(x, y, dx, dy): if dx == 1: x_ = x y_ = y max_y_ = n else: x_ = y y_ = x max_y_ = m counter = [] for i in range(max_y_): if dx == 1: counter.append(max_dim(x_, i, dx, dy)) else: counter.append(max_dim(i, x_, dx, dy)) for i in range(y_ - 1, -1, -1): if counter[i + 1] < counter[i]: counter[i] = counter[i + 1] for i in range(y_ + 1, max_y_): if counter[i - 1] < counter[i]: counter[i] = counter[i - 1] max = 0 for i in range(max_y_): t = find_square(counter, counter[i]) if t > max: max = t return max for i in range(q): order, x, y = [int(c) for c in input().split()] x -= 1 y -= 1 if order == 1: field[x][y] = (field[x][y] + 1) % 2 if order == 2: print(max(count_one(y, x, 1, 0),count_one(y, x, -1, 0),count_one(y, x, 0, 1),count_one(y, x, 0, -1))) # print(field) # print(find_square([2,2,3,4,3,1,1,1,1,0], 4)) ``` No
12,825
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium. The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i, j). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light. Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i, j) belongs to a side of sub-rectangle with (x1, y1) and (x2, y2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition: ((i = x1 or i = x2) and (y1 ≀ j ≀ y2)) or ((j = y1 or j = y2) and (x1 ≀ i ≀ x2)). Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them? Input The first line contains three space-separated integers n, m and q (1 ≀ n, m, q ≀ 1000) β€” the height and width of the digital board, and the number of operations. Then follow n lines, each line containing m space-separated integers. The j-th integer of the i-th line is ai, j β€” the initial state of pixel (i, j). * If ai, j = 0, pixel (i, j) is initially dark. * If ai, j = 1, pixel (i, j) is initially light. Then follow q lines, each line containing three space-separated integers op, x, and y (1 ≀ op ≀ 2; 1 ≀ x ≀ n; 1 ≀ y ≀ m), describing an operation. * If op = 1, the pixel at (x, y) changes its state (from light to dark or from dark to light). * If op = 2, Nanami queries the biggest light block with pixel (x, y) on its side. Output For each query, print a single line containing one integer β€” the answer to Nanami's query. Examples Input 3 4 5 0 1 1 0 1 0 0 1 0 1 1 0 2 2 2 2 1 2 1 2 2 1 2 3 2 2 2 Output 0 2 6 Input 3 3 4 1 1 1 1 1 1 1 1 1 2 2 2 1 2 2 2 1 1 2 2 1 Output 6 3 3 Note Consider the first sample. The first query specifies pixel (2, 2), which is dark itself, so there are no valid light blocks, thus the answer is 0. The second query specifies pixel (1, 2). The biggest light block is the block with (1, 2) as its upper-left vertex and (1, 3) as its lower-right vertex. The last query specifies pixel (2, 2), which became light in the third operation. The biggest light block is the block with (1, 2) as its upper-left vertex and (3, 3) as its lower-right vertex. Submitted Solution: ``` n, m, q = [int(c) for c in input().split()] field = [] for i in range(n): field.append([int(c) for c in input().split()]) def max_dim(x, y, dx, dy): ix = x iy = y count = 0 while (0 <= ix < m) and (0 <= iy < n) and (field[iy][ix] == 1): ix += dx iy += dy count += 1 return count def find_square(arr, value): f = 0 while arr[f] < value: f += 1 l = len(arr) - 1 while arr[l] < value: l -= 1 return (l - f + 1) * value def count_one(x, y, dx, dy): x_ = x y_ = y max_y_ = n counter = [] for i in range(max_y_): counter.append(max_dim(x_, i, dx, dy)) for i in range(y_ - 1, -1, -1): if counter[i + 1] < counter[i]: counter[i] = counter[i + 1] for i in range(y_ + 1, max_y_): if counter[i - 1] < counter[i]: counter[i] = counter[i - 1] max = 0 for i in range(max_y_): t = find_square(counter, counter[i]) if t > max: max = t return max for i in range(q): order, x, y = [int(c) for c in input().split()] x -= 1 y -= 1 if order == 1: field[x][y] = (field[x][y] + 1) % 2 if order == 2: print(max(count_one(y, x, 1, 0),count_one(y, x, -1, 0))) ``` No
12,826
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium. The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i, j). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light. Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i, j) belongs to a side of sub-rectangle with (x1, y1) and (x2, y2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition: ((i = x1 or i = x2) and (y1 ≀ j ≀ y2)) or ((j = y1 or j = y2) and (x1 ≀ i ≀ x2)). Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them? Input The first line contains three space-separated integers n, m and q (1 ≀ n, m, q ≀ 1000) β€” the height and width of the digital board, and the number of operations. Then follow n lines, each line containing m space-separated integers. The j-th integer of the i-th line is ai, j β€” the initial state of pixel (i, j). * If ai, j = 0, pixel (i, j) is initially dark. * If ai, j = 1, pixel (i, j) is initially light. Then follow q lines, each line containing three space-separated integers op, x, and y (1 ≀ op ≀ 2; 1 ≀ x ≀ n; 1 ≀ y ≀ m), describing an operation. * If op = 1, the pixel at (x, y) changes its state (from light to dark or from dark to light). * If op = 2, Nanami queries the biggest light block with pixel (x, y) on its side. Output For each query, print a single line containing one integer β€” the answer to Nanami's query. Examples Input 3 4 5 0 1 1 0 1 0 0 1 0 1 1 0 2 2 2 2 1 2 1 2 2 1 2 3 2 2 2 Output 0 2 6 Input 3 3 4 1 1 1 1 1 1 1 1 1 2 2 2 1 2 2 2 1 1 2 2 1 Output 6 3 3 Note Consider the first sample. The first query specifies pixel (2, 2), which is dark itself, so there are no valid light blocks, thus the answer is 0. The second query specifies pixel (1, 2). The biggest light block is the block with (1, 2) as its upper-left vertex and (1, 3) as its lower-right vertex. The last query specifies pixel (2, 2), which became light in the third operation. The biggest light block is the block with (1, 2) as its upper-left vertex and (3, 3) as its lower-right vertex. Submitted Solution: ``` import sys read = lambda t=int: list(map(t,sys.stdin.readline().split())) array = lambda *ds: [array(*ds[1:]) for _ in range(ds[0])] if ds else 0 rots = [ (lambda x,y:(x,y)), (lambda x,y:(y,n-1-x)), (lambda x,y:(n-1-x,m-1-y)), (lambda x,y:(m-1-y,x))] invs = [ (lambda x,y:(x,y)), (lambda x,y:(n-1-y,x)), (lambda x,y:(n-1-x,m-1-y)), (lambda x,y:(y,m-1-x))] n, m, q = read() # print(rots[0](n-1,m-1)) # print(rots[1](n-1,m-1)) # print(rots[2](n-1,m-1)) # print(rots[3](n-1,m-1)) ar = [read() for _ in range(n)] cols = [array(n,m), array(m,n), array(n,m), array(m,n)] for i in range(4): for x in range(len(cols[i])): for y in range(len(cols[i][0])): ax, ay = invs[i](x,y) # print(i,x,y,ax,ay) cols[i][x][y] = ar[ax][ay] if x != 0 and cols[i][x][y] != 0: cols[i][x][y] += cols[i][x-1][y] # for ar in cols: # for row in ar: # print(row) # print() for _ in range(q): typ, x, y = read() x, y = x-1, y-1 if typ == 1: for i in range(4): rx, ry = rots[i](x, y) if cols[i][rx][ry]: cols[i][rx][ry] = 0 else: cols[i][rx][ry] = 1 if rx != 0: cols[i][rx][ry] += cols[i][rx-1][ry] while rx+1 != len(cols[i]) and cols[i][rx+1][ry]: cols[i][rx+1][ry] = cols[i][rx][ry]+1 rx += 1 if typ == 2: best = 0 for i in range(4): # for row in cols[i]: # print(row) rx, ry = rots[i](x, y) h = cols[i][rx][ry] a, b = ry-1, ry+1 while a != -1 or b != len(cols[i][0]): # print(a,b,i,len(cols[i][0])) if a != -1 and (b == len(cols[i][0]) or cols[i][rx][a] >= cols[i][rx][b]): h = min(h, cols[i][rx][a]) best = max(best, h*(b-a)) a -= 1 elif b != len(cols[i][0]) and (a == -1 or cols[i][rx][b] >= cols[i][rx][a]): h = min(h, cols[i][rx][b]) best = max(best, h*(b-a)) b += 1 print(best) # for ar in cols: # for row in ar: # print(row) # print() ``` No
12,827
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium. The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i, j). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light. Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i, j) belongs to a side of sub-rectangle with (x1, y1) and (x2, y2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition: ((i = x1 or i = x2) and (y1 ≀ j ≀ y2)) or ((j = y1 or j = y2) and (x1 ≀ i ≀ x2)). Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them? Input The first line contains three space-separated integers n, m and q (1 ≀ n, m, q ≀ 1000) β€” the height and width of the digital board, and the number of operations. Then follow n lines, each line containing m space-separated integers. The j-th integer of the i-th line is ai, j β€” the initial state of pixel (i, j). * If ai, j = 0, pixel (i, j) is initially dark. * If ai, j = 1, pixel (i, j) is initially light. Then follow q lines, each line containing three space-separated integers op, x, and y (1 ≀ op ≀ 2; 1 ≀ x ≀ n; 1 ≀ y ≀ m), describing an operation. * If op = 1, the pixel at (x, y) changes its state (from light to dark or from dark to light). * If op = 2, Nanami queries the biggest light block with pixel (x, y) on its side. Output For each query, print a single line containing one integer β€” the answer to Nanami's query. Examples Input 3 4 5 0 1 1 0 1 0 0 1 0 1 1 0 2 2 2 2 1 2 1 2 2 1 2 3 2 2 2 Output 0 2 6 Input 3 3 4 1 1 1 1 1 1 1 1 1 2 2 2 1 2 2 2 1 1 2 2 1 Output 6 3 3 Note Consider the first sample. The first query specifies pixel (2, 2), which is dark itself, so there are no valid light blocks, thus the answer is 0. The second query specifies pixel (1, 2). The biggest light block is the block with (1, 2) as its upper-left vertex and (1, 3) as its lower-right vertex. The last query specifies pixel (2, 2), which became light in the third operation. The biggest light block is the block with (1, 2) as its upper-left vertex and (3, 3) as its lower-right vertex. Submitted Solution: ``` import sys f = sys.stdin n,m,q = map(int, f.readline().strip().split()) a = [] for i in range(n): a.append( [int(u) for u in f.readline().strip().split()] ) for i in range(q): op, y, x = map(int, f.readline().strip().split()) x -= 1 y -= 1 if op==1: a[y][x] = 1 - a[y][x] else: i = 0 max_x1 = m-1 while x+i<m: if a[y][x+i]==0: max_x1 = i-1 break max_x1 = i i += 1 i = 0 max_y1 = n-1 while y+i<n: if a[y+i][x]==0: max_y1 = i-1 break max_y1 = i i += 1 i = 0 min_x1 = 0 while x-i>=0: if a[y][x-i]==0: min_x1 = i-1 break min_x1 = i i += 1 i = 0 min_y1 = 0 while y-i>=0: if a[y-i][x]==0: min_y1 = i-1 break min_y1 = i i += 1 max_S = 0 #print(op, y, x, min_x1, max_x1, min_y1, max_y1) max_S = max(max_S, max_y1+min_y1+1) max_S = max(max_S, max_x1+min_x1+1) if max_x1>0: i = 1 up = min_y1 down = max_y1 while i<=max_x1 and (up>0 or down>0): for k in range(-up,down+1): if a[y+k][x+i]==0: if k<0: up = -k-1 else: down = k-1 max_S = max(max_S, (i+1)*(up+down+1)) i += 1 if max_y1>0: i = 1 up = min_x1 down = max_x1 while i<=max_y1 and (up>0 or down>0): for k in range(-up,down+1): if a[y+i][x+k]==0: if k<0: up = -k-1 else: down = k-1 max_S = max(max_S, (i+1)*(up+down+1)) i += 1 if min_x1>0: i = 1 up = min_y1 down = max_y1 while i<=min_x1 and (up>0 or down>0): for k in range(-up,down+1): if a[y+k][x-i]==0: if k<0: up = -k-1 else: down = k-1 max_S = max(max_S, (i+1)*(up+down+1)) i += 1 if min_y1>0: i = 1 up = min_x1 down = max_x1 while i<=min_y1 and (up>0 or down>0): for k in range(-up,down+1): if a[y-i][x+k]==0: if k<0: up = -k-1 else: down = k-1 max_S = max(max_S, (i+1)*(up+down+1)) i += 1 print(max_S) ``` No
12,828
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` import math import sys from itertools import permutations input = sys.stdin.readline class Node: def __init__(self): self.children = [None]*26 self.isEnd = False self.win = False self.lose = False class Trie: def __init__(self): self.root = Node() def insert(self, key): cur = self.root for i in range(len(key)): if cur.children[ord(key[i])-ord('a')]==None: cur.children[ord(key[i])-ord('a')]=Node() cur = cur.children[ord(key[i])-ord('a')] cur.isEnd = True def search(self, key): cur = self.root for i in range(len(key)): if cur.children[ord(key[i])-ord('a')]==None: return False cur = cur.children[ord(key[i])-ord('a')] if cur!=None and cur.isEnd: return True return False def assignWin(self, cur): flag = True for i in range(26): if cur.children[i]!=None: flag=False self.assignWin(cur.children[i]) if flag: cur.win=False cur.lose=True else: for i in range(26): if cur.children[i]!=None: cur.win = cur.win or (not cur.children[i].win) cur.lose = cur.lose or (not cur.children[i].lose) if __name__=='__main__': t=Trie() n,k=map(int,input().split()) for i in range(n): s=input() if s[-1]=="\n": s= s[:-1] t.insert(s) t.assignWin(t.root) if not t.root.win: print("Second") else: if t.root.lose: print("First") else: if k%2==1: print("First") else: print("Second") ```
12,829
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` # https://codeforces.com/contest/455/problem/B import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ class Trie: def __init__(self): self.arr = {} def insert(self, word): root = self for x in word: if x not in root.arr: root.arr[x] = Trie() root = root.arr[x] def dfs(self): if not len(self.arr): return False, True win, lose = False, False for x in self.arr: w, l = self.arr[x].dfs() win = win or not w lose = lose or not l return win, lose def answer(flag): print("First" if flag else "Second") T = Trie() n, k = map(int, input().split()) for _ in range(n): T.insert(input()) win, lose = T.dfs() if k == 1: answer(win) elif not win: answer(win) elif lose: answer(win) elif k&1: answer(win) else: answer(not win) ```
12,830
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` # -*- coding:utf-8 -*- """ created by shuangquan.huang at 2/11/20 """ import collections import time import os import sys import bisect import heapq from typing import List def make_trie(A): trie = {} for word in A: t = trie for w in word: if w not in t: t[w] = {} t = t[w] # t['#'] = True return trie def game(trie): if not trie: return False return not all([game(t) for k, t in trie.items()]) def can_lose(trie): if not trie: return True return any([not can_lose(t) for k, t in trie.items()]) def solve(N, K, A): trie = make_trie(A) win = game(trie) if not win: return False if K == 1: return True if can_lose(trie): return True return K % 2 == 1 N, K = map(int, input().split()) A = [] for i in range(N): s = input() A.append(s) print('First' if solve(N, K, A) else 'Second') ```
12,831
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` class Node: def __init__(self): self._next = {} self._win = None self._lose = None def get_or_create(self, c: str): return self._next.setdefault(c, Node()) def traverse(self): self._win = False self._lose = True if len(self._next) == 0 else False for _, adj in self._next.items(): adj.traverse() self._win = self._win or not adj._win self._lose = self._lose or not adj._lose class Trie: def __init__(self): self._root = Node() def add(self, key: str): node = self._root for char in key: node = node.get_or_create(char) def traverse(self): self._root.traverse() def get_winner(self, k: int): if not self._root._win: return 'Second' if self._root._lose: return 'First' if k % 2 == 1: return 'First' else: return 'Second' if __name__ == "__main__": n, k = map(int, input().split()) trie = Trie() for _ in range(n): trie.add(input()) trie.traverse() print(trie.get_winner(k)) ```
12,832
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` from sys import stdin, setrecursionlimit setrecursionlimit(200000) n,k = [int(x) for x in stdin.readline().split()] tree = {} for x in range(n): s = stdin.readline().strip() cur = tree for x in s: if not x in cur: cur[x] = {} cur = cur[x] def forced(tree): if not tree: return (False,True) else: win = False lose = False for x in tree: a,b = forced(tree[x]) if not a: win = True if not b: lose = True return (win,lose) a,b = forced(tree) if a == 0: print('Second') elif a == 1 and b == 1: print('First') else: if k%2 == 0: print('Second') else: print('First') ```
12,833
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` N = 100000 Z = 26 #εˆ«η”¨θΏ™ηŽ©ζ„ε„Ώ: trie = [[0] * Z] * N 巨坑!https://www.cnblogs.com/PyLearn/p/7795552.html trie = [[0 for i in range(Z)] for j in range(N)] n = 0 k = 0 nodeNum = 0 def insertNode(): u = 0 string = input() global nodeNum for i in range(len(string)): c = ord(string[i]) - ord('a') if trie[u][c] == 0: nodeNum += 1 trie[u][c] = nodeNum u = trie[u][c] # print(u) stateWin = [False for i in range(N)] stateLose = [False for i in range(N)] def dfs(u): leaf = True for c in range(Z): if (trie[u][c]) != 0: leaf = False dfs(trie[u][c]) stateWin[u] |= (not(stateWin[trie[u][c]])) stateLose[u] |= (not(stateLose[trie[u][c]])) if leaf == True: stateWin[u] = False stateLose[u] = True n,k = map(int,input().split()) for i in range(n): insertNode() dfs(0) # print(stateWin[0]) # print(stateLose[0]) if (stateWin[0] and (stateLose[0] or (k % 2 == 1) )): print("First") else: print("Second") ```
12,834
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` """ Codeforces Contest 260 Div 1 Problem B Author : chaotic_iak Language: Python 3.3.4 """ def main(): n,k = read() s = set() for i in range(n): s.add(read(0)) s = list(s) s.sort() s = treeify(s) res = solve(s) if res == 0: # neither: second player win print("Second") if res == 1: # odd: first player win if k is odd print("First" if k % 2 else "Second") if res == 2: # even: second player win print("Second") if res == 3: # both: first player win print("First") def treeify(s): res = [[] for _ in range(26)] for i in s: if i: res[ord(i[0]) - 97].append(i[1:]) fin = [] for i in range(26): if res[i]: fin.append(treeify(res[i])) return fin def solve(s, parity=2): for i in range(len(s)): if isinstance(s[i], list): s[i] = solve(s[i], 3-parity) if not s: return parity # no possible move: current parity if 0 in s: return 3 # any neither: both if 1 in s and 2 in s: return 3 # any odd and any even: both if 1 in s: return 1 # any odd: odd if 2 in s: return 2 # any even: even return 0 # all both: neither ################################### NON-SOLUTION STUFF BELOW def read(mode=2): # 0: String # 1: List of strings # 2: List of integers inputs = input().strip() if mode == 0: return inputs if mode == 1: return inputs.split() if mode == 2: return map(int, inputs.split()) def write(s="\n"): if isinstance(s, list): s = " ".join(map(str, s)) s = str(s) print(s, end="") main() ```
12,835
Provide tags and a correct Python 3 solution for this coding contest problem. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Tags: dfs and similar, dp, games, implementation, strings, trees Correct Solution: ``` # https://codeforces.com/contest/455/problem/B import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ class Trie: def __init__(self): self.arr = {} def insert(self, word): for x in word: if x not in self.arr: self.arr[x] = Trie() self = self.arr[x] def dfs(self): if not len(self.arr): return False, True win, lose = False, False for x in self.arr: w, l = self.arr[x].dfs() win = win or not w lose = lose or not l return win, lose def answer(flag): print("First" if flag else "Second") T = Trie() n, k = map(int, input().split()) for _ in range(n): T.insert(input()) win, lose = T.dfs() if k == 1 or (not win) or lose or k&1: answer(win) else: answer(not win) ```
12,836
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Submitted Solution: ``` # ------------------- fast io -------------------- import os import sys sys.setrecursionlimit(10**5) 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") # ------------------- fast io -------------------- class Trie: class Node: def __init__(self, char: str = "*"): self.char = char self.children = [] self.word_finished = False self.counter = 1 def __init__(self): self.root = Trie.Node() def add(self, word: str): node = self.root for char in word: found_in_child = False for child in node.children: if child.char == char: child.counter += 1 node = child found_in_child = True break if not found_in_child: new_node = Trie.Node(char) node.children.append(new_node) node = new_node node.word_finished = True def query(self, prefix, root=None): if not root: root = self.root node = root if not root.children: return 0 for char in prefix: char_not_found = True for child in node.children: if child.char == char: char_not_found = False node = child break if char_not_found: return 0 return node n, k = map(int, input().split()) tr = Trie() for _ in range(n): tr.add(input()) def can_win(node): if not node.children: return False for child in node.children: if not can_win(child): return True return False def can_lose(node): if not node.children: return True for child in node.children: if not can_lose(child): return True return False pos = can_win(tr.root) pos2 = can_lose(tr.root) if pos and pos2: print("First") elif not pos: print("Second") else: print("First" if k % 2 else "Second") ``` Yes
12,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Submitted Solution: ``` input = __import__('sys').stdin.readline class Node: def __init__(self): self.end = False self.nxt = {} self.w = None self.l = None def __setitem__(self, i, x): self.nxt[i] = x def __getitem__(self, i): return self.nxt[i] def makeTrie(strs): root = Node() for s in strs: n = root for c in s: i = ord(c) - ord('a') n = n.nxt.setdefault(i, Node()) n.end = True return root def getw(n): if n.w != None: return n.w if not n.nxt: res = False else: res = False for x in n.nxt: if not getw(n.nxt[x]): res = True n.w = res return res def getl(n): if n.l != None: return n.l if not n.nxt: res = True else: res = False for x in n.nxt: if not getl(n.nxt[x]): res = True n.l = res return res n, k = map(int,input().split()) words = [input().rstrip() for i in range(n)] T = makeTrie(words) W = getw(T) L = getl(T) if not W: print("Second") elif L: print("First") else: print("First" if k%2 else "Second") ``` Yes
12,838
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Submitted Solution: ``` N = 10000 Z = 26 #εˆ«η”¨θΏ™ηŽ©ζ„ε„Ώ: trie = [[0] * Z] * N 巨坑!https://www.cnblogs.com/PyLearn/p/7795552.html trie = [[0 for i in range(N)] for j in range(Z)] n = 0 k = 0 nodeNum = 0 def insertNode(): u = 0 string = input() global nodeNum for i in range(len(string)): c = ord(string[i]) - ord('a') if trie[u][c] == 0: nodeNum += 1 trie[u][c] = nodeNum u = trie[u][c] print(u) stateWin = [False for i in range(N)] stateLose = [False for i in range(N)] def dfs(u): leaf = True for c in range(Z): if (trie[u][c]) != 0: leaf = False dfs(trie[u][c]) stateWin[u] |= (not(stateWin[trie[u][c]])) stateLose[u] |= (not(stateLose[trie[u][c]])) if leaf == True: stateWin[u] = False stateLose[u] = True n,k = map(int,input().split()) for i in range(n): insertNode() dfs(0) # print(stateWin[0]) # print(stateLose[0]) if (stateWin[0] and (stateLose[0] or (k % 2 == 1) )): print("First") else: print("Second") ``` No
12,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Submitted Solution: ``` n,k=map(int,input().split()) t=[""]*n for i in range(n) : t[i]=str(input()) p=0 i=1 ch="" while i<=k: print(i,"x") j=0 while j<n : if j==n-1 : i+=1 ch="" break elif (ch in t[j][0:(len(t[j]))]) and (len(t[j])>len(ch)) : ch+=t[j][len(t[j])-1] print(p) p=1-p break j+=1 p=1-p if p==0 : print("First") else : print("Second") ``` No
12,840
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Submitted Solution: ``` #!/usr/local/bin/python3 # insert string s into a trie def insert_string(trie, s): if s == "": return trie else: head = s[0] tail = s[1:] if head in trie: trie[head] = insert_string(trie[head], tail) else: trie[head] = insert_string({}, tail) return trie from functools import reduce # There are 2 players: true and false # trie is the full prefix tree (constant) # node is the current prefix (given as node in trie) # k the number of game left to play # player is the player about to play # returns winner memo = {} def winner(trie, node, player, k): # if (id(node), player, k) in memo: # return memo[id(node), player, k] if node != {}: # slower, but more fun m = [winner(trie, v, not player, k) for (_, v) in node.items()] res = reduce((lambda x, y: x or y), m) elif k == 1: # finished last game res = not player else: # one game is finished # loser starts the next game res = winner(trie, trie, player, k - 1) memo[id(node), player, k] = res return res n, k = (int(j) for j in input().split()) # compute the trie trie = {} for _ in range(n): trie = insert_string(trie, input()) # print(trie) if winner(trie, trie, True, k): print("First") else: print("Second") ``` No
12,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move. Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him. Input The first line contains two integers, n and k (1 ≀ n ≀ 105; 1 ≀ k ≀ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters. Output If the player who moves first wins, print "First", otherwise print "Second" (without the quotes). Examples Input 2 3 a b Output First Input 3 1 a b c Output First Input 1 2 ab Output Second Submitted Solution: ``` # -*- coding:utf-8 -*- """ created by shuangquan.huang at 2/11/20 """ import collections import time import os import sys import bisect import heapq from typing import List def make_trie(A): trie = {} for word in A: t = trie for w in word: if w not in t: t[w] = {} t = t[w] # t['#'] = True return trie def game(trie): if not trie: return False return not all([game(t) for k, t in trie.items()]) def can_lose(trie): if not trie: return True return all([game(t) for k, t in trie.items()]) def solve(N, K, A): trie = make_trie(A) win = game(trie) if not win: return False if K == 1: return True if can_lose(trie): return True return K % 2 == 1 N, K = map(int, input().split()) A = [] for i in range(N): s = input() A.append(s) print('First' if solve(N, K, A) else 'Second') ``` No
12,842
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` operations = [] a = input().split(' ') towers = input().split(' ') k = int(a[1]) for i in range(len(towers)): towers[i]=int(towers[i]) def inst(tset): return max(tset)-min(tset) def fix(towerset): proset=[] for element in towerset: proset.append(element) b = proset.index(max(proset)) c = proset.index(min(proset)) d = inst(proset) e = max(proset)-1 proset[b] -= 1 proset[c] += 1 if proset[c] <= e: return [b+1, c+1, proset] else: return "end" count = 0 result = None while result != "end": h = inst(towers) g=fix(towers) if g == "end": break else: if count == k: break else: operations.append([g[0],g[1]]) towers=g[2] count += 1 print(inst(towers), count) for j in range(len(operations)): print(operations[j][0], operations[j][1]) ```
12,843
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) ans = 0 l = [] r = [] f = True for h in range(k): mi = a[0] ma = a[0] ai = 0 aj = 0 for i in range(len(a)): if a[i] < mi: mi = a[i] ai = i if a[i] > ma: ma = a[i] aj = i if ma - mi <= 1: mi = a[0] ma = a[0] for i in range(len(a)): if a[i] < mi: mi = a[i] if a[i] > ma: ma = a[i] print(ma - mi, ans) for i in range(len(l)): print(l[i], r[i]) f = False break else: a[ai] += 1 a[aj] -= 1 ans += 1 l.append(aj+1) r.append(ai+1) if f == True: mi = a[0] ma = a[0] for i in range(len(a)): if a[i] < mi: mi = a[i] if a[i] > ma: ma = a[i] print(ma - mi, ans) for i in range(len(l)): print(l[i], r[i]) ```
12,844
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` n, k = map(int, input().split()) a, risp = [], [] a = list(map(int, input().split())) s = max(a) - min(a) m = 0 if s < 2: print(s, 0) else: for x in range(k): maxi = max(a) IndMaxi = a.index(maxi) mini = min(a) IndMini = a.index(mini) a[IndMaxi] -= 1 a[IndMini] += 1 s = max(a) - min(a) m += 1 risp.append([IndMaxi + 1, IndMini + 1]) #print(a) if s == 0: break print(s, m) for x in range(len(risp)): print(*risp[x]) ```
12,845
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` n, k = map(int, input().split()) arr = [int(i) for i in input().split()] ans = [] while k >= 0: x = 0 y = 0 for j in range(n): if arr[j] > arr[x]: x = j if arr[j] < arr[y]: y = j if k == 0 or arr[x] - arr[y] <= 1: print(arr[x] - arr[y], len(ans)) for j in ans: print(j[0], j[1]) break if arr[x] != arr[y]: ans.append((x + 1, y + 1)) arr[x] -= 1 arr[y] += 1 k -= 1 ```
12,846
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` n,k=map(int,input().split()) tab=[0 for loop in range(n)] t=input().split() for i in range(n): tab[i]=int(t[i]) def max(): global n y=0 j=0 for i in range(n): if tab[i]>y: y=tab[i] j=i return j def min(): global n x=100000 j=0 for i in range(n): if tab[i]<x: x=tab[i] j=i return j def maxv(): global n y=0 j=0 for i in range(n): if tab[i]>y: y=tab[i] j=i return y def minv(): global n x=100000 j=0 for i in range(n): if tab[i]<x: x=tab[i] j=i return x liste=[(0,0) for loop in range(k)] m=0 v=maxv()-minv() for j in range(k): a=max() b=min() tab[a]-=1 tab[b]+=1 liste[j]=(a+1,b+1) c=maxv()-minv() if c<v: v=c m=j+1 print(maxv()-minv(),m) for i in range(m): (d,e)=liste[i] print(d,e) ```
12,847
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` n,k = map(int,input().split()) arr = list(map(int,input().split())) ans = [] op = 0 factor = max(arr)-min(arr) while factor>1 and op<k: m = arr.index(min(arr)) M = arr.index(max(arr)) arr[m] += 1 arr[M] -= 1 op+=1 ans.append([M+1,m+1]) factor = max(arr)-min(arr) print(factor,op) for i in ans: print(*i) ```
12,848
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` n,k = map(int,input().split()) arr = [int(i) for i in input().split()] ans = [] for i in range(k): mx = arr.index(max(arr)) mn = arr.index(min(arr)) if mx != mn: arr[mx] -= 1 arr[mn] += 1 ans.append([mx+1,mn+1]) print(str(max(arr)-min(arr)) + ' ' + str(len(ans))) for x in ans: print(' '.join(map(str,x))) ```
12,849
Provide tags and a correct Python 3 solution for this coding contest problem. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Tags: brute force, constructive algorithms, greedy, implementation, sortings Correct Solution: ``` n,k = map(int,input().split()) arr = list(map(int,input().split())) lst = [] j = count = 0 check = -1 while j<k: mini = 10**4+3 maxi = 0 for i in range(n): if maxi<arr[i]: max_index = i maxi = arr[i] if mini>arr[i]: min_index = i mini = arr[i] if maxi-mini>1: count += 1 arr[max_index] -= 1 arr[min_index] += 1 lst.append([max_index+1,min_index+1]) else: break j += 1 mini = 10**4+3 maxi = 0 for i in range(n): if maxi<arr[i]: maxi = arr[i] if mini>arr[i]: mini = arr[i] print(maxi-mini,count) for j in lst: print(*j) ```
12,850
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` a, b = map(int, input().split(' ')) towers = list(map(int, input().split(' '))) tow2 = [[towers[i], i+1] for i in range(len(towers))] tot = sum(towers) should = tot // a num1 = (should+1) * a - tot num2 = a - num1 ideal = num1*[should] + num2 * [should+1] ct = 1 x = [] while ct <= b: tow2.sort(key = lambda x:x[0]) if [i[0] for i in tow2] == ideal: break else: x.append([tow2[-1][1], tow2[0][1]]) tow2[0][0] += 1 tow2[-1][0] -= 1 ct += 1 tows = [x[0] for x in tow2] print((max(tows)-min(tows)), ct-1) for i in x: print(i[0], i[1]) ``` Yes
12,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` f = list(map(int, input().split())) heights = list(map(int, input().split())) num = f[0] kops = f[1] minpossible = 0 if sum(heights)%num==0 else 1 curinstability = max(heights)-min(heights) opscounter = 0 rem = list() while curinstability>minpossible and opscounter < kops: lowi = heights.index(min(heights)) highi = heights.index(max(heights)) heights[lowi]+=1 heights[highi]-=1 rem.append((highi+1, lowi+1)) #adjust index by 1 opscounter+=1 curinstability = max(heights)-min(heights) print(max(heights)-min(heights),opscounter) for vals in rem: print(vals[0],vals[1]) ``` Yes
12,852
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` n, k = map (int, input ().split ()) lst = list (map (int, input ().split ())) x = len (lst) for i in range (x) : lst [i] = [lst[i], i] orig = k temp = 0 ans = [] while k > 0 : k -= 1 lst.sort () if lst[n - 1][0] - lst[0][0] > 1 : lst[n - 1][0] -= 1 lst[0][0] += 1 ans.append ([lst[n - 1][1], lst[0][1]]) else : temp += 1 lst.sort () k += temp print (lst[n - 1][0] - lst[0][0], orig - k) for i in ans : print (i[0] + 1, i[1] + 1) ``` Yes
12,853
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` n,k=map(int, input().split()) a=list(map(int, input().split())) d=[[a[i],i] for i in range(n)] d.sort() cnt=0 ops=[] while d[n-1][0]-d[0][0] > 1 and cnt < k: ops.append([d[n-1][1]+1, d[0][1]+1]) d[n-1][0] -= 1 d[0][0] += 1 cnt += 1 d.sort() print(d[n-1][0]-d[0][0], cnt) for f,t in ops: print(f, t) # Made By Mostafa_Khaled ``` Yes
12,854
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 # from sys import stdin # input = stdin.readline def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,6))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass def pmat(A): for ele in A: print(ele,end="\n") n,k=L() A=L() steps=[] moves=[] for i in range(k): steps.append(max(A)-min(A)) x=A.index(min(A)) y=A.index(max(A)) moves.append([y+1,x+1]) z=min(A)+max(A) A[x]=z//2 A[y]=z//2+z%2 steps.append(max(A)-min(A)) x=steps.index(min(steps)) print(steps[x],x) for i in range(x): print(*moves[i]) endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ``` No
12,855
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` st = input() j = 0 for i in range(len(st)): if st[i] == ' ': j = i st1 = st[0:j] n = int(st1) st1 = st[(j+1):len(st)] k = int(st1) i = 0 a = [] st = input() + ' ' while i <= (len(st) - 1): j = i while (st[i] != ' '): i += 1 a.append(int(st[j:i])) i += 1 cnt = 0 mm = 10000000 i_max = 0 i_min = 0 x = [] y = [] while cnt < k: for i in range(len(a)): if a[i] == max(a): i_max = i if a[i] == min(a): i_min = i x.append(i_max) y.append(i_min) a[i_max] -= 1 a[i_min] += 1 cnt += 1 print((max(a) - min(a)), cnt) x = x[::-1] y = y[::-1] for i in range(cnt): print((x[i]+1), (y[i]+1)) ``` No
12,856
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` n,k = map(int,input().split()) arr = list(map(int,input().split())) lst = [] j = count = 0 check = -1 while j<k: mini = 10**4+3 maxi = 0 for i in range(n): if maxi<arr[i]: max_index = i maxi = arr[i] if mini>arr[i]: min_index = i mini = arr[i] if maxi-mini>1: count += 1 arr[max_index] -= 1 arr[min_index] += 1 lst.append([max_index+1,min_index+1]) else: if maxi-mini==1: check = 1 break if maxi-mini==2: check = 0 j += 1 if check==-1: print(maxi-mini,count) elif check==0: print(0,count) else: print(1,count) for j in lst: print(*j) ``` No
12,857
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task. Input The first line contains two space-separated positive integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000) β€” the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≀ ai ≀ 104) β€” the towers' initial heights. Output In the first line print two space-separated non-negative integers s and m (m ≀ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i β‰  j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them. Examples Input 3 2 5 8 5 Output 0 2 2 1 2 3 Input 3 4 2 2 4 Output 1 1 3 2 Input 5 3 8 3 2 6 3 Output 3 3 1 3 1 2 1 3 Note In the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. Submitted Solution: ``` r = [] n,k = map(int,input().split()) l = list(map(int,input().split())) m = 0 s = max(l)-min(l) for lll in range(k): m += 1 s = max(l)-min(l) i = l.index(max(l)) j = l.index(min(l)) if i == j: break l[i],l[j] = l[i]-1,l[j]+1 r.append([i+1,j+1]) s = max(l)-min(l) if max(l) == min(l) or max(l)-min(l) == 1: break print(s,m) for i in r: print(i[0],i[1]) ``` No
12,858
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` n=int(input()) queries=[] names=[] f=[] l=[] for i in range(n): queries.append(input().split(' ')) for i in range(n): for j in range(2): if queries[i][j] in names: if j==0: names.remove(queries[i][j]) l[l.index(queries[i][j])]=queries[i][j-1] else: names.append(queries[i][j]) if j==0: f.append(queries[i][j]) else: if queries[i][j] not in l: l.append(queries[i][j]) print(len(f)) for k in range(len(f)): print(f[k],l[k]) ```
12,859
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` queries = [] for q in range(int(input())): old, new = input().split() done = False for elem in queries: if old == elem[-1]: elem.append(new) done = True break if not done: queries.append([old, new]) print(len(queries)) for elem in queries: print(elem[0], elem[-1]) ```
12,860
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- n = int(input()) b_a = {} for n_ in range(n): b, a = input().split() replaced = False for k in b_a: if b_a[k] == b: b_a[k] = a replaced = True if not replaced: b_a[b] = a print(len(b_a)) for k in b_a: print (k + " " + b_a[k]) ```
12,861
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` #/usr/bin/env python3 N = int(input()) names = [input().split() for i in range(N)] c_to_old = dict() for n in names: if n[0] not in c_to_old: c_to_old[n[1]] = n[0] else: old = c_to_old[n[0]] del c_to_old[n[0]] c_to_old[n[1]] = old print(len(c_to_old)) thing = sorted(c_to_old.items(), key = lambda x: x[1]) for c, o in thing: print(o, c) ```
12,862
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` # MC521 - Desafios de Programacao I - 1s2021 # Contest: 02/04/2021 # Problema J: Misha and Changing Handles # le o numero de alteracoes a serem realizadas n = int(input()) # inicializa o mapa dos idenficadores alt = {} # realiza a leitura das alteracoes e mapeia os identificadores dos usuarios for _ in range(n): # le o identificador antigo e o novo antigo, novo = input().split() # checa se o identficador a ser atualizado existe if(antigo not in alt): # caso nao exista alt[novo] = antigo else: # caso exista, atualiza e remove o antigo alt[novo] = alt[antigo] alt.pop(antigo, None) # imprime a quantidade de usuarios diferentes print(len(alt)) # imprime os idenficadores iniciais e finais de cada usuario for chave in alt: print('{name1} {name2}'.format(name1=alt[chave], name2=chave)) ```
12,863
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` #coding:utf-8 n = int( input()) names = {} changes = 0 for i in range(n): current, changed = map(str, input().split()) if current not in names: names[changed] = current changes += 1 else: aux = names[current] names.pop(current) names[changed] = aux print(changes) for i in names: print(names[i],i) ```
12,864
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` maps = {} for i in range(int(input())): old, new = input().split() if old in maps: maps[new] = maps[old] del maps[old] else: maps[new] = old print(len(maps)) for k, v in maps.items(): print(v + " " + k) ```
12,865
Provide tags and a correct Python 3 solution for this coding contest problem. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Tags: data structures, dsu, strings Correct Solution: ``` n=int(input()) arr=[] for i in range(n): s=input() a=s.split(' ') arr.append(a) array=[['' for col in range(n)]for row in range(2)] a1=[[]for k in range(n)] a1[0].append(arr[0][0]) a1[0].append(arr[0][1]) a2=[] a2.append(arr[0][1]) p=1 while(p<n): a2.append(arr[p][1]) if arr[p][0] in a2: c=0 while(c<p): if arr[p][0] in a1[c]: break else: c=c+1 a1[c].append(arr[p][1]) p=p+1 else: a1[p].append(arr[p][0]) a1[p].append(arr[p][1]) p=p+1 count=0 for z in range(len(a1)): if(a1[z]!=[]): count+=1 print(count) for z in range(len(a1)): if(a1[z]!=[]): print(a1[z][0]+' '+a1[z][-1]) ```
12,866
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` n = int(input()) map = {} for i in range(0,n): input_string = input() input_string = input_string.split(" ") if input_string[0] in map: temp = map[input_string[0]] map.pop(input_string[0]) map[input_string[1]] = temp else: map[input_string[1]] = input_string[0] print(len(map)) for key in map.keys(): value = map[key] print(f'{value} {key}') ``` Yes
12,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` q = int(input()) old = dict() new = dict() for i in range(q): name = input().split() if new.get(name[0]) == None: old[name[0]] = name[1] new[name[1]] = name[0] else: old[new[name[0]]] = name[1] new[name[1]] = new[name[0]] print(len(old)) for i in old: print(i, old[i]) ``` Yes
12,868
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` from collections import defaultdict class DisjSet: def __init__(self, n): self.rank = defaultdict(lambda:1) self.parent = defaultdict(lambda:None) def sol(self,a): if self.parent[a]==None: self.parent[a]=a def find(self, x): #ans=1 if (self.parent[x] != x): self.parent[x] = self.find(self.parent[x]) #ans+=1 return self.parent[x] def Union(self, x, y): xset = self.find(x) yset = self.find(y) if xset == yset: return if self.rank[xset] < self.rank[yset]: self.parent[xset] = yset elif self.rank[xset] > self.rank[yset]: self.parent[yset] = xset else: self.parent[yset] = xset self.rank[xset] = self.rank[xset] + 1 n=int(input()) obj=DisjSet(n+1) temp=[] visited=defaultdict(lambda:None) for p in range(n): a,b=input().split() temp.append([a,b]) obj.sol(a) obj.sol(b) obj.Union(a,b) #print(obj.find('MikeMirzayanov')) cont=0 ans=[] while temp: a,b=temp.pop() if visited[obj.find(b)]==None: ans.append([obj.find(b),b]) cont+=1 visited[obj.find(b)]=True print(cont) for val in ans: print(*val) ``` Yes
12,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` n = int(input()) m, rev = {}, {} for i in range(n): a, b = input().split() if a not in rev: m[a] = b rev[b] = a else: m[rev[a]] = b rev[b] = rev[a] print(len(m)) for key in m: print(key, m[key]) ``` Yes
12,870
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` n = int(input()) p = [] for i in range(n): x, y = map(str, input().split(' ')) for j in range(len(p)): if(p[j][1] == x): p[j][1] = y else: p.append([x,y]) if(p == []): p.append([x,y]) for i in range(len(p)): print(p[i][0] + ' ' + p[i][1]) ``` No
12,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` n = int(input()) a, b = [], [] for i in range(n): x, y = input().split() if x not in b: a.append(x); b.append(y) else: b[b.index(x)] = y for i in range(len(a)): print(a[i], b[i]) ``` No
12,872
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` from math import sqrt,ceil def mi():return map(int,input().split()) def li():return list(mi()) def ii():return int(input()) def si():return input() rank=[] #dsu(disjoint set unit) -> :) def find(x,parent): if(x==parent[x]): return x parent[x]=find(parent[x],parent) return parent[x] def union(x,y,parent): x1=find(x,parent) y1=find(y,parent) if(x1==y1): return if(rank[x1]>=rank[y1]): parent[y]=x1 rank[x1]+=1 else: parent[x]=y1 rank[y1]+=1 def main(): q=ii() old={} a=[] for i in range(q): s1,s2=map(str,input().split()) old[s2]=s1 a.append(s2) for i in range(q): for j in range(q): if(a[j]==old[a[j]]): continue if(a[i]==old[a[j]]): old[a[j]]=old[a[i]] a[j]=a[i] old[a[j]]=a[i] b=[] for i in old.keys(): if i!=old[i]: b.append(i) print(len(b)) for i in b: print(old[i],i) if __name__=="__main__": main() ``` No
12,873
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point. Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that. Input The first line contains integer q (1 ≀ q ≀ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone. Output In the first line output the integer n β€” the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description. Examples Input 5 Misha ILoveCodeforces Vasya Petrov Petrov VasyaPetrov123 ILoveCodeforces MikeMirzayanov Petya Ivanov Output 3 Petya Ivanov Misha MikeMirzayanov Vasya VasyaPetrov123 Submitted Solution: ``` users = dict() nombres = list() cant = input() handles = [] class Handle: def __init__(self, old): self.old = old self.new = None def actualizar(self, new): self.new = new for i in range(int(cant)): nombre = input().split(" ") if nombre[0] not in nombres: nombres.append(nombre[0]) u = Handle(nombre[0]) handles.append(u) if nombre[1] not in nombres: u.actualizar(nombre[1]) nombres.append(nombre[1]) else: if nombre[1] not in nombres: for i in handles: if i.new == nombre[0]: i.actualizar(nombre[1]) handles.remove(i) handles.append(i) break print(len(handles)) a = len(handles) - 1 while a >= 0: print("{} {}".format(handles[a].old, handles[a].new)) a -= 1 ``` No
12,874
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` w,m=[int(x) for x in input().split()] for i in range(101): if m%w==0: m/=w elif (m-1)%w==0: m=m//w elif (m+1)%w==0: m=(m+1)/w else: print("NO") exit() if m==0: print("YES") else: print("NO") ```
12,875
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` w,m = map(int,input().split()) A = [] while m: A.append(m%w) m //= w sz = len(A) A.append(0) for i in range(sz): x = A[i] if x != 0 and x != 1 and x != w-1 and x != w: print("NO") exit() if x == w-1 or x == w: A[i+1] += 1 print("YES") ```
12,876
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` n,m=map(int,input().split()) for i in range(33): m=min(m,abs(n**(32-i)-m)) print("YES" if m==0 else "NO") ```
12,877
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` 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) def putff(a, sep = " ", end = "\n"): [putf(i, sep, end) for i in a] #from math import ceil, gcd, factorial as fac #from collections import defaultdict as dd #from bisect import insort, bisect_left as bl, bisect_right as br def transf(a, w): ans = [] while(a > 0): ans.append(a % w) a //= w return ans[ :: -1] def solve(a, w): ans = [] #print(a) p = 0 for i in range(len(a) - 1, 0, -1): if(a[i] + p >= w): a[i] = (a[i] + p) % w p = 1 else: a[i] += p p = 0 if(a[i] in [0, 1]): ans.append(0) pass elif(a[i] == w - 1): p = 1 ans.append(1) else: return "NO" ans.reverse() #print(a) #print(ans) for i in ans: if(i not in [0, 1]): return "NO" return "YES" def main(): w, m = getf() print(solve([0] + transf(m, w), w)) main() ```
12,878
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` from heapq import heapify, heappush, heappop from collections import Counter, defaultdict, deque, OrderedDict from sys import setrecursionlimit, maxsize from bisect import bisect_left, bisect, insort_left, insort from math import ceil, log, factorial, hypot, pi from fractions import gcd from copy import deepcopy from functools import reduce from operator import mul from itertools import product, permutations, combinations, accumulate, cycle from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits, hexdigits, octdigits prod = lambda l: reduce(mul, l) prodmod = lambda l, mod: reduce(lambda x, y: mul(x,y)%mod, l) def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] def convert_base(num, base): converted = [] while num: num, r = divmod(num, base) converted.append(r) return converted def solve(w, m): w_m = convert_base(m, w) w_m += [0] * (101-len(w_m)) for i in range(101): if w_m[i] == 0 or w_m[i] == 1: continue elif w_m[i] == w or w_m[i] == w-1: w_m[i+1] += 1 else: return False return True w, m = read_list(int) print('YES' if solve(w, m) else 'NO') ```
12,879
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` x=[0]*101 ww,m=map(int,input().split()) if ww==2: print('YES') exit() w=ww c=0 while (m): x[c]=m%w m//=w c+=1 an=1 w=ww vis=[0]*101 for i in range(101): if x[i]==w-1: vis[i]=1 x[i]=0 if i+1>100: an=0 break else: x[i+1]+=1 elif x[i]==w: x[i]=0 x[i+1]+=1 # print(x) for i in range(101): if x[i]>1: an=0 break else: if x[i]==1 and vis[i]!=0: an=0 break print('YES' if an else 'NO') ```
12,880
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` W, M = (input().split(' ')) W = int(W) M = int(M) if W == 2 or W == 3: print("YES") else: N = 16 A = [0]*(N+1) A[0] = 1 for I in range(1, N): A[I] = A[I-1]*W if A[I] > 10000000001000000000: N = I; break #print(N) S = set() ok = False for msk in range(1 << N): curr = 0 for I in range(N): if msk & (1 << I) > 0: curr += A[I] if curr == M or (curr-M in S): ok = True break S.add(curr) if ok: print("YES") else: print("NO") ```
12,881
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Tags: brute force, dp, greedy, math, meet-in-the-middle, number theory Correct Solution: ``` #!/usr/bin/env python3 import sys w, m = list(map(int, sys.stdin.readline().split())) a = sum(pow(w, i) for i in range(101)) + m while a > 0: if a % w > 2: print('NO') sys.exit(0) a //= w print('YES') ```
12,882
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` base,num = map(int,input().split()) if base==3 or base==2 : print("YES") quit() newNum = [] while num > 0: newNum=[num % base] + newNum num //= base newNum=[0]+newNum for i in range(len(newNum)-1,0,-1) : if newNum[i]==base or newNum[i]==base-1 : newNum[i-1]+=1 continue if newNum[i]>1 : print("NO") quit() print("YES") ``` Yes
12,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` w, m = map(int, input().split()) while m > 1: c = m % w if c not in {0, 1, w - 1}: print('NO') exit() m //= w if c == w - 1: m += 1 print('YES') ``` Yes
12,884
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` w, m = map(int, input().split()) while m > 0: digit = m % w if digit == 1: m -= 1 elif digit == w - 1: m += 1 elif digit != 0: m = -1 if m > 0: m //= w print("YES" if m == 0 else "NO") ``` Yes
12,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` w, m = map(int, input().split()) for i in range(100, -1, -1): if abs(m - w**i) < m: m = abs(m - w**i) print('YES' if m == 0 else 'NO') ``` Yes
12,886
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` w,m=map(int,input().split()) if m>1: while m: if 1<m%w<w-1: break m=(m+1)%w print("NO" if m%w>1 else "YES") ``` No
12,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` import math while(1): a,b=input().split() a=int(a) b=int(b) k=math.log(b)//math.log(a) diff=min(abs(b-a**k),abs(b-a**(k+1))) if(diff>=2): if(math.log(diff)/math.log(a)==math.log(diff)//math.log(a) or math.log(diff+1)/math.log(a)==math.log(diff+1)//math.log(a) or math.log(diff-1)/math.log(a)==math.log(diff-1)//math.log(a)): print("YES") break if(diff==abs(b-a**k)): k=k else: k=k+1 m=a**k n=m+1 t=b for x in range (0,1000000000): if(b==m or b==n): print("YES") break elif(b>n): print("NO") break b=t b=b+3**x break ``` No
12,888
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` base,num = map(int,input().split()) if base==3 or base==2 : print("YES") quit() newNum = [] while num > 0: newNum=[num % base] + newNum num //= base for i in range(len(newNum)-1,-1,-1) : if newNum[i]==base-1 : for j in range(i-1,-1,-1) : if newNum[j]==0 : break else : if newNum[j]!=base-1 : print("NO") quit() else : if newNum[i]!=0 and newNum[i]!=1 : print("NO") quit() print("YES") ``` No
12,889
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. Input The first line contains two integers w, m (2 ≀ w ≀ 109, 1 ≀ m ≀ 109) β€” the number defining the masses of the weights and the mass of the item. Output Print word 'YES' if the item can be weighted and 'NO' if it cannot. Examples Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO Note Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. Submitted Solution: ``` w, m = map(int, input().split()) for i in range(101): tmp = m+0 base = 1 for j in range(i+1): tmp += base base *= w while base > 0: if tmp >= base*2: tmp -= base*2 base //= w if tmp == 0: print('YES') exit() print('NO') ``` No
12,890
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` import sys a, b = list(map(int, sys.stdin.readline().split())) if b > a : print(-1) elif b == a: print(a) else: t = (a+b)/(2*int((a+b)/b/2)) print(t) ```
12,891
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` a, b = map(int, input().split()) if a < b: print(-1) else: print((a + b) / (2 * ((a + b) // (2 * b)))) ```
12,892
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` def main(): a, b = [int(i) for i in input().split(" ")] eps = 0.0000000001 if (b > a): print (-1) elif b == a: print(b) elif b == 0: print(0) else: x1, x2 = float('inf'), float('inf') z1, z2 = (a-b)/2, (a+b)/2 k, kk = 1, 1 while kk: while (z1/k) + eps >= b: x1 = (z1/k) k += kk kk *= 2 k -= kk/2 kk //= 4 k, kk = 1, 1 while kk: while (z2/k) + eps >= b: x2 = (z2/k) k += kk kk *= 2 k -= kk/2 kk //= 4 if (min(x1, x2) != float('inf')): print(min(x1, x2)) else: print(-1) if __name__ == "__main__": main() ```
12,893
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` a,b = map(float,input().split(" ")) if a==b: print(b) elif a<b: print(-1) else: n=(a-b)//b+1 if n%2==0:n-=1 if n>1: x1=(a-b)/(n-1) else: x1=999999999999999999 n=(a+b)//b-1 if n%2==0:n-=1 x2=(a+b)/(n+1) print(min(x1,x2)) ```
12,894
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` from fractions import Fraction def solve(a, b): x = Fraction(b) n = a // (x*2) a_ = a % (x*2) if b > a: return -1 if a_ == x: return float(x) if a_ < x: return float((a+b)/(2*n)) if a_ > x: return float((a+b)/(2*n+2)) a, b = map(Fraction, input().split()) print(solve(a, b)) ```
12,895
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` def find(x,b): if x/2//b>0: return x/2/(x/2//b) else: return 10000000000 a,b=map(int,input().split()) if a==b: print("%.9f"%a) elif b>a: print(-1) else: print("%.9f"%min(find(a-b,b),find(a+b,b))) ```
12,896
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` from math import floor a, b = map(int, input().split()) if a < b: print(-1) else: if floor((a-b)/(2*b)) == 0: print((a+b)/(2*floor((a+b)/(2*b)))) else: print(min((a-b)/(2*floor((a-b)/(2*b))), (a+b)/(2*floor((a+b)/(2*b))))) ```
12,897
Provide tags and a correct Python 3 solution for this coding contest problem. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Tags: geometry, math Correct Solution: ``` def main(a,b): if b > a: return(-1) # ver1 k1 = (a - b) // (2*b) if k1 > 0: x1 = (a - b) / (2 * k1) else: x1 = 10**9 k2 = (a + b) // (2*b) x2 = (a + b) / (2*k2) return min(x1, x2) a,b = list(map(int, input().split())) print(main(a,b)) ```
12,898
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positive integers a and b (1 ≀ a, b ≀ 109). Output Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer. Examples Input 3 1 Output 1.000000000000 Input 1 3 Output -1 Input 4 1 Output 1.250000000000 Note You can see following graphs for sample 1 and sample 3. <image> <image> Submitted Solution: ``` from math import floor a, b = map(int, input().split()) if a < 0: print(-1) elif b < 0: print(-1) elif a < b: print(-1) elif a == 0 and b != 0: print(-1) elif a == b: print(b) elif b == 0: print(0) else: n1 = floor((a - b) / (2 * b)) n2 = floor((a + b) / (2 * b)) if n1 == 0: print((a + b) / (2 * n2)) else: x1 = (a - b) / (2 * n1) x2 = (a + b) / (2 * n2) print(min(x1, x2)) ``` Yes
12,899