text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Tags: data structures, trees Correct Solution: ``` from operator import or_, xor import sys n, m = map(int, input().split()) t = [list(map(int, input().split()))] for i in range(n): t += [[(or_, xor)[i & 1](*t[i][j: j + 2]) for j in range(0, len(t[i]), 2)]] for s in sys.stdin: p, b = s.split() p = int(p) - 1 t[0][p] = int(b) for j in range(n): p >>= 1 t[j + 1][p] = (or_, xor)[j & 1](*t[j][p << 1: (p << 1) + 2]) print(t[-1][0]) ```
10,300
Provide tags and a correct Python 3 solution for this coding contest problem. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Tags: data structures, trees Correct Solution: ``` import sys,os,io from sys import stdin if(os.path.exists('input.txt')): sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w") else: input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def powerof2(n): while n>1: if n%2: return False n//=2 return True class SegmentTree: def __init__(self, data, default=0, func=lambda a,b:a+b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data orl = False for i in range(self._size-1,0,-1): if powerof2(i+1): orl = orl ^ True # print(orl,i,self.data[i + i] , self.data[i + i + 1]) if orl: self.data[i] = (self.data[i + i] | self.data[i + i + 1]) else: self.data[i] = (self.data[i + i] ^ self.data[i + i + 1]) # print(self.data) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 orl = True # print(self.data) while idx: if orl: self.data[idx] = (self.data[2 * idx] | self.data[2 * idx + 1]) else: self.data[idx] = (self.data[2 * idx] ^ self.data[2 * idx + 1]) idx >>= 1 orl^= True # print(self.data) def __len__(self): return self._len def query(self, start, stop): """Returns the result of function over the range (inclusive)! [start,stop]""" start += self._size stop += self._size+1 res_left = res_right = self._default orl = True while start < stop: if start & 1: if orl: res_left = (res_left | self.data[start]) else: res_left = (res_left ^ self.data[start]) start += 1 if stop & 1: stop -= 1 if orl: res_right = (self.data[stop] | res_right) else: res_right = (self.data[stop] ^ res_right) start >>= 1 stop >>= 1 orl ^= True return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) n,m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] seg = SegmentTree(a) for i in range(m): p,b = [int(x) for x in input().split()] seg.__setitem__(p-1,b) print(seg.data[1]) ```
10,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` from math import log import sys def buildTree(arr): n = len(arr) tree = [0]*n + arr for i in range(n-1, 0, -1): z = int(log(i, 2)) # determines what level of the tree you're at if N%2 == 0: if z % 2 == 0: tree[i] = tree[2*i]^tree[2*i+1] else: tree[i] = tree[2*i]|tree[2*i+1] else: if z % 2 == 0: tree[i] = tree[2*i]|tree[2*i+1] else: tree[i] = tree[2*i]^tree[2*i+1] return tree def updateTree(tree, ind, value, n): ind += n tree[ind] = value while ind > 1: ind //= 2 z = int(log(ind, 2)) if N%2 == 0: if z % 2 == 0: tree[ind] = tree[2*ind]^tree[2*ind+1] else: tree[ind] = tree[2*ind]|tree[2*ind+1] else: if z % 2 == 0: tree[ind] = tree[2*ind]|tree[2*ind+1] else: tree[ind] = tree[2*ind]^tree[2*ind+1] return tree N, m = map(int, sys.stdin.readline().strip().split()) arr = list(map(int, sys.stdin.readline().strip().split())) tree = buildTree(arr) for i in range(m): ind, val = map(int,sys.stdin.readline().strip().split()) tree = updateTree(tree, ind-1, val, len(arr)) print(tree[1]) ``` Yes
10,302
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` import sys input = sys.stdin.readline N, M = map(int, input().split()) A = list(map(int, input().split())) Query = [list(map(int, input().split())) for _ in range(M)] L = 2**N seg = [0]*(2*L-1) # initialize for i in range(L): seg[i+L-1] = A[i] k = L-1 c = 0 while k > 0: if c%2 == 0: for i in range((k-1)//2, k): seg[i] = seg[2*i+1] | seg[2*i+2] else: for i in range((k-1)//2, k): seg[i] = seg[2*i+1] ^ seg[2*i+2] c += 1 k = (k-1)//2 # update and return v def update(k, a): k += L-1 seg[k] = a c = 0 while k > 0: k = (k-1)//2 if c % 2 == 0: seg[k] = seg[2*k+1] | seg[2*k+2] else: seg[k] = seg[2*k+1] ^ seg[2*k+2] c += 1 return seg[0] for p, b in Query: ans = update(p-1, b) print(ans) ``` Yes
10,303
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 #def input(): return sys.stdin.readline().strip()m input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ aj = lambda: list(map(int, input().split())) def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) n,m = aj() size = 2*(2**n) - 1 A = [-1]*size B = aj() start = size for i in range(len(B)-1,-1,-1): A[-(i+1)] = B[-(i+1)] start -= 1 last = size - len(B) - 1 for i in range(n): l = 2**(n-1-i) for j in range(l): if i%2 == 0: A[last]=A[2*last+1]|A[2*last+2] else: A[last]=A[2*last+1]^A[2*last+2] last-=1 def update(a,b): pos = start + a - 1 step = 0 A[pos] = b while True: pos = (pos-1)//2 if step % 2 == 0: A[pos]=A[2*pos+1]|A[2*pos+2] else: A[pos]=A[2*pos+1]^A[2*pos+2] if pos == 0: break step ^= 1 print(A[0]) #print(A) #print(start) #print(*A) for i in range(m): a,b = aj() update(a,b) ``` Yes
10,304
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` import sys from math import sqrt input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) n,m = map(int,input().split()) a = list(map(int,input().split())) size = 2 * 2**n # 8 segmentTree = [-1]*size # 1~7 levels = [-1]*size idx = 0 #initialize for i in range(int(size/2),size): segmentTree[i] = a[idx] levels[i] = 1 idx+=1 #build segment tree for i in range(2**n-1,0,-1): # 3,2,1 left = 2*i; right = 2*i+1 levels[i] = levels[2*i]+1 if levels[i] % 2 == 0: segmentTree[i] = segmentTree[left] | segmentTree[right] else: segmentTree[i] = segmentTree[left] ^ segmentTree[right] #update segment tree for t in range(m): p,b = map(int,input().split()) segmentTree[2**n+p-1] = b i = 2**n+p-1 while i != 1: parent = int(i/2) left = parent*2; right = parent*2+1 if levels[parent] % 2 == 0: segmentTree[parent] = segmentTree[left] | segmentTree[right] else: segmentTree[parent] = segmentTree[left] ^ segmentTree[right] i = parent print(segmentTree[1]) ``` Yes
10,305
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` import math,sys ## from itertools import permutations, combinations;import heapq,random; from collections import defaultdict,deque import bisect as bi def yes():print('YES') def no():print('NO') #sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w'); def I():return (int(sys.stdin.readline())) def In():return(map(int,sys.stdin.readline().split())) def Sn():return sys.stdin.readline().strip() #sys.setrecursionlimit(1500) def dict(a): d={} for x in a: if d.get(x,-1)!=-1: d[x]+=1 else: d[x]=1 return d def find_gt(a, x): 'Find leftmost value greater than x' i = bi.bisect_left(a, x) if i != len(a): return i else: return -1 class Segmenttreemx(): st,n=[],0 def __init__(self,n,l): self.st=[-P]*(2*n) self.n=n for i in range(n): self.st[i+n]=l[i] for i in range(n-1,0,-1): z=(int(math.log(i,2))+1) if z&1: self.st[i]=(self.st[i<<1]^self.st[i<<1 | 1]) else: self.st[i]=(self.st[i<<1]|self.st[i<<1 | 1]) def update(self,p,val): self.st[p+self.n]=val p+=self.n while p>1: z=(int(math.log(p>>1,2))+1) if z&1: self.st[p>>1]=( self.st[p]^self.st[p^1]) else: self.st[p>>1]=( self.st[p]|self.st[p^1]) p>>=1 def query(self,l,r): l,r=l+self.n,r+self.n res=-P while l<r: if l&1: res=max(res,self.st[l]) l+=1 if r&1: r-=1 res=max(res,self.st[r]) l>>=1 r>>=1 return res def main(): try: n,nQ=In() l=list(In()) N=2**n Sg=Segmenttreemx(N,l) for x in range(nQ): a,b=In() Sg.update(a-1,b) print(Sg.st[1]) except: pass M = 998244353 P = 1000000007 if __name__ == '__main__': # for _ in range(I()):main() for _ in range(1):main() #End# # ******************* All The Best ******************* # ``` No
10,306
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` __author__ = 'ratnesh.mishra' def create_tree(node, start, last): if start == last: tree[node] = arr[start] create_tree.turn = 1 return tree[node] l = node << 1 mid = (start+last) >> 1 left = create_tree(l, start, mid) right = create_tree(l+1, mid+1, last) if create_tree.turn: tree[node] = left | right else: tree[node] = left ^ right create_tree.turn ^= 1 return tree[node] def update_tree(node, start, end, idx): if start == end and start == idx: tree[node] = arr[start] update_tree.turn = 1 return tree[node] mid = (start + end) >> 1 l = node << 1 left, right = -1, -1 if mid >= idx >= start: left = update_tree(l, start, mid, idx) elif end >= idx >= mid+1: right = update_tree(l+1, mid+1, end, idx) if left != -1: if update_tree.turn: tree[node] = left | tree[l+1] else: tree[node] = left ^ tree[l+1] elif right != -1: if update_tree.turn: tree[node] = tree[l] | right else: tree[node] = tree[l] ^ right update_tree.turn ^= 1 return tree[node] if __name__ == '__main__': try: n, m = map(int, input().split()) arr = [0] arr.extend(list(map(int, input().split()))) tree = [0]*(2*len(arr) + 1) turn = 0 create_tree(1, 1, (2*n)) for _ in range(m): i, val = map(int, input().split()) arr[i] = val print(update_tree(1, 1, (2*n), i)) except Exception as e: print(str(e)) ``` No
10,307
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` n, m = list(map(int, input().split(' '))) arr = list(map(int, input().split(' '))) # Align with 1-based indexing arr.insert(0, None) # Full and complete binary tree class Tree(object): def __init__(self, interval, depth = 0, parent = None): self.interval = interval self.parent = parent self.depth = depth # If this isn't a leaf, make two children so we have a full tree if interval[1] - interval[0] > 0: num_elements = interval[1] - interval[0] + 1 # Complete with weight on left left_upper = interval[0] + num_elements // 2 - 1 right_lower = left_upper + 1 self.left = Tree((interval[0], left_upper), depth + 1, self) self.right = Tree((right_lower, interval[1]), depth + 1, self) else: self.left = None self.right = None self.updateNode() # print(self.interval, self.gcd) # if not self.isLeaf(): # print("Left child:\t", self.left.interval) # print("Right child:\t", self.right.interval) def isLeaf(self): return self.left is None and self.right is None # Update this node's gcd def updateNode(self): if self.isLeaf(): self.value = arr[self.interval[0]] elif self.depth & 1: # odd is xor self.value = self.left.value ^ self.right.value else: # even is or self.value = self.left.value | self.right.value # Iterator of the path to the leaf containing the specified index def leafSearch(self, index): currentNode = self while(not currentNode.isLeaf()): yield(currentNode) if index <= currentNode.left.interval[1]: currentNode = currentNode.left else: currentNode = currentNode.right yield(currentNode) # Search to the changed leaf, then update the gcds from the bottom up def updateValue(self, index): for node in [*self.leafSearch(index)][::-1]: node.updateNode() def containsInterval(self, interval): return self.interval[0] <= interval[0] and self.interval[1] >= interval[1] # Build the tree from the bottom up root = Tree((1, len(arr) - 1), 1) # Why the minus? Isn't this 1-based? result = list() for i in range(0, m): index, value = list(map(int, input().split(' '))) # Update the array and tree arr[index] = value root.updateValue(index) # Record the result print(root.value) ``` No
10,308
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v. Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) β†’ (1 or 2 = 3, 3 or 4 = 7) β†’ (3 xor 7 = 4). The result is v = 4. You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a. Input The first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query. Output Print m integers β€” the i-th integer denotes value v for sequence a after the i-th query. Examples Input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 Output 1 3 3 3 Note For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation Submitted Solution: ``` import sys input=sys.stdin.readline import math sys.setrecursionlimit(10**9) def construct(array,cur_pos,tree,start,end): if(start==end): tree[cur_pos]=array[start] else: mid=(start+end)//2 w=int(math.log(int(n-2**math.log(cur_pos+1)))) # print(w) if(w%2!=0): # print(cur_pos,w) tree[cur_pos]=(construct(array,2*cur_pos+1,tree,start,mid)^construct(array,2*cur_pos+2,tree,mid+1,end)) else: # print(cur_pos,w) tree[cur_pos]=(construct(array,2*cur_pos+1,tree,start,mid)|construct(array,2*cur_pos+2,tree,mid+1,end)) return tree[cur_pos] def update(cur_pos,l,r,index,increment): # print(tree) if(l<=index<=r): if(l==r): tree[cur_pos]=increment else: mid=(l+r)//2 w=int(math.log(int(n-2**math.log(cur_pos+1)))) if(w%2!=0): update(2*cur_pos+1,l,mid,index,increment) update(2*cur_pos+2,mid+1,r,index,increment) tree[cur_pos]=tree[2*cur_pos+1]^tree[2*cur_pos+2] else: update(2*cur_pos+1,l,mid,index,increment) update(2*cur_pos+2,mid+1,r,index,increment) tree[cur_pos]=tree[2*cur_pos+1]|tree[2*cur_pos+2] return tree[cur_pos] return 0 l= list(map(int,input().split())) l1=list(map(int,input().split())) n=2**l[0] tree=[0]*(4*n) construct(l1,0,tree,0,n-1) for i in range(l[1]): l2=list(map(int,input().split())) update(0,0,n-1,l2[0]-1,l2[1]) # print(tree,"ppp") print(tree[0]) ``` No
10,309
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` MOVS = [(2,-2),(-2,2),(-2,-2),(2,2)] def check(a): return 0<=a<8 set1 = set() set2 = set() dic1 = dict() dic2 = dict() def cango1(matrix,pos,lap): for dx,dy in MOVS: nx,ny = dx+pos[0],dy+pos[1] if not check (nx) or not check(ny): continue if (nx,ny) in set1: continue dic1[(nx,ny)]=lap%2 set1.add((nx,ny)) cango1(matrix,(nx,ny),lap+1) def cango2(matrix,pos,lap): for dx,dy in MOVS: nx,ny = dx+pos[0],dy+pos[1] if not check(nx) or not check(ny): continue if (nx,ny) in set2: continue dic2[(nx,ny)]=lap%2 set2.add((nx,ny)) cango2(matrix,(nx,ny),lap+1) q = int(input()) for ww in range(q): matrix = [input().strip() for i in range(8)] pos = [] for i in range(8): for j in range(8): if matrix[i][j] == 'K': pos.append((i,j)) set1,set2,dic1,dic2=set(),set(),dict(),dict() cango1(matrix, pos[0],0) cango2(matrix,pos[1],0) if ww!=q-1: input() sec = set1&set2 for x,y in sec: if dic1[(x,y)]==dic2[(x,y)]: print("YES") break else: print("NO") ```
10,310
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` n = int(input()) for t in range(n): if t: input() board = [[c for c in input()] for i in range(8)] k1, k2 = ((i, j) for i in range(8) for j in range(8) if board[i][j] == 'K') if (k1[0] - k2[0]) % 4 == 0 and (k1[1] - k2[1]) % 4 == 0: print('YES') else: print('NO') ```
10,311
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` def check(): board = [] for cont in range(0,8): board.append(input()) l = True for cont in range(0,8): for cont2 in range(0,8): if board[cont][cont2] == 'K': if l: xk1 = cont2 yk1 = cont l = False else: xk2 = cont2 yk2 = cont break for cont in range(0,8): for cont2 in range(0,8): if cont2 %2 == xk1%2 == xk2%2: if cont%2 == yk1%2 == yk2%2: if abs(cont2-xk1)%4 == abs(cont2-xk2)%4: if abs(cont-yk1)%4 == abs(cont-yk2)%4: if board[cont][cont2] != '#': print('YES') return print('NO') return n = int(input()) check() for t in range(0,n-1): a = str(input()) check() ```
10,312
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` import sys import collections class GetOutOfLoop(Exception): pass if __name__ == "__main__": n_cases = int(sys.stdin.readline()) for case in range(n_cases): board = [list(sys.stdin.readline().rstrip()) for i in range(8)] knight_init_loc = [None, None] knight = 0 for current_i in range(8): for current_j in range(8): if board[current_i][current_j] == 'K': knight_init_loc[knight] = (current_i, current_j) knight += 1 to_explore = collections.deque() to_explore.append((knight_init_loc[0], 0)) explored = set() try: while len(to_explore) > 0: ((current_i, current_j), current_step) = to_explore.popleft() explored.add((current_i, current_j)) candidates = set() for inc_i in [-2, 2]: for inc_j in [-2, 2]: next_i, next_j = current_i + inc_i, current_j + inc_j if 0 <= next_i < 8 and 0 <= next_j < 8 and (next_i, next_j) not in explored: candidates.add(((next_i, next_j), current_step + 1)) for (s, next_step) in candidates: if s == knight_init_loc[1] and next_step % 2 == 0: print('YES') raise GetOutOfLoop to_explore.append((s, next_step)) current_step += 1 print('NO') except GetOutOfLoop: pass sys.stdin.readline() ```
10,313
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` for i in range(int(input())): if i : input() ans = [] for i in range(8): s = input() for j in range(8): if s[j] == 'K': ans.append((i, j)) print(['NO' , 'YES'][abs(ans[0][0] - ans[1][0]) % 4 == 0 and abs(ans[0][1] - ans[1][1]) % 4 == 0]) ```
10,314
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` t = int(input()) for _ in range(t): if _: input() knights = [] for i in range(8): s = input().strip() for j in range(8): if s[j] == 'K': knights.append((i,j)) n1 = knights[0] n2 = knights[1] """ if n1[0] % 2 == n2[0] % 2 and n1[1] % 2 == n2[1] % 2: c1 = n1[0]//2 + n1[1]//2 c2 = n2[1]//2 + n2[0]//2 if c1 % 2 == c2 % 2: print('YES') else: print('NO') """ if n1[0] % 4 == n2[0] % 4 and n1[1] % 4 == n2[1] % 4: print('YES') else: print('NO') ```
10,315
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- from math import gcd, ceil def pre(s): n = len(s) pi = [0] * n for i in range(1, n): j = pi[i - 1] while j and s[i] != s[j]: j = pi[j - 1] if s[i] == s[j]: j += 1 pi[i] = j return pi def prod(a): ans = 1 for each in a: ans = (ans * each) return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y from collections import deque def dfs(graph, alpha=0): """Breadth first search on a graph!""" n = len(graph) q = deque([alpha]) used = [False]*n used[alpha] = True dist, parents = [0]*n, [-1]*n while q: v = q.popleft() for u in graph[v]: if not used[u]: used[u] = True q.append(u) dist[u] = dist[v] + 1 parents[u] = v return used, dist for _ in range(int(input()) if True else 1): #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) #s = input() a = [] def pos(i,j): return i*8+j+1 for i in range(8): a += [[k for k in input()]] graph = [[] for i in range(65)] ks = [] for i in range(8): for j in range(8): if a[i][j] == "K":ks += [pos(i,j)] if 1: if i+2 < 8: if 0<=j+2 <8: graph[pos(i,j)] += [pos(i+2,j+2)] graph[pos(i+2, j+2)] += [pos(i,j)] if 0<=j-2<8: graph[pos(i,j)] += [pos(i+2,j-2)] graph[pos(i+2, j-2)] += [pos(i,j)] if 0<=i-2<8: if 0<=j+2 <8: graph[pos(i,j)] += [pos(i-2,j+2)] graph[pos(i-2, j+2)] += [pos(i,j)] if 0<=j-2<8: graph[pos(i,j)] += [pos(i-2,j-2)] graph[pos(i-2, j-2)] += [pos(i,j)] d1,dist1 = dfs(graph, ks[0]) d2,dist2 = dfs(graph,ks[1]) found = False for i in range(1,len(d1)): if d1[i] and d2[i] and dist1[i] == dist2[i]: print("YES") found=True break if not found: print("NO") x=input() ```
10,316
Provide tags and a correct Python 3 solution for this coding contest problem. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Tags: greedy, math Correct Solution: ``` def check(x, y): return 0 <= x < 8 and 0 <= y < 8 def dfs1(x, y, T=0): global first, used if not(check(x, y)) or used[x][y]: return used[x][y] = True first.add((x, y, T)) for pair in (2, 2), (2, -2), (-2, 2), (-2, -2): dfs1(x + pair[0], y + pair[1], 1 - T) def dfs2(x, y, T=0): global second, used if not(check(x, y)) or used[x][y]: return used[x][y] = True second.add((x, y, T)) for pair in (2, 2), (2, -2), (-2, 2), (-2, -2): dfs2(x + pair[0], y + pair[1], 1 - T) t = int(input()) for i in range(t): if i > 0: kuzma = input() board = [input() for i in range(8)] FoundFirst = False for i in range(8): for j in range(8): if board[i][j] == 'K': if not(FoundFirst): First = (i, j) FoundFirst = True else: Second = (i, j) used = [[0 for i in range(8)] for j in range(8)] first = set() dfs1(First[0], First[1]) used = [[0 for i in range(8)] for j in range(8)] second = set() dfs2(Second[0], Second[1]) intersection = first & second IsOk = False for x, y, t in intersection: if board[x][y] != '#': print("YES") IsOk = True break if not(IsOk): print("NO") board = [] ```
10,317
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` t = int(input()) for k in range(t): r8 = range(8) a = [input() for i in r8] ij = [(i, j) for i in r8 for j in r8] x, y = ((i, j) for i, j in ij if a[i][j] == "K") def s(p): d = [(p[0] - 2, p[1] - 2), (p[0] + 2, p[1] - 2), (p[0] - 2, p[1] + 2), (p[0] + 2, p[1] + 2)] return set((i, j) for i, j in ij if (i, j) in d) print("YES" if len(s(x) & s(y)) > 0 else "NO") if k != t - 1: input() ``` Yes
10,318
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` def solve(m, x,y , w,z): for i in range(8): for j in range(8): if m[i][j]: a, pa = movePossible(x,y , i,j) b, pb = movePossible(w,z , i,j) if a and b and pa==pb: return True return False def movePossible(x,y , w,z): a = x-w b = y-z pos=False ka=a//2 kb=b//2 if a%2==0 and b%2==0 and (ka+kb)%2==0: pos=True return pos, ka%2 t = int(input()) for _c in range(t): m = [] primo = True for i in range(8): m.append([]) s = input() k=0 for c in s: if c=='#': m[i].append( False ) else: m[i].append( True ) if c=='K' and primo: x=i y= k primo = False if c=='K' and (not primo): w=i z= k k+=1 if solve(m, x,y , w,z): print("YES") else: print("NO") if _c!=t-1: m=input() ``` Yes
10,319
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` t = int(input()) for _ in range(t): s = [input() for i in range(8)] oh = True flag = True for i in range(8): for j in range(8): if(s[i][j] == 'K'): if(flag): pos1x = i pos1y = j flag = False else: pos2x = i pos2y = j if(pos1x % 4 == pos2x % 4) and (pos1y % 4 == pos2y % 4): print('YES') else: print('NO') if( _ < t - 1): k = input() ``` Yes
10,320
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` T=int(input()) for t in range(T): L=[] for i in range(8): L.append(input()) Moves1=[] Moves2=[] K=[] for i in range(8): Moves1.append([-1]*8) Moves2.append([-1]*8) for j in range(8): if(L[i][j]=='K'): K.append((i,j)) Now=K[0] Explored=[(Now[0],Now[1],0)] Moves1[Now[0]][Now[1]]=0 while(len(Explored)!=0): x=Explored[0][0] y=Explored[0][1] p=Explored[0][2] Explored.pop(0) if(x-2>=0 and y-2>=0): if(Moves1[x-2][y-2]==-1): Moves1[x-2][y-2]=1-p Explored.append((x-2,y-2,1-p)) if(x+2<8 and y-2>=0): if(Moves1[x+2][y-2]==-1): Moves1[x+2][y-2]=1-p Explored.append((x+2,y-2,1-p)) if(x-2>=0 and y+2<8): if(Moves1[x-2][y+2]==-1): Moves1[x-2][y+2]=1-p Explored.append((x-2,y+2,1-p)) if(x+2<8 and y+2<8): if(Moves1[x+2][y+2]==-1): Moves1[x+2][y+2]=1-p Explored.append((x+2,y+2,1-p)) Now=K[1] Explored=[(Now[0],Now[1],0)] Moves2[Now[0]][Now[1]]=0 while(len(Explored)!=0): x=Explored[0][0] y=Explored[0][1] p=Explored[0][2] Explored.pop(0) if(x-2>=0 and y-2>=0): if(Moves2[x-2][y-2]==-1): Moves2[x-2][y-2]=1-p Explored.append((x-2,y-2,1-p)) if(x+2<8 and y-2>=0): if(Moves2[x+2][y-2]==-1): Moves2[x+2][y-2]=1-p Explored.append((x+2,y-2,1-p)) if(x-2>=0 and y+2<8): if(Moves2[x-2][y+2]==-1): Moves2[x-2][y+2]=1-p Explored.append((x-2,y+2,1-p)) if(x+2<8 and y+2<8): if(Moves2[x+2][y+2]==-1): Moves2[x+2][y+2]=1-p Explored.append((x+2,y+2,1-p)) valid=False for i in range(8): for j in range(8): if(Moves1[i][j]!=-1 and Moves1[i][j]==Moves2[i][j] and L[i][j]!="#"): valid=True if(valid): print("YES") else: print("NO") if(t!=T-1): s=input() ``` Yes
10,321
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` t = int(input()) oh = False v = [[False] * 100 for i in range(100)] def dfs(i, j, x ,y): global oh v[i][j] = True if(i == x) and (j == y) and (oh == True): oh = False print("YES") else: if(i > 1) & (j > 1) & (v[i - 2][j - 2] == False): dfs(i - 2, j - 2, x, y) if(i + 2 < 8) & (j + 2 < 8) & (v[i + 2][j + 2] == False): dfs(i + 2, j + 2, x, y) if(i > 1) & (j + 2 < 8) & (v[i - 2][j + 2] == False): dfs(i - 2, j + 2, x, y) if(i + 2 < 8) & (j > 1) & (v[i + 2][j - 2] == False): dfs(i + 2, j - 2, x, y) for _ in range(t): s = [input() for i in range(8)] oh = True flag = True for i in range(8): for j in range(8): if(s[i][j] == 'K'): if(flag): pos1x = i pos1y = j flag = False else: pos2x = i pos2y = j dfs(pos1x, pos1y, pos2x, pos2y) if(oh == True): print("NO") if ( _ < t - 1): k = input() ``` No
10,322
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` def main(): n = int(input()) out = "" for t in range(n): knights = [0 for i in range(16)] valid = [False for i in range(16)] for i in range(8): line = input() #print() for j in range(8): #print(get(i, j), end="\t") if line[j] != '#': valid[get(i, j)] = True if line[j] == 'K': knights[get(i, j)] += 1 for i in range(16): #print(i, knights[i], valid[i]) if knights[i] == 2 and valid[i]: out += "YES\n" break else: out += "NO\n" if t != n-1: input() print(out[:-1]) def get(i, j): x = (i%2)*8 + j if i % 4 > 1: x = (i%2)*8 + (j+2)%4 + (j//4)*2 if j > 3: x += 2 return x if __name__ == "__main__": main() ``` No
10,323
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` import sys import math import collections import heapq t=int(input()) for w in range(t): l=[] for i in range(8): l1=list(input()) l.append(l1) t1,t2=(),() for i in range(8): for j in range(8): if(l[i][j]=='K'): if(t1==()): t1=(i,j) else: t2=(i,j) break if(t2!=()): break k=max(abs(t1[0]-t2[0])-1,0)+max(abs(t1[1]-t2[1])-1,0) if(t1[0]!=t2[0] and t1[1]!=t2[1]): k+=1 if(k%4==3): print("YES") else: print("NO") if(w<t-1): input() ``` No
10,324
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis. Input The first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line. Output For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise. Examples Input 2 ........ ........ ......#. K..##..# .......# ...##..# ......#. K....... ........ ........ ..#..... ..#..#.. ..####.. ...##... ........ ....K#K# Output YES NO Note Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7). On the second board the semiknights will never meet. Submitted Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- from math import gcd, ceil def pre(s): n = len(s) pi = [0] * n for i in range(1, n): j = pi[i - 1] while j and s[i] != s[j]: j = pi[j - 1] if s[i] == s[j]: j += 1 pi[i] = j return pi def prod(a): ans = 1 for each in a: ans = (ans * each) return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def dfs(graph, alpha): """Depth First Search on a graph!""" n = len(graph) visited = [False]*n stack = [alpha] while stack: v = stack[-1] if not visited[v]: visited[v] = True for u in graph[v]: if not visited[u]: stack.append(u) else: stack.pop() return visited for _ in range(int(input()) if True else 1): #n, k = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) #s = input() a = [] def pos(i,j): return i*8+j+1 for i in range(8): a += [[k for k in input()]] graph = [[] for i in range(65)] ks = [] for i in range(8): for j in range(8): if a[i][j] == "K":ks += [pos(i,j)] if a[i][j] != "#": if i+2 < 8: if 0<=j+2 <8: if a[i+2][j+2] != "#": graph[pos(i,j)] += [pos(i+2,j+2)] graph[pos(i+2, j+2)] += [pos(i,j)] if 0<=j-2<8: if a[i+2][j-2] != "#": graph[pos(i,j)] += [pos(i+2,j-2)] graph[pos(i+2, j-2)] += [pos(i,j)] if 0<=i-2<8: if 0<=j+2 <8: if a[i-2][j+2] != "#": graph[pos(i,j)] += [pos(i-2,j+2)] graph[pos(i-2, j+2)] += [pos(i,j)] if 0<=j-2<8: if a[i-2][j-2] != "#": graph[pos(i,j)] += [pos(i-2,j-2)] graph[pos(i-2, j-2)] += [pos(i,j)] d1 = dfs(graph, ks[0]) d2 = dfs(graph,ks[1]) found = False for i in range(len(d1)): if d1[i] and d2[i]: print("YES") found=True break if not found: print("NO") x=input() ``` No
10,325
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair. For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph. <image> You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible! Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n; ai β‰  bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them. If it is impossible to cut the given graph, print "No solution" (without quotes). Examples Input 8 12 1 2 2 3 3 4 4 1 1 3 2 4 3 5 3 6 5 6 6 7 6 8 7 8 Output 1 2 4 1 3 2 1 4 3 5 3 6 5 6 8 6 7 8 Input 3 3 1 2 2 3 3 1 Output No solution Input 3 2 1 2 2 3 Output 1 2 3 Tags: dfs and similar, graphs Correct Solution: ``` import sys input = sys.stdin.readline print = sys.stdout.write def get_input(): n, m = [int(x) for x in input().split(' ')] graph = [[] for _ in range(n + 1)] for _ in range(m): c1, c2 = [int(x) for x in input().split(' ')] graph[c1].append(c2) graph[c2].append(c1) if m % 2 != 0: print("No solution") exit(0) return graph def dfs(graph): n = len(graph) w = [0] * n pi = [None] * n visited = [False] * n finished = [False] * n adjacency = [[] for _ in range(n)] stack = [1] while stack: current_node = stack[-1] if visited[current_node]: stack.pop() if finished[current_node]: w[current_node] = 0 continue # print(current_node, adjacency[current_node]) finished[current_node] = True unpair = [] for adj in adjacency[current_node]: if w[adj] == 0: # print('unpaired ->', adj, w[adj]) unpair.append(adj) else: print(' '.join([str(current_node), str(adj), str(w[adj]), '\n'])) while len(unpair) > 1: print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n'])) w[current_node] = unpair.pop() if unpair else 0 continue visited[current_node] = True not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]] stack += not_blocked_neighbors adjacency[current_node] = not_blocked_neighbors # print('stack:', stack, current_node) # def recursive_dfs(graph): # n = len(graph) # visited = [False] * n # recursive_dfs_visit(graph, 1, visited) # def recursive_dfs_visit(graph, root, visited): # unpair = [] # visited[root] = True # adjacency = [x for x in graph[root] if not visited[x]] # for adj in adjacency: # w = recursive_dfs_visit(graph, adj, visited) # if w == 0: # unpair.append(adj) # else: # print(' '.join([str(root), str(adj), str(w), '\n'])) # while len(unpair) > 1: # print(' '.join([str(unpair.pop()), str(root), str(unpair.pop()), '\n'])) # if unpair: # return unpair.pop() # return 0 if __name__ == "__main__": graph = get_input() dfs(graph) ```
10,326
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair. For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph. <image> You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible! Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n; ai β‰  bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them. If it is impossible to cut the given graph, print "No solution" (without quotes). Examples Input 8 12 1 2 2 3 3 4 4 1 1 3 2 4 3 5 3 6 5 6 6 7 6 8 7 8 Output 1 2 4 1 3 2 1 4 3 5 3 6 5 6 8 6 7 8 Input 3 3 1 2 2 3 3 1 Output No solution Input 3 2 1 2 2 3 Output 1 2 3 Tags: dfs and similar, graphs Correct Solution: ``` import sys input = sys.stdin.readline print = sys.stdout.write def get_input(): n, m = [int(x) for x in input().split(' ')] graph = [[] for _ in range(n + 1)] for _ in range(m): c1, c2 = [int(x) for x in input().split(' ')] graph[c1].append(c2) graph[c2].append(c1) if m % 2 != 0: print("No solution") exit(0) return graph def partitions_bottom_up(graph): n = len(graph) w = [0] * n pi = [None] * n visited = [False] * n finished = [False] * n adjacency = [[] for _ in range(n)] stack = [1] while stack: current_node = stack[-1] if visited[current_node]: stack.pop() if finished[current_node]: w[current_node] = 0 continue finished[current_node] = True unpair = [] for adj in adjacency[current_node]: if w[adj] == 0: unpair.append(adj) else: print(' '.join([str(current_node), str(adj), str(w[adj]), '\n'])) while len(unpair) > 1: print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n'])) w[current_node] = unpair.pop() if unpair else 0 continue visited[current_node] = True not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]] stack += not_blocked_neighbors adjacency[current_node] = not_blocked_neighbors def partitions_top_down(graph): n = len(graph) visited = [False] * n for node in range(1, n): if not visited[node]: prev_node = None current_node = node while current_node is not None: visited[current_node] = True leafs = [prev_node] if prev_node is not None else [] adjacency = [] for adj in graph[current_node]: if not visited[adj]: if len(graph[adj]) == 1: leafs.append(adj) else: adjacency.append(adj) while len(leafs) > 1: print(' '.join([str(leafs.pop()), str(current_node), str(leafs.pop()), '\n'])) if leafs: adjacency.append(leafs.pop()) while len(adjacency) > 1: print(' '.join([str(adjacency.pop()), str(current_node), str(adjacency.pop()), '\n'])) if adjacency: current_node, prev_node = adjacency.pop(), current_node else: current_node = None if __name__ == "__main__": graph = get_input() partitions_bottom_up(graph) ```
10,327
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` n = int(input()) a = [] b = [] c = 0 for i in range(n): x,y = map(int, input().split()) a.append(x) b.append(y) for i in range(n): if a[i] != b[i]: c += 1 if c > 0: print("Happy Alex") else: print("Poor Alex") ```
10,328
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` # with open("input.txt","r") as f: laptops = [] for _ in range(int(input())): laptop = list(map(int,input().split())) laptops.append(laptop) laptops.sort() truth = False for i in range(len(laptops)-1): if laptops[i][0]<laptops[i+1][0] and laptops[i][1]>laptops[i+1][1]: truth = True break if(truth): print("Happy Alex") else: print("Poor Alex") ```
10,329
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` n=int(input()) s='Poor Alex' for i in range(0,n): x, y = input().split() if int(x) > int(y): s='Happy Alex' print(s) ```
10,330
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` n = int(input()) temp1 = 0 for x in range(n): a, b = input().split() a = int(a) b = int(b) if a < b: temp1 += 1 if temp1 == 0: print("Poor Alex") else: print("Happy Alex") ```
10,331
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` def CF456A(): N = int(input()) laptops = [tuple(map(int, input().split())) for _ in range(N)] laptops = sorted(laptops, key=lambda x:(x[0], x[1])) for i in range(N-1): if laptops[i][1] > laptops[i+1][1]: return "Happy Alex" return "Poor Alex" if __name__ == '__main__': res = CF456A() print(res) ```
10,332
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` N=int(input()) q=[[0,0] for i in range(N)] x=False for i in range (N): q[i][0],q[i][1]=map(int,input().split()) s=sorted(q, key=lambda x: x[0]) for k in range(1,N): if s[k-1][1]-s[k][1]>0: x=True if x: print('Happy Alex') else: print('Poor Alex') ```
10,333
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` import sys input=sys.stdin.readline l=[] for i in range(int(input())):l.append(list(map(int,input().split()))) l.sort() m=[i[1]for i in l] print(["Happy","Poor"][m==sorted(m)],"Alex") ```
10,334
Provide tags and a correct Python 3 solution for this coding contest problem. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Tags: sortings Correct Solution: ``` entrada = int(input()) sub = 0 ind = 0 pos = 0 tuplas = [] flag = False for i in range(entrada): tupla = list(int(x) for x in input().split()) tuplas.append(tupla) s = tupla[0] - tupla[1] if s < 0: if sub == 0 and pos == 0: sub = s ind = i elif s < sub or s == sub: if tuplas[ind][0] > tupla[0] and tuplas[ind][1] < tupla[1]: flag = True break else: flag = True break elif s > 0: if sub != 0: flag = True break pos+=1 if flag: print("Happy Alex") else: print("Poor Alex") ```
10,335
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` n=int(input()) L=[0]*(n+1) for k in range(n): a,b=map(int,input().split()) L[a]=b def s(L,n): for k in range(n): if(L[k]>L[k+1]): return "Happy Alex" return "Poor Alex" print(s(L,n)) ``` Yes
10,336
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` n = int(input()) price = [] quality = [] temp = [] for i in range(n): temp = input().split(" ") price.append(int(temp[0])) quality.append(temp[1]) laptop = {} for i in range(n): laptop[price[i]] = quality[i] sortedLaptop = {} sortedLaptop = sorted(zip(laptop.keys(), laptop.values())) q = int(0) result = 0 for k,v in sortedLaptop: if int(v) >= q: q = int(v) else: result = 1 break if result is 1: print("Happy Alex") else: print("Poor Alex") ``` Yes
10,337
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` """http://codeforces.com/problemset/problem/456/A""" def solve(l): l = sorted(l, key=lambda x: x[0]) quality = 0 for i in l: if i[1] <= quality: return True quality = i[1] return False R = lambda: list(map(int, input().split())) n = int(input()) l = [R() for _ in range(n)] r = solve(l) print('Happy Alex' if r else 'Poor Alex') ``` Yes
10,338
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` n = int(input()) p, q = [], [] for _ in range(n): a, b = map(int, input().split()) p.append(a) q.append(b) c = sorted(zip(p, q)) d = list(zip(*c)) m = 0 e = list(d[1]) for i in range(n-1): if e[i] > e[i+1]: m = 1 break if m == 1: print('Happy Alex') else: print('Poor Alex') ``` Yes
10,339
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` # https://codeforces.com/contest/456/problem/A n = int(input()) price, quality = map(int, input().split()) high_quality_laptop = (price, quality) low_price_laptop = (price, quality) for i in range(n - 1): price, quality = map(int, input().split()) if price > low_price_laptop[0] and quality < low_price_laptop[1]: print("Happy Alex") break else: low_price_laptop = price, quality if price > high_quality_laptop[0] and quality < high_quality_laptop[1]: print("Happy Alex") break else: high_quality_laptop = price, quality else: print("Poor Alex") ``` No
10,340
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` import sys input = sys.stdin.readline laptops = [[int(i) for i in input().split()] for _ in range(int(input()))] laptops.sort(reverse = True) best_qual, best_qual_price, flag = 0, -1, True for i in range(len(laptops)): if laptops[i][1] > best_qual: best_qual = laptops[i][1] if laptops[i][0] < best_qual_price: flag = True break best_qual_price = laptops[i][0] if flag: print("Happy Alex") else: print("Poor Alex") ``` No
10,341
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` n=int(input()) c,d=0,0 for i in range(n): a,b=list(map(int,input().rstrip().split())) if a<b: c+=1 else: d+=1 if c>d: print("Happy Alex") else: print("Poor Alex") ``` No
10,342
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop. Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist. Input The first line contains an integer n (1 ≀ n ≀ 105) β€” the number of laptops. Next n lines contain two integers each, ai and bi (1 ≀ ai, bi ≀ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. Output If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes). Examples Input 2 1 2 2 1 Output Happy Alex Submitted Solution: ``` count = int(input()) lis = [] for i in range(0, count): inp = input() a = int(inp.split()[0]) b = int(inp.split()[1]) lis.append((a,b)) lis.sort() for i in range(0, count - 1): if lis[i][0] < lis[i + 1][0] and lis[i][1] < lis[i + 1][1]: print("Poor Alex") exit(0) print("Happy Alex") ``` No
10,343
Provide tags and a correct Python 3 solution for this coding contest problem. There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β€” of n - 1 blocks, the third one β€” of n - 2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; * Each level of the red-green tower should contain blocks of the same color. <image> Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks. Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower. You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7. Input The only line of input contains two integers r and g, separated by a single space β€” the number of available red and green blocks respectively (0 ≀ r, g ≀ 2Β·105, r + g β‰₯ 1). Output Output the only integer β€” the number of different possible red-green towers of height h modulo 109 + 7. Examples Input 4 6 Output 2 Input 9 7 Output 6 Input 1 1 Output 2 Note The image in the problem statement shows all possible red-green towers for the first sample. Tags: dp Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from collections import Counter def main(): mod = 10**9+7 r,g = map(int,input().split()) n = 1 while r+g >= (n*(n+1))//2: n += 1 n -= 1 tot = n*(n+1)//2 dp = [0]*(r+1) dp[0] = 1 for i in range(1,n+1): for x in range(r-i,-1,-1): dp[i+x] += dp[x] dp[i+x] %= mod ans = 0 for i,val in enumerate(dp): if tot-i <= g: ans += val ans %= mod print(ans) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main() ```
10,344
Provide tags and a correct Python 3 solution for this coding contest problem. There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β€” of n - 1 blocks, the third one β€” of n - 2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; * Each level of the red-green tower should contain blocks of the same color. <image> Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks. Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower. You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7. Input The only line of input contains two integers r and g, separated by a single space β€” the number of available red and green blocks respectively (0 ≀ r, g ≀ 2Β·105, r + g β‰₯ 1). Output Output the only integer β€” the number of different possible red-green towers of height h modulo 109 + 7. Examples Input 4 6 Output 2 Input 9 7 Output 6 Input 1 1 Output 2 Note The image in the problem statement shows all possible red-green towers for the first sample. Tags: dp Correct Solution: ``` """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h import bisect from types import GeneratorType BUFSIZE = 8192 class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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") import collections as col import math, string def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) MOD = 10**9+7 mod=10**9+7 #t=int(input()) t=1 p=10**9+7 def ncr_util(): inv[0]=inv[1]=1 fact[0]=fact[1]=1 for i in range(2,300001): inv[i]=(inv[i%p]*(p-p//i))%p for i in range(1,300001): inv[i]=(inv[i-1]*inv[i])%p fact[i]=(fact[i-1]*i)%p def solve(): h=0 for i in range(1000): if (i*(i+1))//2<=(r+g): h=i dp=[0]*(r+1) dp[0]=1 #print(h) for i in range(1,h+1): curr=(i*(i+1))//2 for j in range(r,-1,-1): if j-i>=0 : dp[j]=(dp[j]%mod+dp[j-i]%mod)%mod tot=(h*(h+1))//2 ans=0 for i in range(r+1): if tot-i<=g: ans=(ans%mod+dp[i]%mod)%mod return ans for _ in range(t): #n=int(input()) #n=int(input()) #n,m=(map(int,input().split())) #n1=n #x=int(input()) #b=int(input()) #n,m,k=map(int,input().split()) r,g=map(int,input().split()) #n=int(input()) #s=input() #s1=input() #p=input() #l=list(map(int,input().split())) #l.sort() #l.sort(revrese=True) #l2=list(map(int,input().split())) #l=str(n) #l.sort(reverse=True) #l2.sort(reverse=True) #l1.sort(reverse=True) print(solve()) ```
10,345
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β€” of n - 1 blocks, the third one β€” of n - 2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; * Each level of the red-green tower should contain blocks of the same color. <image> Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks. Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower. You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7. Input The only line of input contains two integers r and g, separated by a single space β€” the number of available red and green blocks respectively (0 ≀ r, g ≀ 2Β·105, r + g β‰₯ 1). Output Output the only integer β€” the number of different possible red-green towers of height h modulo 109 + 7. Examples Input 4 6 Output 2 Input 9 7 Output 6 Input 1 1 Output 2 Note The image in the problem statement shows all possible red-green towers for the first sample. Submitted Solution: ``` mod=10**9+7 dp=[0 for i in range(4*10**5)] acum=dp.copy() n,m=map(int,input().split()) x=n+m y=1 acum[1]=1 while acum[y]<=x: acum[y+1]=(acum[y]+y+1)%mod y+=1 x=acum[y-1] for i in range(1,y+1): dp[i]+=1 dp[i+acum[i-1]+1]-=1 y1=y y=0 for i in range(1,len(dp)): y+=dp[i] y%=mod dp[i]=y ans=0 dp[0]=1 for i in range(n+1): a=x-i if a<=m : ans+=dp[i] print(ans) ``` No
10,346
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β€” of n - 1 blocks, the third one β€” of n - 2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; * Each level of the red-green tower should contain blocks of the same color. <image> Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks. Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower. You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7. Input The only line of input contains two integers r and g, separated by a single space β€” the number of available red and green blocks respectively (0 ≀ r, g ≀ 2Β·105, r + g β‰₯ 1). Output Output the only integer β€” the number of different possible red-green towers of height h modulo 109 + 7. Examples Input 4 6 Output 2 Input 9 7 Output 6 Input 1 1 Output 2 Note The image in the problem statement shows all possible red-green towers for the first sample. Submitted Solution: ``` import math r,g=map(int,input().split()) h=int(math.sqrt(1+2*(r+g)) -0.5) ways=[0 for i in range(min(r,g)+2)] print(h) ways[0]=1 for i in range(1,h+1): for j in range(min(r,g)-i,-1,-1): ways[i+j]+=ways[j] #print(ways) print(sum(ways[(h*(h+1))//2-max(r,g):min(r,g)+1])) ``` No
10,347
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β€” of n - 1 blocks, the third one β€” of n - 2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; * Each level of the red-green tower should contain blocks of the same color. <image> Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks. Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower. You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7. Input The only line of input contains two integers r and g, separated by a single space β€” the number of available red and green blocks respectively (0 ≀ r, g ≀ 2Β·105, r + g β‰₯ 1). Output Output the only integer β€” the number of different possible red-green towers of height h modulo 109 + 7. Examples Input 4 6 Output 2 Input 9 7 Output 6 Input 1 1 Output 2 Note The image in the problem statement shows all possible red-green towers for the first sample. Submitted Solution: ``` import math def find_no(num,i,j,s): #print(i,j,s) if(s==0): return 1 if(i<0 or j<0): return 0 elif(i==0 and j==0): num[0][0]=0 return [i][j] elif(i==0): # if(num[0][j]!=-1): # return num[0][j] # t = int(math.sqrt(2*j)) # if(j==t*(t+1)//2): # num[0][j] = 1 # return 1 # else: # num[0][j] = 0 # return 0 return 1 elif(j==0): # if(num[i][0]!=-1): # return num[i][0] # t = int(math.sqrt(2*i)) # if(i==t*(t+1)//2): # num[i][0]=1 # return 1 # else: # num[i][0]=0 # return 0 return 1 else: if(num[i][j]!=-1): return num[i][j] else: num[i][j] = find_no(num,i-s,j,s-1)+find_no(num,i,j-s,s-1) return num[i][j] b,g = map(int,input().split()) l = math.sqrt(2*(b+g)) r = int(l) s=0 if(r==l): s = int(r-1) else: s = int(r) if(2*(r+g)<(s*s+s)): s-=1 #print(s) num = [[-1 for i in range(b+1)] for j in range(g+1)] ans = find_no(num,g,b,s) #print(num) print(ans%1000000007) ``` No
10,348
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level β€” of n - 1 blocks, the third one β€” of n - 2 blocks, and so on β€” the last level of such tower should consist of the one block. In other words, each successive level should contain one block less than the previous one; * Each level of the red-green tower should contain blocks of the same color. <image> Let h be the maximum possible number of levels of red-green tower, that can be built out of r red and g green blocks meeting the rules above. The task is to determine how many different red-green towers having h levels can be built out of the available blocks. Two red-green towers are considered different if there exists some level, that consists of red blocks in the one tower and consists of green blocks in the other tower. You are to write a program that will find the number of different red-green towers of height h modulo 109 + 7. Input The only line of input contains two integers r and g, separated by a single space β€” the number of available red and green blocks respectively (0 ≀ r, g ≀ 2Β·105, r + g β‰₯ 1). Output Output the only integer β€” the number of different possible red-green towers of height h modulo 109 + 7. Examples Input 4 6 Output 2 Input 9 7 Output 6 Input 1 1 Output 2 Note The image in the problem statement shows all possible red-green towers for the first sample. Submitted Solution: ``` ans = set() def solve(h, r, g): result = 0 for i in range(2**h): if (i < r): continue c = [int(l) for l in str(bin(i))[2:]] for j in range(h - len(str(bin(i))[2:])): c.insert(0, 0) s_r = 0 s_g = 0 buf = [] for f in enumerate(reversed(c)): if f[1]: s_r += f[0] + 1 else: s_g += f[0] + 1 if s_r > r and s_g > g: break if s_r <= r and s_g <= g: if not tuple(c) in ans: ans.add(tuple(c)) result += 1 return result [r, g] = map(int, input().split()) print(solve(int(((1 + 8 * (r + g)) ** 0.5 - 1) / 2), r, g)) ``` No
10,349
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called GukiZiana. For given array a, indexed with integers from 1 to n, and number y, GukiZiana(a, y) represents maximum value of j - i, such that aj = ai = y. If there is no y as an element in a, then GukiZiana(a, y) is equal to - 1. GukiZ also prepared a problem for you. This time, you have two types of queries: 1. First type has form 1 l r x and asks you to increase values of all ai such that l ≀ i ≀ r by the non-negative integer x. 2. Second type has form 2 y and asks you to find value of GukiZiana(a, y). For each query of type 2, print the answer and make GukiZ happy! Input The first line contains two integers n, q (1 ≀ n ≀ 5 * 105, 1 ≀ q ≀ 5 * 104), size of array a, and the number of queries. The second line contains n integers a1, a2, ... an (1 ≀ ai ≀ 109), forming an array a. Each of next q lines contain either four or two numbers, as described in statement: If line starts with 1, then the query looks like 1 l r x (1 ≀ l ≀ r ≀ n, 0 ≀ x ≀ 109), first type query. If line starts with 2, then th query looks like 2 y (1 ≀ y ≀ 109), second type query. Output For each query of type 2, print the value of GukiZiana(a, y), for y value for that query. Examples Input 4 3 1 2 3 4 1 1 2 1 1 1 1 1 2 3 Output 2 Input 2 3 1 2 1 2 2 1 2 3 2 4 Output 0 -1 Submitted Solution: ``` from collections import defaultdict SQRT = 800 #Unrolled Linked List class sqrt_table(): def __init__(self, numbers): self.numbers = numbers self.N = len(numbers) self.SQRT = int(self.N / SQRT) + 1 self.add_tag = [0 for i in range(SQRT+20)] self.groups = [defaultdict(int) for i in range(SQRT+20)] self.belong_group = [0 for i in range(self.N+SQRT)] self.low = [0 for i in range(self.N+10)] self.high = [0 for i in range(self.N+10)] for (i, num) in enumerate(self.numbers): group = int(i/SQRT) self.belong_group[i] = group self.groups[group][num] += 1 self.low[i] = i*SQRT self.high[i] = min((i+1)*SQRT, self.N) def gao(self, l, r, v): if r > self.N: r = self.N group = self.belong_group[l] for i in range(l, r): num = self.numbers[i] self.groups[group][num] -= 1 self.groups[group][num+v] += 1 self.numbers[i] += v def addv(self, l, r, v): lgroup = self.belong_group[l] rgroup = self.belong_group[r] if lgroup == rgroup: self.gao(l, r+1, v) return self.gao(l, (lgroup+1)*SQRT, v) self.gao(rgroup*SQRT, r+1, v) for i in range(lgroup+1, rgroup): self.add_tag[i] += v def search_low(self, v): for i in range(self.SQRT): target = v - self.add_tag[i] if target in self.groups[i] and self.groups[i][target] > 0: low = self.low[i] high = self.high[i] for j in range(low, high): if self.numbers[j] == target: return j return -1 def search_high(self, v): for i in range(self.SQRT-1, -1, -1): target = v - self.add_tag[i] if target in self.groups[i] and self.groups[i][target] > 0: low = self.low[i] high = self.high[i] for j in range(high-1, low-1, -1): if self.numbers[j] == target: return j return -2 def print_info(self): print(self.numbers) print(self.groups[0]) N, Q = map(int, input().split()) Ns = list(map(int, input().split())) ST = sqrt_table(Ns) for qs in range(Q): query = list(map(int, input().split())) if query[0] == 1 and ST.SQRT <= 10: tmp, l, r, v = query ST.addv(l-1, r-1, v) if query[0] == 2: v = query[1] low = ST.search_low(v) if low == -1: print(-1) else: high = ST.search_high(v) print(high-low) ``` No
10,350
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called GukiZiana. For given array a, indexed with integers from 1 to n, and number y, GukiZiana(a, y) represents maximum value of j - i, such that aj = ai = y. If there is no y as an element in a, then GukiZiana(a, y) is equal to - 1. GukiZ also prepared a problem for you. This time, you have two types of queries: 1. First type has form 1 l r x and asks you to increase values of all ai such that l ≀ i ≀ r by the non-negative integer x. 2. Second type has form 2 y and asks you to find value of GukiZiana(a, y). For each query of type 2, print the answer and make GukiZ happy! Input The first line contains two integers n, q (1 ≀ n ≀ 5 * 105, 1 ≀ q ≀ 5 * 104), size of array a, and the number of queries. The second line contains n integers a1, a2, ... an (1 ≀ ai ≀ 109), forming an array a. Each of next q lines contain either four or two numbers, as described in statement: If line starts with 1, then the query looks like 1 l r x (1 ≀ l ≀ r ≀ n, 0 ≀ x ≀ 109), first type query. If line starts with 2, then th query looks like 2 y (1 ≀ y ≀ 109), second type query. Output For each query of type 2, print the value of GukiZiana(a, y), for y value for that query. Examples Input 4 3 1 2 3 4 1 1 2 1 1 1 1 1 2 3 Output 2 Input 2 3 1 2 1 2 2 1 2 3 2 4 Output 0 -1 Submitted Solution: ``` import sys if sys.version[0] == "3": raw_input = input n, q = map(int, raw_input().split()) a = list(map(int, raw_input().split())) otr_size = max(1, int(n ** 0.5 / 2)) otr_cnt = (n + otr_size - 1) // otr_size def get_otr_boundaries(i): return (i * otr_size, min(n, (i + 1) * otr_size)) def get_otr_by_index(i): return i // otr_size otr_delta = [0] * otr_cnt otr_dict = [{} for i in range(otr_cnt)] for i in range(n): otr_dict[get_otr_by_index(i)][a[i]] = otr_dict[get_otr_by_index(i)].get(a[i], 0) + 1 def change_item(i, otr_index, x): otr_dict[otr_index][a[i]] -= 1 a[i] += x otr_dict[otr_index][a[i]] = otr_dict[otr_index].get(a[i], 0) + 1 def get_item(i, otr_index): return a[i] + otr_delta[otr_index] def has_item(val, otr_index): return otr_dict[otr_index].get(val - otr_delta[otr_index]) big_test = q > 10000 for q_num in range(q): query = list(map(int, raw_input().split())) if query[0] == 1: l, r, x = query[1:] l -= 1 r -= 1 l_otr = get_otr_by_index(l) r_otr = get_otr_by_index(r) if l_otr == r_otr: for i in range(l, r + 1): change_item(i, l_otr, x) else: gr1 = get_otr_boundaries(l_otr)[1] gr2 = get_otr_boundaries(r_otr)[0] for i in range(l, gr1): change_item(i, l_otr, x) for i in range(gr2, r + 1): change_item(i, r_otr, x) if not big_test: for i in range(l_otr + 1, r_otr): otr_delta[i] += x else: y = query[1] first = 0 while first < otr_cnt and not has_item(y, first): first += 1 if first == otr_cnt: print(-1) else: second = otr_cnt - 1 while not has_item(y, second): second -= 1 for ind_first in range(*get_otr_boundaries(first)): if get_item(ind_first, first) == y: break for ind_second in reversed(range(*get_otr_boundaries(second))): if get_item(ind_second, second) == y: break print(ind_second - ind_first) # print("DEBUG", a, otr_dict, otr_delta) ``` No
10,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called GukiZiana. For given array a, indexed with integers from 1 to n, and number y, GukiZiana(a, y) represents maximum value of j - i, such that aj = ai = y. If there is no y as an element in a, then GukiZiana(a, y) is equal to - 1. GukiZ also prepared a problem for you. This time, you have two types of queries: 1. First type has form 1 l r x and asks you to increase values of all ai such that l ≀ i ≀ r by the non-negative integer x. 2. Second type has form 2 y and asks you to find value of GukiZiana(a, y). For each query of type 2, print the answer and make GukiZ happy! Input The first line contains two integers n, q (1 ≀ n ≀ 5 * 105, 1 ≀ q ≀ 5 * 104), size of array a, and the number of queries. The second line contains n integers a1, a2, ... an (1 ≀ ai ≀ 109), forming an array a. Each of next q lines contain either four or two numbers, as described in statement: If line starts with 1, then the query looks like 1 l r x (1 ≀ l ≀ r ≀ n, 0 ≀ x ≀ 109), first type query. If line starts with 2, then th query looks like 2 y (1 ≀ y ≀ 109), second type query. Output For each query of type 2, print the value of GukiZiana(a, y), for y value for that query. Examples Input 4 3 1 2 3 4 1 1 2 1 1 1 1 1 2 3 Output 2 Input 2 3 1 2 1 2 2 1 2 3 2 4 Output 0 -1 Submitted Solution: ``` import sys, array if sys.version[0] == "3": raw_input = input n, q = map(int, raw_input().split()) a = list(map(int, raw_input().split())) otr_size = max(1, int(n ** 0.5)) otr_cnt = (n + otr_size - 1) // otr_size def get_otr_boundaries(i): return (i * otr_size, min(n, (i + 1) * otr_size)) def get_otr_by_index(i): return i // otr_size otr_delta = [0] * otr_cnt # array.array("L", [0] * otr_cnt) otr_dict = [{} for i in range(otr_cnt)] for i in range(n): otr_dict[get_otr_by_index(i)][a[i]] = otr_dict[get_otr_by_index(i)].get(a[i], 0) + 1 def change_item(i, otr_index, x): otr_dict[otr_index][a[i]] -= 1 a[i] += x otr_dict[otr_index][a[i]] = otr_dict[otr_index].get(a[i], 0) + 1 def get_item(i, otr_index): return a[i] + otr_delta[otr_index] def has_item(val, otr_index): return otr_dict[otr_index].get(val - otr_delta[otr_index]) big_test = q > 10000 for q_num in range(q): query = list(map(int, raw_input().split())) if query[0] == 1: l, r, x = query[1:] l -= 1 r -= 1 l_otr = get_otr_by_index(l) r_otr = get_otr_by_index(r) if l_otr == r_otr: for i in range(l, r + 1): change_item(i, l_otr, x) else: gr1 = get_otr_boundaries(l_otr)[1] gr2 = get_otr_boundaries(r_otr)[0] for i in range(l, gr1): change_item(i, l_otr, x) for i in range(gr2, r + 1): change_item(i, r_otr, x) if not big_test: for i in range(l_otr + 1, r_otr): otr_delta[i] += x else: y = query[1] first = 0 while first < otr_cnt and not has_item(y, first): first += 1 if first == otr_cnt: print(-1) else: second = otr_cnt - 1 while not has_item(y, second): second -= 1 for ind_first in range(*get_otr_boundaries(first)): if get_item(ind_first, first) == y: break for ind_second in reversed(range(*get_otr_boundaries(second))): if get_item(ind_second, second) == y: break print(ind_second - ind_first) # print("DEBUG", a, otr_dict, otr_delta) ``` No
10,352
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Professor GukiZ was playing with arrays again and accidentally discovered new function, which he called GukiZiana. For given array a, indexed with integers from 1 to n, and number y, GukiZiana(a, y) represents maximum value of j - i, such that aj = ai = y. If there is no y as an element in a, then GukiZiana(a, y) is equal to - 1. GukiZ also prepared a problem for you. This time, you have two types of queries: 1. First type has form 1 l r x and asks you to increase values of all ai such that l ≀ i ≀ r by the non-negative integer x. 2. Second type has form 2 y and asks you to find value of GukiZiana(a, y). For each query of type 2, print the answer and make GukiZ happy! Input The first line contains two integers n, q (1 ≀ n ≀ 5 * 105, 1 ≀ q ≀ 5 * 104), size of array a, and the number of queries. The second line contains n integers a1, a2, ... an (1 ≀ ai ≀ 109), forming an array a. Each of next q lines contain either four or two numbers, as described in statement: If line starts with 1, then the query looks like 1 l r x (1 ≀ l ≀ r ≀ n, 0 ≀ x ≀ 109), first type query. If line starts with 2, then th query looks like 2 y (1 ≀ y ≀ 109), second type query. Output For each query of type 2, print the value of GukiZiana(a, y), for y value for that query. Examples Input 4 3 1 2 3 4 1 1 2 1 1 1 1 1 2 3 Output 2 Input 2 3 1 2 1 2 2 1 2 3 2 4 Output 0 -1 Submitted Solution: ``` n, q = map(int, input().split()) a = list(map(int, input().split())) for _ in range(q): inpt = list(map(int, input().split())) if inpt[0] == 1: for i in range(inpt[1], inpt[2] + 1): a[i] += inpt[3] else: i = 0 j = len(a) - 1 while (a[i] != inpt[1]) and (i < len(a) - 1): i += 1 while (a[j] != inpt[1]) and (j > 0): j -= 1 if i > j: print(-1) else: print(j - i) ``` No
10,353
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` #!/usr/bin/env python from sys import stdin, stderr from math import sqrt EPS = 1e-9 def position_at_time(t, acceletarion, initial_speed, initial_position): return 0.5*acceletarion*t*t + initial_speed*t + initial_position def time_to_reach_speed(final_speed, initial_speed, acceletarion): return abs(float(final_speed - initial_speed)) / acceletarion def time_to_travel_distance(distance_to_travel, initial_speed, acceletarion): return ( -initial_speed + sqrt(initial_speed*initial_speed + 2*acceletarion*distance_to_travel) ) / acceletarion # # Main # a, v = map(int, stdin.readline().split()) l, d, w = map(int, stdin.readline().split()) res = 0.0 vd = w if w >= v: t = time_to_reach_speed(v, 0, a) x = position_at_time(t, a, 0, 0) if x >= d - EPS: t = time_to_travel_distance(d, 0, a) res += t vd = a*t else: res += t + (d - x)/v vd = v else: t = time_to_reach_speed(w, 0, a) x = position_at_time(t, a, 0, 0) if x >= d - EPS: t = time_to_travel_distance(d, 0, a) res += t vd = a*t else: ts = time_to_reach_speed(v, 0, a) ds = position_at_time(ts, a, 0, 0) tf = time_to_reach_speed(v, w, a) df = position_at_time(tf, a, w, 0) if ds + df <= d + EPS: res = ts + (d - ds - df) / v + tf else: lo = w hi = v for tt in range(80): mid = (lo + hi)/2.0 ts = time_to_reach_speed(mid, 0, a) ds = position_at_time(ts, a, 0, 0) tf = time_to_reach_speed(mid, w, a) df = position_at_time(tf, -a, mid, 0) if ds + df > d + EPS: hi = mid else: lo = mid res = time_to_reach_speed(lo, 0, a) + time_to_reach_speed(lo, w, a) vd = w t = time_to_reach_speed(v, vd, a) x = position_at_time(t, a, vd, d) if x >= l - EPS: res += time_to_travel_distance(l-d, vd, a) else: res += t + (l - x)/v print("%.12f" % (res)) ```
10,354
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` from math import sqrt a, v = map(int, input().split()) l, d, w = map(int, input().split()) w = min(v, w) lowtime = (v - w) / a lowdist = v * lowtime - a * lowtime**2 / 2 startdist = v**2 / (2 * a) if startdist + lowdist <= d: ans = v / a + (d - startdist - lowdist) / v + lowtime elif w**2 <= 2 * d * a: u = sqrt(a * d + w**2 / 2) ans = (2 * u - w) / a else: ans = sqrt(2 * d / a) w = ans * a hightime = (v - w) / a highdist = w * hightime + a * hightime**2 / 2 if highdist <= l - d: ans += hightime + (l - d - highdist) / v else: disc = sqrt(w**2 + 2 * a * (l - d)) ans += (disc - w) / a print('%.7f' % ans) ```
10,355
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` a, v = map(int, input().split()) l, d, w = map(int, input().split()) t1, t2 = 0, 0 vt = (d * 2 * a) ** 0.5 v_max = min(v, w) if vt < min(v, w): t1 = (2 * d / a) ** 0.5 v_max = v v0 = vt else: v_mid = min((((2 * a * d) + v_max ** 2) * 0.5) ** 0.5, v) t1 = v_mid / a + (v_max - v_mid) / (-a) s1 = d - (2 * v_mid ** 2 - v_max ** 2) / 2 / a t1 += s1 / v_mid v0 = v_max v_max = v d = l - d vt = (v0 ** 2 + 2 * a * d) ** 0.5 if vt < v_max: t2 = 2 * d / (v0 + vt) else: t2 = (v_max - v0) / a d -= (v_max + v0) / 2 * t2 t2 += d / v_max print('%.8f' %(t1 + t2)) ```
10,356
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` a,v=map(int,input().split()) l,d,w=map(int,input().split()) t=0 def gett(a,b,c): delta=b**2-4*a*c t1=(-b+delta**(1/2))/(2*a) t2=(-b-delta**(1/2))/(2*a) if min(t1,t2)>0: return min(t1,t2) else: return max(t1,t2) if 2*a*d<=w*w or v<=w: if 2*a*l<=v*v: t=(2*l/a)**(1/2) else: t=l/v+v/a/2 else: tmp=d-1/2*v*v/a+1/2*(v-w)**2/a-v*(v-w)/a if tmp<=0: tmp2=l-d-(1/2*(v-w)**2/a+w*(v-w)/a) if tmp2>=0: t=tmp2/v+(v-w)/a+2*gett(a,2*w,w*w/(2*a)-d)+w/a else: t=gett(a/2,w,d-l)+2*gett(a,2*w,w*w/(2*a)-d)+w/a else: tmp2=l-d-(1/2*(v-w)**2/a+w*(v-w)/a) if tmp2>=0: t=tmp2/v+(v-w)/a+(2*v-w)/a+tmp/v else: t=gett(a/2,w,d-l)+(2*v-w)/a+tmp/v print("%.12f" %(t)) ```
10,357
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Sun Mar 4 22:28:47 2018 @author: hp """ [a,v] = [eval(x) for x in str.split(input())] [l,d,w] = [eval(x) for x in str.split(input())] if v <= w: if v ** 2 >= 2 * a *l: #accer all the way t = (2 * l / a) ** 0.5 else: #accer to v,then drive with v s1 = v ** 2 / (2 * a) t1 = v / a s2 = l - s1 t2 = s2 / v t = t1 + t2 else: if w ** 2 >= 2 * a * d: #accer all the way to d if v ** 2 >= 2 * a *l: #accer all the way t = (2 * l / a) ** 0.5 else: #accer to v,then drive with v s1 = v ** 2 / (2 * a) t1 = v / a s2 = l - s1 t2 = s2 / v t = t1 + t2 else: if (2 * a * d + w ** 2) / 2 <= v ** 2: #drive to speed v1 and dec to w,after drive to d,then accer v1 = ((2 * a * d + w ** 2) / 2) ** 0.5 t1 = v1 / a t2 = (v1 - w) / a else: #accer to v,then keep,then dec to w t1 = v / a + (v - w) / a t2 = (d - v ** 2 / (2 * a) - (v ** 2 - w ** 2) / (2 * a)) / v #judge if we can accer to v if v ** 2 - w ** 2 >= 2 * a * (l - d): #accer all the left t3 = ( -w + (w ** 2 + 2 * a * (l - d)) ** 0.5) / a t = t1 + t2 + t3 else: #accert to v,then v t3 = (v - w) / a s3 = w * t3 + a * t3 ** 2 / 2 t4 = (l - d - s3) / v t = t1 + t2 + t3 + t4 print("%.10f" %(t)) ```
10,358
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` import math a, v = map(float, input().split()) l, d, w = map(float, input().split()) res = 0.0 if v <= w: t1 = v / a d1 = 0.5*a*t1*t1 if d1 >= l: res = math.sqrt(l*2/a) else: t2 = (l - d1) / v res = t1 + t2 else: t1 = w / a d1 = 0.5*a*t1*t1 # print(d1) if d1 >= d: t1 = math.sqrt(d*2/a) cur = t1 * a t2 = (v - cur) / a d2 = 0.5*a*t2*t2 + cur*t2 if d2 >= l - d: # print('A') res = math.sqrt(l*2/a) else: # print('B') t1 = v / a t2 = (l - 0.5*a*t1*t1) / v res = t1 + t2 else: t1 = math.sqrt(d/a + w*w/(2*a*a)) t2 = (t1*a - w) / a if t1 * a > v: t1 = v / a tx = (v - w) / a mid = d - 0.5*a*t1*t1 - (0.5*(-a)*tx*tx+v*tx) t2 = tx + mid / v t3 = (v - w) / a d3 = 0.5*a*t3*t3 + w*t3 if d3 >= l - d: # print('C') t3 = (-w + math.sqrt(w*w - 4*0.5*a*(-(l-d)))) / a # print(t1, t2, t3) # t3 = 8.965874696353 - 8.0 - 0.24 # print(0.5*a*t3*t3 + w*t3, l-d) res = t1 + t2 + t3 else: # print('D') t3 = (v - w) / a d3 = 0.5*a*t3*t3 + w*t3 t4 = (l - d - d3) / v # print(t1, t2, t3, t4) res = t1 + t2 + t3 + t4 print(res) ```
10,359
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` import math def getdt(): return map(int, input().split()) def calc(v0, v, a, x): t = (v - v0) / a x0 = v0 * t + 0.5 * a * t * t if x0 >= x: return (x, (math.sqrt(v0 * v0 + 2 * a * x) - v0) / a) return (x0, t) def go(v0, v, a, x): x0, t = calc(v0, v, a, x) return t + (x - x0) / v a, v = getdt() l, d, w = getdt() if w > v: w = v x, t = calc(0, w, a, d) if x == d: print(go(0, v, a, l)) else: print(t + go(w, v, a, (d - x) * 0.5) * 2 + go(w, v, a, l - d)) ```
10,360
Provide tags and a correct Python 3 solution for this coding contest problem. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Tags: implementation, math Correct Solution: ``` from math import sqrt a, v = map(int, input().split()) l, d, w = map(int, input().split()) def findt(u, v, a, dist): front = (v*v-u*u)/(2*a) if front > dist: return (sqrt(u*u+2*a*dist)-u)/a return (v-u)/a + (dist-front)/v def solve(a, v, l, d, w): if v <= w or 2*a*d <= w*w: return findt(0, v, a, l) after = findt(w, v, a, l-d) peak = sqrt(a*d + w*w/2) if peak > v: travel = (v*v-w*w/2)/a before = (2*v-w)/a + (d-travel)/v else: before = (2*peak-w)/a return before + after print(f'{solve(a, v, l, d, w):.8f}') ```
10,361
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` __author__ = 'Darren' def solve(): a, v = map(int, input().split()) l, d, w = map(int, input().split()) total_time = 0.0 if v >= w: if w*w >= 2*a*d: x = (2*a*d) ** 0.5 total_time = x / a if v*v - x*x >= 2*a*(l-d): total_time += (-2*x + (4*x*x + 8*a*(l-d)) ** 0.5) / (2*a) else: total_time += (v-x)/a + (l-d-(v*v-x*x)/(2*a))/v else: if 2*v*v - w*w <= 2*a*d: total_time = v/a + (v-w)/a + (d-(2*v*v-w*w)/(2*a))/v else: x = ((2*a*d+w*w)/2) ** 0.5 total_time = x/a + (x-w)/a if v*v - w*w >= 2*a*(l-d): total_time += (-2*w + (4*w*w+8*a*(l-d)) ** 0.5) / (2*a) else: total_time += (v-w)/a + (l-d-(v*v-w*w)/(2*a))/v else: if v*v >= 2*a*l: total_time = (l*2/a) ** 0.5 else: total_time = v/a + (l-v*v/(2*a))/v print('%.10f' % total_time) if __name__ == '__main__': solve() ``` Yes
10,362
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` from math import sqrt import sys from typing import List, Union def rl(int_: bool = True, is_split: bool = True) -> Union[List[str], List[int]]: if int_: return [int(w) for w in sys.stdin.readline().split()] if is_split: return [w for w in sys.stdin.readline().split()] return sys.stdin.readline().strip() a, v = rl() l, d, w = rl() def time(u, s, a, v): vs = sqrt(u * u + 2 * a * s) # print("vs", vs) if vs <= v: return (vs - u) / a elif vs > v: dv = (v * v - u * u) / (2 * a) # print("dv", dv) if dv >= s: vd = sqrt(u * u + 2 * a * s) # print(vd) return (vd - u) / a else: return ((v - u) / a) + ((s - dv) / v) if w >= v: print(time(0, l, a, v)) elif w < v: vd = sqrt(2 * a * d) # print("vd", vd) if vd <= w: print(time(0, l, a, v)) elif vd > w: v_ = sqrt((w * w + 2 * a * d) / 2) # print(v_) if v_ <= v: td = (v_ / a) + ((v_ - w) / a) elif v_ > v: td = (v / a) + ((d - ((2 * v * v - w * w) / (2 * a))) / v) + ((v - w) / a) print(td + time(w, l - d, a, v)) ``` Yes
10,363
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` import logging logging.basicConfig(level=logging.INFO) def readintGenerator(): while (True): n=0 tmp=list(map(lambda x:int(x), input().split())) m=len(tmp) while (n<m): yield(tmp[n]) n+=1 readint=readintGenerator() a=next(readint) v=next(readint) l=next(readint) d=next(readint) w=next(readint) def sqrt(x): return x**0.5 def cost(v0,l,v,a): s0=(v**2 - v0**2)/(2*a) if (s0<=l): return (v-v0)/a + (l-s0)/v else: v1=sqrt(v0**2+2*a*l) return (v1-v0)/a def calc(a,v,l,d,w): if (v<=w): return cost(0,l,v,a) else: v0=sqrt(2*a*d) if (v0<=w): return cost(0,l,v,a) else: v1=sqrt((2*a*d+w**2)/2) t0=(2*v1-w)/a if (v1<=v): return t0+cost(w,l-d,v,a) else: t0=(d+(2*v**2-2*v*w+w**2)/(2*a))/v return t0+cost(w,l-d,v,a) print("%.8f" %calc(a,v,l,d,w)) ``` Yes
10,364
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` #!/usr/bin/env python """ CodeForces: 5D Follow Trafic Rules Basic equations for acceleration, distance and velocity (speed): eqn-1) final velocity: v = v0 + a * t eqn-2) distance traveled: d = v0 * t + a * t * t / 2 eqn-3) acceleration: v * v - v0 * v0 = 2 * a * d Symbols stand for: a: acceleration d: distance traveled t: travel time v0: initial speed v: final speed """ from math import sqrt def main(): a, v = map(int, input().split()) l, d, w = map(int, input().split()) # if v <= w, virtually no speed limit if v <= w: w = v # there are three cases before reaching the sign: # Case 1: unable to drive over the speed limit # i.e. no need to decelerate during the travel # Case 2: able to drive over the speed limit # Case 2a: able to drive at the max speed # i.e. accelerate and deceleration # Case 2b: unable to drive at the max speed # i.e. find the possible max speed, then same as case 2a ax2 = a * 2 vxv = v * v wxw = w * w ax2xd = ax2 * d # eqn-3: # d1 = travel distance to reach the speed limit # w * w - 0 * 0 = 2 * a * d1 # if d1 >= d or v == w, then Case 1 # otherwise Case 2 if wxw >= ax2xd or v == w: # Case 1: unable to drive over the speed limit # check if able to drive at the max spped before reaching the goal # eqn-3: # m = distance to reach the max speed # v * v - 0 * 0 = 2 * a * m # if m <= l (distance to the goal), then # 2 * a * s <= 2 * a * l # v * v <= 2 * a * l if vxv <= ax2 * l: # able to drive at the max speed # eqn-1: # t1 = time to reach the max speed # v = a * t1 # eqn-3: # d1 = distance traveled to reach the max speed # v * v = 2 * a * d1 # equation: # d2 = remaining distance = l - d1 # t2 = remaining time # d2 = v * t2 hours = (v / a) + ((l - (vxv / ax2)) / v) else: # unable to drive at the max speed # eqn-2: time of the entire travel # l = a * t * t / 2 hours = sqrt(2.0 * l / a) else: # Case 2: able to drive over the speed limit # there are three steps: # Step 1: find the possible max speed and # travel distance at that speed # Step 1a: Case 2a # Step 1b: Case 2b # Step 2: calculate the time to the sing # Step 3: calculate the time after the sign # Step 1: find the possible max speed (p) # and the distance travels (r) at the possible max speed # eqn-3: # d1 = distance to the max speed (acceleration) # d2 = distance to the speed limit (deceleration) # v * v - 0 * 0 = 2 * a * d1 # v * v - w * w = 2 * a * d2 <-- w * w - v * v = 2 * (-a) * d2 # add two equations: # v * v + (v * v - w * w) = 2 * a * (d1 + d2) # if (d1 + d2) <= d, then Case 2a # otherwise Case 2b vxv_wxw = vxv - wxw s = vxv + vxv_wxw if s <= ax2xd: # Case 2a: able to drive at the max speed # i.e. find the distance travels (r) at the max speed # eqn-3: # v * v + (v * v - w * w) = 2 * a * (d1 + d2) # d1 + d2 + r = d p = v r = d - (s / ax2) else: # Case 2b: unable to drive at the max speed # i.e. find the possible max speed (p) # eqn-3: # d1 = distance to reach the possible max speed # d2 = distance to reach the speed limit # p = possible max speed when d1 + d2 == d # p * p - 0 * 0 = 2 * a * d1 # p * p - w * w = 2 * a * d2 <-- w * w - p * p = 2 * (-a) * d2 # add two equation # 2 * (p * p) - (w * w) = 2 * a * (d1 + d2) p = sqrt((ax2xd + wxw) * 0.5) r = 0 # Step 2: calculate the time to the sign # Time to reach the sign # eqn-2: # t1, d1 = time and distance to reach the possible max speed # t2, d2 = time and distance to reach the speed limit # p = 0 + a * t1 # p - w = a * t2 <-- w = p + (-a) * t2 # add two equations: # p + (p - w) = a * (t1 + t2) # equation: # r = travel distance at the possible max speed # t3 = travel time at the possible max speed # r = p * t3 hours = ((p + (p - w)) / a) + (r / p) # Step 3: time after the sign # Check if able to drive at the max speed # eqn-2: # d1 = distance to reach the max speed # v * v - w * w = 2 * a * d1 # if d1 >= d, able to drive at the max speed # else possible reach the max speed g = l - d s = ax2 * g if vxv_wxw >= s: # reach the goal before reaching the max speed # eqn-2: # g = remaining distance # t1 = time to the goal # g = l - d = w * t1 + a * t1 * t1 / 2 # solve the equation for t1 (positive): # t1 = (sqrt(2 * a * g - w * w) - w) / a hours += (sqrt(s + wxw) - w) / a else: # possible to reach the max before reaching the goal # eqn-1: # t1 = time to reach the max speed # v = w + a * t1 # eqn-3: # d1 = distance to reach the max speed # v * v - w * w = 2 * a * d1 # equation: # d2 = remaining distance after reaching the max speed # t2 = time after reaching the max speed # d2 = g - d1 = v * t2 hours += ((v - w) / a) + ((g - (vxv_wxw / ax2)) / v) print("{:.12f}".format(hours)) if __name__ == '__main__': main() ``` Yes
10,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` from math import * a,v=list(map(int,input().split())) l,d,w=list(map(int,input().split())) if v>w: s1=w**2/2/a if d<=s1: t=sqrt(2*d/a) else: t=sqrt(2*s1/a) s2=min((d-s1)/2,(v**2-w**2)/(2*a)) if s2==(d-s1)/2: t+=2*(sqrt(2*(s1+s2)/a)-sqrt(2*s1/a)) else: t+=2*(v-w)/a+(d-s1-2*s1)/v s3=min((v**2-w**2)/2/a,l-d) t+=sqrt(2*(s3+s1)/a)-sqrt(2*s1/a)+(l-d-s3)/v else: s=min(v**2/2/a,l) t=sqrt(2*s/a)+(l-s)/v print(t) ``` No
10,366
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` from math import sqrt import sys from typing import List, Union def rl(int_: bool = True, is_split: bool = True) -> Union[List[str], List[int]]: if int_: return [int(w) for w in sys.stdin.readline().split()] if is_split: return [w for w in sys.stdin.readline().split()] return sys.stdin.readline().strip() a, v = rl() l, d, w = rl() def time(u, s, a, v): vs = sqrt(u * u + 2 * a * s) # print("vs", vs) if vs <= v: return (vs - u) / a elif vs > v: dv = (v * v - u * u) / (2 * a) # print("dv", dv) if dv >= s: vd = sqrt(u * u + 2 * a * s) # print(vd) return (vd - u) / a else: return ((v - u) / a) + ((s - dv) / v) if w >= v: print(time(0, l, a, v)) elif w < v: vd = sqrt(2 * a * d) # print("vd", vd) if vd <= w: print(time(0, l, a, v)) elif vd > w: v_ = sqrt((w * w + 2 * a * d) / 2) # print(v_) if v_ <= v: td = (v_ / a) + ((v_ - w) / a) elif v_ > v: td = (v / a) + ((d - ((2 * v * v - w * w) / 2 * a)) / v) + ((v - w) / a) print(td + time(w, l - d, a, v)) ``` No
10,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` # -*-coding:utf-8 -*- import math a,v=map(float,input().split()) l,d,w=map(float,input().split()) ans=0 if v<w: t0=v/float(a) t1=(l-(a*t0**2)/2.0)/float(v) ans=t0+t1 elif a*math.sqrt(2.0*d/a)<w: t0=v/float(a) l1=(a*t0**2)/2 if l1>=l: ans=math.sqrt(2.0*l/a) else: t1=(l-l1)/float(v) ans=t0+t1 else: t0=(-3*w+math.sqrt(5*w**2+8*a*d))/(2*a) t1=(w+a*t0)/float(a) t2=(v-w)/float(a) if ((w+a*t1)/2)*t1<(l-d): t3=((l-d)-(((w+a*t1)/2)*t1))/float(v) ans=t0+t1+t2+t3 else: t2=((-w)+math.sqrt(w**2+8*a*(l-d)))/(2*a) ans=t0+t1+t2 print(ans) ``` No
10,368
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed. It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≀ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed. The car can enter Bercouver at any speed. Input The first line of the input file contains two integer numbers a and v (1 ≀ a, v ≀ 10000). The second line contains three integer numbers l, d and w (2 ≀ l ≀ 10000; 1 ≀ d < l; 1 ≀ w ≀ 10000). Output Print the answer with at least five digits after the decimal point. Examples Input 1 1 2 1 3 Output 2.500000000000 Input 5 70 200 170 40 Output 8.965874696353 Submitted Solution: ``` from math import sqrt a, v = map(int, input().split()) l, d, w = map(int, input().split()) lowtime = max(0, v - w) / a lowdist = v * lowtime - a * lowtime**2 / 2 startdist = v**2 / (2 * a) if startdist + lowdist <= d: ans = v / a + (d - startdist - lowdist) / v + lowtime else: u = sqrt(a * d + w**2 / 2) ans = u / a if u > w: ans += (u - w) / a w = min(u, w) highdist = min(v, w) * lowtime + a * lowtime**2 / 2 if highdist <= l - d: ans += lowtime + (l - d - highdist) / v else: disc = sqrt(w**2 + 2 * a * (l - d)) ans += (disc - w) / a print('%.7f' % ans) ``` No
10,369
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` def main(): time = input() passed = int(input()) time = time.split(":") time[0] = int(time[0]) time[1] = int(time[1]) hours = int(passed/60) minutes = passed%60 time[1] = (time[1] + minutes) if time[1] > 59: time[1] = time[1]%60 time[0] = (time[0] + 1) % 24 time[0] = (time[0] + hours) % 24 if int(time[0]/10) == 0: time[0] = "0" + str(time[0]) if int(time[1]/10) == 0: time[1] = "0" + str(time[1]) time[0] = str(time[0]) time[1] = str(time[1]) print(time[0] + ":" + time[1]) if __name__ == "__main__": main() ```
10,370
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` import sys import math input = sys.stdin.readline h, m = map(int, input().split(":")) ext = int(input()) time = h * 60 + m + ext h, m = (time // 60) % 24, time % 60 if h < 10: h = str('0' + str(h)) if m < 10: m = str('0' + str(m)) print("{}:{}".format(h,m)) ```
10,371
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` from datetime import datetime, timedelta time = input() hour = int(time[0:2]) mins = int(time[3:5]) add = int(input()) op = datetime(2021, 5 , 18, hour, mins) + timedelta(minutes= add) print(op.strftime("%H:%M")) ```
10,372
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` s = input() n = int(input()) h = n // 60 min = n%60 a=0 if (int(s[3:])+min)//60 :a=(int(s[3:])+min)//60 min = str((int(s[3:])+min)%60) if len(min)==1:min='0'+min h = str((int(s[0:2])+h+a)%24) if len(h)==1:h='0'+h print(h+':'+min) ```
10,373
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` s=input() a=int(input()) arr=s.split(":") hr,mini=int(arr[0]),int(arr[1]) if(a < 60): if(mini+a < 60): l=str(mini+a) if(len(l)==1): print(arr[0]+":"+"0"+l) else: print(arr[0]+":"+l) else: k=(mini+a)//60 rem=(mini+a) % 60 if(hr==23): hr=0 hr+=k-1 else: hr+=k hr%=24 h=str(hr) m=str(rem) if(len(h)==1 and len(m)==1): print("0"+h+":"+"0"+m) elif(len(h)==1): print("0"+h+":"+m) elif(len(m)==1): print(h+":"+"0"+m) else: print(h+":"+m) else: k=a//60 rem=a % 60 if(hr==23): hr=0 hr+=k-1 else: hr+=k hr%=24 if(rem+mini< 60): m=str(mini+rem) h=str(hr) if(len(h)==1 and len(m)==1): print("0"+h+":"+"0"+m) elif(len(h)==1): print("0"+h+":"+m) elif(len(m)==1): print(h+":"+"0"+m) else: print(h+":"+m) else: k=(mini+rem)//60 rem=(mini+rem) % 60 if(hr==23): hr=0 hr+=k-1 else: hr+=k hr%=24 h=str(hr) m=str(rem) if(len(h)==1 and len(m)==1): print("0"+h+":"+"0"+m) elif(len(h)==1): print("0"+h+":"+m) elif(len(m)==1): print(h+":"+"0"+m) else: print(h+":"+m) ```
10,374
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` start_time = input() minutes = int(input()) end_time_in_minutes = (int(start_time[:2]) * 60 + int(start_time[3:]) + minutes) % (24 * 60) ans = str(end_time_in_minutes // 60).zfill(2) + ':' + str(end_time_in_minutes % 60).zfill(2) print(ans) ```
10,375
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` a,b=map(int,input().split(':')) n=int(input()) b+=n a+=b//60 b=b%60 a%=24 if b<10:b='0'+str(b) else:b=str(b) if a<10:a='0'+str(a) else:a=str(a) print(a+':'+b) ```
10,376
Provide tags and a correct Python 3 solution for this coding contest problem. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Tags: implementation Correct Solution: ``` hh, mm = [int(t) for t in input().split(':')] dm = int(input()) mm += dm hh += mm//60 mm %= 60 hh %= 24 print("{0:02}:{1:02}".format(hh, mm)) ```
10,377
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` t= list(map(int,input().split(":"))) x= t[0]*60+t[1]+int(input()) a= int(x/60) b= x%60 if a>=24: a= a%24 if a<10: a= "0"+str(a) if b<10: b= "0"+str(b) a= str(a) b= str(b) s= a+":"+b print(s) ``` Yes
10,378
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` X = list(map(int, input().split(":"))) Min = X[0] * 60 + X[1] + int(input()) Hour = str((Min // 60) % 24) Minute = str(Min % 60) print(Hour if len(Hour) == 2 else '0' + Hour, end=':') print(Minute if len(Minute) == 2 else '0' + Minute) # UB_CodeForces # Advice: Falling down is an accident, staying down is a choice # Location: At Grandma's house # Caption: Start for new exam # CodeNumber: 593 ``` Yes
10,379
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` __author__ = 'Logan' strin = str(input()) time = [int(x.strip()) for x in strin.split(':')] minutes = int(input()) time[1] += minutes time[0] += int(time[1]/60) time[0] = time[0] % 24 time[1] = time[1] % 60 print("%02d:%02d" %(time[0], time[1]) ) ``` Yes
10,380
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` h, m = input().split(':') h = int(h) m = int(m) tot = h * 60 + m add = eval(input()) tot += add tot %= (24 * 60) h = tot // 60 m = tot % 60 if h < 10: print('0'+str(h)+':', end = '') else: print(str(h)+':', end = '') if m < 10: print('0'+str(m)) else: print(str(m)) ``` Yes
10,381
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` st=input() ex=int(input()) h=int(st[:2]) m=int(st[3:]) time=h*60+m+ex if time/60>=24: print("00:",end="") elif time/60<=9: print("0"+str(time//60)+":",end="") else: print(str(time//60)+":",end="") if time-(time//60)*60<=9: print("0",end="") print(str(time-(time//60)*60)) ``` No
10,382
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` t0=input() t1=int(input()) hh=int(t0[0:2]) mm=int(t0[3:5]) x=t1%60 y=int(t1/1440) z=int(t1/60) th=z-24*y tm=x q=tm+mm t=int(q/60) q=q%60 p=hh+th if(t+p>23): p=24-p-t if(p<0): p=-p if(p<10 and q<10): print(f"0{p}:0{q}") elif(p<10 and q>=10): print(f"0{p}:{q}") elif(p>=10 and q<10): print(f"{p}:0{q}") else: print(f"{p}:{q}") ``` No
10,383
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` s = input() n = int(input()) hour = int(s[:s.find(':')]) minute = int(s[s.find(':') + 1:]) if 60 - minute > n: minute += n elif 60 - minute == n: minute = 0 hour += 1 else: hour += 1 minute = abs(60 - minute - n) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if minute > 60: hour += 1 minute = abs(60 - minute) if hour == 24: hour = 0 elif hour > 24: hour = abs(24 - hour) # 20:20 + 121 (60 + 60 + 1) = 22:21 if len(str(hour)) == 1: hour = '0' + str(hour) if len(str(minute)) == 1: minute = '0' + str(minute) print(str(hour) + ':' + str(minute)) ``` No
10,384
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes). The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed. Output The only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed). See the examples to check the input/output format. Examples Input 23:59 10 Output 00:09 Input 20:20 121 Output 22:21 Input 10:10 0 Output 10:10 Submitted Solution: ``` t0=input() t1=int(input()) hh=int(t0[0:2]) mm=int(t0[3:5]) th=int(t1/60) tm=(th*60)-t1 if(tm<0): tm=-tm q=tm+mm t=int(q/60) q=q%60 p=hh+th if(t+p>23): p=24-p-t if(p<0): p=-p if(p<10 and q<10): print(f"0{p}:0{q}") elif(p<10 and q>=10): print(f"0{p}:{q}") elif(p>=10 and q<10): print(f"{p}:0{q}") else: print(f"{p}:{q}") ``` No
10,385
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# #vsInput() def canMake(x): needed=[x*i for i in quantity] #print(x,needed) powder=magic for i in range(n): powder-=max(0,needed[i]-have[i]) if(powder<0): return False return True n,magic=value() quantity=array() have=array() low=0 high=10**15 ans=0 while(low<=high): mid=(low+high)//2 if(canMake(mid)): ans=mid low=mid+1 else: high=mid-1 print(ans) ```
10,386
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` n,k=map(int,input().split()) a=[int(x) for x in input().split()] b=[int(x) for x in input().split()] def bs(m): c=0 for i in range(n): if a[i]*m>b[i]: c+=abs(b[i]-(a[i]*m)) if c<=k: return True else: return False l,h=0,10**10 ans=0 while(l<=h): m=l+(h-l)//2 if bs(m): ans=m l=m+1 else: h=m-1 print(ans) ```
10,387
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) lo = 0 hi = 2*1e9 def p(cookies): powder = k for i in range(len(b)): have = b[i] one = a[i] remainder = have - (one * cookies) if remainder < 0: powder += remainder if powder < 0: return False return True while lo < hi: m = (lo + hi) // 2 if p(m): lo = m + 1 else: hi = m print(int(lo if p(lo) else lo - 1)) """ """ ```
10,388
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left, bisect_right from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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 defaultdict as dd, deque as dq import math, string def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) MOD = 10**9+7 """ Without the powder we can make min(AN//BN) With the powder, we need sum(AN % BN) to make one more Then we need sum(AN) for every other """ def solve(): N, K = getInts() A = getInts() B = getInts() curr_min = 10**10 for i in range(N): curr_min = min(curr_min, B[i]//A[i]) ans = curr_min rem = [] for i in range(N): rem.append(B[i]-curr_min*A[i]) def works(D): req = 0 for i in range(N): req += max(0,D*A[i]-rem[i]) return req <= K assert works(0) assert not works(10**18) left = 0 right = 10**18 while right-left > 1: mid = (right+left)//2 if works(mid): left = mid else: right = mid return ans+left #for _ in range(getInt()): print(solve()) ```
10,389
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` n, k = map(int, input().split()) b = list(map(int, input().split())) a = list(map(int, input().split())) c = [] x = 0 for i in range(n): c.append([a[i]//b[i], a[i], b[i]]) c.append([10**12, 0, 10**10]) c = sorted(c) ans = c[0][0] suma = 0 sumb = 0 i = 0 n += 1 while i < n: j = i cura = 0 curb = 0 while i < n and c[j][0] == c[i][0]: cura += c[i][1] curb += c[i][2] i += 1 if sumb * c[j][0] - suma <= k: ans = max(ans, c[j][0]) else: ans = max(ans, min((suma + k)//sumb, c[j][0]-1)) break suma += cura sumb += curb print(ans) ```
10,390
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` read = lambda: map(int, input().split()) n, k = read() a = list(read()) b = list(read()) c = [0] * n r = [0] * n for i in range(n): c[i] = b[i] // a[i] r[i] = a[i] - b[i] % a[i] def f(x): k1 = k for i in range(n): if c[i] >= x: continue cnt = (x - c[i] - 1) * a[i] + r[i] k1 -= cnt if k1 < 0: return False return True L, R = 0, 10 ** 10 while R - L > 1: M = (L + R) // 2 if f(M): L = M else: R = M ans = L print(ans) ```
10,391
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` import sys,math,bisect sys.setrecursionlimit(10**5) from random import randint inf = float('inf') mod = 10**9+7 "========================================" def lcm(a,b): return int((a/math.gcd(a,b))*b) def gcd(a,b): return int(math.gcd(a,b)) def tobinary(n): return bin(n)[2:] def binarySearch(a,x): i = bisect.bisect_left(a,x) if i!=len(a) and a[i]==x: return i else: return -1 def lowerBound(a, x): i = bisect.bisect_left(a, x) if i: return (i-1) else: return -1 def upperBound(a,x): i = bisect.bisect_right(a,x) if i!= len(a)+1 and a[i-1]==x: return (i-1) else: return -1 def primesInRange(n): ans = [] prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 for p in range(2, n+1): if prime[p]: ans.append(p) return ans def primeFactors(n): factors = [] while n % 2 == 0: factors.append(2) n = n // 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: factors.append(i) n = n // i if n > 2: factors.append(n) return factors def isPrime(n,k=5): if (n <2): return True for i in range(0,k): a = randint(1,n-1) if(pow(a,n-1,n)!=1): return False return True "=========================================" """ n = int(input()) n,k = map(int,input().split()) arr = list(map(int,input().split())) """ from collections import deque,defaultdict,Counter from heapq import heappush, heappop,heapify import string for _ in range(1): n,k=map(int,input().split()) need=list(map(int,input().split())) have=list(map(int,input().split())) def canMake(need,have,toMake,k): req = 0 for i in range(len(need)): if need[i]*toMake <= have[i]: pass else: req+= (need[i]*toMake)-have[i] if req<=k: return True return False ans = 0 l=1 r=1e20 while l<=r: mid=(l+r)//2 if canMake(need,have,mid,k): l=mid+1 ans=max(ans,mid) else: r=mid-1 print(int(ans)) ```
10,392
Provide tags and a correct Python 3 solution for this coding contest problem. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Tags: binary search, implementation Correct Solution: ``` def process(key, a,b, k,n): #print(key, nc,end=" ") for i in range(n): y=b[i]-(a[i]*key) if y<0: k+=y if k<0: return False #print(k, res) if k>=0: return True else: return False def bin_src(a,b,n,k,lo,hi): while (hi-lo>1): mid = ((hi +lo) // 2) val = process(mid,a,b,k,n) if val==True: lo=mid else: hi=mid if(process(lo,a,b,k,n)==True): return lo else: return hi def main(): nk = list(map(int, input().split(" "))) n,k=nk[0],nk[1] a=list(map(int,input().split(" "))) b=list(map(int,input().split(" "))) print(bin_src(a,b,n,k, 0, (2*(10**9))+1)) if __name__=="__main__": main() ```
10,393
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` def ok(x): need = 0 for i in range(n): tmp = a[i] * x - b[i] if tmp > 0: need += tmp return need <= k n, k = (int(_) for _ in input().split()) a = [int(_) for _ in input().split()] b = [int(_) for _ in input().split()] lo, hi = 0, 2 * 10 ** 9 while lo <= hi: mid = (lo + hi) >> 1 if ok(mid): lo = mid + 1 else: hi = mid - 1 print(hi) ``` Yes
10,394
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` I=lambda:list(map(int,input().split())) n,k=I() a=I() b=I() l=0 r=2*10**9 while l<r: m=(l+r)//2+1;s=sum(max(a[i]*m-b[i],0)for i in range(n)) if s>k:r=m-1 else:l=m print(l) ``` Yes
10,395
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` """ keywords : python input intput python how to take input in python Python Input :- 1. Just one value : a = int(input()) 2. Two or three consecutive values : m,n=map(int,input().split()) 3. Array as a space separated line : ar=list(map(int,input().split())) """ n, k = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) def check(mid): left = 0 for i in range(n): left += max(0, mid * a[i] - b[i]) return left <= k def binsearch(lo, hi): ans = int(-1e18) while lo <= hi: mid = (lo + hi + 1) // 2 #print("min = ", mid) if check(mid): ans = max(ans, mid) lo = mid + 1 else: hi = mid - 1 return ans ans = binsearch(0, int(1e18)) print(ans) ``` Yes
10,396
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` def check(a,b,midd,k): ans1=0 for i in range(n): if a[i]*midd<=b[i]: continue ans1+=(midd*a[i]-b[i]) if ans1>k:return False return True n,k=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) l=0 r=3*(10**9) ans=0 while l<=r: mid=(l+r)//2 if check(a,b,mid,k): l=mid+1 ans=max(ans,mid) else:r=mid-1 print(ans) ``` Yes
10,397
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` from math import ceil,sqrt,gcd,log,floor from collections import deque def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def li(): return list(mi()) def msi(): return map(str,input().strip().split(" ")) def lsi(): return list(msi()) #for _ in range(ii()): n,k=mi() a=li() b=li() l=0 r=1000000005 while(l<r): m=(l+r)//2 s=0 for i in range(n): if(b[i]<(m*a[i])): s+=(m*a[i]-b[i]) if(s>k): r=m-1 else: m1=m s1=s l=m+1 k-=s1 m1+=(k//sum(a)) print(m1) ``` No
10,398
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The term of this problem is the same as the previous one, the only exception β€” increased restrictions. Input The first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has. Output Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder. Examples Input 1 1000000000 1 1000000000 Output 2000000000 Input 10 1 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1 1 1 1 1 1 1 1 1 1 Output 0 Input 3 1 2 1 4 11 3 16 Output 4 Input 4 3 4 3 5 6 11 12 14 20 Output 3 Submitted Solution: ``` n,k=input().split() n=int(n) k=int(k) a=[] a=input().split() b=input().split() for i in range(n): a[i],b[i]=int(a[i]),int(b[i]) min=b[0]//a[0] for i in range(1,n): if(min>b[i]//a[i]): min=b[i]//a[i] qty=min for i in range(n): b[i]-=a[i]*min diff=0 for i in range(n): if(a[i]-b[i]>0): diff+=a[i]-b[i] else: k+=b[i]-a[i] if(diff>k): print(qty) elif(diff==k): print(qty+1) else: k-=diff total=sum(a) print(qty+k//total+1) ``` No
10,399